repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
aomran/micromachinejs | webpack.config.babel.js | 1000 | const path = require('path');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const CompressionPlugin = require('compression-webpack-plugin');
const unminified = {
entry: './src/micromachine.js',
module: {
rules: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
],
},
output: {
filename: 'micromachine.js',
path: path.resolve(__dirname, 'dist'),
library: 'MicroMachine',
libraryTarget: 'umd',
},
};
const minified = {
entry: './src/micromachine.js',
module: {
rules: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' },
],
},
output: {
filename: 'micromachine.min.js',
path: path.resolve(__dirname, 'dist'),
library: 'MicroMachine',
libraryTarget: 'umd',
},
plugins: [
new UglifyJSPlugin(),
new CompressionPlugin({
asset: '[path].gz[query]',
algorithm: 'gzip',
test: /\.(js|html)$/,
}),
],
};
module.exports = [unminified, minified];
| mit |
Tentoe/dotally | src/actions/openDotaAPI.js | 865 |
export const FETCH_OPENDOTAPLAYER = 'FETCH_OPENDOTAPLAYER';
export const fetchOpenDotaPlayer = player => ({
type: FETCH_OPENDOTAPLAYER,
payload: {
client: 'openDota',
request: {
url: `/api/players/${player.steamID3}`,
},
},
player,
}
);
export const FETCH_OPENDOTACOUNTS = 'FETCH_OPENDOTACOUNTS';
export const fetchOpenDotaCounts = player => ({
type: FETCH_OPENDOTACOUNTS,
payload: {
client: 'openDota',
request: {
url: `/api/players/${player.steamID3}/counts?date=91`, //TODO dynamic date
},
},
player,
}
);
export const FETCH_OPENDOTAHEROES = 'FETCH_OPENDOTAHEROES';
export const fetchOpenDotaHeroes = player => ({
type: FETCH_OPENDOTAHEROES,
payload: {
client: 'openDota',
request: {
url: `/api/players/${player.steamID3}/heroes?date=91`, //TODO dynamic date
},
},
player,
}
);
| mit |
aquatir/remember_java_api | code-sample-java/code-sample-java-algorithms-and-data-structures/src/test/java/queues/QueueOnTwoStacksTest.java | 1045 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package queues;
import codesample.data_structures.queues.QueueOnTwoStacks;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class QueueOnTwoStacksTest {
private QueueOnTwoStacks<Integer> queue;
/**
* Test of enqueue method, of class QueueOnTwoStacks.
*/
@Test
public void testEnqueueAndDequeue() {
queue = new QueueOnTwoStacks<>();
queue.enqueue(1);
queue.enqueue(2);
assertEquals(queue.dequeue(), new Integer(1));
assertEquals(queue.dequeue(), new Integer(2));
}
/**
* Test exception thrown when attempting to dequeue from empty queue
*/
@Test(expected = IllegalArgumentException.class)
public void testDequeueEmpty() {
queue = new QueueOnTwoStacks<>(); /* queue is empty when just created */
queue.dequeue();
}
}
| mit |
blnz/palomar | src/main/java/com/blnz/xsl/expr/ObjectTypeFunction.java | 2718 | // $Id: RegexpMatchFunction.java 122 2005-04-05 01:22:51Z blindsey $
package com.blnz.xsl.expr;
import com.blnz.xsl.om.*;
// import com.blnz.xsl.sax.*;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.regex.Matcher;
import java.net.URL;
/**
* Represents the EXSL exsl:object-type function
* For more information consult exsl specification at:
* <A HREF="http://www.exslt.org/exsl/functions/object-type/exsl.object-type.html">Specification</A>.
*/
class ObjectTypeFunction extends Function1
{
/**
*
*/
public ConvertibleExpr makeCallExpr(ConvertibleExpr e) throws ParseException
{
ConvertibleExpr objType = new LiteralExpr("string");
if (e instanceof ConvertibleVariantExpr) {
final VariantExpr ve = e.makeVariantExpr();
final Name varName = (e instanceof GlobalVariableRefExpr) ?
((GlobalVariableRefExpr)e).getName() : null;
return new ConvertibleStringExpr() {
public String eval(Node node, ExprContext context)
throws XSLException
{
if (varName != null && varName.getNamespace() != null) {
if (context.getExtensionContext(varName.getNamespace())
.available(varName.getLocalPart())) {
return "external";
}
}
Variant v = ve.eval(node, context);
if (v.isBoolean()) {
return "boolean";
} else if (v.isNumber()) {
return "number";
} else if (v.isString()) {
return "string";
} else if (v.isNodeSet()) {
return "node-set";
} else if (v instanceof com.blnz.xsl.tr.ResultFragmentVariant) {
return "RTF";
}
return "unknown";
}
};
} else if (e instanceof ConvertibleNumberExpr) {
objType = new LiteralExpr("number");
} else if (e instanceof ConvertibleBooleanExpr) {
objType = new LiteralExpr("boolean");
} else if (e instanceof ConvertibleNodeSetExpr) {
objType = new LiteralExpr("boolean");
} else if (e instanceof ConvertibleStringExpr) {
objType = new LiteralExpr("string");
}
return objType;
}
}
| mit |
Ghangseok/dkn | manage_book.php | 5430 | <?php
require "header.php";
$host = "localhost";
$db_username = "root";
$db_password = "";
$dbname = "DKN";
//$username = $_SESSION["username"];
//$name = $_SESSION["name"];
$username = "redeteus";
$name = "Ghang seok Seo";
$is_scheduled = "Y";
$schedules = array();
if (isset($_GET['id'])) {
echo "==================================================================================";
}
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $db_username, $db_password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT A.appointment_id
, A.branch_id
, B.name as branch_name
, A.date
, CASE A.time WHEN '01' THEN '09:00'
WHEN '02' THEN '11:00'
WHEN '03' THEN '13:00'
WHEN '04' THEN '15:00'
WHEN '05' THEN '17:00'
WHEN '06' THEN '19:00'
END as time
, A.username
, B.name as customer_name
, A.visitor_name
, A.tel
, A.email
, A.address
, A.city
, A.province
, A.postal
, A.make
, A.model
, A.year
, A.is_scheduled
FROM Appointments A
INNER JOIN Users U
ON A.username = U.username
INNER JOIN Branches B
ON A.branch_id = B.branch_id
ORDER BY A.date, A.time"
);
$stmt->bindParam(':is_scheduled', $is_scheduled);
$stmt->execute();
while($result = $stmt->fetch(PDO::FETCH_OBJ)) {
array_push($schedules, $result);
}
$stmt = null;
$conn = null;
} catch(PDOException $e) {
echo "<script type='text/javascript'>alert('Error: " . $e->getMessage() . "');</script>";
//header("Location:503.html");
}
?>
<div class="container" style="background: white">
<h2>Service Schedule</h2>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Branch</th>
<th>Date</th>
<th>Time</th>
<th>Username</th>
<th>Name</th>
<th>Visitor</th>
<th>Contact</th>
<th>Email</th>
<th>Address</th>
<th>City</th>
<th>Province</th>
<th>Postal</th>
<th>Make</th>
<th>Model</th>
<th>Year</th>
<th>Confirm</th>
</tr>
</thead>
<tbody>
<?php
foreach ($schedules as $event) {
?>
<tr>
<td><?php echo $event->appointment_id ?></td>
<td><?php echo $event->branch_name ?></td>
<td><?php echo $event->date ?></td>
<td><?php echo $event->time ?></td>
<td><?php echo $event->username ?></td>
<td><?php echo $event->customer_name ?></td>
<td><?php echo $event->visitor_name ?></td>
<td><?php echo $event->tel ?></td>
<td><?php echo $event->email ?></td>
<td><?php echo $event->address ?></td>
<td><?php echo $event->city ?></td>
<td><?php echo $event->province ?></td>
<td><?php echo $event->postal ?></td>
<td><?php echo $event->make ?></td>
<td><?php echo $event->model ?></td>
<td><?php echo $event->year ?></td>
<td><div class="btn-group-vertical">
<a href="book_confirm.php?id=<?php echo $event->appointment_id ?>&is_s=Y" class="btn btn-success" role="button">Accept</a>
<a href="book_confirm.php?id=<?php echo $event->appointment_id ?>&is_s=N" class="btn btn-danger" role="button">Decline</a>
</div></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
<!-- /.container -->
<?php
require "footer.php";
?>
| mit |
hypergroup/hyper.chrome | src/content/search.js | 722 | /**
* Module dependencies
*/
const dom = require('react').createElement;
module.exports = function(id, hasResult) {
function onChange(evt) {
let val = evt.target.value;
if (val && val.charAt(0) !== '/') val = '/' + val;
if (val === '/') val = '';
if (val) history.replaceState('', document.title, '#' + val);
else history.replaceState('', document.title, document.location.href.split('#')[0]);
window.dispatchEvent(new Event('hashchange'));
}
const found = id ? (hasResult ? ' found' : ' missing') : '';
if (!id) id = '/';
return (
dom('div', {className: 'search' + found},
dom('input', {ref: 'search-field', type: 'text', value: id, onChange: onChange})
)
);
};
| mit |
sabertazimi/hust-lab | operatingSystems/ics2017/navy-apps/apps/nwm/src/events.cpp | 3683 | #include <nwm.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#define DECL(n, h) {n, sizeof(n) - 1, &WindowManager::evt_##h},
static struct EventHandler {
const char *pattern;
int length;
void (WindowManager::*handler)(const char *);
} handlers[] = {
FOREACH_EVENT(DECL)
};
void WindowManager::handle_event(const char *evt) {
if (evt[0] == '#') return;
for (auto &h: handlers) {
if (strncmp(evt, h.pattern, h.length) == 0) {
(this->*h.handler)(evt + h.length);
break;
}
}
}
// ---------- EVENT HANDLERS ----------
void WindowManager::evt_timer(const char *evt) {
uint32_t now;
sscanf(evt, "%d", &now);
if (now > uptime) {
uptime = now;
}
for (Window *w: windows) {
if (w) {
assert(w->write_fd);
char buf[64]; sprintf(buf, "t %d\n", now);
write(w->write_fd, buf, strlen(buf));
}
}
for (Window *w: windows) {
if (w) w->update();
}
render();
}
static int ctrl = 0, alt = 0, shift = 0;
void WindowManager::evt_keydown(const char *evt) {
char key[20];
sscanf(evt, "%s", key);
if (strcmp(key, "LALT") == 0) { alt = 1; return; }
if (strcmp(key, "LCTRL") == 0) { ctrl = 1; return; }
if (strcmp(key, "LSHIFT") == 0 || strcmp(key, "RSHIFT") == 0) { shift ^= 1; return; }
if (ctrl || alt) {
char event[20];
sprintf(event, "%s%s%s", ctrl ? "C-" : "", alt ? "A-" : "", key);
handle_event(event);
} else {
if (display_appfinder) {
if (strcmp(key, "LEFT") == 0) appfinder->prev();
if (strcmp(key, "TAB") == 0) appfinder->next();
if (strcmp(key, "RIGHT") == 0) appfinder->next();
if (strcmp(key, "RETURN") == 0) {
spawn(appfinder->getcmd());
display_appfinder = false;
appfinder->draw();
}
if (strcmp(key, "ESCAPE") == 0) {
display_appfinder = false;
appfinder->draw();
}
} else if (focus) {
assert(focus->write_fd);
char buf[64]; sprintf(buf, "kd %s\n", key);
write(focus->write_fd, buf, strlen(buf));
}
}
}
void WindowManager::evt_keyup(const char *evt) {
char key[20];
sscanf(evt, "%s", key);
if (strcmp(key, "LALT") == 0) {
alt = 0;
if (display_switcher) {
switcher->draw();
}
display_switcher = false;
return;
}
if (strcmp(key, "LCTRL") == 0) {
ctrl = 0;
return;
}
if (strcmp(key, "LSHIFT") == 0 || strcmp(key, "RSHIFT") == 0) {
shift ^= 1;
return;
}
if (focus && !display_appfinder) {
assert(focus->write_fd);
char buf[64]; sprintf(buf, "ku %s\n", key);
write(focus->write_fd, buf, strlen(buf));
}
}
void WindowManager::evt_switch_window(const char *evt) {
int i = 0;
if (!focus) return;
display_switcher = true;
if (display_appfinder) {
display_appfinder = false;
appfinder->draw();
}
while (windows[i] != focus) i ++;
while (1) {
i ++;
if (i >= 16) i = 0;
if (windows[i]) break;
}
set_focus(windows[i]);
}
void WindowManager::evt_moveup_window(const char *evt) {
if (focus && focus != appfinder) {
focus->move(focus->x, focus->y - 10);
}
}
void WindowManager::evt_movedown_window(const char *evt) {
if (focus && focus != appfinder) {
focus->move(focus->x, focus->y + 10);
}
}
void WindowManager::evt_moveleft_window(const char *evt) {
if (focus && focus != appfinder) {
focus->move(focus->x - 10, focus->y);
}
}
void WindowManager::evt_moveright_window(const char *evt) {
if (focus && focus != appfinder) {
focus->move(focus->x + 10, focus->y);
}
}
void WindowManager::evt_appfinder(const char *evt) {
if (!display_switcher) {
display_appfinder = true;
appfinder->draw();
}
}
| mit |
Stonecoin/stonecoin | src/qt/optionsdialog.cpp | 7670 | #include "optionsdialog.h"
#include "ui_optionsdialog.h"
#include "bitcoinamountfield.h"
#include "bitcoinunits.h"
#include "monitoreddatamapper.h"
#include "netbase.h"
#include "optionsmodel.h"
#include "qvalidatedlineedit.h"
#include "qvaluecombobox.h"
#include <QCheckBox>
#include <QDir>
#include <QIntValidator>
#include <QLabel>
#include <QLineEdit>
#include <QLocale>
#include <QMessageBox>
#include <QPushButton>
#include <QRegExp>
#include <QRegExpValidator>
#include <QTabWidget>
#include <QWidget>
OptionsDialog::OptionsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fRestartWarningDisplayed_Proxy(false),
fRestartWarningDisplayed_Lang(false),
fProxyIpValid(true)
{
ui->setupUi(this);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->socksVersion->setEnabled(false);
ui->socksVersion->addItem("5", 5);
ui->socksVersion->addItem("4", 4);
ui->socksVersion->setCurrentIndex(0);
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(0, 65535, this));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_WS_MAC
ui->tabWindow->setVisible(false);
#endif
/* Display elements init */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach(const QString &langStr, translations.entryList())
{
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if(langStr.contains("_"))
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
else
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
ui->unit->setModel(new BitcoinUnits(this));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));
connect(ui->lang, SIGNAL(activated(int)), this, SLOT(showRestartWarning_Lang()));
/* Widget-to-option mapper */
mapper = new MonitoredDataMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* enable save buttons when data modified */
connect(mapper, SIGNAL(viewModified()), this, SLOT(enableSaveButtons()));
/* disable save buttons when new data loaded */
connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableSaveButtons()));
/* disable/enable save buttons when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpValid(bool)), this, SLOT(setSaveButtonState(bool)));
}
OptionsDialog::~OptionsDialog()
{
delete ui;
}
void OptionsDialog::setModel(OptionsModel *model)
{
this->model = model;
if(model)
{
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->transactionFee, OptionsModel::Fee);
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
mapper->addMapping(ui->detachDatabases, OptionsModel::DetachDatabases);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
/* Window */
#ifndef Q_WS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses);
}
void OptionsDialog::enableSaveButtons()
{
// prevent enabling of the save buttons when data modified, if there is an invalid proxy address present
if(fProxyIpValid)
setSaveButtonState(true);
}
void OptionsDialog::disableSaveButtons()
{
setSaveButtonState(false);
}
void OptionsDialog::setSaveButtonState(bool fState)
{
ui->applyButton->setEnabled(fState);
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::on_applyButton_clicked()
{
mapper->submit();
ui->applyButton->setEnabled(false);
}
void OptionsDialog::showRestartWarning_Proxy()
{
if(!fRestartWarningDisplayed_Proxy)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting stonecoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Proxy = true;
}
}
void OptionsDialog::showRestartWarning_Lang()
{
if(!fRestartWarningDisplayed_Lang)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting stonecoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Lang = true;
}
}
void OptionsDialog::updateDisplayUnit()
{
if(model)
{
// Update transactionFee with the current unit
ui->transactionFee->setDisplayUnit(model->getDisplayUnit());
}
}
bool OptionsDialog::eventFilter(QObject *object, QEvent *event)
{
if(object == ui->proxyIp && event->type() == QEvent::FocusOut)
{
// Check proxyIP for a valid IPv4/IPv6 address
CService addr;
if(!LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr))
{
ui->proxyIp->setValid(false);
fProxyIpValid = false;
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
emit proxyIpValid(false);
}
else
{
fProxyIpValid = true;
ui->statusLabel->clear();
emit proxyIpValid(true);
}
}
return QDialog::eventFilter(object, event);
}
| mit |
tcyrus/tjhsst-electron-dayschedule | main.js | 458 | const {ipcMain} = require('electron')
const menubar = require('menubar')
const mb = menubar({
width: 300,
height: 275,
'preload-window': true
})
mb.on('ready', () => console.log('App is Ready'))
ipcMain.on('devtools', () => mb.window.openDevTools())
ipcMain.on('title', (event, arg) => mb.tray.setTitle(arg))
ipcMain.on('quit', () => mb.app.quit())
mb.on('after-hide', () => mb.window.webContents.sendInputEvent({
type: 'keyDown',
keyCode: 'T'
})) | mit |
dynamicreflectance/multicolor | source/Attenuation.hpp | 561 | #pragma once
/* Attenuation.hpp
*
* Copyright (C) 2017 Dynamic Reflectance
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
namespace multicolor {
struct Attenuation
{
float kc;
float kl;
float kq;
Attenuation()
: kc(1.0f)
, kl(0.0f)
, kq(0.0f)
{
}
Attenuation(float a_kc, float a_kl, float a_kq)
: kc(a_kc)
, kl(a_kl)
, kq(a_kq)
{
}
};
} // namespace multicolor | mit |
evillatoro/SnapFix | app/src/main/java/edwinvillatoro/snapfix/objects/ChatMessage.java | 965 | package edwinvillatoro.snapfix.objects;
import java.util.Date;
/**
* Created by Bryan on 11/7/2017.
*/
public class ChatMessage {
private long msgTime;
private String msgText;
private String msgUser;
public ChatMessage(String messageText, String messageUser) {
this.msgText = messageText;
this.msgUser = messageUser;
// Initialize to current time
msgTime = new Date().getTime();
}
public ChatMessage(){
}
public String getMessageText() {
return msgText;
}
public void setMessageText(String messageText) {
this.msgText = messageText;
}
public String getMessageUser() {
return msgUser;
}
public void setMessageUser(String messageUser) {
this.msgUser = messageUser;
}
public long getMessageTime() {
return msgTime;
}
public void setMessageTime(long messageTime) {
this.msgTime = messageTime;
}
}
| mit |
mikeckennedy/mongodb_schema_design_mannheim | data/json_examples/book_embedded.js | 412 | // Books collection
x =
{
"_id": "29832A3792E374",
"title": "The great schema debate",
"price": 19.00,
"reviews": [
{
"_id": "374592A379232",
"user": "mkennedy",
"stars": 4,
"comments": "Simple and effective coverage"
},
{ /*...*/ },
{ /*...*/ }
]
}
;
| mit |
justin-espedal/polydes | Data Structures Extension/src/com/polydes/datastruct/data/types/HaxeTypeConverter.java | 3155 | package com.polydes.datastruct.data.types;
import java.util.HashMap;
import org.apache.commons.lang3.StringUtils;
import com.polydes.common.data.core.DataList;
import com.polydes.common.data.core.DataSet;
import com.polydes.common.data.types.DataType;
import com.polydes.common.data.types.Types;
import com.polydes.common.data.types.builtin.basic.ArrayType;
import com.polydes.datastruct.DataStructuresExtension;
/**
* Kind of a hack class to make it so we can still have Haxe types
* in our input/output instead of corresponding Java types.
*/
public class HaxeTypeConverter
{
private static HaxeTypes getHT()
{
return DataStructuresExtension.get().getHaxeTypes();
}
@SuppressWarnings("rawtypes")
private static HashMap<String, Coder> coders;
static
{
coders = new HashMap<>();
coders.put(Types._Array.getId(), new ArrayCoder());
coders.put(Types._Set.getId(), new SetCoder());
}
public static Object decode(DataType<?> type, String s)
{
if(coders.containsKey(type.getId()))
return coders.get(type.getId()).decode(s);
else
return type.decode(s);
}
@SuppressWarnings({"unchecked", "rawtypes"})
public static String encode(DataType type, Object o)
{
if(coders.containsKey(type.getId()))
return coders.get(type.getId()).encode(o);
else
return type.encode(o);
}
static interface Coder<T>
{
T decode(String s);
String encode(T t);
}
static class ArrayCoder implements Coder<DataList>
{
@Override
public DataList decode(String s)
{
if(s.isEmpty())
return null;
int i = s.lastIndexOf(":");
String typename = s.substring(i + 1);
DataType<?> genType = getHT().getItem(typename).dataType;
DataList list = new DataList(genType);
for(String s2 : ArrayType.getEmbeddedArrayStrings(s))
list.add(HaxeTypeConverter.decode(genType, s2));
return list;
}
@Override
public String encode(DataList array)
{
if(array == null)
return "";
String s = "[";
for(int i = 0; i < array.size(); ++i)
s += HaxeTypeConverter.encode(array.genType, array.get(i)) + (i < array.size() - 1 ? "," : "");
s += "]:" + getHT().getHaxeFromDT(array.genType.getId()).getHaxeType();
return s;
}
}
static class SetCoder implements Coder<DataSet>
{
@Override
public DataSet decode(String s)
{
int typeMark = s.lastIndexOf(":");
if(typeMark == -1)
return new DataSet(DSTypes._Dynamic);
DataType<?> dtype = getHT().getItem(s.substring(typeMark + 1)).dataType;
if(dtype == null)
return new DataSet(DSTypes._Dynamic);
DataSet toReturn = new DataSet(dtype);
for(String s2 : StringUtils.split(s.substring(1, typeMark - 1), ","))
toReturn.add(HaxeTypeConverter.decode(dtype, s2));
return toReturn;
}
@Override
public String encode(DataSet t)
{
Object[] a = t.toArray(new Object[0]);
String s = "[";
DataType<?> type = t.genType;
for(int i = 0; i < a.length; ++i)
{
s += HaxeTypeConverter.encode(type, a[i]);
if(i < a.length - 1)
s += ",";
}
s += "]:" + getHT().getHaxeFromDT(type.getId()).getHaxeType();
return s;
}
}
}
| mit |
3rd-KaTZe/Export_DCS | KTZ_SIOC_UH1.lua | 14337 | ------------------------------------------------------------------------
-- KaTZ-Pit FC3 functions repo --
------------------------------------------------------------------------
k.export.uh1.slow = function()
-- Attention !!!!!!!! pour boucle lente, le nom est différent que boucle rapide : Device(0) >> MainPanel
local MainPanel = GetDevice(0)
-- Test de la précence de Device 0 , comme table valide
if type(MainPanel) ~= "table" then
return ""
end
MainPanel:update_arguments()
-- ============== Valeur Test ============================================================
-- ============== Horloge de Mission ============================================================
k.sioc.send(42,LoGetModelTime())-- Heure de la mission
-- ============== Position de l'Avion ===============================================================
local myXCoord, myZCoord
if LoGetPlayerPlaneId() then
local objPlayer = LoGetObjectById(LoGetPlayerPlaneId())
myXCoord, myZCoord = k.common.getXYCoords(objPlayer.LatLongAlt.Lat, objPlayer.LatLongAlt.Long)
k.sioc.send(60,myXCoord)
k.sioc.send(62,myZCoord)
k.sioc.send(64,objPlayer.LatLongAlt.Lat*1000000)
k.sioc.send(66,objPlayer.LatLongAlt.Long*1000000)
k.sioc.send(110,objPlayer.LatLongAlt.Alt*100)--ok
end
-- ============== Parametres de Vol (lents) ====================================================
-- ADI
local ADI_FF = math.floor(MainPanel:get_argument_value(148)) -- ADI Failure Flag
local ADI_IDX = MainPanel:get_argument_value(138)*1000 -- ADI Index
k.sioc.send(146,50005000 + 10000 * ADI_FF + ADI_IDX)
-- Altitude Radar , Index Low et High
local Altirad_HDX = math.floor(MainPanel:get_argument_value(466) * 1000) -- Index High Setting
local Altirad_LDX = MainPanel:get_argument_value(444) * 1000 -- Index Low Setting
k.sioc.send(124,50005000 + 10000 * Altirad_HDX + Altirad_LDX)
-- Alarme Low et High , Flag on/off
local Altirad_HF = math.floor(MainPanel:get_argument_value(465)+0.2) -- Alti Rad high alti Alarme
local Altirad_LF = math.floor(MainPanel:get_argument_value(447)+0.2) -- Alti Rad low alti Alarme
local Altirad_O = MainPanel:get_argument_value(467) -- Alti Rad Off Flag
k.sioc.send(126,555 + Altirad_HF * 100 + Altirad_LF * 10 + Altirad_O)
-- ============== Parametres Moteur (lents) ====================================================
local Oil_P_1 = math.floor(MainPanel:get_argument_value(113)*1000) -- Oil Pressure : non linéaire export cadran
local Oil_P_2 = 0 -- Non utilisé sur UH-1 un seul moteur
local Oil_PGB_1 = math.floor(MainPanel:get_argument_value(115)*1000) -- Oil Pressure Gear Box
local Oil_T_1 = math.floor(MainPanel:get_argument_value(114)*1000) -- Oil Temp left : non linéaire export cadran
local Oil_T_2 = 0 -- Non utilisé sur UH-1 un seul moteur
local Oil_TGB_1 = math.floor(MainPanel:get_argument_value(116) * 1000) -- Oil Temp Gear Box : non linéaire export cadran
k.sioc.send(260,50005000 + 10000 * Oil_P_1 + Oil_P_2) -- Engine Oil Pressure (L,R)
k.sioc.send(265,50005000 + Oil_PGB_1) -- GearBox Oil Pressure
k.sioc.send(250,50005000 + 10000 * Oil_T_1 + Oil_T_2) -- Engine Oil Temp (L,R)
k.sioc.send(255,50005000 + Oil_TGB_1) -- GearBox Oil Temp
-- ============== Switch Moteur Engine Panel ==============================================
local EngStart = MainPanel:get_argument_value(213)
local Trim = MainPanel:get_argument_value(89) -- Force Trim
local Hyd = MainPanel:get_argument_value(90) -- HYD CONT
local RmpLow = MainPanel:get_argument_value(80) -- Low Rpm
local Fuel = MainPanel:get_argument_value(81) -- Fuel On/Off
local Gov = MainPanel:get_argument_value(85) -- Gov On/Off
local Ice = MainPanel:get_argument_value(84) -- De-Ice
k.sioc.send(270,5555555 + Ice * 1000000 + Gov * 100000 + Fuel * 10000 + RmpLow * 1000 + Hyd * 100 + Trim * 10 + EngStart)
-- ============== Parametres Fuel (lents) =======================================================
local Fuel_qty = MainPanel:get_argument_value(239)* 1000 -- valeur non linéaire à ajuster
local Fuel_sel = math.floor(MainPanel:get_argument_value(126)* 1000) -- Fuel Pressure sur UH-1
k.sioc.send(404,50005000 + Fuel_sel*10000 + Fuel_qty) -- Utilisation du canal Fuel Internal Forward
-- ============== Parametres Electrique ===========================================================
-- Regroupement des Position Switches AC et DC sur une valeur (Canal switch DC de SIOC)
local Elec_S1 = MainPanel:get_argument_value(219) -- Position Switch Batterie
local Elec_S2 = MainPanel:get_argument_value(220) -- Stby Gen
local Elec_S3 = MainPanel:get_argument_value(221) -- Non Essential Bus
local Elec_S4 = math.floor(MainPanel:get_argument_value(218)*10+0.2) -- DC Voltmetre
local Elec_S5 = 0 -- Non utilisé sur UH-1
local Elec_S6 = math.floor(MainPanel:get_argument_value(214)*10+0.2) -- AC Voltmetre
local Elec_S7 = MainPanel:get_argument_value(215) -- Inverter
local Elec_S8 = MainPanel:get_argument_value(238) -- Pitot
local Elec_SW_DC = 55050555 + Elec_S8 * 10000000 + Elec_S7 * 1000000 + Elec_S6 * 100000 + Elec_S5 * 10000 + Elec_S4 * 1000 + Elec_S3 * 100 + Elec_S2 * 10 + Elec_S1
k.sioc.send(504,Elec_SW_DC) -- Position Switch DC
-- Voyants --------------------------------------------------------------
-- Regroupement des Position Switches AC et DC sur une valeur (Canal Voyant AC de SIOC)
local Elec_V6 = MainPanel:get_argument_value(107) -- Voyant Gen1
local Elec_V7 = 0
local Elec_V8 = MainPanel:get_argument_value(108) -- Voyant Ground AC
local Elec_V9 = MainPanel:get_argument_value(106) -- Voyant Hacheur DCAC PO500
k.sioc.send(516,5555 + Elec_V9 * 1000 + Elec_V8 * 100 + Elec_V7 * 10 + Elec_V6) -- Voyant Electric AC
-- Voltage AC et DC --------------------------------------------------------------
local VoltAC = math.floor(MainPanel:get_argument_value(150)*1000) -- Voltage AC
local VoltDC = MainPanel:get_argument_value(149)*1000 -- Voltage DC
k.sioc.send(510,50005000 + VoltAC * 10000 + VoltDC)
-- ============== Status Eléments Mécaniques ======================================================== WIP : a mettre à jour pour Mi-8
--local DoorL = math.floor(MainPanel:get_argument_value(420)*10) -- Porte Cockpit , Left0 fermée , 1 ouverte
--local DoorR = math.floor(MainPanel:get_argument_value(422)*10) -- Porte Cockpit , Right0 fermée , 1 ouverte
--k.sioc.send(602,55 + DoorL * 10 + DoorR) -- Positions Portes
-- ============== Données de Navigation ===============================================================
-- ============== Status Armement ==================================================================
local WPN_8 = math.floor(MainPanel:get_argument_value(252)) -- Switch Masterarm
local WPN_8a = math.floor(MainPanel:get_argument_value(254)+0.5) -- Lamp Masterarm Armed
local WPN_8b = math.floor(MainPanel:get_argument_value(255)+0.5) -- Lamp Masterarm Safe
local WPN_9 = math.floor(MainPanel:get_argument_value(253)) -- Switch Gun Select L-R-All
local WPN_10 = math.floor(MainPanel:get_argument_value(256)) -- Switch 40-275-762
local WPN_11 = math.floor(MainPanel:get_argument_value(257)*10+0.2) -- Selecteur 7 Posit Rocket Pair
k.sioc.send(1020,555550 + WPN_8 * 100000 + WPN_8a * 10000 + WPN_8b * 1000 + WPN_9 * 100 + WPN_10 * 10 + WPN_11)
-- ============== Status Flare ==================================================================
local FLR_5 = math.floor(MainPanel:get_argument_value(456)) -- Safe Arm Flare
local FLR_5B = math.floor(MainPanel:get_argument_value(458)+0.5) -- Armed Lamp
local FLR_nb = math.floor(MainPanel:get_argument_value(460)*10+ 0.2 ) * 10 + math.floor(MainPanel:get_argument_value(461)*10) -- Flare Number
-- Chaff Non modelisées dans DCS
--local FLR_9 = math.floor(MainPanel:get_argument_value(459)) -- Man Prgm
-- local FLR_chaf = math.floor(MainPanel:get_argument_value(462)*10) * 10 + math.floor(MainPanel:get_argument_value(463)*10) -- Chaff Number
k.sioc.send(1025,5500 + FLR_5 * 1000 + FLR_5B * 100 + FLR_nb) -- Position Switch, Lamp, et nb flare
-- k.sioc.send(1027,50005000 + FLR_nb * 10000 + FLR_chaf)
-- ============== Module Alarme ==================================================================================
local Alrm_Fire = math.floor(MainPanel:get_argument_value(275)) -- Alarme Fire
local Alrm_Rpm = math.floor(MainPanel:get_argument_value(276)) -- Alarme Low RPM
local Alrm_MW = math.floor(MainPanel:get_argument_value(277)) -- Alarme MAster Warning
local V_Start = math.floor(MainPanel:get_argument_value(213)) -- Engine Start
k.sioc.send(574,5555 + Alrm_Fire * 1000 + Alrm_Rpm * 100 + Alrm_MW * 10 + V_Start)
-- ============== Miaou the end ==================================================================================
end
k.export.uh1.fast = function()
-- Récupération des données à lire --------------------
-- Attention !!!!!!!! pour boucle rapide, le nom est différent que boucle lente : Device(0) >> lMainPanel
local lMainPanel = GetDevice(0)
-- Test de la précence de Device 0 , comme table valide
if type(lMainPanel) ~= "table" then
return ""
end
lMainPanel:update_arguments()
-- ============== Debug 21 à 29 =========================================================================
-- Zone utilisé pour tester de nouvelles valeurs
--k.sioc.send(21,lMainPanel:get_argument_value(465)*100)
--k.sioc.send(22,lMainPanel:get_argument_value(447)*100)
--k.sioc.send(23,lMainPanel:get_argument_value(456)*100)
--k.sioc.send(24,lMainPanel:get_argument_value(457)*100)
--k.sioc.send(25,lMainPanel:get_argument_value(464)*100)
--k.sioc.send(26,lMainPanel:get_argument_value(460)*100)
--k.sioc.send(27,lMainPanel:get_argument_value(461)*1000)
--k.sioc.send(28,lMainPanel:get_argument_value(45)*1000)
--k.sioc.send(29,lMainPanel:get_argument_value(180)*1000)
-- ============== Clock =========================================================================
-- ============== Contrôle de l'appareil =========================================================================
-- ============== Position des Commandes de vol =========================================================================
-- Stick Roll/pitch Position
k.sioc.send(80,50005000 + math.floor(lMainPanel:get_argument_value(187)* 1000) * 10000 + math.floor(lMainPanel:get_argument_value(186)*-1000))
-- Rudder + Collective
k.sioc.send(82,50005000 + math.floor(lMainPanel:get_argument_value(184)* 1000) * 10000 + math.floor(lMainPanel:get_argument_value(200)*1000))
-- ============== Parametres de Vol ===============================================================
k.sioc.send(102,lMainPanel:get_argument_value(117)*1000) -- IAS Badin
k.sioc.send(112, 50005000 + math.floor(lMainPanel:get_argument_value(179) * 1000) * 10000 + lMainPanel:get_argument_value(180) * 1000)
-- Alti Baro deux aiguilles
k.sioc.send(120,lMainPanel:get_argument_value(443)*1000) -- Alti Radar valeur non linéaire
k.sioc.send(130,lMainPanel:get_argument_value(134)*1000) -- Vario (-30m/s , +30 m/s) ... valeur non linéaire à ajuster dans html
k.sioc.send(140,lMainPanel:get_argument_value(143)* -1000) -- Pitch (ADI)
k.sioc.send(142,lMainPanel:get_argument_value(142)*1000) -- Bank ou Roll (ADI)
--k.sioc.send(150,lMainPanel:get_argument_value(11)*1000) -- Boussole
local EUP_S = math.floor(lMainPanel:get_argument_value(132)*1000) -- EUP_Speed
local EUP_SS = math.floor(lMainPanel:get_argument_value(133)*1000) -- EUP_Sideslip
local EUP = 50005000 + EUP_S * 10000 + EUP_SS
k.sioc.send(180,EUP) -- EUP_Data
-- Donnée Altiradar
local Altirad1 = math.floor((lMainPanel:get_argument_value(468)+ 0.02) *10)
local Altirad2 = math.floor((lMainPanel:get_argument_value(469)+ 0.02) *10)
local Altirad3 = math.floor((lMainPanel:get_argument_value(470)+ 0.02) *10)
local Altirad4 = math.floor((lMainPanel:get_argument_value(471)+ 0.02) *10)
k.sioc.send(122,(500000000 + Altirad1 * 1000000 + Altirad2 * 10000 + Altirad3 * 100 + Altirad4))
-- ============== Parametres ==============================================================
-- ============== Parametres HSI ==================================================================
k.sioc.send(152,lMainPanel:get_argument_value(165)*3600) -- CAP (Export 0.1 degrés)
k.sioc.send(154,lMainPanel:get_argument_value(160)*3600) -- Course (Ecart par rapport à la couronne des caps)
k.sioc.send(156,lMainPanel:get_argument_value(159)*3600) -- Waypoint (Ecart par rapport à la couronne des caps)
-- ============== Parametres ILS ==================================================================
-- ============== Parametres Rotor =================================================================
k.sioc.send(230,lMainPanel:get_argument_value(123)*1100) -- Rotor rpm : max 110
-- ============== Parametres Moteur (Fast) ================================================================
local RPM_L = math.floor(lMainPanel:get_argument_value(122)*1100) -- rpm left : max 110
local RPM_R = 0 -- rpm right : unused on UH1
k.sioc.send(202,50005000 + RPM_L * 10000 + RPM_R) -- Groupage RPM L et R dans une donnée
local EngT_L = math.floor(lMainPanel:get_argument_value(121)*1000) -- temp left : max 1000
local EngT_R = 0 -- temp right : unused on UH1
k.sioc.send(204,50005000 + EngT_L * 10000 + EngT_R) -- Groupage Température L et R dans une donnée
-- ============== Parametres Turbine Torque/Rpm/Exhaust ===================================================================
local Torque = math.floor(lMainPanel:get_argument_value(124)*1000)
local Gas = math.floor(lMainPanel:get_argument_value(119)*1000)
k.sioc.send(240,50005000 + Torque * 10000 + Gas)
k.sioc.send(242,50005000 + lMainPanel:get_argument_value(121)*1000) -- Exhaust Temperature
-- ============== Position de l'Avion ===============================================================
end
k.info("KTZ_SIOC_UH1 chargé") | mit |
alphabetum/autocap | recipes/nginx.rb | 578 | namespace :deploy do
############################################################################
# Nginx Tasks
############################################################################
namespace :nginx do
[ :stop, :start ].each do |t|
desc "#{t.to_s.capitalize} nginx"
task t, :roles => :app do
send(run_method, "/etc/init.d/nginx #{t.to_s}")
end
end
desc "restart nginx"
task :restart, :roles => :app do
send(run_method, "/etc/init.d/nginx stop")
send(run_method, "/etc/init.d/nginx start")
end
end
end | mit |
dyfvicture/LoopringWallet | common/libs/signing.js | 1043 | // @flow
import EthTx from 'ethereumjs-tx';
import { sha3, ecsign } from 'ethereumjs-util';
import { isValidRawTx } from 'libs/validators';
import type { RawTransaction } from 'libs/transaction';
export function signRawTxWithPrivKey(
privKey: Buffer,
rawTx: RawTransaction
): string {
if (!isValidRawTx(rawTx)) {
throw new Error('Invalid raw transaction');
}
let eTx = new EthTx(rawTx);
eTx.sign(privKey);
return '0x' + eTx.serialize().toString('hex');
}
export function signMessageWithPrivKey(
privKey: Buffer,
msg: string,
address: string,
date: string
): string {
let spacer = msg.length > 0 && date.length > 0 ? ' ' : '';
let fullMessage = msg + spacer + date;
let hash = sha3(fullMessage);
let signed = ecsign(hash, privKey);
let combined = Buffer.concat([
Buffer.from(signed.r),
Buffer.from(signed.s),
Buffer.from([signed.v])
]);
let combinedHex = combined.toString('hex');
return JSON.stringify({
address: address,
msg: fullMessage,
sig: '0x' + combinedHex
});
}
| mit |
nathanConn/Runner | app/controllers/gears_controller.rb | 1976 | class GearsController < ApplicationController
# before_action :set_gear, only: [:show, :edit, :update, :destroy]
# GET /gears
# GET /gears.json
def index
@gears = Gear.all
end
# GET /gears/1
# GET /gears/1.json
def show
end
# GET /gears/new
def new
@gear = Gear.new
end
# GET /gears/1/edit
def edit
end
# POST /gears
# POST /gears.json
def create
@character = Character.find(params[:character_id])
@gear = @character.gears.create(gear_params)
redirect_to character_path(@character)
end
# respond_to do |format|
# if @gear.save
# format.html { redirect_to @gear, notice: 'Gear was successfully created.' }
# format.json { render :show, status: :created, location: @gear }
# else
# format.html { render :new }
# format.json { render json: @gear.errors, status: :unprocessable_entity }
# end
# end
# end
# PATCH/PUT /gears/1
# PATCH/PUT /gears/1.json
# def update
# respond_to do |format|
# if @gear.update(gear_params)
# format.html { redirect_to @gear, notice: 'Gear was successfully updated.' }
# format.json { render :show, status: :ok, location: @gear }
# else
# format.html { render :edit }
# format.json { render json: @gear.errors, status: :unprocessable_entity }
# end
# end
# end
# DELETE /gears/1
# DELETE /gears/1.json
def destroy
@character = Character.find(params[:character_id])
@gear = @character.gears.find(params[:id])
@gear.destroy
redirect_to character_path(@character)
end
private
# # Use callbacks to share common setup or constraints between actions.
# def set_gear
# @gear = Gear.find(params[:id])
# end
# Never trust parameters from the scary internet, only allow the white list through.
def gear_params
params.require(:gear).permit(:name, :rating, :wireless, :misc, :character_id)
end
end
| mit |
ceph/Diamond | src/collectors/endecadgraph/test/testendecadgraph.py | 1913 | #!/usr/bin/python
# coding=utf-8
################################################################################
from test import CollectorTestCase
from test import get_collector_config
from mock import patch
from diamond.collector import Collector
from endecadgraph import EndecaDgraphCollector
class TestEndecaDgraphCollector(CollectorTestCase):
def setUp(self):
config = get_collector_config('EndecaDgraphCollector', {
})
self.collector = EndecaDgraphCollector(config, None)
def test_import(self):
self.assertTrue(EndecaDgraphCollector)
@patch('urllib2.urlopen')
@patch.object(Collector, 'publish')
def test_real_data(self, publish_mock, urlopen_mock):
urlopen_mock.return_value = self.getFixture('data1.xml')
self.collector.collect()
self.assertPublishedMany(publish_mock, {})
urlopen_mock.return_value = self.getFixture('data2.xml')
self.collector.collect()
# assert with a random selection (instead of 1000+)
metrics = {
'statistics.cache_section.main_cache.aggregatedrecordcount.entry_count': 3957,
'statistics.cache_section.main_cache.dval_bincount.entry_count': 4922448,
'statistics.hot_spot_analysis.content_spotlighting_performance.min': 0.0209961,
'statistics.hot_spot_analysis.insertion_sort_time.avg': 0.00523964,
'statistics.hot_spot_analysis.ordinal_insertion_sort_time.n': 1484793,
'statistics.search_performance_analysis.qconj_lookupphr.min': 0.000976562,
'statistics.updates.update_latency.commit.audit_stat_calculation_time_resume_.n': 0,
}
self.assertPublishedMany(publish_mock, metrics)
self.setDocExample(collector=self.collector.__class__.__name__,
metrics=metrics,
defaultpath=self.collector.config['path'])
| mit |
itmanagerro/tresting | src/qt/locale/bitcoin_ca.ts | 122262 | <TS language="ca" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Right-click to edit address or label</source>
<translation>Feu clic dret per a editar l'adreça o l'etiqueta</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Crea una nova adreça</translation>
</message>
<message>
<source>&New</source>
<translation>&Nova</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copia l'adreça seleccionada al porta-retalls del sistema</translation>
</message>
<message>
<source>&Copy</source>
<translation>&Copia</translation>
</message>
<message>
<source>C&lose</source>
<translation>&Tanca</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>Elimina l'adreça sel·leccionada actualment de la llista</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Exporta les dades de la pestanya actual a un fitxer</translation>
</message>
<message>
<source>&Export</source>
<translation>&Exporta</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Elimina</translation>
</message>
<message>
<source>Choose the address to send coins to</source>
<translation>Trieu l'adreça on enviar les monedes</translation>
</message>
<message>
<source>Choose the address to receive coins with</source>
<translation>Trieu l'adreça on rebre les monedes</translation>
</message>
<message>
<source>C&hoose</source>
<translation>&Tria</translation>
</message>
<message>
<source>Sending addresses</source>
<translation>Adreces d'enviament</translation>
</message>
<message>
<source>Receiving addresses</source>
<translation>Adreces de recepció</translation>
</message>
<message>
<source>These are your Linuxcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Aquestes són les vostres adreces de Linuxcoin per enviar els pagaments. Sempre reviseu l'import i l'adreça del destinatari abans de transferir monedes.</translation>
</message>
<message>
<source>These are your Linuxcoin addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source>
<translation>Aquestes són les vostres adreces Linuxcoin per rebre pagaments. Es recomana utilitzar una adreça nova de recepció per a cada transacció.</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>&Copia l'adreça</translation>
</message>
<message>
<source>Copy &Label</source>
<translation>Copia l'eti&queta</translation>
</message>
<message>
<source>&Edit</source>
<translation>&Edita</translation>
</message>
<message>
<source>Export Address List</source>
<translation>Exporta la llista d'adreces</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Fitxer separat per comes (*.csv)</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>L'exportació ha fallat</translation>
</message>
<message>
<source>There was an error trying to save the address list to %1. Please try again.</source>
<translation>S'ha produït un error en desar la llista d'adreces a %1. Torneu-ho a provar.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<source>Address</source>
<translation>Adreça</translation>
</message>
<message>
<source>(no label)</source>
<translation>(sense etiqueta)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Passphrase Dialog</source>
<translation>Diàleg de contrasenya</translation>
</message>
<message>
<source>Enter passphrase</source>
<translation>Introduïu una contrasenya</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Nova contrasenya</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Repetiu la nova contrasenya</translation>
</message>
<message>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Introduïu la contrasenya nova al moneder.<br/>Utilitzeu una contrasenya de <b>deu o més caràcters aleatoris</b>, o <b>vuit o més paraules</b>.</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>Encripta el moneder</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Aquesta operació requereix la contrasenya del moneder per a desbloquejar-lo.</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>Desbloqueja el moneder</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Aquesta operació requereix la contrasenya del moneder per desencriptar-lo.</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>Desencripta el moneder</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>Canvia la contrasenya</translation>
</message>
<message>
<source>Enter the old passphrase and new passphrase to the wallet.</source>
<translation>Introduïu la contrasenya antiga i la contrasenya nova al moneder.</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>Confirma l'encriptació del moneder</translation>
</message>
<message>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LINUXCOINS</b>!</source>
<translation>Avís: si encripteu el vostre moneder i perdeu la contrasenya, <b>PERDREU TOTS ELS VOSTRES LINUXCOINS</b>!</translation>
</message>
<message>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Esteu segur que voleu encriptar el vostre moneder?</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>Moneder encriptat</translation>
</message>
<message>
<source>%1 will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your linuxcoins from being stolen by malware infecting your computer.</source>
<translation>Ara es tancarà el %1 per finalitzar el procés d'encriptació. Recordeu que encriptar el vostre moneder no garanteix que les vostres linuxcoins no puguin ser robades per programari maliciós que infecti l'ordinador.</translation>
</message>
<message>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>IMPORTANT: Tota copia de seguretat que hàgiu realitzat hauria de ser reemplaçada pel, recentment generat, fitxer encriptat del moneder. Per motius de seguretat, les còpies de seguretat anteriors del fitxer de moneder no encriptat esdevindran inusables tan aviat com començar a utilitzar el nou moneder encriptat.</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>L'encriptació del moneder ha fallat</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>L'encriptació del moneder ha fallat per un error intern. El moneder no ha estat encriptat.</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>Les contrasenyes introduïdes no coincideixen.</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>El desbloqueig del moneder ha fallat</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>La contrasenya introduïda per a desencriptar el moneder és incorrecta.</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>La desencriptació del moneder ha fallat</translation>
</message>
<message>
<source>Wallet passphrase was successfully changed.</source>
<translation>La contrasenya del moneder ha estat modificada correctament.</translation>
</message>
<message>
<source>Warning: The Caps Lock key is on!</source>
<translation>Avís: Les lletres majúscules estan activades!</translation>
</message>
</context>
<context>
<name>BanTableModel</name>
<message>
<source>IP/Netmask</source>
<translation>IP / Màscara de xarxa</translation>
</message>
<message>
<source>Banned Until</source>
<translation>Bandejat fins</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<source>Sign &message...</source>
<translation>Signa el &missatge...</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>S'està sincronitzant amb la xarxa ...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&Panorama general</translation>
</message>
<message>
<source>Node</source>
<translation>Node</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>Mostra el panorama general del moneder</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&Transaccions</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Cerca a l'historial de transaccions</translation>
</message>
<message>
<source>E&xit</source>
<translation>S&urt</translation>
</message>
<message>
<source>Quit application</source>
<translation>Surt de l'aplicació</translation>
</message>
<message>
<source>&About %1</source>
<translation>Qu&ant al %1</translation>
</message>
<message>
<source>Show information about %1</source>
<translation>Mosta informació sobre el %1</translation>
</message>
<message>
<source>About &Qt</source>
<translation>Quant a &Qt</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Mostra informació sobre Qt</translation>
</message>
<message>
<source>&Options...</source>
<translation>&Opcions...</translation>
</message>
<message>
<source>Modify configuration options for %1</source>
<translation>Modifica les opcions de configuració de %1</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>&Encripta el moneder...</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>&Realitza una còpia de seguretat del moneder...</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>&Canvia la contrasenya...</translation>
</message>
<message>
<source>&Sending addresses...</source>
<translation>Adreces d'e&nviament...</translation>
</message>
<message>
<source>&Receiving addresses...</source>
<translation>Adreces de &recepció...</translation>
</message>
<message>
<source>Open &URI...</source>
<translation>Obre un &URI...</translation>
</message>
<message>
<source>Reindexing blocks on disk...</source>
<translation>S'estan reindexant els blocs al disc...</translation>
</message>
<message>
<source>Send coins to a Linuxcoin address</source>
<translation>Envia monedes a una adreça Linuxcoin</translation>
</message>
<message>
<source>Backup wallet to another location</source>
<translation>Realitza una còpia de seguretat del moneder a una altra ubicació</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>Canvia la contrasenya d'encriptació del moneder</translation>
</message>
<message>
<source>&Debug window</source>
<translation>&Finestra de depuració</translation>
</message>
<message>
<source>Open debugging and diagnostic console</source>
<translation>Obre la consola de diagnòstic i depuració</translation>
</message>
<message>
<source>&Verify message...</source>
<translation>&Verifica el missatge...</translation>
</message>
<message>
<source>Linuxcoin</source>
<translation>Linuxcoin</translation>
</message>
<message>
<source>Wallet</source>
<translation>Moneder</translation>
</message>
<message>
<source>&Send</source>
<translation>&Envia</translation>
</message>
<message>
<source>&Receive</source>
<translation>&Rep</translation>
</message>
<message>
<source>&Show / Hide</source>
<translation>&Mostra / Amaga</translation>
</message>
<message>
<source>Show or hide the main Window</source>
<translation>Mostra o amaga la finestra principal</translation>
</message>
<message>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Encripta les claus privades pertanyents al moneder</translation>
</message>
<message>
<source>Sign messages with your Linuxcoin addresses to prove you own them</source>
<translation>Signa el missatges amb la seva adreça de Linuxcoin per provar que les poseeixes</translation>
</message>
<message>
<source>Verify messages to ensure they were signed with specified Linuxcoin addresses</source>
<translation>Verifiqueu els missatges per assegurar-vos que han estat signats amb una adreça Linuxcoin específica.</translation>
</message>
<message>
<source>&File</source>
<translation>&Fitxer</translation>
</message>
<message>
<source>&Settings</source>
<translation>&Configuració</translation>
</message>
<message>
<source>&Help</source>
<translation>&Ajuda</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>Barra d'eines de les pestanyes</translation>
</message>
<message>
<source>Request payments (generates QR codes and linuxcoin: URIs)</source>
<translation>Sol·licita pagaments (genera codis QR i linuxcoin: URI)</translation>
</message>
<message>
<source>Show the list of used sending addresses and labels</source>
<translation>Mostra la llista d'adreces d'enviament i etiquetes utilitzades</translation>
</message>
<message>
<source>Show the list of used receiving addresses and labels</source>
<translation>Mostra la llista d'adreces de recepció i etiquetes utilitzades</translation>
</message>
<message>
<source>Open a linuxcoin: URI or payment request</source>
<translation>Obre una linuxcoin: sol·licitud d'URI o pagament</translation>
</message>
<message>
<source>&Command-line options</source>
<translation>Opcions de la &línia d'ordres</translation>
</message>
<message numerus="yes">
<source>%n active connection(s) to Linuxcoin network</source>
<translation><numerusform>%n connexió activa a la xarxa Linuxcoin</numerusform><numerusform>%n connexions actives a la xarxa Linuxcoin</numerusform></translation>
</message>
<message>
<source>Indexing blocks on disk...</source>
<translation>S'estan indexant els blocs al disc...</translation>
</message>
<message>
<source>Processing blocks on disk...</source>
<translation>S'estan processant els blocs al disc...</translation>
</message>
<message>
<source>No block source available...</source>
<translation>No hi ha cap font de bloc disponible...</translation>
</message>
<message numerus="yes">
<source>Processed %n block(s) of transaction history.</source>
<translation><numerusform>S'han processat %n bloc de l'historial de transacció.</numerusform><numerusform>S'han processat %n blocs de l'historial de transacció.</numerusform></translation>
</message>
<message numerus="yes">
<source>%n hour(s)</source>
<translation><numerusform>%n hora</numerusform><numerusform>%n hores</numerusform></translation>
</message>
<message numerus="yes">
<source>%n day(s)</source>
<translation><numerusform>%n dia</numerusform><numerusform>%n dies</numerusform></translation>
</message>
<message numerus="yes">
<source>%n week(s)</source>
<translation><numerusform>%n setmana</numerusform><numerusform>%n setmanes</numerusform></translation>
</message>
<message>
<source>%1 and %2</source>
<translation>%1 i %2</translation>
</message>
<message numerus="yes">
<source>%n year(s)</source>
<translation><numerusform>%n any</numerusform><numerusform>%n anys</numerusform></translation>
</message>
<message>
<source>%1 behind</source>
<translation>%1 darrere</translation>
</message>
<message>
<source>Last received block was generated %1 ago.</source>
<translation>El darrer bloc rebut ha estat generat fa %1.</translation>
</message>
<message>
<source>Transactions after this will not yet be visible.</source>
<translation>Les transaccions a partir d'això no seran visibles.</translation>
</message>
<message>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<source>Warning</source>
<translation>Avís</translation>
</message>
<message>
<source>Information</source>
<translation>Informació</translation>
</message>
<message>
<source>Up to date</source>
<translation>Al dia</translation>
</message>
<message>
<source>Show the %1 help message to get a list with possible Linuxcoin command-line options</source>
<translation>Mostra el missatge d'ajuda del %1 per obtenir una llista amb les possibles opcions de línia d'ordres de Linuxcoin</translation>
</message>
<message>
<source>%1 client</source>
<translation>Client de %1</translation>
</message>
<message>
<source>Catching up...</source>
<translation>S'està posant al dia ...</translation>
</message>
<message>
<source>Date: %1
</source>
<translation>Data: %1
</translation>
</message>
<message>
<source>Amount: %1
</source>
<translation>Import: %1
</translation>
</message>
<message>
<source>Type: %1
</source>
<translation>Tipus: %1
</translation>
</message>
<message>
<source>Label: %1
</source>
<translation>Etiqueta: %1
</translation>
</message>
<message>
<source>Address: %1
</source>
<translation>Adreça: %1
</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>Transacció enviada</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>Transacció entrant</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>El moneder està <b>encriptat</b> i actualment <b>desbloquejat</b></translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>El moneder està <b>encriptat</b> i actualment <b>bloquejat</b></translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Coin Selection</source>
<translation>Selecció de moneda</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Quantitat:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Import:</translation>
</message>
<message>
<source>Priority:</source>
<translation>Prioritat:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Comissió</translation>
</message>
<message>
<source>Dust:</source>
<translation>Polsim:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Comissió posterior:</translation>
</message>
<message>
<source>Change:</source>
<translation>Canvi:</translation>
</message>
<message>
<source>(un)select all</source>
<translation>(des)selecciona-ho tot</translation>
</message>
<message>
<source>Tree mode</source>
<translation>Mode arbre</translation>
</message>
<message>
<source>List mode</source>
<translation>Mode llista</translation>
</message>
<message>
<source>Amount</source>
<translation>Import</translation>
</message>
<message>
<source>Received with label</source>
<translation>Rebut amb l'etiqueta</translation>
</message>
<message>
<source>Received with address</source>
<translation>Rebut amb l'adreça</translation>
</message>
<message>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<source>Confirmations</source>
<translation>Confirmacions</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Confirmat</translation>
</message>
<message>
<source>Priority</source>
<translation>Prioritat</translation>
</message>
<message>
<source>Copy address</source>
<translation>Copia l'adreça</translation>
</message>
<message>
<source>Copy label</source>
<translation>Copia l'etiqueta</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Copia l'import</translation>
</message>
<message>
<source>Copy transaction ID</source>
<translation>Copia l'ID de transacció</translation>
</message>
<message>
<source>Copy quantity</source>
<translation>Copia la quantitat</translation>
</message>
<message>
<source>Copy fee</source>
<translation>Copia la comissió</translation>
</message>
<message>
<source>Copy after fee</source>
<translation>Copia la comissió posterior</translation>
</message>
<message>
<source>Copy bytes</source>
<translation>Copia els bytes</translation>
</message>
<message>
<source>Copy priority</source>
<translation>Copia la prioritat</translation>
</message>
<message>
<source>Copy dust</source>
<translation>Copia el polsim</translation>
</message>
<message>
<source>Copy change</source>
<translation>Copia el canvi</translation>
</message>
<message>
<source>highest</source>
<translation>el més alt</translation>
</message>
<message>
<source>higher</source>
<translation>més alt</translation>
</message>
<message>
<source>high</source>
<translation>alt</translation>
</message>
<message>
<source>medium-high</source>
<translation>mig-alt</translation>
</message>
<message>
<source>medium</source>
<translation>mig</translation>
</message>
<message>
<source>low-medium</source>
<translation>baix-mig</translation>
</message>
<message>
<source>low</source>
<translation>baix</translation>
</message>
<message>
<source>lower</source>
<translation>més baix</translation>
</message>
<message>
<source>lowest</source>
<translation>el més baix</translation>
</message>
<message>
<source>(%1 locked)</source>
<translation>(%1 bloquejada)</translation>
</message>
<message>
<source>none</source>
<translation>cap</translation>
</message>
<message>
<source>yes</source>
<translation>sí</translation>
</message>
<message>
<source>no</source>
<translation>no</translation>
</message>
<message>
<source>This label turns red if the transaction size is greater than 1000 bytes.</source>
<translation>Aquesta etiqueta es torna en vermell si la transacció és superior a 1000 bytes.</translation>
</message>
<message>
<source>This means a fee of at least %1 per kB is required.</source>
<translation>Això comporta que cal una comissió d'almenys %1 per kB.</translation>
</message>
<message>
<source>Can vary +/- 1 byte per input.</source>
<translation>Pot variar +/- 1 byte per entrada.</translation>
</message>
<message>
<source>Transactions with higher priority are more likely to get included into a block.</source>
<translation>Les transaccions amb una major prioritat són més propenses a ser incloses en un bloc.</translation>
</message>
<message>
<source>This label turns red if the priority is smaller than "medium".</source>
<translation>Aquesta etiqueta es torna en vermell si la propietat és inferior que la «mitjana».</translation>
</message>
<message>
<source>This label turns red if any recipient receives an amount smaller than the current dust threshold.</source>
<translation>Aquesta etiqueta es torna vermella si cap recipient rep un import inferior al llindar de polsim actual.</translation>
</message>
<message>
<source>Can vary +/- %1 satoshi(s) per input.</source>
<translation>Pot variar en +/- %1 satoshi(s) per entrada.</translation>
</message>
<message>
<source>(no label)</source>
<translation>(sense etiqueta)</translation>
</message>
<message>
<source>change from %1 (%2)</source>
<translation>canvia de %1 (%2)</translation>
</message>
<message>
<source>(change)</source>
<translation>(canvia)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>Edita l'adreça</translation>
</message>
<message>
<source>&Label</source>
<translation>&Etiqueta</translation>
</message>
<message>
<source>The label associated with this address list entry</source>
<translation>L'etiqueta associada amb aquesta entrada de llista d'adreces</translation>
</message>
<message>
<source>The address associated with this address list entry. This can only be modified for sending addresses.</source>
<translation>L'adreça associada amb aquesta entrada de llista d'adreces. Només es pot modificar per a les adreces d'enviament.</translation>
</message>
<message>
<source>&Address</source>
<translation>&Adreça</translation>
</message>
<message>
<source>New receiving address</source>
<translation>Nova adreça de recepció</translation>
</message>
<message>
<source>New sending address</source>
<translation>Nova adreça d'enviament</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>Edita l'adreça de recepció</translation>
</message>
<message>
<source>Edit sending address</source>
<translation>Edita l'adreça d'enviament</translation>
</message>
<message>
<source>The entered address "%1" is not a valid Linuxcoin address.</source>
<translation>L'adreça introduïda «%1» no és una adreça de Linuxcoin vàlida.</translation>
</message>
<message>
<source>The entered address "%1" is already in the address book.</source>
<translation>L'adreça introduïda «%1» ja és present a la llibreta d'adreces.</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>No s'ha pogut desbloquejar el moneder.</translation>
</message>
<message>
<source>New key generation failed.</source>
<translation>Ha fallat la generació d'una clau nova.</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<source>A new data directory will be created.</source>
<translation>Es crearà un nou directori de dades.</translation>
</message>
<message>
<source>name</source>
<translation>nom</translation>
</message>
<message>
<source>Directory already exists. Add %1 if you intend to create a new directory here.</source>
<translation>El directori ja existeix. Afegeix %1 si vols crear un nou directori en aquesta ubicació.</translation>
</message>
<message>
<source>Path already exists, and is not a directory.</source>
<translation>El camí ja existeix i no és cap directori.</translation>
</message>
<message>
<source>Cannot create data directory here.</source>
<translation>No es pot crear el directori de dades aquí.</translation>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>version</source>
<translation>versió</translation>
</message>
<message>
<source>(%1-bit)</source>
<translation>(%1-bit)</translation>
</message>
<message>
<source>About %1</source>
<translation>Quant al %1</translation>
</message>
<message>
<source>Command-line options</source>
<translation>Opcions de línia d'ordres</translation>
</message>
<message>
<source>Usage:</source>
<translation>Ús:</translation>
</message>
<message>
<source>command-line options</source>
<translation>Opcions de la línia d'ordres</translation>
</message>
<message>
<source>UI Options:</source>
<translation>Opcions d'interfície d'usuari:</translation>
</message>
<message>
<source>Choose data directory on startup (default: %u)</source>
<translation>Trieu el directori de dades a l'inici (per defecte: %u)</translation>
</message>
<message>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Defineix la llengua, per exemple «de_DE» (per defecte: la definida pel sistema)</translation>
</message>
<message>
<source>Start minimized</source>
<translation>Inicia minimitzat</translation>
</message>
<message>
<source>Set SSL root certificates for payment request (default: -system-)</source>
<translation>Defineix els certificats arrel SSL per a la sol·licitud de pagament (per defecte: els del sistema)</translation>
</message>
<message>
<source>Show splash screen on startup (default: %u)</source>
<translation>Mostra la pantalla de benvinguda a l'inici (per defecte: %u)</translation>
</message>
<message>
<source>Reset all settings changed in the GUI</source>
<translation>Reinicialitza tots els canvis de configuració fets des de la interfície gràfica</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Welcome</source>
<translation>Us donem la benvinguda</translation>
</message>
<message>
<source>Welcome to %1.</source>
<translation>Us donem la benvinguda a %1.</translation>
</message>
<message>
<source>As this is the first time the program is launched, you can choose where %1 will store its data.</source>
<translation>Com és la primera vegada que s'executa el programa, podeu triar on %1 emmagatzemarà les dades.</translation>
</message>
<message>
<source>%1 will download and store a copy of the Linuxcoin block chain. At least %2GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source>
<translation>%1 baixarà i emmagatzemarà una còpia de la cadena de blocs de Linuxcoin. Com a mínim %2GB de dades s'emmagatzemaran en aquest directori, i augmentarà al llarg del temps. El moneder també s'emmagatzemarà en aquest directori.</translation>
</message>
<message>
<source>Use the default data directory</source>
<translation>Utilitza el directori de dades per defecte</translation>
</message>
<message>
<source>Use a custom data directory:</source>
<translation>Utilitza un directori de dades personalitzat:</translation>
</message>
<message>
<source>Error: Specified data directory "%1" cannot be created.</source>
<translation>Error: el directori de dades «%1» especificat no pot ser creat.</translation>
</message>
<message>
<source>Error</source>
<translation>Error</translation>
</message>
<message numerus="yes">
<source>%n GB of free space available</source>
<translation><numerusform>%n GB d'espai lliure disponible</numerusform><numerusform>%n GB d'espai lliure disponible</numerusform></translation>
</message>
<message numerus="yes">
<source>(of %n GB needed)</source>
<translation><numerusform>(de %n GB necessari)</numerusform><numerusform>(de %n GB necessaris)</numerusform></translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
<message>
<source>Open URI</source>
<translation>Obre un URI</translation>
</message>
<message>
<source>Open payment request from URI or file</source>
<translation>Obre una sol·licitud de pagament des d'un URI o un fitxer</translation>
</message>
<message>
<source>URI:</source>
<translation>URI:</translation>
</message>
<message>
<source>Select payment request file</source>
<translation>Selecciona un fitxer de sol·licitud de pagament</translation>
</message>
<message>
<source>Select payment request file to open</source>
<translation>Seleccioneu el fitxer de sol·licitud de pagament per obrir</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Opcions</translation>
</message>
<message>
<source>&Main</source>
<translation>&Principal</translation>
</message>
<message>
<source>Automatically start %1 after logging in to the system.</source>
<translation>Inicieu %1 automàticament després d'entrar en el sistema.</translation>
</message>
<message>
<source>&Start %1 on system login</source>
<translation>&Inicia %1 en l'entrada al sistema</translation>
</message>
<message>
<source>Size of &database cache</source>
<translation>Mida de la memòria cau de la base de &dades</translation>
</message>
<message>
<source>MB</source>
<translation>MB</translation>
</message>
<message>
<source>Number of script &verification threads</source>
<translation>Nombre de fils de &verificació d'scripts</translation>
</message>
<message>
<source>Accept connections from outside</source>
<translation>Accepta connexions de fora</translation>
</message>
<message>
<source>Allow incoming connections</source>
<translation>Permet connexions entrants</translation>
</message>
<message>
<source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source>
<translation>Adreça IP del proxy (p. ex. IPv4: 127.0.0.1 / IPv6: ::1)</translation>
</message>
<message>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Exit in the menu.</source>
<translation>Minimitza en comptes de sortir de l'aplicació quan la finestra es tanca. Quan s'habilita aquesta opció l'aplicació es tancara només quan se selecciona Surt del menú. </translation>
</message>
<message>
<source>Third party URLs (e.g. a block explorer) that appear in the transactions tab as context menu items. %s in the URL is replaced by transaction hash. Multiple URLs are separated by vertical bar |.</source>
<translation>URL de terceres parts (p. ex. explorador de blocs) que apareix en la pestanya de transaccions com elements del menú contextual. %s en l'URL es reemplaçat pel resum de la transacció. Diferents URL estan separades per una barra vertical |.</translation>
</message>
<message>
<source>Third party transaction URLs</source>
<translation>URL de transaccions de terceres parts</translation>
</message>
<message>
<source>Active command-line options that override above options:</source>
<translation>Opcions de línies d'ordre active que sobreescriuen les opcions de dalt:</translation>
</message>
<message>
<source>Reset all client options to default.</source>
<translation>Reestableix totes les opcions del client.</translation>
</message>
<message>
<source>&Reset Options</source>
<translation>&Reestableix les opcions</translation>
</message>
<message>
<source>&Network</source>
<translation>&Xarxa</translation>
</message>
<message>
<source>(0 = auto, <0 = leave that many cores free)</source>
<translation>(0 = auto, <0 = deixa tants nuclis lliures)</translation>
</message>
<message>
<source>W&allet</source>
<translation>&Moneder</translation>
</message>
<message>
<source>Expert</source>
<translation>Expert</translation>
</message>
<message>
<source>Enable coin &control features</source>
<translation>Activa les funcions de &control de les monedes</translation>
</message>
<message>
<source>If you disable the spending of unconfirmed change, the change from a transaction cannot be used until that transaction has at least one confirmation. This also affects how your balance is computed.</source>
<translation>Si inhabiliteu la despesa d'un canvi sense confirmar, el canvi d'una transacció no pot ser utilitzat fins que la transacció no tingui com a mínim una confirmació. Això també afecta com es calcula el vostre balanç.</translation>
</message>
<message>
<source>&Spend unconfirmed change</source>
<translation>&Gasta el canvi sense confirmar</translation>
</message>
<message>
<source>Automatically open the Linuxcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Obre el port del client de Linuxcoin al router de forma automàtica. Això només funciona quan el router implementa UPnP i l'opció està activada.</translation>
</message>
<message>
<source>Map port using &UPnP</source>
<translation>Port obert amb &UPnP</translation>
</message>
<message>
<source>Connect to the Linuxcoin network through a SOCKS5 proxy.</source>
<translation>Connecta a la xarxa Linuxcoin a través d'un proxy SOCKS5.</translation>
</message>
<message>
<source>&Connect through SOCKS5 proxy (default proxy):</source>
<translation>&Connecta a través d'un proxy SOCKS5 (proxy per defecte):</translation>
</message>
<message>
<source>Proxy &IP:</source>
<translation>&IP del proxy:</translation>
</message>
<message>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Port del proxy (per exemple 9050)</translation>
</message>
<message>
<source>Used for reaching peers via:</source>
<translation>Utilitzat per arribar als iguals mitjançant:</translation>
</message>
<message>
<source>Shows, if the supplied default SOCKS5 proxy is used to reach peers via this network type.</source>
<translation>Mostra si el proxy SOCKS5 per defecte proporcionat s'utilitza per arribar als iguals mitjançant aquest tipus de xarxa.</translation>
</message>
<message>
<source>IPv4</source>
<translation>IPv4</translation>
</message>
<message>
<source>IPv6</source>
<translation>IPv6</translation>
</message>
<message>
<source>Tor</source>
<translation>Tor</translation>
</message>
<message>
<source>Connect to the Linuxcoin network through a separate SOCKS5 proxy for Tor hidden services.</source>
<translation>Conectar a la red de Linuxcoin a través de un proxy SOCKS5 per als serveis ocults de Tor</translation>
</message>
<message>
<source>Use separate SOCKS5 proxy to reach peers via Tor hidden services:</source>
<translation>Utilitza un proxy SOCKS4 apart per a arribar als iguals a través de serveis ocults de Tor:</translation>
</message>
<message>
<source>&Window</source>
<translation>&Finestra</translation>
</message>
<message>
<source>&Hide the icon from the system tray.</source>
<translation>Ama&ga la icona de la safata del sistema.</translation>
</message>
<message>
<source>Hide tray icon</source>
<translation>Amaga la icona de la safata</translation>
</message>
<message>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Mostra només la icona de la barra en minimitzar la finestra.</translation>
</message>
<message>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimitza a la barra d'aplicacions en comptes de la barra de tasques</translation>
</message>
<message>
<source>M&inimize on close</source>
<translation>M&inimitza en tancar</translation>
</message>
<message>
<source>&Display</source>
<translation>&Pantalla</translation>
</message>
<message>
<source>User Interface &language:</source>
<translation>&Llengua de la interfície d'usuari:</translation>
</message>
<message>
<source>The user interface language can be set here. This setting will take effect after restarting %1.</source>
<translation>Aquí es pot definir la llengua de la interfície d'usuari. Aquest paràmetre tindrà efecte en reiniciar el %1.</translation>
</message>
<message>
<source>&Unit to show amounts in:</source>
<translation>&Unitats per mostrar els imports en:</translation>
</message>
<message>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Selecciona la unitat de subdivisió per defecte per mostrar en la interfície quan s'envien monedes.</translation>
</message>
<message>
<source>Whether to show coin control features or not.</source>
<translation>Si voleu mostrar les funcions de control de monedes o no.</translation>
</message>
<message>
<source>&OK</source>
<translation>&D'acord</translation>
</message>
<message>
<source>&Cancel</source>
<translation>&Cancel·la</translation>
</message>
<message>
<source>default</source>
<translation>Per defecte</translation>
</message>
<message>
<source>none</source>
<translation>cap</translation>
</message>
<message>
<source>Confirm options reset</source>
<translation>Confirmeu el reestabliment de les opcions</translation>
</message>
<message>
<source>Client restart required to activate changes.</source>
<translation>Cal reiniciar el client per activar els canvis.</translation>
</message>
<message>
<source>Client will be shut down. Do you want to proceed?</source>
<translation>S'aturarà el client. Voleu procedir?</translation>
</message>
<message>
<source>This change would require a client restart.</source>
<translation>Amb aquest canvi cal un reinici del client.</translation>
</message>
<message>
<source>The supplied proxy address is invalid.</source>
<translation>L'adreça proxy introduïda és invalida.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>Formulari</translation>
</message>
<message>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Linuxcoin network after a connection is established, but this process has not completed yet.</source>
<translation>La informació mostrada pot no estar al día. El teu moneder es sincronitza automàticament amb la xarxa Linuxcoin un cop s'ha establert connexió, però aquest proces no s'ha completat encara.</translation>
</message>
<message>
<source>Watch-only:</source>
<translation>Només lectura:</translation>
</message>
<message>
<source>Available:</source>
<translation>Disponible:</translation>
</message>
<message>
<source>Your current spendable balance</source>
<translation>El balanç que podeu gastar actualment</translation>
</message>
<message>
<source>Pending:</source>
<translation>Pendent:</translation>
</message>
<message>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source>
<translation>Total de transaccions que encara han de confirmar-se i que encara no compten en el balanç que es pot gastar</translation>
</message>
<message>
<source>Immature:</source>
<translation>Immadur:</translation>
</message>
<message>
<source>Mined balance that has not yet matured</source>
<translation>Balanç minat que encara no ha madurat</translation>
</message>
<message>
<source>Balances</source>
<translation>Balances</translation>
</message>
<message>
<source>Total:</source>
<translation>Total:</translation>
</message>
<message>
<source>Your current total balance</source>
<translation>El balanç total actual</translation>
</message>
<message>
<source>Your current balance in watch-only addresses</source>
<translation>El vostre balanç actual en adreces de només lectura</translation>
</message>
<message>
<source>Spendable:</source>
<translation>Que es pot gastar:</translation>
</message>
<message>
<source>Recent transactions</source>
<translation>Transaccions recents</translation>
</message>
<message>
<source>Unconfirmed transactions to watch-only addresses</source>
<translation>Transaccions sense confirmar a adreces de només lectura</translation>
</message>
<message>
<source>Mined balance in watch-only addresses that has not yet matured</source>
<translation>Balanç minat en adreces de només lectura que encara no ha madurat</translation>
</message>
<message>
<source>Current total balance in watch-only addresses</source>
<translation>Balanç total actual en adreces de només lectura</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<source>Payment request error</source>
<translation>Error de la sol·licitud de pagament</translation>
</message>
<message>
<source>Cannot start linuxcoin: click-to-pay handler</source>
<translation>No es pot iniciar linuxcoin: controlador click-to-pay</translation>
</message>
<message>
<source>URI handling</source>
<translation>Gestió d'URI</translation>
</message>
<message>
<source>Network request error</source>
<translation>Error en la sol·licitud de xarxa</translation>
</message>
<message>
<source>Payment acknowledged</source>
<translation>Pagament reconegut</translation>
</message>
</context>
<context>
<name>PeerTableModel</name>
<message>
<source>User Agent</source>
<translation>Agent d'usuari</translation>
</message>
<message>
<source>Node/Service</source>
<translation>Node/Servei</translation>
</message>
<message>
<source>Ping Time</source>
<translation>Temps de ping</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Import</translation>
</message>
<message>
<source>Enter a Linuxcoin address (e.g. %1)</source>
<translation>Introduïu una adreça de Linuxcoin (p. ex. %1)</translation>
</message>
<message>
<source>%1 d</source>
<translation>%1 d</translation>
</message>
<message>
<source>%1 h</source>
<translation>%1 h</translation>
</message>
<message>
<source>%1 m</source>
<translation>%1 m</translation>
</message>
<message>
<source>%1 s</source>
<translation>%1 s</translation>
</message>
<message>
<source>None</source>
<translation>Cap</translation>
</message>
<message>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<source>%1 ms</source>
<translation>%1 ms</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
<message>
<source>&Save Image...</source>
<translation>De&sa la imatge...</translation>
</message>
<message>
<source>&Copy Image</source>
<translation>&Copia la imatge</translation>
</message>
<message>
<source>Save QR Code</source>
<translation>Desa el codi QR</translation>
</message>
<message>
<source>PNG Image (*.png)</source>
<translation>Imatge PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<source>Client version</source>
<translation>Versió del client</translation>
</message>
<message>
<source>&Information</source>
<translation>&Informació</translation>
</message>
<message>
<source>Debug window</source>
<translation>Finestra de depuració</translation>
</message>
<message>
<source>General</source>
<translation>General</translation>
</message>
<message>
<source>Using BerkeleyDB version</source>
<translation>Utilitzant BerkeleyDB versió</translation>
</message>
<message>
<source>Datadir</source>
<translation>Datadir</translation>
</message>
<message>
<source>Startup time</source>
<translation>&Temps d'inici</translation>
</message>
<message>
<source>Network</source>
<translation>Xarxa</translation>
</message>
<message>
<source>Name</source>
<translation>Nom</translation>
</message>
<message>
<source>Number of connections</source>
<translation>Nombre de connexions</translation>
</message>
<message>
<source>Block chain</source>
<translation>Cadena de blocs</translation>
</message>
<message>
<source>Current number of blocks</source>
<translation>Nombre de blocs actuals</translation>
</message>
<message>
<source>Memory Pool</source>
<translation>Reserva de memòria</translation>
</message>
<message>
<source>Current number of transactions</source>
<translation>Nombre actual de transaccions</translation>
</message>
<message>
<source>Memory usage</source>
<translation>Us de memoria</translation>
</message>
<message>
<source>Received</source>
<translation>Rebut</translation>
</message>
<message>
<source>Sent</source>
<translation>Enviat</translation>
</message>
<message>
<source>&Peers</source>
<translation>&Iguals</translation>
</message>
<message>
<source>Banned peers</source>
<translation>Iguals bandejats</translation>
</message>
<message>
<source>Select a peer to view detailed information.</source>
<translation>Seleccioneu un igual per mostrar informació detallada.</translation>
</message>
<message>
<source>Whitelisted</source>
<translation>A la llista blanca</translation>
</message>
<message>
<source>Direction</source>
<translation>Direcció</translation>
</message>
<message>
<source>Version</source>
<translation>Versió</translation>
</message>
<message>
<source>Starting Block</source>
<translation>Bloc d'inici</translation>
</message>
<message>
<source>Synced Headers</source>
<translation>Capçaleres sincronitzades</translation>
</message>
<message>
<source>Synced Blocks</source>
<translation>Blocs sincronitzats</translation>
</message>
<message>
<source>User Agent</source>
<translation>Agent d'usuari</translation>
</message>
<message>
<source>Services</source>
<translation>Serveis</translation>
</message>
<message>
<source>Ban Score</source>
<translation>Puntuació de bandeig</translation>
</message>
<message>
<source>Connection Time</source>
<translation>Temps de connexió</translation>
</message>
<message>
<source>Last Send</source>
<translation>Darrer enviament</translation>
</message>
<message>
<source>Last Receive</source>
<translation>Darrera recepció</translation>
</message>
<message>
<source>Ping Time</source>
<translation>Temps de ping</translation>
</message>
<message>
<source>The duration of a currently outstanding ping.</source>
<translation>La duració d'un ping més destacat actualment.</translation>
</message>
<message>
<source>Ping Wait</source>
<translation>Espera de ping</translation>
</message>
<message>
<source>Time Offset</source>
<translation>Diferència horària</translation>
</message>
<message>
<source>Last block time</source>
<translation>Últim temps de bloc</translation>
</message>
<message>
<source>&Open</source>
<translation>&Obre</translation>
</message>
<message>
<source>&Console</source>
<translation>&Consola</translation>
</message>
<message>
<source>&Network Traffic</source>
<translation>Trà&nsit de la xarxa</translation>
</message>
<message>
<source>&Clear</source>
<translation>Nete&ja</translation>
</message>
<message>
<source>Totals</source>
<translation>Totals</translation>
</message>
<message>
<source>In:</source>
<translation>Dins:</translation>
</message>
<message>
<source>Out:</source>
<translation>Fora:</translation>
</message>
<message>
<source>Debug log file</source>
<translation>Fitxer de registre de depuració</translation>
</message>
<message>
<source>Clear console</source>
<translation>Neteja la consola</translation>
</message>
<message>
<source>&Disconnect Node</source>
<translation>&Desconnecta el node</translation>
</message>
<message>
<source>Ban Node for</source>
<translation>Bandeja el node durant</translation>
</message>
<message>
<source>1 &hour</source>
<translation>1 &hora</translation>
</message>
<message>
<source>1 &day</source>
<translation>1 &dia</translation>
</message>
<message>
<source>1 &week</source>
<translation>1 &setmana</translation>
</message>
<message>
<source>1 &year</source>
<translation>1 &any</translation>
</message>
<message>
<source>&Unban Node</source>
<translation>&Desbandeja el node</translation>
</message>
<message>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Utilitza les fletxes d'amunt i avall per navegar per l'historial, i <b>Ctrl-L<\b> per netejar la pantalla.</translation>
</message>
<message>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Escriviu <b>help<\b> per a obtenir un llistat de les ordres disponibles.</translation>
</message>
<message>
<source>%1 B</source>
<translation>%1 B</translation>
</message>
<message>
<source>%1 KB</source>
<translation>%1 KB</translation>
</message>
<message>
<source>%1 MB</source>
<translation>%1 MB</translation>
</message>
<message>
<source>%1 GB</source>
<translation>%1 GB</translation>
</message>
<message>
<source>(node id: %1)</source>
<translation>(id del node: %1)</translation>
</message>
<message>
<source>via %1</source>
<translation>a través de %1</translation>
</message>
<message>
<source>never</source>
<translation>mai</translation>
</message>
<message>
<source>Inbound</source>
<translation>Entrant</translation>
</message>
<message>
<source>Outbound</source>
<translation>Sortint</translation>
</message>
<message>
<source>Yes</source>
<translation>Sí</translation>
</message>
<message>
<source>No</source>
<translation>No</translation>
</message>
<message>
<source>Unknown</source>
<translation>Desconegut</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Amount:</source>
<translation>Im&port:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Etiqueta:</translation>
</message>
<message>
<source>&Message:</source>
<translation>&Missatge:</translation>
</message>
<message>
<source>Reuse one of the previously used receiving addresses. Reusing addresses has security and privacy issues. Do not use this unless re-generating a payment request made before.</source>
<translation>Reutilitza una de les adreces de recepció utilitzades anteriorment. La reutilització d'adreces pot comportar problemes de seguretat i privadesa. No ho utilitzeu llevat que torneu a generar una sol·licitud de pagament feta abans.</translation>
</message>
<message>
<source>R&euse an existing receiving address (not recommended)</source>
<translation>R&eutilitza una adreça de recepció anterior (no recomanat)</translation>
</message>
<message>
<source>An optional message to attach to the payment request, which will be displayed when the request is opened. Note: The message will not be sent with the payment over the Linuxcoin network.</source>
<translation>Un missatge opcional que s'adjuntarà a la sol·licitud de pagament, que es mostrarà quan s'obri la sol·licitud. Nota: El missatge no s'enviarà amb el pagament per la xarxa Linuxcoin.</translation>
</message>
<message>
<source>An optional label to associate with the new receiving address.</source>
<translation>Una etiqueta opcional que s'associarà amb la nova adreça receptora.</translation>
</message>
<message>
<source>Use this form to request payments. All fields are <b>optional</b>.</source>
<translation>Utilitzeu aquest formulari per sol·licitar pagaments. Tots els camps són <b>opcionals</b>.</translation>
</message>
<message>
<source>An optional amount to request. Leave this empty or zero to not request a specific amount.</source>
<translation>Un import opcional per sol·licitar. Deixeu-ho en blanc o zero per no sol·licitar cap import específic.</translation>
</message>
<message>
<source>Clear all fields of the form.</source>
<translation>Esborra tots els camps del formuari.</translation>
</message>
<message>
<source>Clear</source>
<translation>Neteja</translation>
</message>
<message>
<source>Requested payments history</source>
<translation>Historial de pagaments sol·licitats</translation>
</message>
<message>
<source>&Request payment</source>
<translation>&Sol·licitud de pagament</translation>
</message>
<message>
<source>Show the selected request (does the same as double clicking an entry)</source>
<translation>Mostra la sol·licitud seleccionada (fa el mateix que el doble clic a una entrada)</translation>
</message>
<message>
<source>Show</source>
<translation>Mostra</translation>
</message>
<message>
<source>Remove the selected entries from the list</source>
<translation>Esborra les entrades seleccionades de la llista</translation>
</message>
<message>
<source>Remove</source>
<translation>Esborra</translation>
</message>
<message>
<source>Copy label</source>
<translation>Copia l'etiqueta</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Copia l'import</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>QR Code</source>
<translation>Codi QR</translation>
</message>
<message>
<source>Copy &URI</source>
<translation>Copia l'&URI</translation>
</message>
<message>
<source>Copy &Address</source>
<translation>Copia l'&adreça</translation>
</message>
<message>
<source>&Save Image...</source>
<translation>De&sa la imatge...</translation>
</message>
<message>
<source>Request payment to %1</source>
<translation>Sol·licita un pagament a %1</translation>
</message>
<message>
<source>Payment information</source>
<translation>Informació de pagament</translation>
</message>
<message>
<source>URI</source>
<translation>URI</translation>
</message>
<message>
<source>Address</source>
<translation>Adreça</translation>
</message>
<message>
<source>Amount</source>
<translation>Import</translation>
</message>
<message>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<source>Message</source>
<translation>Missatge</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<source>Message</source>
<translation>Missatge</translation>
</message>
<message>
<source>(no label)</source>
<translation>(sense etiqueta)</translation>
</message>
<message>
<source>(no message)</source>
<translation>(sense missatge)</translation>
</message>
<message>
<source>(no amount requested)</source>
<translation>(no s'ha sol·licitat import)</translation>
</message>
<message>
<source>Requested</source>
<translation>Sol·licitat</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>Envia monedes</translation>
</message>
<message>
<source>Coin Control Features</source>
<translation>Característiques de control de les monedes</translation>
</message>
<message>
<source>Inputs...</source>
<translation>Entrades...</translation>
</message>
<message>
<source>automatically selected</source>
<translation>seleccionat automàticament</translation>
</message>
<message>
<source>Insufficient funds!</source>
<translation>Fons insuficients!</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Quantitat:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Bytes:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Import:</translation>
</message>
<message>
<source>Priority:</source>
<translation>Prioritat:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Comissió:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Comissió posterior:</translation>
</message>
<message>
<source>Change:</source>
<translation>Canvi:</translation>
</message>
<message>
<source>If this is activated, but the change address is empty or invalid, change will be sent to a newly generated address.</source>
<translation>Si s'activa això, però l'adreça de canvi està buida o bé no és vàlida, el canvi s'enviarà a una adreça generada de nou.</translation>
</message>
<message>
<source>Custom change address</source>
<translation>Personalitza l'adreça de canvi</translation>
</message>
<message>
<source>Transaction Fee:</source>
<translation>Comissió de transacció</translation>
</message>
<message>
<source>Choose...</source>
<translation>Tria...</translation>
</message>
<message>
<source>collapse fee-settings</source>
<translation>redueix els paràmetres de comissió</translation>
</message>
<message>
<source>per kilobyte</source>
<translation>per kilobyte</translation>
</message>
<message>
<source>If the custom fee is set to 1000 satoshis and the transaction is only 250 bytes, then "per kilobyte" only pays 250 satoshis in fee, while "total at least" pays 1000 satoshis. For transactions bigger than a kilobyte both pay by kilobyte.</source>
<translation>Si la comissió personalitzada es defineix a 1000 satoshis i la transacció és de només 250 bytes, llavors «per kilobyte» només es paguen 250 satoshis en una comissió, mentre que amb la de «total com a mínim» es pagarien 1000 satoshis. Per a transaccions superiors al kilobyte, en tots dos casos es paga per kilobyte.</translation>
</message>
<message>
<source>Hide</source>
<translation>Amaga</translation>
</message>
<message>
<source>total at least</source>
<translation>total com a mínim</translation>
</message>
<message>
<source>Paying only the minimum fee is just fine as long as there is less transaction volume than space in the blocks. But be aware that this can end up in a never confirming transaction once there is more demand for linuxcoin transactions than the network can process.</source>
<translation>No hi ha cap problema en pagar només la comissió mínima sempre que hi hagi menys volum de transacció que espai en els blocs. Però tingueu present que això pot acabar en una transacció que mai es confirmi una vegada hi hagi més demanda de transaccions de linuxcoins que la xarxa pugui processar.</translation>
</message>
<message>
<source>(read the tooltip)</source>
<translation>(llegiu l'indicador de funció)</translation>
</message>
<message>
<source>Recommended:</source>
<translation>Recomanada:</translation>
</message>
<message>
<source>Custom:</source>
<translation>Personalitzada:</translation>
</message>
<message>
<source>(Smart fee not initialized yet. This usually takes a few blocks...)</source>
<translation>(No s'ha inicialitzat encara la comissió intel·ligent. Normalment pren uns pocs blocs...)</translation>
</message>
<message>
<source>Confirmation time:</source>
<translation>Temps de confirmació:</translation>
</message>
<message>
<source>normal</source>
<translation>normal</translation>
</message>
<message>
<source>fast</source>
<translation>ràpid</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>Envia a múltiples destinataris al mateix temps</translation>
</message>
<message>
<source>Add &Recipient</source>
<translation>Afegeix &destinatari</translation>
</message>
<message>
<source>Clear all fields of the form.</source>
<translation>Netejar tots els camps del formulari.</translation>
</message>
<message>
<source>Dust:</source>
<translation>Polsim:</translation>
</message>
<message>
<source>Clear &All</source>
<translation>Neteja-ho &tot</translation>
</message>
<message>
<source>Balance:</source>
<translation>Balanç:</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>Confirma l'acció d'enviament</translation>
</message>
<message>
<source>S&end</source>
<translation>E&nvia</translation>
</message>
<message>
<source>Copy quantity</source>
<translation>Copia la quantitat</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Copia l'import</translation>
</message>
<message>
<source>Copy fee</source>
<translation>Copia la comissió</translation>
</message>
<message>
<source>Copy after fee</source>
<translation>Copia la comissió posterior</translation>
</message>
<message>
<source>Copy bytes</source>
<translation>Copia els bytes</translation>
</message>
<message>
<source>Copy priority</source>
<translation>Copia la prioritat</translation>
</message>
<message>
<source>Copy dust</source>
<translation>Copia el polsim</translation>
</message>
<message>
<source>Copy change</source>
<translation>Copia el canvi</translation>
</message>
<message>
<source>Total Amount %1</source>
<translation>Import total %1</translation>
</message>
<message>
<source>or</source>
<translation>o</translation>
</message>
<message>
<source>Confirm send coins</source>
<translation>Confirma l'enviament de monedes</translation>
</message>
<message>
<source>The recipient address is not valid. Please recheck.</source>
<translation>L'adreça del destinatari no és vàlida. Torneu-la a comprovar.</translation>
</message>
<message>
<source>The amount to pay must be larger than 0.</source>
<translation>L'import a pagar ha de ser major que 0.</translation>
</message>
<message>
<source>The amount exceeds your balance.</source>
<translation>L'import supera el vostre balanç.</translation>
</message>
<message>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>El total excedeix el vostre balanç quan s'afegeix la comissió a la transacció %1.</translation>
</message>
<message>
<source>Duplicate address found: addresses should only be used once each.</source>
<translation>S'ha trobat una adreça duplicada: les adreces només s'haurien d'utilitzar una vegada cada una.</translation>
</message>
<message>
<source>Transaction creation failed!</source>
<translation>La creació de la transacció ha fallat!</translation>
</message>
<message>
<source>(no label)</source>
<translation>(sense etiqueta)</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>Q&uantitat:</translation>
</message>
<message>
<source>Pay &To:</source>
<translation>Paga &a:</translation>
</message>
<message>
<source>&Label:</source>
<translation>&Etiqueta:</translation>
</message>
<message>
<source>Choose previously used address</source>
<translation>Escull una adreça feta servir anteriorment</translation>
</message>
<message>
<source>This is a normal payment.</source>
<translation>Això és un pagament normal.</translation>
</message>
<message>
<source>The Linuxcoin address to send the payment to</source>
<translation>L'adreça Linuxcoin on enviar el pagament</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alta+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Enganxar adreça del porta-retalls</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Remove this entry</source>
<translation>Elimina aquesta entrada</translation>
</message>
<message>
<source>The fee will be deducted from the amount being sent. The recipient will receive less linuxcoins than you enter in the amount field. If multiple recipients are selected, the fee is split equally.</source>
<translation>La comissió es deduirà de l'import que s'enviarà. El destinatari rebrà menys linuxcoins que les que introduïu al camp d'import. Si se seleccionen múltiples destinataris, la comissió es dividirà per igual.</translation>
</message>
<message>
<source>S&ubtract fee from amount</source>
<translation>S&ubstreu la comissió de l'import</translation>
</message>
<message>
<source>Message:</source>
<translation>Missatge:</translation>
</message>
<message>
<source>This is an unauthenticated payment request.</source>
<translation>Aquesta és una sol·licitud de pagament no autenticada.</translation>
</message>
<message>
<source>This is an authenticated payment request.</source>
<translation>Aquesta és una sol·licitud de pagament autenticada.</translation>
</message>
<message>
<source>Enter a label for this address to add it to the list of used addresses</source>
<translation>Introduïu una etiqueta per a aquesta adreça per afegir-la a la llista d'adreces utilitzades</translation>
</message>
<message>
<source>A message that was attached to the linuxcoin: URI which will be stored with the transaction for your reference. Note: This message will not be sent over the Linuxcoin network.</source>
<translation>Un missatge que s'ha adjuntat al linuxcoin: URI que s'emmagatzemarà amb la transacció per a la vostra referència. Nota: el missatge no s'enviarà a través de la xarxa Linuxcoin.</translation>
</message>
<message>
<source>Pay To:</source>
<translation>Paga a:</translation>
</message>
<message>
<source>Memo:</source>
<translation>Memo:</translation>
</message>
</context>
<context>
<name>SendConfirmationDialog</name>
</context>
<context>
<name>ShutdownWindow</name>
<message>
<source>Do not shut down the computer until this window disappears.</source>
<translation>No apagueu l'ordinador fins que no desaparegui aquesta finestra.</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signatures - Signa / verifica un missatge</translation>
</message>
<message>
<source>&Sign Message</source>
<translation>&Signa el missatge</translation>
</message>
<message>
<source>You can sign messages/agreements with your addresses to prove you can receive linuxcoins sent to them. Be careful not to sign anything vague or random, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Podeu signar missatges/acords amb les vostres adreces per provar que rebeu les linuxcoins que s'hi envien. Aneu amb compte no signar res que sigui vague o aleatori, perquè en alguns atacs de suplantació es pot provar que hi signeu la vostra identitat. Només signeu aquelles declaracions completament detallades en què hi esteu d'acord. </translation>
</message>
<message>
<source>The Linuxcoin address to sign the message with</source>
<translation>L'adreça Linuxcoin amb què signar el missatge</translation>
</message>
<message>
<source>Choose previously used address</source>
<translation>Tria les adreces fetes servir amb anterioritat</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Enganxa l'adreça del porta-retalls</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Enter the message you want to sign here</source>
<translation>Introduïu aquí el missatge que voleu signar</translation>
</message>
<message>
<source>Signature</source>
<translation>Signatura</translation>
</message>
<message>
<source>Copy the current signature to the system clipboard</source>
<translation>Copia la signatura actual al porta-retalls del sistema</translation>
</message>
<message>
<source>Sign the message to prove you own this Linuxcoin address</source>
<translation>Signa el missatge per provar que ets propietari d'aquesta adreça Linuxcoin</translation>
</message>
<message>
<source>Sign &Message</source>
<translation>Signa el &missatge</translation>
</message>
<message>
<source>Reset all sign message fields</source>
<translation>Neteja tots els camps de clau</translation>
</message>
<message>
<source>Clear &All</source>
<translation>Neteja-ho &tot</translation>
</message>
<message>
<source>&Verify Message</source>
<translation>&Verifica el missatge</translation>
</message>
<message>
<source>Enter the receiver's address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack. Note that this only proves the signing party receives with the address, it cannot prove sendership of any transaction!</source>
<translation>Introduïu l'adreça del receptor, el missatge (assegureu-vos de copiar els salts de línia, espais, tabuladors, etc. exactament) i signatura de sota per verificar el missatge. Tingueu cura de no llegir més en la signatura del que està al missatge signat, per evitar ser enganyat per un atac d'home-en-el-mig. Tingueu en compte que això només demostra que la part que signa rep amb l'adreça, i no es pot provar l'enviament de qualsevol transacció!</translation>
</message>
<message>
<source>The Linuxcoin address the message was signed with</source>
<translation>L'adreça Linuxcoin amb què va ser signat el missatge</translation>
</message>
<message>
<source>Verify the message to ensure it was signed with the specified Linuxcoin address</source>
<translation>Verificar el missatge per assegurar-se que ha estat signat amb una adreça Linuxcoin específica</translation>
</message>
<message>
<source>Verify &Message</source>
<translation>Verifica el &missatge</translation>
</message>
<message>
<source>Reset all verify message fields</source>
<translation>Neteja tots els camps de verificació de missatge</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<source>KB/s</source>
<translation>KB/s</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Status</source>
<translation>Estat</translation>
</message>
<message>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<source>Source</source>
<translation>Font</translation>
</message>
<message>
<source>Generated</source>
<translation>Generada</translation>
</message>
<message>
<source>From</source>
<translation>De</translation>
</message>
<message>
<source>unknown</source>
<translation>desconegut</translation>
</message>
<message>
<source>To</source>
<translation>A</translation>
</message>
<message>
<source>own address</source>
<translation>adreça pròpia</translation>
</message>
<message>
<source>Debit</source>
<translation>Dèbit</translation>
</message>
<message>
<source>Total debit</source>
<translation>Dèbit total</translation>
</message>
<message>
<source>Total credit</source>
<translation>Crèdit total</translation>
</message>
<message>
<source>Transaction fee</source>
<translation>Comissió de transacció</translation>
</message>
<message>
<source>Net amount</source>
<translation>Import net</translation>
</message>
<message>
<source>Message</source>
<translation>Missatge</translation>
</message>
<message>
<source>Comment</source>
<translation>Comentari</translation>
</message>
<message>
<source>Transaction ID</source>
<translation>ID de la transacció</translation>
</message>
<message>
<source>Amount</source>
<translation>Import</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation>Aquest panell mostra una descripció detallada de la transacció</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<source>Type</source>
<translation>Tipus</translation>
</message>
<message>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<source>Offline</source>
<translation>Fora de línia</translation>
</message>
<message>
<source>Unconfirmed</source>
<translation>Sense confirmar</translation>
</message>
<message>
<source>Abandoned</source>
<translation>Abandonada</translation>
</message>
<message>
<source>Received with</source>
<translation>Rebuda amb</translation>
</message>
<message>
<source>Received from</source>
<translation>Rebuda de</translation>
</message>
<message>
<source>Sent to</source>
<translation>Enviada a</translation>
</message>
<message>
<source>Payment to yourself</source>
<translation>Pagament a un mateix</translation>
</message>
<message>
<source>Mined</source>
<translation>Minada</translation>
</message>
<message>
<source>(no label)</source>
<translation>(sense etiqueta)</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>Received with</source>
<translation>Rebuda amb</translation>
</message>
<message>
<source>Sent to</source>
<translation>Enviada a</translation>
</message>
<message>
<source>Mined</source>
<translation>Minada</translation>
</message>
<message>
<source>Copy address</source>
<translation>Copia l'adreça</translation>
</message>
<message>
<source>Copy label</source>
<translation>Copia l'etiqueta</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Copia l'import</translation>
</message>
<message>
<source>Copy transaction ID</source>
<translation>Copia l'ID de transacció</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Fitxer separat per comes (*.csv)</translation>
</message>
<message>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<source>Type</source>
<translation>Tipus</translation>
</message>
<message>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<source>Address</source>
<translation>Adreça</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>L'exportació ha fallat</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
<message>
<source>Unit to show amounts in. Click to select another unit.</source>
<translation>Unitat en què mostrar els imports. Feu clic per seleccionar una altra unitat.</translation>
</message>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
</context>
<context>
<name>WalletView</name>
</context>
<context>
<name>bitcoin-core</name>
<message>
<source>Options:</source>
<translation>Opcions:</translation>
</message>
<message>
<source>Specify data directory</source>
<translation>Especifica el directori de dades</translation>
</message>
<message>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Connecta al node per obtenir les adreces de les connexions, i desconnecta</translation>
</message>
<message>
<source>Specify your own public address</source>
<translation>Especifiqueu la vostra adreça pública</translation>
</message>
<message>
<source>Accept command line and JSON-RPC commands</source>
<translation>Accepta la línia d'ordres i ordres JSON-RPC </translation>
</message>
<message>
<source>If <category> is not supplied or if <category> = 1, output all debugging information.</source>
<translation>Si no es proporciona <category> o si <category> = 1, treu a la sortida tota la informació de depuració.</translation>
</message>
<message>
<source>Prune configured below the minimum of %d MiB. Please use a higher number.</source>
<translation>Poda configurada per sota el mínim de %d MiB. Utilitzeu un nombre superior.</translation>
</message>
<message>
<source>Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)</source>
<translation>Poda: la darrera sincronització del moneder va més enllà de les dades podades. Cal que activeu -reindex (baixeu tota la cadena de blocs de nou en cas de node podat)</translation>
</message>
<message>
<source>Reduce storage requirements by pruning (deleting) old blocks. This mode is incompatible with -txindex and -rescan. Warning: Reverting this setting requires re-downloading the entire blockchain. (default: 0 = disable pruning blocks, >%u = target size in MiB to use for block files)</source>
<translation>Reduïu els requisits d'emmagatzematge podant (suprimint) els blocs antics. Aquest mode és incompatible amb -txindex i -rescan. Avís: la reversió d'aquest paràmetre implica haver de tornar a baixar la cadena de blocs sencera. (per defecte: 0 = inhabilita la poda de blocs, >%u = mida objectiu en MiB per utilitzar en els fitxers de blocs)</translation>
</message>
<message>
<source>Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.</source>
<translation>Els rescanejos no són possible en el mode de poda. Caldrà que utilitzeu -reindex, que tornarà a baixar la cadena de blocs sencera.</translation>
</message>
<message>
<source>Error: A fatal internal error occurred, see debug.log for details</source>
<translation>Error: s'ha produït un error intern fatal. Vegeu debug.log per a més detalls</translation>
</message>
<message>
<source>Fee (in %s/kB) to add to transactions you send (default: %s)</source>
<translation>Comissió (en %s/kB) per afegir a les transaccions que envieu (per defecte: %s)</translation>
</message>
<message>
<source>Pruning blockstore...</source>
<translation>S'està podant la cadena de blocs...</translation>
</message>
<message>
<source>Run in the background as a daemon and accept commands</source>
<translation>Executa en segon pla com a programa dimoni i accepta ordres</translation>
</message>
<message>
<source>Unable to start HTTP server. See debug log for details.</source>
<translation>No s'ha pogut iniciar el servidor HTTP. Vegeu debug.log per a més detalls.</translation>
</message>
<message>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Accepta connexions de fora (per defecte: 1 si no -proxy o -connect)</translation>
</message>
<message>
<source>Linuxcoin Core</source>
<translation>Linuxcoin Core</translation>
</message>
<message>
<source>-fallbackfee is set very high! This is the transaction fee you may pay when fee estimates are not available.</source>
<translation>-fallbackfee és molt elevat. Aquesta és la comissió de transacció que podeu pagar quan les estimacions de comissions no estan disponibles.</translation>
</message>
<message>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Vincula a una adreça específica i sempre escolta-hi. Utilitza la notació [host]:port per IPv6</translation>
</message>
<message>
<source>Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup</source>
<translation>Elimina totes les transaccions del moneder i només recupera aquelles de la cadena de blocs a través de -rescan a l'inici</translation>
</message>
<message>
<source>Distributed under the MIT software license, see the accompanying file COPYING or <http://www.opensource.org/licenses/mit-license.php>.</source>
<translation>Distribuït sota llicència de programari MIT. Vegeu el fitxer acompanyant COPYING o <http://www.opensource.org/licenses/mit-license.php>.</translation>
</message>
<message>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Executa una ordre quan una transacció del moneder canviï (%s en cmd es canvia per TxID)</translation>
</message>
<message>
<source>Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)</source>
<translation>Defineix el nombre de fils de verificació d'scripts (%u a %d, 0 = auto, <0 = deixa tants nuclis lliures, per defecte: %d)</translation>
</message>
<message>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>Aquesta és una versió de pre-llançament - utilitza-la sota la teva responsabilitat - No usar per a minería o aplicacions de compra-venda</translation>
</message>
<message>
<source>Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.</source>
<translation>Avís: la xarxa no sembla que hi estigui plenament d'acord. Alguns miners sembla que estan experimentant problemes.</translation>
</message>
<message>
<source>Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>Avís: sembla que no estem plenament d'acord amb els nostres iguals! Podria caler que actualitzar l'aplicació, o potser que ho facin altres nodes.</translation>
</message>
<message>
<source>Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.</source>
<translation>Afegeix a la llista blanca els iguals que es connecten de la màscara de xarxa o adreça IP donada. Es pot especificar moltes vegades.</translation>
</message>
<message>
<source><category> can be:</source>
<translation><category> pot ser:</translation>
</message>
<message>
<source>Block creation options:</source>
<translation>Opcions de la creació de blocs:</translation>
</message>
<message>
<source>Connect only to the specified node(s)</source>
<translation>Connecta només al(s) node(s) especificats</translation>
</message>
<message>
<source>Connection options:</source>
<translation>Opcions de connexió:</translation>
</message>
<message>
<source>Corrupted block database detected</source>
<translation>S'ha detectat una base de dades de blocs corrupta</translation>
</message>
<message>
<source>Debugging/Testing options:</source>
<translation>Opcions de depuració/proves:</translation>
</message>
<message>
<source>Do not load the wallet and disable wallet RPC calls</source>
<translation>No carreguis el moneder i inhabilita les crides RPC del moneder</translation>
</message>
<message>
<source>Do you want to rebuild the block database now?</source>
<translation>Voleu reconstruir la base de dades de blocs ara?</translation>
</message>
<message>
<source>Error initializing block database</source>
<translation>Error carregant la base de dades de blocs</translation>
</message>
<message>
<source>Error initializing wallet database environment %s!</source>
<translation>Error inicialitzant l'entorn de la base de dades del moneder %s!</translation>
</message>
<message>
<source>Error loading block database</source>
<translation>Error carregant la base de dades del bloc</translation>
</message>
<message>
<source>Error opening block database</source>
<translation>Error en obrir la base de dades de blocs</translation>
</message>
<message>
<source>Error: Disk space is low!</source>
<translation>Error: Espai al disc baix!</translation>
</message>
<message>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Ha fallat escoltar a qualsevol port. Feu servir -listen=0 si voleu fer això.</translation>
</message>
<message>
<source>Importing...</source>
<translation>S'està important...</translation>
</message>
<message>
<source>Incorrect or no genesis block found. Wrong datadir for network?</source>
<translation>No s'ha trobat el bloc de gènesi o és incorrecte. El directori de dades de la xarxa és incorrecte?</translation>
</message>
<message>
<source>Invalid -onion address: '%s'</source>
<translation>Adreça -onion no vàlida: '%s'</translation>
</message>
<message>
<source>Not enough file descriptors available.</source>
<translation>No hi ha suficient descriptors de fitxers disponibles.</translation>
</message>
<message>
<source>Only connect to nodes in network <net> (ipv4, ipv6 or onion)</source>
<translation>Només connecta als nodes de la xarxa <net> (ipv4, ipv6 o onion)</translation>
</message>
<message>
<source>Prune cannot be configured with a negative value.</source>
<translation>La poda no es pot configurar amb un valor negatiu.</translation>
</message>
<message>
<source>Prune mode is incompatible with -txindex.</source>
<translation>El mode de poda és incompatible amb -txindex.</translation>
</message>
<message>
<source>Set database cache size in megabytes (%d to %d, default: %d)</source>
<translation>Defineix la mida de la memòria cau de la base de dades en megabytes (%d a %d, per defecte: %d)</translation>
</message>
<message>
<source>Set maximum block size in bytes (default: %d)</source>
<translation>Defineix la mida màxim del bloc en bytes (per defecte: %d)</translation>
</message>
<message>
<source>Specify wallet file (within data directory)</source>
<translation>Especifica un fitxer de moneder (dins del directori de dades)</translation>
</message>
<message>
<source>Use UPnP to map the listening port (default: %u)</source>
<translation>Utilitza UPnP per a mapejar el port d'escolta (per defecte: %u)</translation>
</message>
<message>
<source>Verifying blocks...</source>
<translation>S'estan verificant els blocs...</translation>
</message>
<message>
<source>Verifying wallet...</source>
<translation>S'està verificant el moneder...</translation>
</message>
<message>
<source>Wallet %s resides outside data directory %s</source>
<translation>El moneder %s resideix fora del directori de dades %s</translation>
</message>
<message>
<source>Wallet options:</source>
<translation>Opcions de moneder:</translation>
</message>
<message>
<source>Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times</source>
<translation>Permet les connexions JSON-RPC d'una font específica. Vàlid per a <ip> són una IP individual (p. ex., 1.2.3.4), una xarxa / màscara de xarxa (p. ex., 1.2.3.4/255.255.255.0) o una xarxa/CIDR (p. ex., 1.2.3.4/24). Es pot especificar aquesta opció moltes vegades</translation>
</message>
<message>
<source>Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6</source>
<translation>Vincula l'adreça donada i posa a la llista blanca els iguals que s'hi connectin. Feu servir la notació [host]:port per a IPv6</translation>
</message>
<message>
<source>Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)</source>
<translation>Vincula a l'adreça donada per a escoltar les connexions JSON-RPC. Feu servir la notació [host]:port per a IPv6. Aquesta opció pot ser especificada moltes vegades (per defecte: vincula a totes les interfícies)</translation>
</message>
<message>
<source>Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)</source>
<translation>Crea fitxers nous amb els permisos per defecte del sistema, en comptes de l'umask 077 (només efectiu amb la funcionalitat de moneder inhabilitada)</translation>
</message>
<message>
<source>Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)</source>
<translation>Descobreix l'adreça IP pròpia (per defecte: 1 quan s'escolta i no -externalip o -proxy)</translation>
</message>
<message>
<source>Error: Listening for incoming connections failed (listen returned error %s)</source>
<translation>Error: ha fallat escoltar les connexions entrants (l'escoltament ha retornat l'error %s)</translation>
</message>
<message>
<source>Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)</source>
<translation>Executa l'ordre quan es rebi un avís rellevant o veiem una forquilla molt llarga (%s en cmd és reemplaçat per un missatge)</translation>
</message>
<message>
<source>If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)</source>
<translation>Si no s'especifica una paytxfee (comissió de transacció de pagament), inclogueu suficient comissió per tal que les transaccions comencin a confirmar-se en una mitja de n blocs (per defecte: %u)</translation>
</message>
<message>
<source>Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)</source>
<translation>Import no vàlid per a -maxtxfee=<amount>: '%s' (cal que sigui com a mínim la comissió de minrelay de %s per evitar que les comissions s'encallin)</translation>
</message>
<message>
<source>Maximum size of data in data carrier transactions we relay and mine (default: %u)</source>
<translation>Mida màxima de les dades en les transaccions de l'operador en què confiem i en les meves (per defecte: %u)</translation>
</message>
<message>
<source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source>
<translation>Consulta a adreces d'iguals a través de DNS, si es troba baix en adreces (per defecte: 1 a menys que -connect)</translation>
</message>
<message>
<source>Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)</source>
<translation>Genera a l'atzar credencials per a cada connexió proxy. Això habilita l'aïllament del flux de Tor (per defecte: %u)</translation>
</message>
<message>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: %d)</source>
<translation>Defineix la mida màxima de transaccions d'alta prioritat / baixa comissió en bytes (per defecte: %d)</translation>
</message>
<message>
<source>The transaction amount is too small to send after the fee has been deducted</source>
<translation>L'import de la transacció és massa petit per enviar-la després que se'n dedueixi la comissió</translation>
</message>
<message>
<source>This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.</source>
<translation>Aquest producte inclou programari desenvolupat pel projecte OpenSSL per a ús a l'OpenSSL Toolkit <https://www.openssl.org/> i programari criptogràfic escrit per Eric Young i programari UPnP escrit per Thomas Bernard.</translation>
</message>
<message>
<source>Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway</source>
<translation>Els iguals en la llista blanca no poden ser bandejats per DoS i es transmetran sempre llurs transaccions, fins i tot si ja són a la mempool. Això és útil, p. ex., per a una passarel·la</translation>
</message>
<message>
<source>You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain</source>
<translation>Cal que torneu a construir la base de dades fent servir -reindex per tornar al mode no podat. Això tornarà a baixar la cadena de blocs sencera</translation>
</message>
<message>
<source>(default: %u)</source>
<translation>(per defecte: %u)</translation>
</message>
<message>
<source>Accept public REST requests (default: %u)</source>
<translation>Accepta sol·licituds REST públiques (per defecte: %u)</translation>
</message>
<message>
<source>Connect through SOCKS5 proxy</source>
<translation>Connecta a través del proxy SOCKS5</translation>
</message>
<message>
<source>Error reading from database, shutting down.</source>
<translation>Error en llegir la base de dades, tancant.</translation>
</message>
<message>
<source>Information</source>
<translation>&Informació</translation>
</message>
<message>
<source>Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)</source>
<translation>Import no vàlid per a -paytxfee=<amount>: «%s» (ha de ser com a mínim %s)</translation>
</message>
<message>
<source>Invalid netmask specified in -whitelist: '%s'</source>
<translation>S'ha especificat una màscara de xarxa no vàlida a -whitelist: «%s»</translation>
</message>
<message>
<source>Keep at most <n> unconnectable transactions in memory (default: %u)</source>
<translation>Manté com a màxim <n> transaccions no connectables en memòria (per defecte: %u)</translation>
</message>
<message>
<source>Need to specify a port with -whitebind: '%s'</source>
<translation>Cal especificar un port amb -whitebind: «%s»</translation>
</message>
<message>
<source>Node relay options:</source>
<translation>Opcions de transmissió del node:</translation>
</message>
<message>
<source>RPC server options:</source>
<translation>Opcions del servidor RPC:</translation>
</message>
<message>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Envia informació de traça/depuració a la consola en comptes del fitxer debug.log</translation>
</message>
<message>
<source>Send transactions as zero-fee transactions if possible (default: %u)</source>
<translation>Envia les transaccions com a transaccions de comissió zero sempre que sigui possible (per defecte: %u) </translation>
</message>
<message>
<source>Show all debugging options (usage: --help -help-debug)</source>
<translation>Mostra totes les opcions de depuració (ús: --help --help-debug)</translation>
</message>
<message>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Redueix el fitxer debug.log durant l'inici del client (per defecte: 1 quan no -debug)</translation>
</message>
<message>
<source>Signing transaction failed</source>
<translation>Ha fallat la signatura de la transacció</translation>
</message>
<message>
<source>The transaction amount is too small to pay the fee</source>
<translation>L'import de la transacció és massa petit per pagar-ne una comissió</translation>
</message>
<message>
<source>This is experimental software.</source>
<translation>Això és programari experimental.</translation>
</message>
<message>
<source>Transaction amount too small</source>
<translation>Import de la transacció massa petit</translation>
</message>
<message>
<source>Transaction amounts must be positive</source>
<translation>Els imports de les transaccions han de ser positius</translation>
</message>
<message>
<source>Transaction too large for fee policy</source>
<translation>Transacció massa gran per a la política de comissions</translation>
</message>
<message>
<source>Transaction too large</source>
<translation>La transacció és massa gran</translation>
</message>
<message>
<source>Unable to bind to %s on this computer (bind returned error %s)</source>
<translation>No s'ha pogut vincular a %s en aquest ordinador (la vinculació ha retornat l'error %s)</translation>
</message>
<message>
<source>Username for JSON-RPC connections</source>
<translation>Nom d'usuari per a connexions JSON-RPC</translation>
</message>
<message>
<source>Warning</source>
<translation>Avís</translation>
</message>
<message>
<source>Zapping all transactions from wallet...</source>
<translation>Se suprimeixen totes les transaccions del moneder...</translation>
</message>
<message>
<source>Password for JSON-RPC connections</source>
<translation>Contrasenya per a connexions JSON-RPC</translation>
</message>
<message>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Executa l'ordre quan el millor bloc canviï (%s en cmd es reemplaça per un resum de bloc)</translation>
</message>
<message>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permet consultes DNS per a -addnode, -seednode i -connect</translation>
</message>
<message>
<source>Loading addresses...</source>
<translation>S'estan carregant les adreces...</translation>
</message>
<message>
<source>(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)</source>
<translation>(1 = manté les metadades de les tx, p. ex., propietari del compte i informació de sol·licitud del pagament, 2 = prescindeix de les metadades de les tx)</translation>
</message>
<message>
<source>How thorough the block verification of -checkblocks is (0-4, default: %u)</source>
<translation>Com d'exhaustiva és la verificació de blocs del -checkblocks (0-4, per defecte: %u)</translation>
</message>
<message>
<source>Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)</source>
<translation>Manté un índex complet de transaccions, utilitzat per la crida rpc getrawtransaction (per defecte: %u)</translation>
</message>
<message>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: %u)</source>
<translation>Nombre de segons necessaris perquè els iguals de comportament qüestionable puguin tornar a connectar-se (per defecte: %u)</translation>
</message>
<message>
<source>Output debugging information (default: %u, supplying <category> is optional)</source>
<translation>Informació de sortida de la depuració (per defecte: %u, proporcionar <category> és opcional)</translation>
</message>
<message>
<source>Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)</source>
<translation>Utilitza un proxy SOCKS4 apart per a arribar als iguals a través de serveis ocults de Tor (per defecte: %s)</translation>
</message>
<message>
<source>(default: %s)</source>
<translation>(per defecte: %s)</translation>
</message>
<message>
<source>Always query for peer addresses via DNS lookup (default: %u)</source>
<translation>Demana sempre les adreces dels iguals a través de consultes DNS (per defecte: %u)</translation>
</message>
<message>
<source>How many blocks to check at startup (default: %u, 0 = all)</source>
<translation>Quants blocs per comprovar a l'inici (per defecte: %u, 0 = tots)</translation>
</message>
<message>
<source>Include IP addresses in debug output (default: %u)</source>
<translation>Inclou l'adreça IP a la sortida de depuració (per defecte: %u)</translation>
</message>
<message>
<source>Invalid -proxy address: '%s'</source>
<translation>Adreça -proxy invalida: '%s'</translation>
</message>
<message>
<source>Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)</source>
<translation>Escolta les connexions JSON-RPC en <port> (per defecte: %u o testnet: %u)</translation>
</message>
<message>
<source>Listen for connections on <port> (default: %u or testnet: %u)</source>
<translation>Escolta les connexions en <port> (per defecte: %u o testnet: %u)</translation>
</message>
<message>
<source>Maintain at most <n> connections to peers (default: %u)</source>
<translation>Manté com a màxim <n> connexions a iguals (per defecte: %u)</translation>
</message>
<message>
<source>Make the wallet broadcast transactions</source>
<translation>Fes que el moneder faci difusió de les transaccions</translation>
</message>
<message>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)</source>
<translation>Memòria intermèdia màxima de recepció per connexió, <n>*1000 bytes (per defecte: %u)</translation>
</message>
<message>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: %u)</source>
<translation>Memòria intermèdia màxima d'enviament per connexió, <n>*1000 bytes (per defecte: %u)</translation>
</message>
<message>
<source>Prepend debug output with timestamp (default: %u)</source>
<translation>Posa davant de la sortida de depuració una marca horària (per defecte: %u)</translation>
</message>
<message>
<source>Relay and mine data carrier transactions (default: %u)</source>
<translation>Retransmet i mina les transaccions de l'operador (per defecte: %u)</translation>
</message>
<message>
<source>Relay non-P2SH multisig (default: %u)</source>
<translation>Retransmet multisig no P2SH (per defecte: %u)</translation>
</message>
<message>
<source>Set key pool size to <n> (default: %u)</source>
<translation>Defineix la mida clau disponible a <n> (per defecte: %u)</translation>
</message>
<message>
<source>Set the number of threads to service RPC calls (default: %d)</source>
<translation>Defineix el nombre de fils a crides de servei RPC (per defecte: %d)</translation>
</message>
<message>
<source>Specify configuration file (default: %s)</source>
<translation>Especifica el fitxer de configuració (per defecte: %s)</translation>
</message>
<message>
<source>Specify connection timeout in milliseconds (minimum: 1, default: %d)</source>
<translation>Especifica el temps d'espera de la connexió en milisegons (mínim: 1, per defecte: %d)</translation>
</message>
<message>
<source>Specify pid file (default: %s)</source>
<translation>Especifica el fitxer pid (per defecte: %s)</translation>
</message>
<message>
<source>Spend unconfirmed change when sending transactions (default: %u)</source>
<translation>Gasta el canvi no confirmat en enviar les transaccions (per defecte: %u)</translation>
</message>
<message>
<source>Threshold for disconnecting misbehaving peers (default: %u)</source>
<translation>Llindar per a desconnectar els iguals de comportament qüestionable (per defecte: %u)</translation>
</message>
<message>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Xarxa desconeguda especificada a -onlynet: '%s'</translation>
</message>
<message>
<source>Insufficient funds</source>
<translation>Balanç insuficient</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>S'està carregant l'índex de blocs...</translation>
</message>
<message>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Afegeix un node per a connectar-s'hi i intenta mantenir-hi la connexió oberta</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>S'està carregant el moneder...</translation>
</message>
<message>
<source>Cannot downgrade wallet</source>
<translation>No es pot reduir la versió del moneder</translation>
</message>
<message>
<source>Cannot write default address</source>
<translation>No es pot escriure l'adreça per defecte</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>S'està reescanejant...</translation>
</message>
<message>
<source>Done loading</source>
<translation>Ha acabat la càrrega</translation>
</message>
<message>
<source>Error</source>
<translation>Error</translation>
</message>
</context>
</TS>
| mit |
TonnyORG/ScioTest1 | generated-classes/Map/CommentTableMap.php | 17354 | <?php
namespace Map;
use \Comment;
use \CommentQuery;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\InstancePoolTrait;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\DataFetcher\DataFetcherInterface;
use Propel\Runtime\Exception\PropelException;
use Propel\Runtime\Map\RelationMap;
use Propel\Runtime\Map\TableMap;
use Propel\Runtime\Map\TableMapTrait;
/**
* This class defines the structure of the 'comments' table.
*
*
*
* This map class is used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
*/
class CommentTableMap extends TableMap
{
use InstancePoolTrait;
use TableMapTrait;
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = '.Map.CommentTableMap';
/**
* The default database name for this class
*/
const DATABASE_NAME = 'propel_scio1';
/**
* The table name for this class
*/
const TABLE_NAME = 'comments';
/**
* The related Propel class for this table
*/
const OM_CLASS = '\\Comment';
/**
* A class that can be returned by this tableMap
*/
const CLASS_DEFAULT = 'Comment';
/**
* The total number of columns
*/
const NUM_COLUMNS = 4;
/**
* The number of lazy-loaded columns
*/
const NUM_LAZY_LOAD_COLUMNS = 0;
/**
* The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS)
*/
const NUM_HYDRATE_COLUMNS = 4;
/**
* the column name for the COMMENT_ID field
*/
const COL_COMMENT_ID = 'comments.COMMENT_ID';
/**
* the column name for the USER_ID field
*/
const COL_USER_ID = 'comments.USER_ID';
/**
* the column name for the COMMENT field
*/
const COL_COMMENT = 'comments.COMMENT';
/**
* the column name for the CREATED_DATE field
*/
const COL_CREATED_DATE = 'comments.CREATED_DATE';
/**
* The default string format for model objects of the related table
*/
const DEFAULT_STRING_FORMAT = 'YAML';
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
protected static $fieldNames = array (
self::TYPE_PHPNAME => array('CommentId', 'UserId', 'Comment', 'CreatedDate', ),
self::TYPE_STUDLYPHPNAME => array('commentId', 'userId', 'comment', 'createdDate', ),
self::TYPE_COLNAME => array(CommentTableMap::COL_COMMENT_ID, CommentTableMap::COL_USER_ID, CommentTableMap::COL_COMMENT, CommentTableMap::COL_CREATED_DATE, ),
self::TYPE_RAW_COLNAME => array('COL_COMMENT_ID', 'COL_USER_ID', 'COL_COMMENT', 'COL_CREATED_DATE', ),
self::TYPE_FIELDNAME => array('comment_id', 'user_id', 'comment', 'created_date', ),
self::TYPE_NUM => array(0, 1, 2, 3, )
);
/**
* holds an array of keys for quick access to the fieldnames array
*
* first dimension keys are the type constants
* e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0
*/
protected static $fieldKeys = array (
self::TYPE_PHPNAME => array('CommentId' => 0, 'UserId' => 1, 'Comment' => 2, 'CreatedDate' => 3, ),
self::TYPE_STUDLYPHPNAME => array('commentId' => 0, 'userId' => 1, 'comment' => 2, 'createdDate' => 3, ),
self::TYPE_COLNAME => array(CommentTableMap::COL_COMMENT_ID => 0, CommentTableMap::COL_USER_ID => 1, CommentTableMap::COL_COMMENT => 2, CommentTableMap::COL_CREATED_DATE => 3, ),
self::TYPE_RAW_COLNAME => array('COL_COMMENT_ID' => 0, 'COL_USER_ID' => 1, 'COL_COMMENT' => 2, 'COL_CREATED_DATE' => 3, ),
self::TYPE_FIELDNAME => array('comment_id' => 0, 'user_id' => 1, 'comment' => 2, 'created_date' => 3, ),
self::TYPE_NUM => array(0, 1, 2, 3, )
);
/**
* Initialize the table attributes and columns
* Relations are not initialized by this method since they are lazy loaded
*
* @return void
* @throws PropelException
*/
public function initialize()
{
// attributes
$this->setName('comments');
$this->setPhpName('Comment');
$this->setClassName('\\Comment');
$this->setPackage('');
$this->setUseIdGenerator(true);
// columns
$this->addPrimaryKey('COMMENT_ID', 'CommentId', 'INTEGER', true, null, null);
$this->addForeignKey('USER_ID', 'UserId', 'INTEGER', 'users', 'USER_ID', true, null, null);
$this->addColumn('COMMENT', 'Comment', 'VARCHAR', true, 255, null);
$this->addColumn('CREATED_DATE', 'CreatedDate', 'TIMESTAMP', true, null, null);
} // initialize()
/**
* Build the RelationMap objects for this table relationships
*/
public function buildRelations()
{
$this->addRelation('User', '\\User', RelationMap::MANY_TO_ONE, array('user_id' => 'user_id', ), 'CASCADE', null);
} // buildRelations()
/**
* Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table.
*
* For tables with a single-column primary key, that simple pkey value will be returned. For tables with
* a multi-column primary key, a serialize()d version of the primary key will be returned.
*
* @param array $row resultset row.
* @param int $offset The 0-based offset for reading from the resultset row.
* @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME
* TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM
*
* @return string The primary key hash of the row
*/
public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM)
{
// If the PK cannot be derived from the row, return NULL.
if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('CommentId', TableMap::TYPE_PHPNAME, $indexType)] === null) {
return null;
}
return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('CommentId', TableMap::TYPE_PHPNAME, $indexType)];
}
/**
* Retrieves the primary key from the DB resultset row
* For tables with a single-column primary key, that simple pkey value will be returned. For tables with
* a multi-column primary key, an array of the primary key columns will be returned.
*
* @param array $row resultset row.
* @param int $offset The 0-based offset for reading from the resultset row.
* @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME
* TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM
*
* @return mixed The primary key of the row
*/
public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM)
{
return (int) $row[
$indexType == TableMap::TYPE_NUM
? 0 + $offset
: self::translateFieldName('CommentId', TableMap::TYPE_PHPNAME, $indexType)
];
}
/**
* The class that the tableMap will make instances of.
*
* If $withPrefix is true, the returned path
* uses a dot-path notation which is translated into a path
* relative to a location on the PHP include_path.
* (e.g. path.to.MyClass -> 'path/to/MyClass.php')
*
* @param boolean $withPrefix Whether or not to return the path with the class name
* @return string path.to.ClassName
*/
public static function getOMClass($withPrefix = true)
{
return $withPrefix ? CommentTableMap::CLASS_DEFAULT : CommentTableMap::OM_CLASS;
}
/**
* Populates an object of the default type or an object that inherit from the default.
*
* @param array $row row returned by DataFetcher->fetch().
* @param int $offset The 0-based offset for reading from the resultset row.
* @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType().
One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME
* TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM.
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return array (Comment object, last column rank)
*/
public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM)
{
$key = CommentTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType);
if (null !== ($obj = CommentTableMap::getInstanceFromPool($key))) {
// We no longer rehydrate the object, since this can cause data loss.
// See http://www.propelorm.org/ticket/509
// $obj->hydrate($row, $offset, true); // rehydrate
$col = $offset + CommentTableMap::NUM_HYDRATE_COLUMNS;
} else {
$cls = CommentTableMap::OM_CLASS;
/** @var Comment $obj */
$obj = new $cls();
$col = $obj->hydrate($row, $offset, false, $indexType);
CommentTableMap::addInstanceToPool($obj, $key);
}
return array($obj, $col);
}
/**
* The returned array will contain objects of the default type or
* objects that inherit from the default.
*
* @param DataFetcherInterface $dataFetcher
* @return array
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function populateObjects(DataFetcherInterface $dataFetcher)
{
$results = array();
// set the class once to avoid overhead in the loop
$cls = static::getOMClass(false);
// populate the object(s)
while ($row = $dataFetcher->fetch()) {
$key = CommentTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType());
if (null !== ($obj = CommentTableMap::getInstanceFromPool($key))) {
// We no longer rehydrate the object, since this can cause data loss.
// See http://www.propelorm.org/ticket/509
// $obj->hydrate($row, 0, true); // rehydrate
$results[] = $obj;
} else {
/** @var Comment $obj */
$obj = new $cls();
$obj->hydrate($row);
$results[] = $obj;
CommentTableMap::addInstanceToPool($obj, $key);
} // if key exists
}
return $results;
}
/**
* Add all the columns needed to create a new object.
*
* Note: any columns that were marked with lazyLoad="true" in the
* XML schema will not be added to the select list and only loaded
* on demand.
*
* @param Criteria $criteria object containing the columns to add.
* @param string $alias optional table alias
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function addSelectColumns(Criteria $criteria, $alias = null)
{
if (null === $alias) {
$criteria->addSelectColumn(CommentTableMap::COL_COMMENT_ID);
$criteria->addSelectColumn(CommentTableMap::COL_USER_ID);
$criteria->addSelectColumn(CommentTableMap::COL_COMMENT);
$criteria->addSelectColumn(CommentTableMap::COL_CREATED_DATE);
} else {
$criteria->addSelectColumn($alias . '.COMMENT_ID');
$criteria->addSelectColumn($alias . '.USER_ID');
$criteria->addSelectColumn($alias . '.COMMENT');
$criteria->addSelectColumn($alias . '.CREATED_DATE');
}
}
/**
* Returns the TableMap related to this object.
* This method is not needed for general use but a specific application could have a need.
* @return TableMap
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getTableMap()
{
return Propel::getServiceContainer()->getDatabaseMap(CommentTableMap::DATABASE_NAME)->getTable(CommentTableMap::TABLE_NAME);
}
/**
* Add a TableMap instance to the database for this tableMap class.
*/
public static function buildTableMap()
{
$dbMap = Propel::getServiceContainer()->getDatabaseMap(CommentTableMap::DATABASE_NAME);
if (!$dbMap->hasTable(CommentTableMap::TABLE_NAME)) {
$dbMap->addTableObject(new CommentTableMap());
}
}
/**
* Performs a DELETE on the database, given a Comment or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or Comment object or primary key or array of primary keys
* which is used to create the DELETE statement
* @param ConnectionInterface $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
* if supported by native driver or if emulated using Propel.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doDelete($values, ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getWriteConnection(CommentTableMap::DATABASE_NAME);
}
if ($values instanceof Criteria) {
// rename for clarity
$criteria = $values;
} elseif ($values instanceof \Comment) { // it's a model object
// create criteria based on pk values
$criteria = $values->buildPkeyCriteria();
} else { // it's a primary key, or an array of pks
$criteria = new Criteria(CommentTableMap::DATABASE_NAME);
$criteria->add(CommentTableMap::COL_COMMENT_ID, (array) $values, Criteria::IN);
}
$query = CommentQuery::create()->mergeWith($criteria);
if ($values instanceof Criteria) {
CommentTableMap::clearInstancePool();
} elseif (!is_object($values)) { // it's a primary key, or an array of pks
foreach ((array) $values as $singleval) {
CommentTableMap::removeInstanceFromPool($singleval);
}
}
return $query->delete($con);
}
/**
* Deletes all rows from the comments table.
*
* @param ConnectionInterface $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver).
*/
public static function doDeleteAll(ConnectionInterface $con = null)
{
return CommentQuery::create()->doDeleteAll($con);
}
/**
* Performs an INSERT on the database, given a Comment or Criteria object.
*
* @param mixed $criteria Criteria or Comment object containing data that is used to create the INSERT statement.
* @param ConnectionInterface $con the ConnectionInterface connection to use
* @return mixed The new primary key.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doInsert($criteria, ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getWriteConnection(CommentTableMap::DATABASE_NAME);
}
if ($criteria instanceof Criteria) {
$criteria = clone $criteria; // rename for clarity
} else {
$criteria = $criteria->buildCriteria(); // build Criteria from Comment object
}
if ($criteria->containsKey(CommentTableMap::COL_COMMENT_ID) && $criteria->keyContainsValue(CommentTableMap::COL_COMMENT_ID) ) {
throw new PropelException('Cannot insert a value for auto-increment primary key ('.CommentTableMap::COL_COMMENT_ID.')');
}
// Set the correct dbName
$query = CommentQuery::create()->mergeWith($criteria);
// use transaction because $criteria could contain info
// for more than one table (I guess, conceivably)
return $con->transaction(function () use ($con, $query) {
return $query->doInsert($con);
});
}
} // CommentTableMap
// This is the static code needed to register the TableMap for this table with the main Propel class.
//
CommentTableMap::buildTableMap();
| mit |
jkogler/StratCon | app/scripts/board.js | 3365 | // Strategic Conquest
// board.js
// J Kogler
// 10/10/14
//
function Board(t, c, u) {
this.terrain = t;
this.cityManager = c;
this.unitManager = u;
// a class to manage drag movement.
this.dragManager = new DragManager();
}
Board.prototype.draw = function () {
// draw the terrain
var display = document.getElementById('display');
$('#game-board').html(this.renderTerrain(this.terrain));
};
Board.prototype.makeTile = function (x, y) {
var self = this;
var c = this.cityManager;
var t = this.terrain;
var u = this.unitManager;
var units = u.getUnits(x, y);
var span = $('<img>');
// show cities as first priority -- we need to annotate these with a number of units in it
var city = c.isCity(x, y);
if (city) {
if (city.force === SCTypes.forceType.neutral) {
span.attr('src', './images/city.png');
} else if (city.force === SCTypes.forceType.red) {
span.attr('src', './images/city-red.png');
} else {
span.attr('src', './images/city-blue.png');
}
}
// If there are units, lets show the units first.
else if (units.length > 0) {
var u1 = units[0];
if (u1.force === SCTypes.forceType.red) {
span.attr('src', './images/tank-red.png');
} else if (u1.force === SCTypes.forceType.blue) {
span.attr('src', './images/tank-blue.png');
}
}
// Show the terrain if here is nothing here.
else if (t.isGround(x, y)) {
span.attr('src', './images/grass.png');
} else {
span.attr('src', './images/water.png');
}
span.addClass('game-tile');
span.data('x', x);
span.data('y', y);
span.draggable({
start: function(event, ui){console.log('start');},
stop: function(event, ui){console.log('stop')}
});
// On Dbl click if its a city open up a production dialog
span.on('dblclick',
function () {
var x = $(this).data('x');
var y = $(this).data('y');
var city = c.isCity(x, y);
if (city) {
city.productionDialog();
}
});
// on Click if its not a city, give info on it in the console.
span.on('click',
function () {
var x = $(this).data('x');
var y = $(this).data('y');
var s = '[' + x + ',' + y + '] ';
if (t.isGround(x, y)) {
s += 'Ground ';
} else {
s += 'Water ';
}
var city = c.isCity(x, y);
if (city) {
s += ' with city (force = ' + city.force + '; production = '
+ city.productionType + ' with '
+ city.daysRemaining + ' days left until next unit is ready)';
}
console.log(s);
var ulist = u.getUnits(x, y);
for (var i in ulist) {
var unit = ulist[i];
console.log('\t Unit force=' + unit.force + ' type=' + unit.type + ' strength=' + unit.strength
+ ' dest=[' + unit.destX + ',' + unit.destY + ']');
}
});
return span;
};
Board.prototype.renderTerrain = function () {
var t = this.terrain;
// render a single tile.
var container = $('<div id=\'impl\'>');
for (var y = 0; y < t.size; y++) {
var row = $('<div>').appendTo(container);
row.addClass('game-row');
for (var x = 0; x < t.size; x++) {
this.makeTile(x, y).appendTo(row);
}
var br = $('<br>').appendTo(row);
}
return container;
} | mit |
KingOfDog/MATH | src/handlers/SettingsHandler.java | 6787 | package handlers;
import java.io.IOException;
import com.jfoenix.controls.JFXCheckBox;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXSlider;
import com.jfoenix.controls.JFXSnackbar;
import com.jfoenix.controls.JFXTextField;
//import com.sun.org.apache.xpath.internal.operations.Bool;
import initializers.InitSettings;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import properties.BooleanProperty;
import properties.IntegerProperty;
import properties.Property;
import resources.lang.Locales;
import settings.Settings;
import resources.lang.Language;
public class SettingsHandler {
private static Scene scene;
private static Node exerciseContainer;
private static Node mainContainer;
private static Settings settings = Settings.getInstance();
public static void setDefault(Scene scene) {
SettingsHandler.scene = scene;
SettingsHandler.exerciseContainer = ((ScrollPane) scene.lookup("#exerciseContainer")).getContent();
SettingsHandler.mainContainer = ((ScrollPane) scene.lookup("#mainContainer")).getContent();
// Replace the checkboxes' values with the values from the settings file
for (BooleanProperty p : settings.booleanSettings) {
try {
((JFXCheckBox) lookupProperty(p)).setSelected(p.getValue());
} catch (NullPointerException e) {
System.err.println("Could not find a Checkbox with the id:" + p.getName() + " Could not set the Checkbox to the value:" + p.getValue());
} catch (ClassCastException e) {
System.err.println("Could not cast the Node with the id:" + p.getName() + " to a Checkbox. The value:" + p.getValue() + " was not set!");
}
}
// Replace the text fields' values with the values from the settings file
for (IntegerProperty p : settings.integerSettings) {
try {
((JFXTextField) lookupProperty(p)).setText(String.valueOf(p.getValue()));
} catch (NullPointerException e) {
System.err.println("Could not find a TextField with the id:" + p.getName() + ". The value:" + p.getValue() + " was not set!");
} catch (ClassCastException e) {
System.err.println("Could not cast the Node with the id:" + p.getName() + " to a TextField. The value:" + p.getValue() + " was not set!");
}
}
// Replace the sliders' values with the values from the settings file
for(IntegerProperty p : settings.sliderSettings) {
try {
((JFXSlider) lookupProperty(p)).setValue(p.getValue());
} catch (NullPointerException e) {
System.err.println("Could not find a Slider with the id:" + p.getName() + ". The value:" + p.getValue() + " was not set!");
} catch (ClassCastException e) {
System.err.println("Could not cast the Node with the id:" + p.getName() + " to a Slider. The value:" + p.getValue() + " was not set!");
}
}
// Label difficulty = (Label) scene.lookup("#difficulty");
// difficulty.setText(String.valueOf(Difficulty.getDifficulty()));
@SuppressWarnings("unchecked")
JFXComboBox<Label> language = (JFXComboBox<Label>) mainContainer.lookup("#language");
// Add all available languages the the combo box
language.getItems().add(new Label(Locales.ENGLISH.getName()));
language.getItems().add(new Label(Locales.GERMAN.getName()));
language.getItems().add(new Label(Locales.FRENCH.getName()));
language.getItems().add(new Label(Locales.CHINESE.getName()));
language.getItems().add(new Label(Locales.RUSSIAN.getName()));
language.getItems().add(new Label(Locales.SPAIN.getName()));
// Select the current language
if (settings.lang.getValue().equals(Locales.ENGLISH.getLocale())) language.getSelectionModel().select(0);
else if (settings.lang.getValue().equals(Locales.GERMAN.getLocale())) language.getSelectionModel().select(1);
else if (settings.lang.getValue().equals(Locales.FRENCH.getLocale())) language.getSelectionModel().select(2);
else if (settings.lang.getValue().equals(Locales.CHINESE.getLocale())) language.getSelectionModel().select(3);
else if (settings.lang.getValue().equals(Locales.RUSSIAN.getLocale())) language.getSelectionModel().select(4);
else if (settings.lang.getValue().equals(Locales.SPAIN.getLocale())) language.getSelectionModel().select(5);
else language.getSelectionModel().select(0);
}
@FXML
public static void updateAndSave(Scene scene, StackPane sp, Stage stage) {
update(scene);
FileHandler.writeSettings();
JFXSnackbar notify = new JFXSnackbar(sp);
notify.show(Language.get("settings.saved"), 5000);
SettingsHandler.setDefault(scene);
}
public static void update(Scene scene) {
for(BooleanProperty p : settings.booleanSettings) {
p.setValue(((JFXCheckBox) lookupProperty(p)).isSelected());
}
for(IntegerProperty p : settings.integerSettings) {
p.setValue(Integer.parseInt(((JFXTextField) lookupProperty(p)).getText()));
}
for(IntegerProperty p : settings.sliderSettings) {
p.setValue((int) ((JFXSlider) lookupProperty(p)).getValue());
}
@SuppressWarnings("unchecked")
String language = ((Label) ((JFXComboBox<Label>) scene.lookup("#language")).getSelectionModel().getSelectedItem()).getText();
if(language.equals(Locales.ENGLISH.getName())) {
settings.lang.setValue(Locales.ENGLISH.getLocale());
} else if(language.equals(Locales.GERMAN.getName())) {
settings.lang.setValue(Locales.GERMAN.getLocale());
} else if(language.equals(Locales.FRENCH.getName())) {
settings.lang.setValue(Locales.FRENCH.getLocale());
} else if(language.equals(Locales.CHINESE.getName())) {
settings.lang.setValue(Locales.CHINESE.getLocale());
} else if(language.equals(Locales.RUSSIAN.getName())) {
settings.lang.setValue(Locales.RUSSIAN.getLocale());
} else if(language.equals(Locales.SPAIN.getName())) {
settings.lang.setValue(Locales.SPAIN.getLocale());
} else {
settings.lang.setValue(Locales.ENGLISH.getLocale());
}
}
private static Node lookupProperty(Property prop) {
Node n = scene.lookup("#" + prop.getName());
if (n == null) {
n = mainContainer.lookup("#" + prop.getName());
if (n == null) {
n = exerciseContainer.lookup("#" + prop.getName());
}
}
return n;
}
}
| mit |
IgorFachini/Angular-Test | Angular4x/my-app/src/app/app.module.ts | 392 | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ModalComponent } from './modal/modal.component';
@NgModule({
declarations: [
AppComponent,
ModalComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
| mit |
ronnyp07/eLap | public/ciudad/services/ciudad.client.services.js | 1019 | 'use strict';
// Crear el service 'patients'
angular.module('ciudad')
.factory('Ciudad', ['$resource', function($resource) {
// Usar el service '$resource' para devolver un objeto '$resource' Patients
return $resource('api/ciudad/:ciudadId', {
ciudadId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}])
.factory('Notify', ['$rootScope', function($rootScope) {
var notify = {};
notify.msg = '';
notify.sendbroadCast = function(mgs){
this.msg = mgs;
this.broadCast(mgs);
console.log(this.mgs);
}
notify.broadCast = function(msg){
$rootScope.$broadcast('noError', msg);
}
notify.sendMsg = function(msg, data){
data = data || {};
$rootScope.$emit(msg, data);
}
notify.getMsg = function(msg, func, scope){
var unbind = $rootScope.$on(msg, func);
if(scope){
scope.$on('destroy', unbind);
}
};
return notify;
// Usar el service '$resource' para devolver un objeto '$resource' Patients
}])
| mit |
davidmogar/quizzer-php | quizzer/domain/Grade.php | 527 | <?php
class Grade
{
private $studentId;
private $grade;
function __construct($studentId, $grade)
{
$this->grade = $grade;
$this->studentId = $studentId;
}
public function getGrade()
{
return $this->grade;
}
public function setGrade($grade)
{
$this->grade = $grade;
}
public function getStudentId()
{
return $this->studentId;
}
public function setStudentId($studentId)
{
$this->studentId = $studentId;
}
} | mit |
Diorite/Diorite | diorite-utils/config/src/main/java/org/diorite/config/serialization/snakeyaml/IteratorWrapper.java | 1600 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016. Diorite (by Bartłomiej Mazur (aka GotoFinal))
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.diorite.config.serialization.snakeyaml;
import java.util.Iterator;
final class IteratorWrapper implements Iterable<Object>
{
private Iterator<Object> iterator;
@SuppressWarnings("unchecked")
IteratorWrapper(Iterator<?> iterator)
{
this.iterator = (Iterator<Object>) iterator;
}
@Override
public Iterator<Object> iterator()
{
return this.iterator;
}
}
| mit |
zhujun1980/fcache | fcache/time_utils.cc | 354 | //
// time_utils.cc
// BloomFilter
//
// Created by zhu jun on 14-8-20.
// Copyright (c) 2014年 Weibo. All rights reserved.
//
#include "time_utils.h"
double Now() {
struct timeval tp = {0};
if (!gettimeofday(&tp, NULL)) {
return (double)(tp.tv_sec + tp.tv_usec / 1000000.00);;
} else {
return (double)time(0);
}
}
| mit |
viktorkh/elastickit_express | node_modules/searchkit/lib/src/__test__/core/query/query_dsl/compound/FilteredQuerySpec.js | 401 | "use strict";
var _1 = require("../../../../../");
it("FilteredQuery", function () {
var filtered = {
filter: {
term: { color: "red" }
},
query: {
match: {
keywords: "sky"
}
}
};
expect(_1.FilteredQuery(filtered))
.toEqual({ filtered: filtered });
});
//# sourceMappingURL=FilteredQuerySpec.js.map | mit |
huailiang/GameEngineen | Assets/uLua/Source/LuaWrap/UIAtlasWrap.cs | 9820 | using System;
using UnityEngine;
using System.Collections.Generic;
using LuaInterface;
using Object = UnityEngine.Object;
public class UIAtlasWrap
{
public static void Register(IntPtr L)
{
LuaMethod[] regs = new LuaMethod[]
{
new LuaMethod("GetSprite", GetSprite),
new LuaMethod("GetRandomSprite", GetRandomSprite),
new LuaMethod("MarkSpriteListAsChanged", MarkSpriteListAsChanged),
new LuaMethod("SortAlphabetically", SortAlphabetically),
new LuaMethod("GetListOfSprites", GetListOfSprites),
new LuaMethod("CheckIfRelated", CheckIfRelated),
new LuaMethod("MarkAsChanged", MarkAsChanged),
new LuaMethod("New", _CreateUIAtlas),
new LuaMethod("GetClassType", GetClassType),
new LuaMethod("__eq", Lua_Eq),
};
LuaField[] fields = new LuaField[]
{
new LuaField("spriteMaterial", get_spriteMaterial, set_spriteMaterial),
new LuaField("premultipliedAlpha", get_premultipliedAlpha, null),
new LuaField("spriteList", get_spriteList, set_spriteList),
new LuaField("texture", get_texture, null),
new LuaField("pixelSize", get_pixelSize, set_pixelSize),
new LuaField("replacement", get_replacement, set_replacement),
};
LuaScriptMgr.RegisterLib(L, "UIAtlas", typeof(UIAtlas), regs, fields, typeof(MonoBehaviour));
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _CreateUIAtlas(IntPtr L)
{
LuaDLL.luaL_error(L, "UIAtlas class does not have a constructor function");
return 0;
}
static Type classType = typeof(UIAtlas);
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetClassType(IntPtr L)
{
LuaScriptMgr.Push(L, classType);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_spriteMaterial(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
UIAtlas obj = (UIAtlas)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name spriteMaterial");
}
else
{
LuaDLL.luaL_error(L, "attempt to index spriteMaterial on a nil value");
}
}
LuaScriptMgr.Push(L, obj.spriteMaterial);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_premultipliedAlpha(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
UIAtlas obj = (UIAtlas)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name premultipliedAlpha");
}
else
{
LuaDLL.luaL_error(L, "attempt to index premultipliedAlpha on a nil value");
}
}
LuaScriptMgr.Push(L, obj.premultipliedAlpha);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_spriteList(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
UIAtlas obj = (UIAtlas)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name spriteList");
}
else
{
LuaDLL.luaL_error(L, "attempt to index spriteList on a nil value");
}
}
LuaScriptMgr.PushObject(L, obj.spriteList);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_texture(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
UIAtlas obj = (UIAtlas)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name texture");
}
else
{
LuaDLL.luaL_error(L, "attempt to index texture on a nil value");
}
}
LuaScriptMgr.Push(L, obj.texture);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_pixelSize(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
UIAtlas obj = (UIAtlas)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name pixelSize");
}
else
{
LuaDLL.luaL_error(L, "attempt to index pixelSize on a nil value");
}
}
LuaScriptMgr.Push(L, obj.pixelSize);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int get_replacement(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
UIAtlas obj = (UIAtlas)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name replacement");
}
else
{
LuaDLL.luaL_error(L, "attempt to index replacement on a nil value");
}
}
LuaScriptMgr.Push(L, obj.replacement);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_spriteMaterial(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
UIAtlas obj = (UIAtlas)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name spriteMaterial");
}
else
{
LuaDLL.luaL_error(L, "attempt to index spriteMaterial on a nil value");
}
}
obj.spriteMaterial = (Material)LuaScriptMgr.GetUnityObject(L, 3, typeof(Material));
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_spriteList(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
UIAtlas obj = (UIAtlas)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name spriteList");
}
else
{
LuaDLL.luaL_error(L, "attempt to index spriteList on a nil value");
}
}
obj.spriteList = (List<UISpriteData>)LuaScriptMgr.GetNetObject(L, 3, typeof(List<UISpriteData>));
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_pixelSize(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
UIAtlas obj = (UIAtlas)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name pixelSize");
}
else
{
LuaDLL.luaL_error(L, "attempt to index pixelSize on a nil value");
}
}
obj.pixelSize = (float)LuaScriptMgr.GetNumber(L, 3);
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int set_replacement(IntPtr L)
{
object o = LuaScriptMgr.GetLuaObject(L, 1);
UIAtlas obj = (UIAtlas)o;
if (obj == null)
{
LuaTypes types = LuaDLL.lua_type(L, 1);
if (types == LuaTypes.LUA_TTABLE)
{
LuaDLL.luaL_error(L, "unknown member name replacement");
}
else
{
LuaDLL.luaL_error(L, "attempt to index replacement on a nil value");
}
}
obj.replacement = (UIAtlas)LuaScriptMgr.GetUnityObject(L, 3, typeof(UIAtlas));
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetSprite(IntPtr L)
{
LuaScriptMgr.CheckArgsCount(L, 2);
UIAtlas obj = (UIAtlas)LuaScriptMgr.GetUnityObjectSelf(L, 1, "UIAtlas");
string arg0 = LuaScriptMgr.GetLuaString(L, 2);
UISpriteData o = obj.GetSprite(arg0);
LuaScriptMgr.PushObject(L, o);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetRandomSprite(IntPtr L)
{
LuaScriptMgr.CheckArgsCount(L, 2);
UIAtlas obj = (UIAtlas)LuaScriptMgr.GetUnityObjectSelf(L, 1, "UIAtlas");
string arg0 = LuaScriptMgr.GetLuaString(L, 2);
string o = obj.GetRandomSprite(arg0);
LuaScriptMgr.Push(L, o);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int MarkSpriteListAsChanged(IntPtr L)
{
LuaScriptMgr.CheckArgsCount(L, 1);
UIAtlas obj = (UIAtlas)LuaScriptMgr.GetUnityObjectSelf(L, 1, "UIAtlas");
obj.MarkSpriteListAsChanged();
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int SortAlphabetically(IntPtr L)
{
LuaScriptMgr.CheckArgsCount(L, 1);
UIAtlas obj = (UIAtlas)LuaScriptMgr.GetUnityObjectSelf(L, 1, "UIAtlas");
obj.SortAlphabetically();
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int GetListOfSprites(IntPtr L)
{
int count = LuaDLL.lua_gettop(L);
if (count == 1)
{
UIAtlas obj = (UIAtlas)LuaScriptMgr.GetUnityObjectSelf(L, 1, "UIAtlas");
BetterList<string> o = obj.GetListOfSprites();
LuaScriptMgr.PushObject(L, o);
return 1;
}
else if (count == 2)
{
UIAtlas obj = (UIAtlas)LuaScriptMgr.GetUnityObjectSelf(L, 1, "UIAtlas");
string arg0 = LuaScriptMgr.GetLuaString(L, 2);
BetterList<string> o = obj.GetListOfSprites(arg0);
LuaScriptMgr.PushObject(L, o);
return 1;
}
else
{
LuaDLL.luaL_error(L, "invalid arguments to method: UIAtlas.GetListOfSprites");
}
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int CheckIfRelated(IntPtr L)
{
LuaScriptMgr.CheckArgsCount(L, 2);
UIAtlas arg0 = (UIAtlas)LuaScriptMgr.GetUnityObject(L, 1, typeof(UIAtlas));
UIAtlas arg1 = (UIAtlas)LuaScriptMgr.GetUnityObject(L, 2, typeof(UIAtlas));
bool o = UIAtlas.CheckIfRelated(arg0,arg1);
LuaScriptMgr.Push(L, o);
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int MarkAsChanged(IntPtr L)
{
LuaScriptMgr.CheckArgsCount(L, 1);
UIAtlas obj = (UIAtlas)LuaScriptMgr.GetUnityObjectSelf(L, 1, "UIAtlas");
obj.MarkAsChanged();
return 0;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int Lua_Eq(IntPtr L)
{
LuaScriptMgr.CheckArgsCount(L, 2);
Object arg0 = LuaScriptMgr.GetLuaObject(L, 1) as Object;
Object arg1 = LuaScriptMgr.GetLuaObject(L, 2) as Object;
bool o = arg0 == arg1;
LuaScriptMgr.Push(L, o);
return 1;
}
}
| mit |
mtils/php-ems | src/Ems/Contracts/Core/InputCaster.php | 693 | <?php
namespace Ems\Contracts\Core;
/**
* Interface InputCaster
*
* @deprecated Use \Ems\Contracts\Foundation\InputNormalizer or InputProcessor
* @package Ems\Contracts\Core
*/
interface InputCaster extends NamedCallableChain
{
/**
* After the input data is validated perform this method to cast the
* data for use in your repositories/model/database. Here you would
* remove _confirmation fields.
*
* @param array $input
* @param array $metadata (optional)
* @param string $resourceName (optional)
*
* @return array The corrected data
**/
public function cast(array $input, array $metadata = [], $resourceName = null);
}
| mit |
hoovercj/vscode | src/vs/platform/markers/common/markerService.ts | 9253 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { isFalsyOrEmpty, isNonEmptyArray } from 'vs/base/common/arrays';
import { Schemas } from 'vs/base/common/network';
import { IDisposable } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { Event, Emitter } from 'vs/base/common/event';
import { IMarkerService, IMarkerData, IResourceMarker, IMarker, MarkerStatistics, MarkerSeverity } from './markers';
import { ResourceMap } from 'vs/base/common/map';
import { Iterable } from 'vs/base/common/iterator';
class DoubleResourceMap<V>{
private _byResource = new ResourceMap<Map<string, V>>();
private _byOwner = new Map<string, ResourceMap<V>>();
set(resource: URI, owner: string, value: V) {
let ownerMap = this._byResource.get(resource);
if (!ownerMap) {
ownerMap = new Map();
this._byResource.set(resource, ownerMap);
}
ownerMap.set(owner, value);
let resourceMap = this._byOwner.get(owner);
if (!resourceMap) {
resourceMap = new ResourceMap();
this._byOwner.set(owner, resourceMap);
}
resourceMap.set(resource, value);
}
get(resource: URI, owner: string): V | undefined {
let ownerMap = this._byResource.get(resource);
return ownerMap?.get(owner);
}
delete(resource: URI, owner: string): boolean {
let removedA = false;
let removedB = false;
let ownerMap = this._byResource.get(resource);
if (ownerMap) {
removedA = ownerMap.delete(owner);
}
let resourceMap = this._byOwner.get(owner);
if (resourceMap) {
removedB = resourceMap.delete(resource);
}
if (removedA !== removedB) {
throw new Error('illegal state');
}
return removedA && removedB;
}
values(key?: URI | string): Iterable<V> {
if (typeof key === 'string') {
return this._byOwner.get(key)?.values() ?? Iterable.empty();
}
if (URI.isUri(key)) {
return this._byResource.get(key)?.values() ?? Iterable.empty();
}
return Iterable.map(Iterable.concat(...this._byOwner.values()), map => map[1]);
}
}
class MarkerStats implements MarkerStatistics {
errors: number = 0;
infos: number = 0;
warnings: number = 0;
unknowns: number = 0;
private readonly _data = new ResourceMap<MarkerStatistics>();
private readonly _service: IMarkerService;
private readonly _subscription: IDisposable;
constructor(service: IMarkerService) {
this._service = service;
this._subscription = service.onMarkerChanged(this._update, this);
}
dispose(): void {
this._subscription.dispose();
}
private _update(resources: readonly URI[]): void {
for (const resource of resources) {
const oldStats = this._data.get(resource);
if (oldStats) {
this._substract(oldStats);
}
const newStats = this._resourceStats(resource);
this._add(newStats);
this._data.set(resource, newStats);
}
}
private _resourceStats(resource: URI): MarkerStatistics {
const result: MarkerStatistics = { errors: 0, warnings: 0, infos: 0, unknowns: 0 };
// TODO this is a hack
if (resource.scheme === Schemas.inMemory || resource.scheme === Schemas.walkThrough || resource.scheme === Schemas.walkThroughSnippet) {
return result;
}
for (const { severity } of this._service.read({ resource })) {
if (severity === MarkerSeverity.Error) {
result.errors += 1;
} else if (severity === MarkerSeverity.Warning) {
result.warnings += 1;
} else if (severity === MarkerSeverity.Info) {
result.infos += 1;
} else {
result.unknowns += 1;
}
}
return result;
}
private _substract(op: MarkerStatistics) {
this.errors -= op.errors;
this.warnings -= op.warnings;
this.infos -= op.infos;
this.unknowns -= op.unknowns;
}
private _add(op: MarkerStatistics) {
this.errors += op.errors;
this.warnings += op.warnings;
this.infos += op.infos;
this.unknowns += op.unknowns;
}
}
export class MarkerService implements IMarkerService {
declare readonly _serviceBrand: undefined;
private readonly _onMarkerChanged = new Emitter<readonly URI[]>();
readonly onMarkerChanged: Event<readonly URI[]> = Event.debounce(this._onMarkerChanged.event, MarkerService._debouncer, 0);
private readonly _data = new DoubleResourceMap<IMarker[]>();
private readonly _stats: MarkerStats;
constructor() {
this._stats = new MarkerStats(this);
}
dispose(): void {
this._stats.dispose();
}
getStatistics(): MarkerStatistics {
return this._stats;
}
remove(owner: string, resources: URI[]): void {
for (const resource of resources || []) {
this.changeOne(owner, resource, []);
}
}
changeOne(owner: string, resource: URI, markerData: IMarkerData[]): void {
if (isFalsyOrEmpty(markerData)) {
// remove marker for this (owner,resource)-tuple
const removed = this._data.delete(resource, owner);
if (removed) {
this._onMarkerChanged.fire([resource]);
}
} else {
// insert marker for this (owner,resource)-tuple
const markers: IMarker[] = [];
for (const data of markerData) {
const marker = MarkerService._toMarker(owner, resource, data);
if (marker) {
markers.push(marker);
}
}
this._data.set(resource, owner, markers);
this._onMarkerChanged.fire([resource]);
}
}
private static _toMarker(owner: string, resource: URI, data: IMarkerData): IMarker | undefined {
let {
code, severity,
message, source,
startLineNumber, startColumn, endLineNumber, endColumn,
relatedInformation,
tags,
} = data;
if (!message) {
return undefined;
}
// santize data
startLineNumber = startLineNumber > 0 ? startLineNumber : 1;
startColumn = startColumn > 0 ? startColumn : 1;
endLineNumber = endLineNumber >= startLineNumber ? endLineNumber : startLineNumber;
endColumn = endColumn > 0 ? endColumn : startColumn;
return {
resource,
owner,
code,
severity,
message,
source,
startLineNumber,
startColumn,
endLineNumber,
endColumn,
relatedInformation,
tags,
};
}
changeAll(owner: string, data: IResourceMarker[]): void {
const changes: URI[] = [];
// remove old marker
const existing = this._data.values(owner);
if (existing) {
for (let data of existing) {
const first = Iterable.first(data);
if (first) {
changes.push(first.resource);
this._data.delete(first.resource, owner);
}
}
}
// add new markers
if (isNonEmptyArray(data)) {
// group by resource
const groups = new ResourceMap<IMarker[]>();
for (const { resource, marker: markerData } of data) {
const marker = MarkerService._toMarker(owner, resource, markerData);
if (!marker) {
// filter bad markers
continue;
}
const array = groups.get(resource);
if (!array) {
groups.set(resource, [marker]);
changes.push(resource);
} else {
array.push(marker);
}
}
// insert all
for (const [resource, value] of groups) {
this._data.set(resource, owner, value);
}
}
if (changes.length > 0) {
this._onMarkerChanged.fire(changes);
}
}
read(filter: { owner?: string; resource?: URI; severities?: number, take?: number; } = Object.create(null)): IMarker[] {
let { owner, resource, severities, take } = filter;
if (!take || take < 0) {
take = -1;
}
if (owner && resource) {
// exactly one owner AND resource
const data = this._data.get(resource, owner);
if (!data) {
return [];
} else {
const result: IMarker[] = [];
for (const marker of data) {
if (MarkerService._accept(marker, severities)) {
const newLen = result.push(marker);
if (take > 0 && newLen === take) {
break;
}
}
}
return result;
}
} else if (!owner && !resource) {
// all
const result: IMarker[] = [];
for (let markers of this._data.values()) {
for (let data of markers) {
if (MarkerService._accept(data, severities)) {
const newLen = result.push(data);
if (take > 0 && newLen === take) {
return result;
}
}
}
}
return result;
} else {
// of one resource OR owner
const iterable = this._data.values(resource ?? owner!);
const result: IMarker[] = [];
for (const markers of iterable) {
for (const data of markers) {
if (MarkerService._accept(data, severities)) {
const newLen = result.push(data);
if (take > 0 && newLen === take) {
return result;
}
}
}
}
return result;
}
}
private static _accept(marker: IMarker, severities?: number): boolean {
return severities === undefined || (severities & marker.severity) === marker.severity;
}
// --- event debounce logic
private static _dedupeMap: ResourceMap<true>;
private static _debouncer(last: URI[] | undefined, event: readonly URI[]): URI[] {
if (!last) {
MarkerService._dedupeMap = new ResourceMap();
last = [];
}
for (const uri of event) {
if (!MarkerService._dedupeMap.has(uri)) {
MarkerService._dedupeMap.set(uri, true);
last.push(uri);
}
}
return last;
}
}
| mit |
mnsl/Sia | modules/consensus/changelog_test.go | 2106 | package consensus
import (
"testing"
"github.com/NebulousLabs/Sia/modules"
"github.com/NebulousLabs/Sia/types"
)
// TestIntegrationChangeLog does a general test of the changelog by creating a
// subscriber that subscribes partway into startup and checking that the
// correct ordering of blocks are provided.
func TestIntegrationChangeLog(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
t.Parallel()
// Get a blank consensus set tester so that the mocked subscriber can join
// immediately after genesis.
cst, err := blankConsensusSetTester("TestIntegrationChangeLog")
if err != nil {
t.Fatal(err)
}
defer cst.Close()
// Add a mocked subscriber and check that it receives the correct number of
// blocks.
ms := newMockSubscriber()
cst.cs.ConsensusSetSubscribe(&ms, modules.ConsensusChangeBeginning)
if ms.updates[0].AppliedBlocks[0].ID() != cst.cs.blockRoot.Block.ID() {
t.Fatal("subscription did not correctly receive the genesis block")
}
if len(ms.updates) != 1 {
t.Fatal("subscription resulted in the wrong number of blocks being sent")
}
// Create a copy of the subscriber that will subscribe to the consensus at
// the tail of the updates.
tailSubscriber := ms.copySub()
cst.cs.ConsensusSetSubscribe(&tailSubscriber, tailSubscriber.updates[len(tailSubscriber.updates)-1].ID)
if len(tailSubscriber.updates) != 1 {
t.Fatal("subscription resulted in the wrong number of blocks being sent")
}
// Create a copy of the subscriber that will join when it is not at 0, but it is behind.
behindSubscriber := ms.copySub()
cst.addSiafunds()
cst.mineSiacoins()
cst.cs.ConsensusSetSubscribe(&behindSubscriber, behindSubscriber.updates[len(behindSubscriber.updates)-1].ID)
if types.BlockHeight(len(behindSubscriber.updates)) != cst.cs.dbBlockHeight()+1 {
t.Fatal("subscription resulted in the wrong number of blocks being sent")
}
if len(ms.updates) != len(tailSubscriber.updates) {
t.Error("subscribers have inconsistent update chains")
}
if len(ms.updates) != len(behindSubscriber.updates) {
t.Error("subscribers have inconsistent update chains")
}
}
| mit |
EasyNetQ/EasyNetQ | Source/EasyNetQ.Tests/SerializationTests.cs | 655 | using FluentAssertions;
using Xunit;
namespace EasyNetQ.Tests;
public class SerializationTests
{
[Fact]
public void Should_Deserialize_Exceptions()
{
var str1 = Newtonsoft.Json.JsonConvert.SerializeObject(new EasyNetQException("blablabla"));
var ex1 = Newtonsoft.Json.JsonConvert.DeserializeObject<EasyNetQException>(str1);
ex1.Message.Should().Be("blablabla");
var str2 = Newtonsoft.Json.JsonConvert.SerializeObject(new EasyNetQResponderException("Ooops"));
var ex2 = Newtonsoft.Json.JsonConvert.DeserializeObject<EasyNetQResponderException>(str2);
ex2.Message.Should().Be("Ooops");
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2019_11_01/src/main/java/com/microsoft/azure/management/network/v2019_11_01/implementation/VpnGatewaysInner.java | 73463 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2019_11_01.implementation;
import com.microsoft.azure.arm.collection.InnerSupportsGet;
import com.microsoft.azure.arm.collection.InnerSupportsDelete;
import com.microsoft.azure.arm.collection.InnerSupportsListing;
import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.AzureServiceFuture;
import com.microsoft.azure.CloudException;
import com.microsoft.azure.ListOperationCallback;
import com.microsoft.azure.management.network.v2019_11_01.TagsObject;
import com.microsoft.azure.Page;
import com.microsoft.azure.PagedList;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import com.microsoft.rest.Validator;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.HTTP;
import retrofit2.http.PATCH;
import retrofit2.http.Path;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Query;
import retrofit2.http.Url;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;
import com.microsoft.azure.LongRunningFinalState;
import com.microsoft.azure.LongRunningOperationOptions;
/**
* An instance of this class provides access to all the operations defined
* in VpnGateways.
*/
public class VpnGatewaysInner implements InnerSupportsGet<VpnGatewayInner>, InnerSupportsDelete<Void>, InnerSupportsListing<VpnGatewayInner> {
/** The Retrofit service to perform REST calls. */
private VpnGatewaysService service;
/** The service client containing this operation class. */
private NetworkManagementClientImpl client;
/**
* Initializes an instance of VpnGatewaysInner.
*
* @param retrofit the Retrofit instance built from a Retrofit Builder.
* @param client the instance of the service client containing this operation class.
*/
public VpnGatewaysInner(Retrofit retrofit, NetworkManagementClientImpl client) {
this.service = retrofit.create(VpnGatewaysService.class);
this.client = client;
}
/**
* The interface defining all the services for VpnGateways to be
* used by Retrofit to perform actually REST calls.
*/
interface VpnGatewaysService {
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.VpnGateways getByResourceGroup" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}")
Observable<Response<ResponseBody>> getByResourceGroup(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.VpnGateways createOrUpdate" })
@PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}")
Observable<Response<ResponseBody>> createOrUpdate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Query("api-version") String apiVersion, @Body VpnGatewayInner vpnGatewayParameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.VpnGateways beginCreateOrUpdate" })
@PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}")
Observable<Response<ResponseBody>> beginCreateOrUpdate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Query("api-version") String apiVersion, @Body VpnGatewayInner vpnGatewayParameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.VpnGateways updateTags" })
@PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}")
Observable<Response<ResponseBody>> updateTags(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body TagsObject vpnGatewayParameters, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.VpnGateways delete" })
@HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}", method = "DELETE", hasBody = true)
Observable<Response<ResponseBody>> delete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.VpnGateways beginDelete" })
@HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}", method = "DELETE", hasBody = true)
Observable<Response<ResponseBody>> beginDelete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.VpnGateways reset" })
@POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/reset")
Observable<Response<ResponseBody>> reset(@Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.VpnGateways beginReset" })
@POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/reset")
Observable<Response<ResponseBody>> beginReset(@Path("resourceGroupName") String resourceGroupName, @Path("gatewayName") String gatewayName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.VpnGateways listByResourceGroup" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways")
Observable<Response<ResponseBody>> listByResourceGroup(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.VpnGateways list" })
@GET("subscriptions/{subscriptionId}/providers/Microsoft.Network/vpnGateways")
Observable<Response<ResponseBody>> list(@Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.VpnGateways listByResourceGroupNext" })
@GET
Observable<Response<ResponseBody>> listByResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_11_01.VpnGateways listNext" })
@GET
Observable<Response<ResponseBody>> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
}
/**
* Retrieves the details of a virtual wan vpn gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the VpnGatewayInner object if successful.
*/
public VpnGatewayInner getByResourceGroup(String resourceGroupName, String gatewayName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, gatewayName).toBlocking().single().body();
}
/**
* Retrieves the details of a virtual wan vpn gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<VpnGatewayInner> getByResourceGroupAsync(String resourceGroupName, String gatewayName, final ServiceCallback<VpnGatewayInner> serviceCallback) {
return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, gatewayName), serviceCallback);
}
/**
* Retrieves the details of a virtual wan vpn gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VpnGatewayInner object
*/
public Observable<VpnGatewayInner> getByResourceGroupAsync(String resourceGroupName, String gatewayName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, gatewayName).map(new Func1<ServiceResponse<VpnGatewayInner>, VpnGatewayInner>() {
@Override
public VpnGatewayInner call(ServiceResponse<VpnGatewayInner> response) {
return response.body();
}
});
}
/**
* Retrieves the details of a virtual wan vpn gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VpnGatewayInner object
*/
public Observable<ServiceResponse<VpnGatewayInner>> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String gatewayName) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (gatewayName == null) {
throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null.");
}
final String apiVersion = "2019-11-01";
return service.getByResourceGroup(this.client.subscriptionId(), resourceGroupName, gatewayName, apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VpnGatewayInner>>>() {
@Override
public Observable<ServiceResponse<VpnGatewayInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<VpnGatewayInner> clientResponse = getByResourceGroupDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<VpnGatewayInner> getByResourceGroupDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<VpnGatewayInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<VpnGatewayInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param vpnGatewayParameters Parameters supplied to create or Update a virtual wan vpn gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the VpnGatewayInner object if successful.
*/
public VpnGatewayInner createOrUpdate(String resourceGroupName, String gatewayName, VpnGatewayInner vpnGatewayParameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, vpnGatewayParameters).toBlocking().last().body();
}
/**
* Creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param vpnGatewayParameters Parameters supplied to create or Update a virtual wan vpn gateway.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<VpnGatewayInner> createOrUpdateAsync(String resourceGroupName, String gatewayName, VpnGatewayInner vpnGatewayParameters, final ServiceCallback<VpnGatewayInner> serviceCallback) {
return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, vpnGatewayParameters), serviceCallback);
}
/**
* Creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param vpnGatewayParameters Parameters supplied to create or Update a virtual wan vpn gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<VpnGatewayInner> createOrUpdateAsync(String resourceGroupName, String gatewayName, VpnGatewayInner vpnGatewayParameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, vpnGatewayParameters).map(new Func1<ServiceResponse<VpnGatewayInner>, VpnGatewayInner>() {
@Override
public VpnGatewayInner call(ServiceResponse<VpnGatewayInner> response) {
return response.body();
}
});
}
/**
* Creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param vpnGatewayParameters Parameters supplied to create or Update a virtual wan vpn gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<VpnGatewayInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String gatewayName, VpnGatewayInner vpnGatewayParameters) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (gatewayName == null) {
throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null.");
}
if (vpnGatewayParameters == null) {
throw new IllegalArgumentException("Parameter vpnGatewayParameters is required and cannot be null.");
}
Validator.validate(vpnGatewayParameters);
final String apiVersion = "2019-11-01";
Observable<Response<ResponseBody>> observable = service.createOrUpdate(this.client.subscriptionId(), resourceGroupName, gatewayName, apiVersion, vpnGatewayParameters, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<VpnGatewayInner>() { }.getType());
}
/**
* Creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param vpnGatewayParameters Parameters supplied to create or Update a virtual wan vpn gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the VpnGatewayInner object if successful.
*/
public VpnGatewayInner beginCreateOrUpdate(String resourceGroupName, String gatewayName, VpnGatewayInner vpnGatewayParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, vpnGatewayParameters).toBlocking().single().body();
}
/**
* Creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param vpnGatewayParameters Parameters supplied to create or Update a virtual wan vpn gateway.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<VpnGatewayInner> beginCreateOrUpdateAsync(String resourceGroupName, String gatewayName, VpnGatewayInner vpnGatewayParameters, final ServiceCallback<VpnGatewayInner> serviceCallback) {
return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, vpnGatewayParameters), serviceCallback);
}
/**
* Creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param vpnGatewayParameters Parameters supplied to create or Update a virtual wan vpn gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VpnGatewayInner object
*/
public Observable<VpnGatewayInner> beginCreateOrUpdateAsync(String resourceGroupName, String gatewayName, VpnGatewayInner vpnGatewayParameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, vpnGatewayParameters).map(new Func1<ServiceResponse<VpnGatewayInner>, VpnGatewayInner>() {
@Override
public VpnGatewayInner call(ServiceResponse<VpnGatewayInner> response) {
return response.body();
}
});
}
/**
* Creates a virtual wan vpn gateway if it doesn't exist else updates the existing gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param vpnGatewayParameters Parameters supplied to create or Update a virtual wan vpn gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VpnGatewayInner object
*/
public Observable<ServiceResponse<VpnGatewayInner>> beginCreateOrUpdateWithServiceResponseAsync(String resourceGroupName, String gatewayName, VpnGatewayInner vpnGatewayParameters) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (gatewayName == null) {
throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null.");
}
if (vpnGatewayParameters == null) {
throw new IllegalArgumentException("Parameter vpnGatewayParameters is required and cannot be null.");
}
Validator.validate(vpnGatewayParameters);
final String apiVersion = "2019-11-01";
return service.beginCreateOrUpdate(this.client.subscriptionId(), resourceGroupName, gatewayName, apiVersion, vpnGatewayParameters, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VpnGatewayInner>>>() {
@Override
public Observable<ServiceResponse<VpnGatewayInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<VpnGatewayInner> clientResponse = beginCreateOrUpdateDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<VpnGatewayInner> beginCreateOrUpdateDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<VpnGatewayInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<VpnGatewayInner>() { }.getType())
.register(201, new TypeToken<VpnGatewayInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Updates virtual wan vpn gateway tags.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the VpnGatewayInner object if successful.
*/
public VpnGatewayInner updateTags(String resourceGroupName, String gatewayName) {
return updateTagsWithServiceResponseAsync(resourceGroupName, gatewayName).toBlocking().single().body();
}
/**
* Updates virtual wan vpn gateway tags.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<VpnGatewayInner> updateTagsAsync(String resourceGroupName, String gatewayName, final ServiceCallback<VpnGatewayInner> serviceCallback) {
return ServiceFuture.fromResponse(updateTagsWithServiceResponseAsync(resourceGroupName, gatewayName), serviceCallback);
}
/**
* Updates virtual wan vpn gateway tags.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VpnGatewayInner object
*/
public Observable<VpnGatewayInner> updateTagsAsync(String resourceGroupName, String gatewayName) {
return updateTagsWithServiceResponseAsync(resourceGroupName, gatewayName).map(new Func1<ServiceResponse<VpnGatewayInner>, VpnGatewayInner>() {
@Override
public VpnGatewayInner call(ServiceResponse<VpnGatewayInner> response) {
return response.body();
}
});
}
/**
* Updates virtual wan vpn gateway tags.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VpnGatewayInner object
*/
public Observable<ServiceResponse<VpnGatewayInner>> updateTagsWithServiceResponseAsync(String resourceGroupName, String gatewayName) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (gatewayName == null) {
throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null.");
}
final String apiVersion = "2019-11-01";
final Map<String, String> tags = null;
TagsObject vpnGatewayParameters = new TagsObject();
vpnGatewayParameters.withTags(null);
return service.updateTags(this.client.subscriptionId(), resourceGroupName, gatewayName, apiVersion, this.client.acceptLanguage(), vpnGatewayParameters, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VpnGatewayInner>>>() {
@Override
public Observable<ServiceResponse<VpnGatewayInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<VpnGatewayInner> clientResponse = updateTagsDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
/**
* Updates virtual wan vpn gateway tags.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the VpnGatewayInner object if successful.
*/
public VpnGatewayInner updateTags(String resourceGroupName, String gatewayName, Map<String, String> tags) {
return updateTagsWithServiceResponseAsync(resourceGroupName, gatewayName, tags).toBlocking().single().body();
}
/**
* Updates virtual wan vpn gateway tags.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param tags Resource tags.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<VpnGatewayInner> updateTagsAsync(String resourceGroupName, String gatewayName, Map<String, String> tags, final ServiceCallback<VpnGatewayInner> serviceCallback) {
return ServiceFuture.fromResponse(updateTagsWithServiceResponseAsync(resourceGroupName, gatewayName, tags), serviceCallback);
}
/**
* Updates virtual wan vpn gateway tags.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VpnGatewayInner object
*/
public Observable<VpnGatewayInner> updateTagsAsync(String resourceGroupName, String gatewayName, Map<String, String> tags) {
return updateTagsWithServiceResponseAsync(resourceGroupName, gatewayName, tags).map(new Func1<ServiceResponse<VpnGatewayInner>, VpnGatewayInner>() {
@Override
public VpnGatewayInner call(ServiceResponse<VpnGatewayInner> response) {
return response.body();
}
});
}
/**
* Updates virtual wan vpn gateway tags.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param tags Resource tags.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VpnGatewayInner object
*/
public Observable<ServiceResponse<VpnGatewayInner>> updateTagsWithServiceResponseAsync(String resourceGroupName, String gatewayName, Map<String, String> tags) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (gatewayName == null) {
throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null.");
}
Validator.validate(tags);
final String apiVersion = "2019-11-01";
TagsObject vpnGatewayParameters = new TagsObject();
vpnGatewayParameters.withTags(tags);
return service.updateTags(this.client.subscriptionId(), resourceGroupName, gatewayName, apiVersion, this.client.acceptLanguage(), vpnGatewayParameters, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VpnGatewayInner>>>() {
@Override
public Observable<ServiceResponse<VpnGatewayInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<VpnGatewayInner> clientResponse = updateTagsDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<VpnGatewayInner> updateTagsDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<VpnGatewayInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<VpnGatewayInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Deletes a virtual wan vpn gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
*/
public void delete(String resourceGroupName, String gatewayName) {
deleteWithServiceResponseAsync(resourceGroupName, gatewayName).toBlocking().last().body();
}
/**
* Deletes a virtual wan vpn gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Void> deleteAsync(String resourceGroupName, String gatewayName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, gatewayName), serviceCallback);
}
/**
* Deletes a virtual wan vpn gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<Void> deleteAsync(String resourceGroupName, String gatewayName) {
return deleteWithServiceResponseAsync(resourceGroupName, gatewayName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
}
/**
* Deletes a virtual wan vpn gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String gatewayName) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (gatewayName == null) {
throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null.");
}
final String apiVersion = "2019-11-01";
Observable<Response<ResponseBody>> observable = service.delete(this.client.subscriptionId(), resourceGroupName, gatewayName, apiVersion, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType());
}
/**
* Deletes a virtual wan vpn gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
*/
public void beginDelete(String resourceGroupName, String gatewayName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, gatewayName).toBlocking().single().body();
}
/**
* Deletes a virtual wan vpn gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Void> beginDeleteAsync(String resourceGroupName, String gatewayName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, gatewayName), serviceCallback);
}
/**
* Deletes a virtual wan vpn gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponse} object if successful.
*/
public Observable<Void> beginDeleteAsync(String resourceGroupName, String gatewayName) {
return beginDeleteWithServiceResponseAsync(resourceGroupName, gatewayName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
}
/**
* Deletes a virtual wan vpn gateway.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponse} object if successful.
*/
public Observable<ServiceResponse<Void>> beginDeleteWithServiceResponseAsync(String resourceGroupName, String gatewayName) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (gatewayName == null) {
throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null.");
}
final String apiVersion = "2019-11-01";
return service.beginDelete(this.client.subscriptionId(), resourceGroupName, gatewayName, apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
@Override
public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
try {
ServiceResponse<Void> clientResponse = beginDeleteDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<Void> beginDeleteDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<Void, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<Void>() { }.getType())
.register(202, new TypeToken<Void>() { }.getType())
.register(204, new TypeToken<Void>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Resets the primary of the vpn gateway in the specified resource group.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the VpnGatewayInner object if successful.
*/
public VpnGatewayInner reset(String resourceGroupName, String gatewayName) {
return resetWithServiceResponseAsync(resourceGroupName, gatewayName).toBlocking().last().body();
}
/**
* Resets the primary of the vpn gateway in the specified resource group.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<VpnGatewayInner> resetAsync(String resourceGroupName, String gatewayName, final ServiceCallback<VpnGatewayInner> serviceCallback) {
return ServiceFuture.fromResponse(resetWithServiceResponseAsync(resourceGroupName, gatewayName), serviceCallback);
}
/**
* Resets the primary of the vpn gateway in the specified resource group.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<VpnGatewayInner> resetAsync(String resourceGroupName, String gatewayName) {
return resetWithServiceResponseAsync(resourceGroupName, gatewayName).map(new Func1<ServiceResponse<VpnGatewayInner>, VpnGatewayInner>() {
@Override
public VpnGatewayInner call(ServiceResponse<VpnGatewayInner> response) {
return response.body();
}
});
}
/**
* Resets the primary of the vpn gateway in the specified resource group.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<VpnGatewayInner>> resetWithServiceResponseAsync(String resourceGroupName, String gatewayName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (gatewayName == null) {
throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-11-01";
Observable<Response<ResponseBody>> observable = service.reset(resourceGroupName, gatewayName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPostOrDeleteResultAsync(observable, new LongRunningOperationOptions().withFinalStateVia(LongRunningFinalState.LOCATION), new TypeToken<VpnGatewayInner>() { }.getType());
}
/**
* Resets the primary of the vpn gateway in the specified resource group.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the VpnGatewayInner object if successful.
*/
public VpnGatewayInner beginReset(String resourceGroupName, String gatewayName) {
return beginResetWithServiceResponseAsync(resourceGroupName, gatewayName).toBlocking().single().body();
}
/**
* Resets the primary of the vpn gateway in the specified resource group.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<VpnGatewayInner> beginResetAsync(String resourceGroupName, String gatewayName, final ServiceCallback<VpnGatewayInner> serviceCallback) {
return ServiceFuture.fromResponse(beginResetWithServiceResponseAsync(resourceGroupName, gatewayName), serviceCallback);
}
/**
* Resets the primary of the vpn gateway in the specified resource group.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VpnGatewayInner object
*/
public Observable<VpnGatewayInner> beginResetAsync(String resourceGroupName, String gatewayName) {
return beginResetWithServiceResponseAsync(resourceGroupName, gatewayName).map(new Func1<ServiceResponse<VpnGatewayInner>, VpnGatewayInner>() {
@Override
public VpnGatewayInner call(ServiceResponse<VpnGatewayInner> response) {
return response.body();
}
});
}
/**
* Resets the primary of the vpn gateway in the specified resource group.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param gatewayName The name of the gateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the VpnGatewayInner object
*/
public Observable<ServiceResponse<VpnGatewayInner>> beginResetWithServiceResponseAsync(String resourceGroupName, String gatewayName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (gatewayName == null) {
throw new IllegalArgumentException("Parameter gatewayName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-11-01";
return service.beginReset(resourceGroupName, gatewayName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<VpnGatewayInner>>>() {
@Override
public Observable<ServiceResponse<VpnGatewayInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<VpnGatewayInner> clientResponse = beginResetDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<VpnGatewayInner> beginResetDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<VpnGatewayInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<VpnGatewayInner>() { }.getType())
.register(202, new TypeToken<Void>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Lists all the VpnGateways in a resource group.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<VpnGatewayInner> object if successful.
*/
public PagedList<VpnGatewayInner> listByResourceGroup(final String resourceGroupName) {
ServiceResponse<Page<VpnGatewayInner>> response = listByResourceGroupSinglePageAsync(resourceGroupName).toBlocking().single();
return new PagedList<VpnGatewayInner>(response.body()) {
@Override
public Page<VpnGatewayInner> nextPage(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Lists all the VpnGateways in a resource group.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<VpnGatewayInner>> listByResourceGroupAsync(final String resourceGroupName, final ListOperationCallback<VpnGatewayInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByResourceGroupSinglePageAsync(resourceGroupName),
new Func1<String, Observable<ServiceResponse<Page<VpnGatewayInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VpnGatewayInner>>> call(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Lists all the VpnGateways in a resource group.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<VpnGatewayInner> object
*/
public Observable<Page<VpnGatewayInner>> listByResourceGroupAsync(final String resourceGroupName) {
return listByResourceGroupWithServiceResponseAsync(resourceGroupName)
.map(new Func1<ServiceResponse<Page<VpnGatewayInner>>, Page<VpnGatewayInner>>() {
@Override
public Page<VpnGatewayInner> call(ServiceResponse<Page<VpnGatewayInner>> response) {
return response.body();
}
});
}
/**
* Lists all the VpnGateways in a resource group.
*
* @param resourceGroupName The resource group name of the VpnGateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<VpnGatewayInner> object
*/
public Observable<ServiceResponse<Page<VpnGatewayInner>>> listByResourceGroupWithServiceResponseAsync(final String resourceGroupName) {
return listByResourceGroupSinglePageAsync(resourceGroupName)
.concatMap(new Func1<ServiceResponse<Page<VpnGatewayInner>>, Observable<ServiceResponse<Page<VpnGatewayInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VpnGatewayInner>>> call(ServiceResponse<Page<VpnGatewayInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Lists all the VpnGateways in a resource group.
*
ServiceResponse<PageImpl<VpnGatewayInner>> * @param resourceGroupName The resource group name of the VpnGateway.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<VpnGatewayInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<VpnGatewayInner>>> listByResourceGroupSinglePageAsync(final String resourceGroupName) {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
final String apiVersion = "2019-11-01";
return service.listByResourceGroup(this.client.subscriptionId(), resourceGroupName, apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<VpnGatewayInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VpnGatewayInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<VpnGatewayInner>> result = listByResourceGroupDelegate(response);
return Observable.just(new ServiceResponse<Page<VpnGatewayInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<VpnGatewayInner>> listByResourceGroupDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<VpnGatewayInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<VpnGatewayInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Lists all the VpnGateways in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<VpnGatewayInner> object if successful.
*/
public PagedList<VpnGatewayInner> list() {
ServiceResponse<Page<VpnGatewayInner>> response = listSinglePageAsync().toBlocking().single();
return new PagedList<VpnGatewayInner>(response.body()) {
@Override
public Page<VpnGatewayInner> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Lists all the VpnGateways in a subscription.
*
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<VpnGatewayInner>> listAsync(final ListOperationCallback<VpnGatewayInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listSinglePageAsync(),
new Func1<String, Observable<ServiceResponse<Page<VpnGatewayInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VpnGatewayInner>>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Lists all the VpnGateways in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<VpnGatewayInner> object
*/
public Observable<Page<VpnGatewayInner>> listAsync() {
return listWithServiceResponseAsync()
.map(new Func1<ServiceResponse<Page<VpnGatewayInner>>, Page<VpnGatewayInner>>() {
@Override
public Page<VpnGatewayInner> call(ServiceResponse<Page<VpnGatewayInner>> response) {
return response.body();
}
});
}
/**
* Lists all the VpnGateways in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<VpnGatewayInner> object
*/
public Observable<ServiceResponse<Page<VpnGatewayInner>>> listWithServiceResponseAsync() {
return listSinglePageAsync()
.concatMap(new Func1<ServiceResponse<Page<VpnGatewayInner>>, Observable<ServiceResponse<Page<VpnGatewayInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VpnGatewayInner>>> call(ServiceResponse<Page<VpnGatewayInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Lists all the VpnGateways in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<VpnGatewayInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<VpnGatewayInner>>> listSinglePageAsync() {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-11-01";
return service.list(this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<VpnGatewayInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VpnGatewayInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<VpnGatewayInner>> result = listDelegate(response);
return Observable.just(new ServiceResponse<Page<VpnGatewayInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<VpnGatewayInner>> listDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<VpnGatewayInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<VpnGatewayInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Lists all the VpnGateways in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<VpnGatewayInner> object if successful.
*/
public PagedList<VpnGatewayInner> listByResourceGroupNext(final String nextPageLink) {
ServiceResponse<Page<VpnGatewayInner>> response = listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<VpnGatewayInner>(response.body()) {
@Override
public Page<VpnGatewayInner> nextPage(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Lists all the VpnGateways in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<VpnGatewayInner>> listByResourceGroupNextAsync(final String nextPageLink, final ServiceFuture<List<VpnGatewayInner>> serviceFuture, final ListOperationCallback<VpnGatewayInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByResourceGroupNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<VpnGatewayInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VpnGatewayInner>>> call(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Lists all the VpnGateways in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<VpnGatewayInner> object
*/
public Observable<Page<VpnGatewayInner>> listByResourceGroupNextAsync(final String nextPageLink) {
return listByResourceGroupNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<VpnGatewayInner>>, Page<VpnGatewayInner>>() {
@Override
public Page<VpnGatewayInner> call(ServiceResponse<Page<VpnGatewayInner>> response) {
return response.body();
}
});
}
/**
* Lists all the VpnGateways in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<VpnGatewayInner> object
*/
public Observable<ServiceResponse<Page<VpnGatewayInner>>> listByResourceGroupNextWithServiceResponseAsync(final String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<VpnGatewayInner>>, Observable<ServiceResponse<Page<VpnGatewayInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VpnGatewayInner>>> call(ServiceResponse<Page<VpnGatewayInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Lists all the VpnGateways in a resource group.
*
ServiceResponse<PageImpl<VpnGatewayInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<VpnGatewayInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<VpnGatewayInner>>> listByResourceGroupNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listByResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<VpnGatewayInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VpnGatewayInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<VpnGatewayInner>> result = listByResourceGroupNextDelegate(response);
return Observable.just(new ServiceResponse<Page<VpnGatewayInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<VpnGatewayInner>> listByResourceGroupNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<VpnGatewayInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<VpnGatewayInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Lists all the VpnGateways in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<VpnGatewayInner> object if successful.
*/
public PagedList<VpnGatewayInner> listNext(final String nextPageLink) {
ServiceResponse<Page<VpnGatewayInner>> response = listNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<VpnGatewayInner>(response.body()) {
@Override
public Page<VpnGatewayInner> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Lists all the VpnGateways in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<VpnGatewayInner>> listNextAsync(final String nextPageLink, final ServiceFuture<List<VpnGatewayInner>> serviceFuture, final ListOperationCallback<VpnGatewayInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<VpnGatewayInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VpnGatewayInner>>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Lists all the VpnGateways in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<VpnGatewayInner> object
*/
public Observable<Page<VpnGatewayInner>> listNextAsync(final String nextPageLink) {
return listNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<VpnGatewayInner>>, Page<VpnGatewayInner>>() {
@Override
public Page<VpnGatewayInner> call(ServiceResponse<Page<VpnGatewayInner>> response) {
return response.body();
}
});
}
/**
* Lists all the VpnGateways in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<VpnGatewayInner> object
*/
public Observable<ServiceResponse<Page<VpnGatewayInner>>> listNextWithServiceResponseAsync(final String nextPageLink) {
return listNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<VpnGatewayInner>>, Observable<ServiceResponse<Page<VpnGatewayInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VpnGatewayInner>>> call(ServiceResponse<Page<VpnGatewayInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Lists all the VpnGateways in a subscription.
*
ServiceResponse<PageImpl<VpnGatewayInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<VpnGatewayInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<VpnGatewayInner>>> listNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<VpnGatewayInner>>>>() {
@Override
public Observable<ServiceResponse<Page<VpnGatewayInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<VpnGatewayInner>> result = listNextDelegate(response);
return Observable.just(new ServiceResponse<Page<VpnGatewayInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<VpnGatewayInner>> listNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<VpnGatewayInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<VpnGatewayInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
}
| mit |
aidan959/ExamCorrector | bin/number2commaseperated.py | 221 | def splitstring(thestring):
arr = thestring.split(",")
returns =[]
for i in arr:
returns.append(",".join(i))
return returns
while True:
for i in splitstring(input()):
print (i) | mit |
d4l3k/go-sct | geoip/geoip.go | 695 | // geoip returns the lat/lng of the target IP address (or current machine)
package geoip
import (
"encoding/json"
"fmt"
"net/http"
)
type GeoIP struct {
City string `json:"city"`
Latitude float64 `json:"lat"`
Longitude float64 `json:"lon"`
}
// LookupIP looks up the geolocation information for the specified address ("" for current host).
func LookupIP(address string) (*GeoIP, error) {
response, err := http.Get(fmt.Sprintf("http://ip-api.com/json/%s?fields=lat,lon,city", address))
if err != nil {
return nil, err
}
defer response.Body.Close()
var geo GeoIP
if err := json.NewDecoder(response.Body).Decode(&geo); err != nil {
return nil, err
}
return &geo, nil
}
| mit |
kervi/kervi | kervi-core/tests/mockup_sensor_device.py | 861 | from kervi.hal import SensorDeviceDriver
class MockupSensorDeviceDriver(SensorDeviceDriver):
def __init__(self):
SensorDeviceDriver.__init__(self)
self.value = 0
def read_value(self):
return self.value
@property
def type(self):
return "temperature"
@property
def unit(self):
return "C"
class MockupMultiDimSensorDeviceDriver(SensorDeviceDriver):
def __init__(self):
self.value1 = 0
self.value2 = 0
self.value3 = 0
def read_value(self):
return [self.value1, self.value2, self.value3]
@property
def dimensions(self):
return 3
@property
def dimension_labels(self):
return ["heading", "pitch", "roll"]
@property
def type(self):
return "position"
@property
def unit(self):
return "degree" | mit |
raphaelrodrigues/tvcalendar | src/main/webapp/scripts/app/admin/metrics/metrics.controller.js | 2092 | 'use strict';
angular.module('tvcalendarApp')
.controller('MetricsController', function ($scope, MonitoringService, $modal) {
$scope.metrics = {};
$scope.updatingMetrics = true;
$scope.refresh = function () {
$scope.updatingMetrics = true;
MonitoringService.getMetrics().then(function (promise) {
$scope.metrics = promise;
$scope.updatingMetrics = false;
}, function (promise) {
$scope.metrics = promise.data;
$scope.updatingMetrics = false;
});
};
$scope.$watch('metrics', function (newValue) {
$scope.servicesStats = {};
$scope.cachesStats = {};
angular.forEach(newValue.timers, function (value, key) {
if (key.indexOf('web.rest') !== -1 || key.indexOf('service') !== -1) {
$scope.servicesStats[key] = value;
}
if (key.indexOf('net.sf.ehcache.Cache') !== -1) {
// remove gets or puts
var index = key.lastIndexOf('.');
var newKey = key.substr(0, index);
// Keep the name of the domain
index = newKey.lastIndexOf('.');
$scope.cachesStats[newKey] = {
'name': newKey.substr(index + 1),
'value': value
};
}
});
});
$scope.refresh();
$scope.refreshThreadDumpData = function() {
MonitoringService.threadDump().then(function(data) {
var modalInstance = $modal.open({
templateUrl: 'scripts/app/admin/metrics/metrics.modal.html',
controller: 'MetricsModalController',
size: 'lg',
resolve: {
threadDump: function() {
return data;
}
}
});
});
};
});
| mit |
raul75/AlessioCoin | src/qt/locale/bitcoin_bg.ts | 116991 | <?xml version="1.0" ?><!DOCTYPE TS><TS language="bg" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About AlessioCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>AlessioCoin</b> version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The NovaCoin developers
Copyright © 2014 The BlackCoin developers
Copyright © 2014 The AlessioCoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
Това е експериментален софтуер.
Разпространява се под MIT/X11 софтуерен лиценз, виж COPYING или http://www.opensource.org/licenses/mit-license.php.
Използван е софтуер, разработен от OpenSSL Project за употреба в OpenSSL Toolkit (http://www.openssl.org/), криптографски софтуер разработен от Eric Young ([email protected]) и UPnP софтуер разработен от Thomas Bernard.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Двоен клик за редакция на адрес или име</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Създаване на нов адрес</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Копирай избрания адрес</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-46"/>
<source>These are your AlessioCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<source>&Copy Address</source>
<translation>&Копирай</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a AlessioCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Изтрий избрания адрес от списъка</translation>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified AlessioCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Изтрий</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+65"/>
<source>Copy &Label</source>
<translation>Копирай &име</translation>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation>&Редактирай</translation>
</message>
<message>
<location line="+250"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>CSV файл (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Име</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(без име)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Въведи парола</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Нова парола</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Още веднъж</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+35"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Въведете нова парола за портфейла.<br/>Моля използвайте <b>поне 10 случайни символа</b> или <b>8 или повече думи</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Криптиране на портфейла</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Тази операция изисква Вашата парола за отключване на портфейла.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Отключване на портфейла</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Тази операция изисква Вашата парола за декриптиране на портфейла.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Декриптиране на портфейла</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Смяна на паролата</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Въведете текущата и новата парола за портфейла.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Потвърждаване на криптирането</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR COINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Портфейлът е криптиран</translation>
</message>
<message>
<location line="-58"/>
<source>AlessioCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Криптирането беше неуспешно</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Криптирането на портфейла беше неуспешно поради неизвестен проблем. Портфейлът не е криптиран.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Паролите не съвпадат</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Отключването беше неуспешно</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Паролата въведена за декриптиране на портфейла е грешна.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Декриптирането беше неуспешно</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Паролата на портфейла беше променена успешно.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+280"/>
<source>Sign &message...</source>
<translation>Подписване на &съобщение...</translation>
</message>
<message>
<location line="+242"/>
<source>Synchronizing with network...</source>
<translation>Синхронизиране с мрежата...</translation>
</message>
<message>
<location line="-308"/>
<source>&Overview</source>
<translation>&Баланс</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Обобщена информация за портфейла</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&Транзакции</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>История на транзакциите</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-13"/>
<source>&Receive coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-7"/>
<source>&Send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>E&xit</source>
<translation>Из&ход</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Изход от приложението</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about AlessioCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>За &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Покажи информация за Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Опции...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>&Криптиране на портфейла...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Запазване на портфейла...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Смяна на паролата...</translation>
</message>
<message numerus="yes">
<location line="+250"/>
<source>~%n block(s) remaining</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-247"/>
<source>&Export...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Send coins to a AlessioCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Modify configuration options for AlessioCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Encrypt or decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Променя паролата за портфейла</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>&Проверка на съобщение...</translation>
</message>
<message>
<location line="-200"/>
<source>AlessioCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation>Портфейл</translation>
</message>
<message>
<location line="+178"/>
<source>&About AlessioCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>&File</source>
<translation>&Файл</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Настройки</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Помощ</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Раздели</translation>
</message>
<message>
<location line="+8"/>
<source>Actions toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+60"/>
<source>AlessioCoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to AlessioCoin network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+40"/>
<source>Downloaded %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+413"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-403"/>
<source>%n second(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="-284"/>
<source>&Unlock Wallet...</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+288"/>
<source>%n minute(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s) ago</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Up to date</source>
<translation>Синхронизиран</translation>
</message>
<message>
<location line="+7"/>
<source>Catching up...</source>
<translation>Зарежда блокове...</translation>
</message>
<message>
<location line="+10"/>
<source>Last received block was generated %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>Изходяща транзакция</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Входяща транзакция</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid AlessioCoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Портфейлът е <b>криптиран</b> и <b>отключен</b></translation>
</message>
<message>
<location line="+10"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Портфейлът е <b>криптиран</b> и <b>заключен</b></translation>
</message>
<message>
<location line="+25"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+76"/>
<source>%n second(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+18"/>
<source>Not staking</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+109"/>
<source>A fatal error occurred. AlessioCoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+90"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Сума:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+551"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Сума</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Потвърдени</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-515"/>
<source>Copy address</source>
<translation>Копирай адрес</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Копирай име</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Копирай сума</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+155"/>
<source>DUST</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
This label turns red, if the priority is smaller than "medium".
This means a fee of at least %1 per kb is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(без име)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Редактиране на адрес</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Име</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Адрес</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+20"/>
<source>New receiving address</source>
<translation>Нов адрес за получаване</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Нов адрес за изпращане</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Редактиране на входящ адрес</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Редактиране на изходящ адрес</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Вече има адрес "%1" в списъка с адреси.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid AlessioCoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Отключването на портфейла беше неуспешно.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Създаването на ключ беше неуспешно.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+420"/>
<location line="+12"/>
<source>AlessioCoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Опции</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Основни</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>&Такса за изходяща транзакция</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start AlessioCoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start AlessioCoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Detach databases at shutdown</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Мрежа</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the AlessioCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Отваряне на входящия порт чрез &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the AlessioCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Прозорец</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>След минимизиране ще е видима само иконата в системния трей.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Минимизиране в системния трей</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>При затваряне на прозореца приложението остава минимизирано. Ако изберете тази опция, приложението може да се затвори само чрез Изход в менюто.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>М&инимизиране при затваряне</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Интерфейс</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Език:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting AlessioCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>Мерни единици:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Изберете единиците, показвани по подразбиране в интерфейса.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show AlessioCoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>Показвай и адресите в списъка с транзакции</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to show coin control features or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+55"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+149"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting AlessioCoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Прокси адресът е невалиден.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Форма</translation>
</message>
<message>
<location line="+33"/>
<location line="+231"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the AlessioCoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-160"/>
<source>Stake:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-107"/>
<source>Wallet</source>
<translation>Портфейл</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Total:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Последни транзакции</b></translation>
</message>
<message>
<location line="-108"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+113"/>
<location line="+1"/>
<source>out of sync</source>
<translation>несинхронизиран</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+348"/>
<source>N/A</source>
<translation>N/A</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Мрежа</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the AlessioCoin-Qt help message to get a list with possible AlessioCoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>AlessioCoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>AlessioCoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the AlessioCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Изчисти конзолата</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the AlessioCoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Използвайте стрелки надолу и нагореза разглеждане на историятаот команди и <b>Ctrl-L</b> за изчистване на конзолата.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Изпращане</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Сума:</translation>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 CAM</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-191"/>
<source>Priority:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Изпращане към повече от един получател</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Добави &получател</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>&Изчисти</translation>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Баланс:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 CAM</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Потвърдете изпращането</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>И&зпрати</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a AlessioCoin address (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Копирай сума</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+86"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Потвърждаване</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Невалиден адрес на получателя.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Сумата трябва да е по-голяма от 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+251"/>
<source>WARNING: Invalid AlessioCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(без име)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>С&ума:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Плати &На:</translation>
</message>
<message>
<location line="+24"/>
<location filename="../sendcoinsentry.cpp" line="+25"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Въведете име за този адрес, за да го добавите в списъка с адреси</translation>
</message>
<message>
<location line="+9"/>
<source>&Label:</source>
<translation>&Име:</translation>
</message>
<message>
<location line="+18"/>
<source>The address to send the payment to (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Вмъкни от клипборда</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a AlessioCoin address (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Подпиши / Провери съобщение</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>&Подпиши</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Можете да подпишете съобщение като доказателство, че притежавате определен адрес. Бъдете внимателни и не подписвайте съобщения, които биха разкрили лична информация без вашето съгласие.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Вмъкни от клипборда</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Въведете съобщението тук</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Копиране на текущия подпис</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this AlessioCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>&Изчисти</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>&Провери</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified AlessioCoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a AlessioCoin address (e.g. SXywGBZBowrppUwwNUo1GCRDTibzJi7g2M)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Натиснете "Подписване на съобщение" за да създадете подпис</translation>
</message>
<message>
<location line="+3"/>
<source>Enter AlessioCoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Въведеният адрес е невалиден.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Моля проверете адреса и опитайте отново.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Не е наличен частният ключ за въведеният адрес.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Подписването на съобщение бе неуспешно.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Съобщението е подписано.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Подписът не може да бъде декодиран.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Проверете подписа и опитайте отново.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Подписът не отговаря на комбинацията от съобщение и адрес.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Проверката на съобщението беше неуспешна.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Съобщението е потвърдено.</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation>Подлежи на промяна до %1</translation>
</message>
<message numerus="yes">
<location line="-2"/>
<source>Open for %n block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+8"/>
<source>conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/офлайн</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/непотвърдени</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>включена в %1 блока</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Статус</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Източник</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Издадени</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>От</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>За</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>собствен адрес</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>име</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Кредит</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Дебит</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Такса</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Сума нето</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Съобщение</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Коментар</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Транзакция</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Сума</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>true</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>false</translation>
</message>
<message>
<location line="-211"/>
<source>, has not been successfully broadcast yet</source>
<translation>, все още не е изпратено</translation>
</message>
<message>
<location line="+35"/>
<source>unknown</source>
<translation>неизвестен</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Транзакция</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Описание на транзакцията</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+226"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Тип</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Сума</translation>
</message>
<message>
<location line="+60"/>
<source>Open until %1</source>
<translation>Подлежи на промяна до %1</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Потвърдени (%1 потвърждения)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Блокът не е получен от останалите участници и най-вероятно няма да бъде одобрен.</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Генерирана, но отхвърлена от мрежата</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Получени с</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Получен от</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Изпратени на</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Емитирани</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location line="+190"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Състояние на транзакцията. Задръжте върху това поле за брой потвърждения.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Дата и час на получаване.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Тип на транзакцията.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Получател на транзакцията.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Сума извадена или добавена към баланса.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+55"/>
<location line="+16"/>
<source>All</source>
<translation>Всички</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Днес</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Тази седмица</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Този месец</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Предния месец</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Тази година</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>От - до...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Получени</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Изпратени на</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Собствени</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Емитирани</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Други</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Търсене по адрес или име</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Минимална сума</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Копирай адрес</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Копирай име</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Копирай сума</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Редактирай име</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+144"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>CSV файл (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Потвърдени</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Дата</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Тип</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Име</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Адрес</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Сума</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ИД</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>От:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>до</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+206"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+33"/>
<source>AlessioCoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Използване:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or AlessioCoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Вписване на команди</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Получете помощ за команда</translation>
</message>
<message>
<location line="+2"/>
<source>Options:</source>
<translation>Опции:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: AlessioCoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: AlessioCoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Определете директория за данните</translation>
</message>
<message>
<location line="+2"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Listen for connections on <port> (default: 51737 or testnet: 51997)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Stake your coins to support network and gain reward (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Праг на прекъсване на връзката при непорядъчно държащи се пиъри (по подразбиране:100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Брой секунди до възтановяване на връзката за зле държащите се пиъри (по подразбиране:86400)</translation>
</message>
<message>
<location line="-44"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Detach block and address databases. Increases shutdown time (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>Listen for JSON-RPC connections on <port> (default: 51736 or testnet: 51996)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>Error: Transaction creation failed </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>Error: Wallet locked, unable to create transaction </source>
<translation type="unfinished"/>
</message>
<message>
<location line="-8"/>
<source>Importing blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Importing bootstrap blockchain data file.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-88"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Използвайте тестовата мрежа</translation>
</message>
<message>
<location line="-24"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-38"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+117"/>
<source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+61"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong AlessioCoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-18"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-30"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-62"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+94"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-90"/>
<source>Find peers using DNS lookup (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync checkpoints policy (default: strict)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+83"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-82"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+41"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Изпрати локализиращата или дебъг информацията към конзолата, вместо файлът debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-42"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+109"/>
<source>Unable to sign checkpoint, wrong checkpointkey?
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<source>Username for JSON-RPC connections</source>
<translation>Потребителско име за JSON-RPC връзките</translation>
</message>
<message>
<location line="+47"/>
<source>Verifying database integrity...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+57"/>
<source>WARNING: syncronized checkpoint violation detected, but skipped!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>Password for JSON-RPC connections</source>
<translation>Парола за JSON-RPC връзките</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=AlessioCoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "AlessioCoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+51"/>
<source>Find peers using internet relay chat (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Разреши JSON-RPC връзките от отучнен IP адрес</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Изпрати команди до възел функциониращ на <ip> (По подразбиране: 127.0.0.1)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Повторно сканиране на блок-връзка за липсващи портефейлни транзакции</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 2500, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Използвайте OpenSSL (https) за JSON-RPC връзките</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Сертификатен файл на сървъра (По подразбиране:server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Поверителен ключ за сървъра (default: server.pem)</translation>
</message>
<message>
<location line="+1"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+53"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-158"/>
<source>This help message</source>
<translation>Това помощно съобщение</translation>
</message>
<message>
<location line="+95"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot obtain a lock on data directory %s. AlessioCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>AlessioCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+140"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Loading addresses...</source>
<translation>Зареждане на адресите...</translation>
</message>
<message>
<location line="-15"/>
<source>Error loading blkindex.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of AlessioCoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart AlessioCoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Невалиден -proxy address: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-24"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Error: could not start node</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sending...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-34"/>
<source>Loading block index...</source>
<translation>Зареждане на блок индекса...</translation>
</message>
<message>
<location line="-103"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+122"/>
<source>Unable to bind to %s on this computer. AlessioCoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-97"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Loading wallet...</source>
<translation>Зареждане на портфейла...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot initialize keypool</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Преразглеждане на последовтелността от блокове...</translation>
</message>
<message>
<location line="+5"/>
<source>Done loading</source>
<translation>Зареждането е завършено</translation>
</message>
<message>
<location line="-167"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Error</source>
<translation>Грешка</translation>
</message>
<message>
<location line="+6"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS>
| mit |
BancDelTempsDAW/symfony | src/bonavall/BancdeltempsBundle/Entity/Provincia.php | 1204 | <?php
namespace bonavall\BancdeltempsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Provincia
* @ORM\Entity
* @ORM\Table(name="provincia")
*
*/
class Provincia
{
/**
* @var integer
*
* @ORM\Column(name="idprovincia", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="provincia", type="string", length=50, nullable=false)
*/
private $provincia;
/**
* @var string
*
* @ORM\Column(name="provinciaseo", type="string", length=50, nullable=false)
*/
private $provinciaseo;
public function getId() {
return $this->id;
}
public function getProvincia() {
return $this->provincia;
}
public function setProvincia($provincia) {
$this->provincia = $provincia;
}
public function getProvinciaseo() {
return $this->provinciaseo;
}
public function setProvinciaseo($provinciaseo) {
$this->provinciaseo = $provinciaseo;
}
public function __toString() {
return $this->provincia;
}
}
| mit |
seryckd/hexmatch | sprite.js | 3583 | // TODO
// -- modify load() so that a default height and width can be specified,
// in which case do not need to specify height and width on every line
// although can override if want
/*globals IMAGE*/
"use strict";
/*
SpriteRef = {
name : "",
height:
width:
x:,
y: ,
}
*/
/*
// spritesheet
// spriteref
// spriteanim
SPRITE.load("twinkle", "images/twinkle.png", [
{ name: "1", height:40, height:40, x:0, y:0 }
],
[
{ name:"shine1", refs:[ "1", "2", "3" ], durationms:100}
]
);
var sheet = SPRITE.sheet("twinkle");
var spriteref = sheet.sprite("1");
SPRITE.image(spriteref);
var spriteanim = sheet.animation("shine1");
spriteanim.update(time);
var spriteref = spriteanim.image(time);
*/
var SpriteInfo = function (info, image) {
this.name = info.name;
this.height = info.height;
this.width = info.width;
this.x = info.x;
this.y = info.y;
// reference to SpriteSheet.image
this.image = image;
};
var SpriteAnimation = function (animation) {
this.animation = animation;
this.name = animation.name;
this.elapsedms = 0;
this.currentframe = 0;
this.currentsprite = this.animation.sprites[0];
};
SpriteAnimation.prototype.update = function (intervalms) {
this.elapsedms += intervalms;
if (this.elapsedms >= this.animation.durationms) {
this.elapsedms = 0;
this.currentframe += 1;
if (this.currentframe >= this.animation.sprites.length) {
this.currentframe = 0;
}
this.currentsprite = this.animation.sprites[this.currentframe];
}
};
SpriteAnimation.prototype.sprite = function () {
return this.currentsprite;
};
var SPRITE = (function () {
var sheets = {};
return {
// Public Interface
load: function (name, filename, sprites, animations) {
var image = IMAGE.load(name, filename),
sheet = {
name: name,
image: image,
sprites: [], // map name, SpriteInfo
animations: [] // map name, SpriteAnimation
},
count,
count2,
count3,
sprite,
animation,
spriteinfos,
spriteinfo,
spritename;
for (count = 0; count < sprites.length; count += 1) {
sprite = sprites[count];
sheet.sprites[sprite.name] = new SpriteInfo(sprite, image);
}
if (animations) {
for (count2 = 0; count2 < animations.length; count2 += 1) {
animation = animations[count2];
spriteinfos = [];
for (count3 = 0; count3 < animation.spritenames.length; count3 += 1) {
spritename = animation.spritenames[count3];
spriteinfo = sheet.sprites[spritename];
spriteinfos.push(spriteinfo);
}
sheet.animations[animation.name] = {
name: animation.name,
durationms: animation.durationms,
sprites: spriteinfos,
makeinstance: function () {
return new SpriteAnimation(this);
}
};
}
}
sheets[name] = sheet;
},
// return SpriteInfo
sprite: function (sheetname, spritename) {
return sheets[sheetname].sprites[spritename];
},
// return SpriteAnimation
animation: function (sheetname, animationname) {
var sa = sheets[sheetname].animations[animationname];
return sa.makeinstance();
}
};
}());
| mit |
firebaugh/pympi | test/test_praat.py | 10283 | #!/bin/env python
# -*- coding: utf-8 -*-
import unittest
import tempfile
import os
from pympi.Praat import TextGrid
class PraatTest(unittest.TestCase):
def setUp(self):
self.tg = TextGrid(xmax=20)
self.maxdiff = None
# Test all the Praat.TextGrid functions
def test_sort_tiers(self):
self.tg.add_tier('t2')
self.tg.add_tier('t1')
self.tg.add_tier('t3')
self.tg.add_tier('t6')
self.tg.add_tier('t4')
self.tg.add_tier('t5')
tiernames = ['t1', 't2', 't3', 't4', 't5', 't6']
self.tg.sort_tiers()
self.assertEqual([a[1] for a in self.tg.get_tier_name_num()],
tiernames)
self.tg.sort_tiers(lambda x: list(reversed(tiernames)).index(x.name))
self.assertEqual([a[1] for a in self.tg.get_tier_name_num()],
list(reversed(tiernames)))
def test_add_tier(self):
self.assertRaises(ValueError, self.tg.add_tier, 'a', number=-1)
self.assertRaises(ValueError, self.tg.add_tier, 'a', number=10)
self.tg.add_tier('tier1')
self.assertEqual(len(self.tg.tiers), 1)
self.assertEqual(self.tg.tiers[0].tier_type, 'IntervalTier')
self.tg.add_tier('tier2', tier_type='TextTier')
self.assertEqual(len(self.tg.tiers), 2)
self.assertEqual(self.tg.tiers[1].tier_type, 'TextTier')
self.tg.add_tier('tier3')
self.assertEqual(len(self.tg.tiers), 3)
self.assertEqual(['tier1', 'tier2', 'tier3'],
[a.name for a in self.tg.tiers])
self.tg.add_tier('tier4', number=2)
self.assertEqual(len(self.tg.tiers), 4)
self.assertEqual(4, len(self.tg.tiers))
def test_remove_tier(self):
self.assertRaises(Exception, self.tg.remove_tier, -1)
self.assertRaises(Exception, self.tg.remove_tier, 10)
self.tg.add_tier('tier1')
self.tg.add_tier('tier2')
self.tg.add_tier('tier3')
self.tg.add_tier('tier4', number=2)
self.tg.remove_tier(3)
self.assertEqual(len(self.tg.tiers), 3)
self.assertEqual(['tier1', 'tier3', 'tier4'],
sorted(a.name for a in self.tg.tiers))
self.tg.remove_tier('tier1')
self.assertEqual(len(self.tg.tiers), 2)
self.assertEqual(['tier3', 'tier4'],
sorted(a.name for a in self.tg.tiers))
self.tg.remove_tier(2)
self.assertEqual(len(self.tg.tiers), 1)
self.assertEqual(['tier4'], [a.name for a in self.tg.tiers])
self.tg.remove_tier('tier4')
self.assertTrue(not self.tg.tiers)
def test_get_tier(self):
self.assertRaises(Exception, self.tg.get_tier, -1)
self.assertRaises(Exception, self.tg.get_tier, 'a')
self.assertRaises(Exception, self.tg.get_tier, 10)
tier1 = self.tg.add_tier('tier1')
tier2 = self.tg.add_tier('tier2')
tier3 = self.tg.add_tier('tier3')
self.assertEqual(tier1, self.tg.get_tier(tier1.name))
self.assertEqual(tier3, self.tg.get_tier(tier3.name))
self.assertEqual(self.tg.tiers[1], self.tg.get_tier(tier2.name))
def test_change_tier_name(self):
self.assertRaises(Exception,
self.tg.change_tier_name, -1, 'b')
self.assertRaises(Exception,
self.tg.change_tier_name, 'a', 'b')
self.assertRaises(Exception,
self.tg.change_tier_name, 10, 'b')
self.tg.add_tier('tier1')
tier2 = self.tg.add_tier('tier2')
self.tg.add_tier('tier3')
self.tg.change_tier_name('tier1', 'tier1a')
self.assertEqual(['tier1a', 'tier2', 'tier3'],
[a.name for a in self.tg.tiers])
self.tg.change_tier_name(self.tg.tiers.index(tier2)+1, 'tier2a')
self.assertEqual(['tier1a', 'tier2a', 'tier3'],
[a.name for a in self.tg.tiers])
self.tg.change_tier_name('tier1a', 'tier1')
self.assertEqual(['tier1', 'tier2a', 'tier3'],
[a.name for a in self.tg.tiers])
def test_get_tiers(self):
self.tg.add_tier('tier1')
self.tg.add_tier('tier2')
self.tg.add_tier('tier3')
self.assertEqual(self.tg.tiers,
list(self.tg.get_tiers()))
def test_get_tier_name_num(self):
self.tg.add_tier('tier1')
self.tg.add_tier('tier2')
self.tg.add_tier('tier3', number=2)
self.assertEqual([(1, 'tier1'), (2, 'tier3'), (3, 'tier2')],
list(self.tg.get_tier_name_num()))
def test_to_file(self):
for codec in ['utf-8', 'latin_1', 'mac_roman']:
self.tg = TextGrid(xmax=20)
tier1 = self.tg.add_tier('tier')
tier1.add_interval(1, 2, 'i1')
tier1.add_interval(2, 3, 'i2')
tier1.add_interval(4, 5, 'i3')
tier4 = self.tg.add_tier('tier')
tier4.add_interval(1, 2, u'i1ü')
tier4.add_interval(2.0, 3, 'i2')
tier4.add_interval(4, 5.0, 'i3')
tier2 = self.tg.add_tier('tier2', tier_type='TextTier')
tier2.add_point(1, u'p1ü')
tier2.add_point(2, 'p1')
tier2.add_point(3, 'p1')
tempf = tempfile.mkstemp()[1]
# Normal mode
self.tg.to_file(tempf, codec=codec)
TextGrid(tempf, codec=codec)
# Short mode
self.tg.to_file(tempf, codec=codec, mode='s')
TextGrid(tempf, codec=codec)
# Binary mode
self.tg.to_file(tempf, mode='b')
TextGrid(tempf)
os.remove(tempf)
def test_to_eaf(self):
tier1 = self.tg.add_tier('tier1')
tier2 = self.tg.add_tier('tier2', tier_type='TextTier')
tier1.add_interval(0, 1, 'int1')
tier1.add_interval(2, 3, 'int2')
tier1.add_interval(5, 6, 'int3')
tier2.add_point(1.5, 'point1')
tier2.add_point(2.5, 'point2')
tier2.add_point(3.5, 'point3')
eaf = self.tg.to_eaf(True, 0.03)
self.assertRaises(ValueError, self.tg.to_eaf, pointlength=-1)
self.assertEqual(sorted(eaf.get_tier_names()),
sorted(['default', 'tier1', 'tier2']))
self.assertEqual(sorted(eaf.get_annotation_data_for_tier('tier1')),
sorted([(0, 1000, 'int1'), (5000, 6000, 'int3'),
(2000, 3000, 'int2')]))
self.assertEqual(sorted(eaf.get_annotation_data_for_tier('tier2')),
sorted([(2500, 2530, 'point2'),
(1500, 1530, 'point1'),
(3500, 3530, 'point3')]))
# Test all the Praat.Tier functions
def setup_tier(self):
self.tier1 = self.tg.add_tier('tier1')
self.tier2 = self.tg.add_tier('tier2', tier_type='TextTier')
def test_add_point(self):
self.setup_tier()
self.assertRaises(Exception, self.tier1.add_point, 5, 'a')
self.tier2.add_point(5, 't')
self.assertEqual([(5, 't')], self.tier2.intervals)
self.assertRaises(Exception, self.tier2.add_point, 5, 'a')
self.tier2.add_point(6, 'a')
self.assertEqual([(5, 't'), (6, 'a')], self.tier2.intervals)
self.tier2.add_point(5, 'a', False)
def test_add_interval(self):
self.setup_tier()
self.assertRaises(Exception,
self.tier2.add_interval, 5, 6, 'a')
self.assertRaises(Exception, self.tier2.add_interval, 6, 5, 'a')
self.tier1.add_interval(5, 6, 't')
self.assertEqual([(5, 6, 't')], self.tier1.intervals)
self.assertRaises(Exception, self.tier1.add_interval, 5.5, 6.5, 't')
self.tier1.add_interval(6, 7, 'a')
self.assertEqual([(5, 6, 't'), (6, 7, 'a')], self.tier1.intervals)
self.tier1.add_interval(5.5, 6.5, 't', False)
def test_remove_interval(self):
self.setup_tier()
self.assertRaises(Exception, self.tier2.remove_interval, 5)
self.tier1.add_interval(5, 6, 'a')
self.tier1.add_interval(6, 7, 'b')
self.tier1.add_interval(7, 8, 'c')
self.tier1.remove_interval(5.5)
self.assertEqual([(6, 7, 'b'), (7, 8, 'c')],
self.tier1.intervals)
self.tier1.remove_interval(8)
self.assertEqual([(6, 7, 'b')],
self.tier1.intervals)
self.tier1.remove_interval(8)
self.assertEqual([(6, 7, 'b')],
self.tier1.intervals)
def test_remove_point(self):
self.setup_tier()
self.assertRaises(Exception, self.tier1.remove_point, 5)
self.tier2.add_point(5, 'a')
self.tier2.add_point(6, 'b')
self.tier2.add_point(7, 'c')
self.tier2.remove_point(5)
self.assertEqual([(6, 'b'), (7, 'c')],
self.tier2.intervals)
self.tier2.remove_point(7)
self.assertEqual([(6, 'b')],
self.tier2.intervals)
self.tier2.remove_point(7)
self.assertEqual([(6, 'b')],
self.tier2.intervals)
def test_get_intervals(self):
self.setup_tier()
self.tier1.add_interval(5, 6, 'a')
self.tier1.add_interval(7, 8, 'c')
self.tier1.add_interval(6, 7, 'b')
self.assertEqual([(5, 6, 'a'), (6, 7, 'b'), (7, 8, 'c')],
sorted(self.tier1.get_intervals()))
self.tier2.add_point(5, 'a')
self.tier2.add_point(7, 'c')
self.tier2.add_point(6, 'b')
self.assertEqual([(5, 'a'), (6, 'b'), (7, 'c')],
sorted(self.tier2.get_intervals()))
def test_clear_intervals(self):
self.setup_tier()
self.tier1.add_interval(5, 6, 'a')
self.tier1.add_interval(6, 7, 'b')
self.tier1.add_interval(7, 8, 'c')
self.tier1.clear_intervals()
self.assertEqual([], self.tier1.intervals)
self.tier2.add_point(5, 'a')
self.tier2.add_point(6, 'b')
self.tier2.add_point(7, 'c')
self.tier2.clear_intervals()
self.assertEqual([], self.tier2.intervals)
if __name__ == '__main__':
unittest.main()
| mit |
ashemedai/ProDBG | src/native/ui/bgfx/ui_host.cpp | 2068 | #include "ui_host.h"
#include "dialogs.h"
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef PRODBG_MAC
extern void MacDialog_infoDialog(const char* title, const char* message);
extern void MacDialog_errorDialog(const char* title, const char* message);
extern void MacDialog_warningDialog(const char* title, const char* message);
PDMessageFuncs g_serviceMessageFuncs =
{
MacDialog_infoDialog,
MacDialog_errorDialog,
MacDialog_warningDialog,
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#elif PRODBG_WIN
void Windows_infoDialog(const char*, const char*);
void Windows_errorDialog(const char*, const char*);
void Windows_warningDialog(const char*, const char*);
PDMessageFuncs g_serviceMessageFuncs =
{
Windows_infoDialog,
Windows_errorDialog,
Windows_warningDialog,
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#else
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Dummy_infoDialog(const char*, const char*) {}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Dummy_errorDialog(const char*, const char*) {}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Dummy_warningDialog(const char*, const char*) {}
PDMessageFuncs g_serviceMessageFuncs =
{
Dummy_infoDialog,
Dummy_errorDialog,
Dummy_warningDialog,
};
#endif
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PDDialogFuncs g_dialogFuncs =
{
Dialog_open,
Dialog_save,
Dialog_selectDirectory,
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| mit |
aschereT/adaptiveBrightnessFlipper | flipAdaptiveBrightness/flipAdaptiveBrightness.cpp | 1473 | // flipAdaptiveBrightness.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <memory>
#include <cstdio>
using namespace std;
string exec(const char* cmd) {
shared_ptr<FILE> pipe(_popen(cmd, "r"), _pclose);
if (!pipe) return "ERROR";
char buffer[256];
std::string result = "";
while (!feof(pipe.get())) {
if (fgets(buffer, 256, pipe.get()) != NULL)
result += buffer;
}
return result;
}
string findCurrentAdaptiveValue(string status)
{
int point = status.find("Current AC Power Setting Index: 0x0000000");
cout << "String last position: " << point << endl;
string currentVal = status.substr(point+41, 1);
return currentVal;
}
int main()
{
string status = exec("powercfg /q SCHEME_CURRENT SUB_VIDEO ADAPTBRIGHT");
cout << "(" << status << ")" << endl;
string currentVal = findCurrentAdaptiveValue(status);
if (!(currentVal == "0" || currentVal == "1"))
{
cout << "Currentval not expected: " << currentVal << endl;
system("pause");
return 1;
}
cout << "Current AC value: (" << currentVal << ")" << endl;
if (currentVal == "1")
{
system("powercfg /SETACVALUEINDEX SCHEME_CURRENT SUB_VIDEO ADAPTBRIGHT 000");
cout << "Set value to: 0" << endl;
}
else
{
system("powercfg /SETACVALUEINDEX SCHEME_CURRENT SUB_VIDEO ADAPTBRIGHT 001");
cout << "Set value to: 1" << endl;
}
system("sc stop SensrSvc");
system("sc start SensrSvc");
//system("pause");
}
| mit |
Silicoin/PC_software | build/moc_bitcoingui.cpp | 6418 | /****************************************************************************
** Meta object code from reading C++ file 'bitcoingui.h'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/qt/bitcoingui.h"
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'bitcoingui.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.6. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_BitcoinGUI[] = {
// content:
6, // revision
0, // classname
0, 0, // classinfo
24, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: signature, parameters, type, tag, flags
11, 34, 40, 40, 0x0a,
41, 63, 40, 40, 0x0a,
82, 107, 40, 40, 0x0a,
114, 150, 40, 40, 0x0a,
174, 204, 40, 40, 0x2a,
224, 245, 40, 40, 0x0a,
265, 284, 40, 40, 0x0a,
291, 347, 40, 40, 0x0a,
377, 40, 40, 40, 0x08,
396, 40, 40, 40, 0x08,
414, 40, 40, 40, 0x08,
436, 40, 40, 40, 0x08,
459, 486, 40, 40, 0x08,
491, 40, 40, 40, 0x28,
511, 486, 40, 40, 0x08,
539, 40, 40, 40, 0x28,
560, 486, 40, 40, 0x08,
590, 40, 40, 40, 0x28,
613, 40, 40, 40, 0x08,
630, 40, 40, 40, 0x08,
645, 673, 40, 40, 0x08,
687, 40, 40, 40, 0x28,
711, 40, 40, 40, 0x08,
726, 40, 40, 40, 0x08,
0 // eod
};
static const char qt_meta_stringdata_BitcoinGUI[] = {
"BitcoinGUI\0setNumConnections(int)\0"
"count\0\0setNumBlocks(int,int)\0"
"count,nTotalBlocks\0setEncryptionStatus(int)\0"
"status\0message(QString,QString,uint,bool*)\0"
"title,message,style,ret\0"
"message(QString,QString,uint)\0"
"title,message,style\0askFee(qint64,bool*)\0"
"nFeeRequired,payFee\0handleURI(QString)\0"
"strURI\0incomingTransaction(QString,int,qint64,QString,QString)\0"
"date,unit,amount,type,address\0"
"gotoOverviewPage()\0gotoHistoryPage()\0"
"gotoAddressBookPage()\0gotoReceiveCoinsPage()\0"
"gotoSendCoinsPage(QString)\0addr\0"
"gotoSendCoinsPage()\0gotoSignMessageTab(QString)\0"
"gotoSignMessageTab()\0gotoVerifyMessageTab(QString)\0"
"gotoVerifyMessageTab()\0optionsClicked()\0"
"aboutClicked()\0showNormalIfMinimized(bool)\0"
"fToggleHidden\0showNormalIfMinimized()\0"
"toggleHidden()\0detectShutdown()\0"
};
void BitcoinGUI::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Q_ASSERT(staticMetaObject.cast(_o));
BitcoinGUI *_t = static_cast<BitcoinGUI *>(_o);
switch (_id) {
case 0: _t->setNumConnections((*reinterpret_cast< int(*)>(_a[1]))); break;
case 1: _t->setNumBlocks((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 2: _t->setEncryptionStatus((*reinterpret_cast< int(*)>(_a[1]))); break;
case 3: _t->message((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2])),(*reinterpret_cast< uint(*)>(_a[3])),(*reinterpret_cast< bool*(*)>(_a[4]))); break;
case 4: _t->message((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2])),(*reinterpret_cast< uint(*)>(_a[3]))); break;
case 5: _t->askFee((*reinterpret_cast< qint64(*)>(_a[1])),(*reinterpret_cast< bool*(*)>(_a[2]))); break;
case 6: _t->handleURI((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 7: _t->incomingTransaction((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< qint64(*)>(_a[3])),(*reinterpret_cast< const QString(*)>(_a[4])),(*reinterpret_cast< const QString(*)>(_a[5]))); break;
case 8: _t->gotoOverviewPage(); break;
case 9: _t->gotoHistoryPage(); break;
case 10: _t->gotoAddressBookPage(); break;
case 11: _t->gotoReceiveCoinsPage(); break;
case 12: _t->gotoSendCoinsPage((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 13: _t->gotoSendCoinsPage(); break;
case 14: _t->gotoSignMessageTab((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 15: _t->gotoSignMessageTab(); break;
case 16: _t->gotoVerifyMessageTab((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 17: _t->gotoVerifyMessageTab(); break;
case 18: _t->optionsClicked(); break;
case 19: _t->aboutClicked(); break;
case 20: _t->showNormalIfMinimized((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 21: _t->showNormalIfMinimized(); break;
case 22: _t->toggleHidden(); break;
case 23: _t->detectShutdown(); break;
default: ;
}
}
}
const QMetaObjectExtraData BitcoinGUI::staticMetaObjectExtraData = {
0, qt_static_metacall
};
const QMetaObject BitcoinGUI::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_BitcoinGUI,
qt_meta_data_BitcoinGUI, &staticMetaObjectExtraData }
};
#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &BitcoinGUI::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION
const QMetaObject *BitcoinGUI::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}
void *BitcoinGUI::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_BitcoinGUI))
return static_cast<void*>(const_cast< BitcoinGUI*>(this));
return QMainWindow::qt_metacast(_clname);
}
int BitcoinGUI::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 24)
qt_static_metacall(this, _c, _id, _a);
_id -= 24;
}
return _id;
}
QT_END_MOC_NAMESPACE
| mit |
justcarakas/forkcms | src/Modules/Backend/Domain/AjaxAction/AjaxActionNameDBALType.php | 317 | <?php
namespace ForkCMS\Modules\Backend\Domain\AjaxAction;
use ForkCMS\Core\Domain\Doctrine\ValueObjectDBALType;
use Stringable;
class AjaxActionNameDBALType extends ValueObjectDBALType
{
protected function fromString(string $value): Stringable
{
return AjaxActionName::fromString($value);
}
}
| mit |
huysentruitw/win-beacon | src/WinBeacon.Stack/Hci/DataReceivedEventArgs.cs | 934 | /*
* Copyright 2015-2019 Huysentruit Wouter
*
* See LICENSE file.
*/
using System;
namespace WinBeacon.Stack.Hci
{
/// <summary>
/// Event arguments for the DataReceived event.
/// </summary>
internal class DataReceivedEventArgs : EventArgs
{
/// <summary>
/// The received data.
/// </summary>
public byte[] Data { get; private set; }
/// <summary>
/// The type of the received data.
/// </summary>
public DataType DataType { get; private set; }
/// <summary>
/// Constructs a new DataReceivedEventArgs instance.
/// </summary>
/// <param name="data">The received data.</param>
/// <param name="dataType">The type of the received data.</param>
public DataReceivedEventArgs(byte[] data, DataType dataType)
{
Data = data;
DataType = dataType;
}
}
}
| mit |
SickheadGames/Torsion | code/wxWidgets/src/common/tbarbase.cpp | 19928 | /////////////////////////////////////////////////////////////////////////////
// Name: common/tbarbase.cpp
// Purpose: wxToolBarBase implementation
// Author: Julian Smart
// Modified by: VZ at 11.12.99 (wxScrollableToolBar split off)
// Created: 04/01/98
// RCS-ID: $Id: tbarbase.cpp,v 1.78.2.1 2006/02/16 03:03:43 RD Exp $
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma implementation "tbarbase.h"
#endif
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_TOOLBAR
#ifndef WX_PRECOMP
#include "wx/control.h"
#endif
#include "wx/frame.h"
#if wxUSE_IMAGE
#include "wx/image.h"
#include "wx/settings.h"
#endif // wxUSE_IMAGE
#include "wx/toolbar.h"
// ----------------------------------------------------------------------------
// wxWidgets macros
// ----------------------------------------------------------------------------
BEGIN_EVENT_TABLE(wxToolBarBase, wxControl)
END_EVENT_TABLE()
#include "wx/listimpl.cpp"
WX_DEFINE_LIST(wxToolBarToolsList);
// ============================================================================
// implementation
// ============================================================================
// ----------------------------------------------------------------------------
// wxToolBarToolBase
// ----------------------------------------------------------------------------
IMPLEMENT_DYNAMIC_CLASS(wxToolBarToolBase, wxObject)
bool wxToolBarToolBase::Enable(bool enable)
{
if ( m_enabled == enable )
return false;
m_enabled = enable;
return true;
}
bool wxToolBarToolBase::Toggle(bool toggle)
{
wxASSERT_MSG( CanBeToggled(), _T("can't toggle this tool") );
if ( m_toggled == toggle )
return false;
m_toggled = toggle;
return true;
}
bool wxToolBarToolBase::SetToggle(bool toggle)
{
wxItemKind kind = toggle ? wxITEM_CHECK : wxITEM_NORMAL;
if ( m_kind == kind )
return false;
m_kind = kind;
return true;
}
bool wxToolBarToolBase::SetShortHelp(const wxString& help)
{
if ( m_shortHelpString == help )
return false;
m_shortHelpString = help;
return true;
}
bool wxToolBarToolBase::SetLongHelp(const wxString& help)
{
if ( m_longHelpString == help )
return false;
m_longHelpString = help;
return true;
}
#if WXWIN_COMPATIBILITY_2_2
const wxBitmap& wxToolBarToolBase::GetBitmap1() const
{
return GetNormalBitmap();
}
const wxBitmap& wxToolBarToolBase::GetBitmap2() const
{
return GetDisabledBitmap();
}
void wxToolBarToolBase::SetBitmap1(const wxBitmap& bmp)
{
SetNormalBitmap(bmp);
}
void wxToolBarToolBase::SetBitmap2(const wxBitmap& bmp)
{
SetDisabledBitmap(bmp);
}
#endif // WXWIN_COMPATIBILITY_2_2
// ----------------------------------------------------------------------------
// wxToolBarBase adding/deleting items
// ----------------------------------------------------------------------------
wxToolBarBase::wxToolBarBase()
{
// the list owns the pointers
m_xMargin = m_yMargin = 0;
m_maxRows = m_maxCols = 0;
m_toolPacking = m_toolSeparation = 0;
m_defaultWidth = 16;
m_defaultHeight = 15;
}
wxToolBarToolBase *wxToolBarBase::DoAddTool(int id,
const wxString& label,
const wxBitmap& bitmap,
const wxBitmap& bmpDisabled,
wxItemKind kind,
const wxString& shortHelp,
const wxString& longHelp,
wxObject *clientData,
wxCoord WXUNUSED(xPos),
wxCoord WXUNUSED(yPos))
{
InvalidateBestSize();
return InsertTool(GetToolsCount(), id, label, bitmap, bmpDisabled,
kind, shortHelp, longHelp, clientData);
}
wxToolBarToolBase *wxToolBarBase::InsertTool(size_t pos,
int id,
const wxString& label,
const wxBitmap& bitmap,
const wxBitmap& bmpDisabled,
wxItemKind kind,
const wxString& shortHelp,
const wxString& longHelp,
wxObject *clientData)
{
wxCHECK_MSG( pos <= GetToolsCount(), (wxToolBarToolBase *)NULL,
_T("invalid position in wxToolBar::InsertTool()") );
wxToolBarToolBase *tool = CreateTool(id, label, bitmap, bmpDisabled, kind,
clientData, shortHelp, longHelp);
if ( !InsertTool(pos, tool) )
{
delete tool;
return NULL;
}
return tool;
}
wxToolBarToolBase *wxToolBarBase::AddTool(wxToolBarToolBase *tool)
{
return InsertTool(GetToolsCount(), tool);
}
wxToolBarToolBase *
wxToolBarBase::InsertTool(size_t pos, wxToolBarToolBase *tool)
{
wxCHECK_MSG( pos <= GetToolsCount(), (wxToolBarToolBase *)NULL,
_T("invalid position in wxToolBar::InsertTool()") );
if ( !tool || !DoInsertTool(pos, tool) )
{
return NULL;
}
m_tools.Insert(pos, tool);
return tool;
}
wxToolBarToolBase *wxToolBarBase::AddControl(wxControl *control)
{
return InsertControl(GetToolsCount(), control);
}
wxToolBarToolBase *wxToolBarBase::InsertControl(size_t pos, wxControl *control)
{
wxCHECK_MSG( control, (wxToolBarToolBase *)NULL,
_T("toolbar: can't insert NULL control") );
wxCHECK_MSG( control->GetParent() == this, (wxToolBarToolBase *)NULL,
_T("control must have toolbar as parent") );
wxCHECK_MSG( pos <= GetToolsCount(), (wxToolBarToolBase *)NULL,
_T("invalid position in wxToolBar::InsertControl()") );
wxToolBarToolBase *tool = CreateTool(control);
if ( !InsertTool(pos, tool) )
{
delete tool;
return NULL;
}
return tool;
}
wxControl *wxToolBarBase::FindControl( int id )
{
for ( wxToolBarToolsList::compatibility_iterator node = m_tools.GetFirst();
node;
node = node->GetNext() )
{
const wxToolBarToolBase * const tool = node->GetData();
if ( tool->IsControl() )
{
wxControl * const control = tool->GetControl();
if ( !control )
{
wxFAIL_MSG( _T("NULL control in toolbar?") );
}
else if ( control->GetId() == id )
{
// found
return control;
}
}
}
return NULL;
}
wxToolBarToolBase *wxToolBarBase::AddSeparator()
{
return InsertSeparator(GetToolsCount());
}
wxToolBarToolBase *wxToolBarBase::InsertSeparator(size_t pos)
{
wxCHECK_MSG( pos <= GetToolsCount(), (wxToolBarToolBase *)NULL,
_T("invalid position in wxToolBar::InsertSeparator()") );
wxToolBarToolBase *tool = CreateTool(wxID_SEPARATOR,
wxEmptyString,
wxNullBitmap, wxNullBitmap,
wxITEM_SEPARATOR, (wxObject *)NULL,
wxEmptyString, wxEmptyString);
if ( !tool || !DoInsertTool(pos, tool) )
{
delete tool;
return NULL;
}
m_tools.Insert(pos, tool);
return tool;
}
wxToolBarToolBase *wxToolBarBase::RemoveTool(int id)
{
size_t pos = 0;
wxToolBarToolsList::compatibility_iterator node;
for ( node = m_tools.GetFirst(); node; node = node->GetNext() )
{
if ( node->GetData()->GetId() == id )
break;
pos++;
}
if ( !node )
{
// don't give any error messages - sometimes we might call RemoveTool()
// without knowing whether the tool is or not in the toolbar
return (wxToolBarToolBase *)NULL;
}
wxToolBarToolBase *tool = node->GetData();
if ( !DoDeleteTool(pos, tool) )
{
return (wxToolBarToolBase *)NULL;
}
m_tools.Erase(node);
return tool;
}
bool wxToolBarBase::DeleteToolByPos(size_t pos)
{
wxCHECK_MSG( pos < GetToolsCount(), false,
_T("invalid position in wxToolBar::DeleteToolByPos()") );
wxToolBarToolsList::compatibility_iterator node = m_tools.Item(pos);
if ( !DoDeleteTool(pos, node->GetData()) )
{
return false;
}
delete node->GetData();
m_tools.Erase(node);
return true;
}
bool wxToolBarBase::DeleteTool(int id)
{
size_t pos = 0;
wxToolBarToolsList::compatibility_iterator node;
for ( node = m_tools.GetFirst(); node; node = node->GetNext() )
{
if ( node->GetData()->GetId() == id )
break;
pos++;
}
if ( !node || !DoDeleteTool(pos, node->GetData()) )
{
return false;
}
delete node->GetData();
m_tools.Erase(node);
return true;
}
wxToolBarToolBase *wxToolBarBase::FindById(int id) const
{
wxToolBarToolBase *tool = (wxToolBarToolBase *)NULL;
for ( wxToolBarToolsList::compatibility_iterator node = m_tools.GetFirst();
node;
node = node->GetNext() )
{
tool = node->GetData();
if ( tool->GetId() == id )
{
// found
break;
}
tool = NULL;
}
return tool;
}
void wxToolBarBase::UnToggleRadioGroup(wxToolBarToolBase *tool)
{
wxCHECK_RET( tool, _T("NULL tool in wxToolBarTool::UnToggleRadioGroup") );
if ( !tool->IsButton() || tool->GetKind() != wxITEM_RADIO )
return;
wxToolBarToolsList::compatibility_iterator node = m_tools.Find(tool);
wxCHECK_RET( node, _T("invalid tool in wxToolBarTool::UnToggleRadioGroup") );
wxToolBarToolsList::compatibility_iterator nodeNext = node->GetNext();
while ( nodeNext )
{
wxToolBarToolBase *tool = nodeNext->GetData();
if ( !tool->IsButton() || tool->GetKind() != wxITEM_RADIO )
break;
if ( tool->Toggle(false) )
{
DoToggleTool(tool, false);
}
nodeNext = nodeNext->GetNext();
}
wxToolBarToolsList::compatibility_iterator nodePrev = node->GetPrevious();
while ( nodePrev )
{
wxToolBarToolBase *tool = nodePrev->GetData();
if ( !tool->IsButton() || tool->GetKind() != wxITEM_RADIO )
break;
if ( tool->Toggle(false) )
{
DoToggleTool(tool, false);
}
nodePrev = nodePrev->GetPrevious();
}
}
void wxToolBarBase::ClearTools()
{
while ( GetToolsCount() )
{
DeleteToolByPos(0);
}
}
bool wxToolBarBase::Realize()
{
return true;
}
wxToolBarBase::~wxToolBarBase()
{
WX_CLEAR_LIST(wxToolBarToolsList, m_tools);
// notify the frame that it doesn't have a tool bar any longer to avoid
// dangling pointers
wxFrame *frame = wxDynamicCast(GetParent(), wxFrame);
if ( frame && frame->GetToolBar() == this )
{
frame->SetToolBar(NULL);
}
}
// ----------------------------------------------------------------------------
// wxToolBarBase tools state
// ----------------------------------------------------------------------------
void wxToolBarBase::EnableTool(int id, bool enable)
{
wxToolBarToolBase *tool = FindById(id);
if ( tool )
{
if ( tool->Enable(enable) )
{
DoEnableTool(tool, enable);
}
}
}
void wxToolBarBase::ToggleTool(int id, bool toggle)
{
wxToolBarToolBase *tool = FindById(id);
if ( tool && tool->CanBeToggled() )
{
if ( tool->Toggle(toggle) )
{
UnToggleRadioGroup(tool);
DoToggleTool(tool, toggle);
}
}
}
void wxToolBarBase::SetToggle(int id, bool toggle)
{
wxToolBarToolBase *tool = FindById(id);
if ( tool )
{
if ( tool->SetToggle(toggle) )
{
DoSetToggle(tool, toggle);
}
}
}
void wxToolBarBase::SetToolShortHelp(int id, const wxString& help)
{
wxToolBarToolBase *tool = FindById(id);
if ( tool )
{
(void)tool->SetShortHelp(help);
}
}
void wxToolBarBase::SetToolLongHelp(int id, const wxString& help)
{
wxToolBarToolBase *tool = FindById(id);
if ( tool )
{
(void)tool->SetLongHelp(help);
}
}
wxObject *wxToolBarBase::GetToolClientData(int id) const
{
wxToolBarToolBase *tool = FindById(id);
return tool ? tool->GetClientData() : (wxObject *)NULL;
}
void wxToolBarBase::SetToolClientData(int id, wxObject *clientData)
{
wxToolBarToolBase *tool = FindById(id);
wxCHECK_RET( tool, _T("no such tool in wxToolBar::SetToolClientData") );
tool->SetClientData(clientData);
}
int wxToolBarBase::GetToolPos(int id) const
{
size_t pos = 0;
wxToolBarToolsList::compatibility_iterator node;
for ( node = m_tools.GetFirst(); node; node = node->GetNext() )
{
if ( node->GetData()->GetId() == id )
return pos;
pos++;
}
return wxNOT_FOUND;
}
bool wxToolBarBase::GetToolState(int id) const
{
wxToolBarToolBase *tool = FindById(id);
wxCHECK_MSG( tool, false, _T("no such tool") );
return tool->IsToggled();
}
bool wxToolBarBase::GetToolEnabled(int id) const
{
wxToolBarToolBase *tool = FindById(id);
wxCHECK_MSG( tool, false, _T("no such tool") );
return tool->IsEnabled();
}
wxString wxToolBarBase::GetToolShortHelp(int id) const
{
wxToolBarToolBase *tool = FindById(id);
wxCHECK_MSG( tool, wxEmptyString, _T("no such tool") );
return tool->GetShortHelp();
}
wxString wxToolBarBase::GetToolLongHelp(int id) const
{
wxToolBarToolBase *tool = FindById(id);
wxCHECK_MSG( tool, wxEmptyString, _T("no such tool") );
return tool->GetLongHelp();
}
// ----------------------------------------------------------------------------
// wxToolBarBase geometry
// ----------------------------------------------------------------------------
void wxToolBarBase::SetMargins(int x, int y)
{
m_xMargin = x;
m_yMargin = y;
}
void wxToolBarBase::SetRows(int WXUNUSED(nRows))
{
// nothing
}
// ----------------------------------------------------------------------------
// event processing
// ----------------------------------------------------------------------------
// Only allow toggle if returns true
bool wxToolBarBase::OnLeftClick(int id, bool toggleDown)
{
wxCommandEvent event(wxEVT_COMMAND_TOOL_CLICKED, id);
event.SetEventObject(this);
// we use SetInt() to make wxCommandEvent::IsChecked() return toggleDown
event.SetInt((int)toggleDown);
// and SetExtraLong() for backwards compatibility
event.SetExtraLong((long)toggleDown);
// Send events to this toolbar instead (and thence up the window hierarchy)
GetEventHandler()->ProcessEvent(event);
return true;
}
// Call when right button down.
void wxToolBarBase::OnRightClick(int id,
long WXUNUSED(x),
long WXUNUSED(y))
{
wxCommandEvent event(wxEVT_COMMAND_TOOL_RCLICKED, id);
event.SetEventObject(this);
event.SetInt(id);
GetEventHandler()->ProcessEvent(event);
}
// Called when the mouse cursor enters a tool bitmap (no button pressed).
// Argument is wxID_ANY if mouse is exiting the toolbar.
// Note that for this event, the id of the window is used,
// and the integer parameter of wxCommandEvent is used to retrieve
// the tool id.
void wxToolBarBase::OnMouseEnter(int id)
{
wxCommandEvent event(wxEVT_COMMAND_TOOL_ENTER, GetId());
event.SetEventObject(this);
event.SetInt(id);
wxFrame *frame = wxDynamicCast(GetParent(), wxFrame);
if( frame )
{
wxString help;
wxToolBarToolBase* tool = id == wxID_ANY ? (wxToolBarToolBase*)NULL : FindById(id);
if(tool)
help = tool->GetLongHelp();
frame->DoGiveHelp( help, id != wxID_ANY );
}
(void)GetEventHandler()->ProcessEvent(event);
}
// ----------------------------------------------------------------------------
// UI updates
// ----------------------------------------------------------------------------
// Do the toolbar button updates (check for EVT_UPDATE_UI handlers)
void wxToolBarBase::UpdateWindowUI(long flags)
{
wxWindowBase::UpdateWindowUI(flags);
// There is no sense in updating the toolbar UI
// if the parent window is about to get destroyed
wxWindow *tlw = wxGetTopLevelParent( this );
if (tlw && wxPendingDelete.Member( tlw ))
return;
wxEvtHandler* evtHandler = GetEventHandler() ;
for ( wxToolBarToolsList::compatibility_iterator node = m_tools.GetFirst();
node;
node = node->GetNext() )
{
int id = node->GetData()->GetId();
wxUpdateUIEvent event(id);
event.SetEventObject(this);
if ( evtHandler->ProcessEvent(event) )
{
if ( event.GetSetEnabled() )
EnableTool(id, event.GetEnabled());
if ( event.GetSetChecked() )
ToggleTool(id, event.GetChecked());
#if 0
if ( event.GetSetText() )
// Set tooltip?
#endif // 0
}
}
}
#if wxUSE_IMAGE
/*
* Make a greyed-out image suitable for disabled buttons.
* This code is adapted from wxNewBitmapButton in FL.
*/
bool wxCreateGreyedImage(const wxImage& src, wxImage& dst)
{
dst = src.Copy();
unsigned char rBg, gBg, bBg;
if ( src.HasMask() )
{
src.GetOrFindMaskColour(&rBg, &gBg, &bBg);
dst.SetMaskColour(rBg, gBg, bBg);
}
else // assuming the pixels along the edges are of the background color
{
rBg = src.GetRed(0, 0);
gBg = src.GetGreen(0, 0);
bBg = src.GetBlue(0, 0);
}
const wxColour colBg(rBg, gBg, bBg);
const wxColour colDark = wxSystemSettings::GetColour(wxSYS_COLOUR_3DSHADOW);
const wxColour colLight = wxSystemSettings::GetColour(wxSYS_COLOUR_3DHIGHLIGHT);
// Second attempt, just making things monochrome
const int width = src.GetWidth();
const int height = src.GetHeight();
for ( int x = 0; x < width; x++ )
{
for ( int y = 0; y < height; y++ )
{
const int r = src.GetRed(x, y);
const int g = src.GetGreen(x, y);
const int b = src.GetBlue(x, y);
if ( r == rBg && g == gBg && b == bBg )
{
// Leave the background colour as-is
continue;
}
// Change light things to the background colour
wxColour col;
if ( r >= (colLight.Red() - 50) &&
g >= (colLight.Green() - 50) &&
b >= (colLight.Blue() - 50) )
{
col = colBg;
}
else // Change dark things to really dark
{
col = colDark;
}
dst.SetRGB(x, y, col.Red(), col.Green(), col.Blue());
}
}
return true;
}
#endif // wxUSE_IMAGE
#endif // wxUSE_TOOLBAR
| mit |
fmsouza/wcode | src/common/utils/index.js | 27 | export * from './keyboard'; | mit |
Hinny/strange-eons-xwing-plug-in | X-wing/resources/x-wing/components/huge-ship-card/huge-ship-card.js | 70038 | useLibrary( 'diy' );
useLibrary( 'ui' );
useLibrary( 'imageutils' );
useLibrary( 'markup' );
importClass( java.awt.BasicStroke );
importClass( java.awt.Stroke );
importClass( java.awt.RenderingHints );
importClass( java.awt.Graphics2D );
importClass( arkham.diy.ListItem );
importClass( arkham.component.DefaultPortrait );
// When the script is run directly from the editor, this will load
// the test-lib library, which does the setup tasks that the
// plug-in would have done if it was run. This lets us test and
// develop the plug-in without having to rebuild the plug-in bundle
// and start a new copy of Strange Eons every time we make a change.
if( sourcefile == 'Quickscript' ) {
useLibrary( 'project:X-wing/resources/x-wing/test-lib.js' );
}
const Xwing = Eons.namedObjects.Xwing;
portraits = [];
// Returns the number of portraits we will be using.
function getPortraitCount() {
return portraits.length;
}
// Given an index from 0 to getPortraitCount()-1, this
// function must return the (index+1)th Portrait.
function getPortrait( index ) {
if( index < 0 || index >= portraits.length ) {
throw new Error( 'invalid portrait index: ' + index );
}
return portraits[ index ];
}
function create( diy ) {
diy.version = 3;
diy.extensionName = 'Xwing.seext';
diy.faceStyle = FaceStyle.SIX_FACES;
diy.transparentFaces = true;
diy.variableSizedFaces = true;
diy.customPortraitHandling = true;
// Card Art
portraits[0] = new DefaultPortrait( diy, 'huge-fore-front' );
portraits[0].setScaleUsesMinimum( false );
portraits[0].facesToUpdate = [0];
portraits[0].backgroundFilled = true;
portraits[0].clipping = true;
portraits[0].installDefault();
portraits[1] = new DefaultPortrait( diy, 'huge-fore-back' );
portraits[1].setScaleUsesMinimum( false );
portraits[1].facesToUpdate = [1];
portraits[1].backgroundFilled = true;
portraits[1].clipping = true;
portraits[1].installDefault();
portraits[2] = new DefaultPortrait( diy, 'huge-aft-front' );
portraits[2].setScaleUsesMinimum( false );
portraits[2].facesToUpdate = [2];
portraits[2].backgroundFilled = true;
portraits[2].clipping = true;
portraits[2].installDefault();
portraits[3] = new DefaultPortrait( diy, 'huge-aft-back' );
portraits[3].setScaleUsesMinimum( false );
portraits[3].facesToUpdate = [3];
portraits[3].backgroundFilled = true;
portraits[3].clipping = true;
portraits[3].installDefault();
// Ship Icon, Card
portraits[4] = new DefaultPortrait( diy, 'huge-ship-card' );
portraits[4].setScaleUsesMinimum( true );
portraits[4].facesToUpdate = [0,1,2,3];
portraits[4].backgroundFilled = false;
portraits[4].clipping = true;
portraits[4].installDefault();
// Ship Icon, Token
portraits[5] = new DefaultPortrait( portraits[4], 'huge-ship-token' );
portraits[5].setScaleUsesMinimum( true );
portraits[5].facesToUpdate = [4];
portraits[5].backgroundFilled = false;
portraits[5].clipping = true;
portraits[5].installDefault();
diy.setTemplateKey( 0, 'huge-rebel-fore' );
diy.setTemplateKey( 1, 'huge-rebel-fore' );
diy.setTemplateKey( 2, 'huge-rebel-aft' );
diy.setTemplateKey( 3, 'huge-rebel-aft' );
diy.setTemplateKey( 4, 'huge-double-token' );
diy.setTemplateKey( 5, 'huge-double-token' );
// install the example ship
diy.name = #xw-huge-ship;
$Affiliation = #xw-huge-affiliation;
$PilotSkill = #xw-huge-ps;
$ForeDesignation = #xw-huge-fore-designation;
$ForeText = #xw-huge-fore-text;
$ForeTextFlavor = #xw-huge-fore-text-flavor;
$ForeCrippledText = #xw-huge-fore-crippled-text;
$ForeCrippledTextFlavor = #xw-huge-fore-crippled-text-flavor;
$ForePwv = #xw-huge-fore-pwv;
$ForeCrippledPwv = #xw-huge-fore-crippled-pwv;
$ForeRange = #xw-huge-fore-range;
$ForeCrippledRange = #xw-huge-fore-crippled-range;
$ForeArc = #xw-huge-fore-arc;
$ForeTurret = #xw-huge-fore-turret;
$ForeEnergy = #xw-huge-fore-energy;
$ForeCrippledEnergy = #xw-huge-fore-crippled-energy;
$ForeHull = #xw-huge-fore-hull;
$ForeShield = #xw-huge-fore-shield;
$ForeRecoverAction = #xw-huge-fore-recover;
$ForeReinforceAction = #xw-huge-fore-reinforce;
$ForeCoordinateAction = #xw-huge-fore-coordinate;
$ForeJamAction = #xw-huge-fore-jam;
$ForeLockAction = #xw-huge-fore-lock;
$ForeUpgrade1 = #xw-huge-fore-upgrade-1;
$ForeUpgrade2 = #xw-huge-fore-upgrade-2;
$ForeUpgrade3 = #xw-huge-fore-upgrade-3;
$ForeUpgrade4 = #xw-huge-fore-upgrade-4;
$ForeUpgrade5 = #xw-huge-fore-upgrade-5;
$ForeUpgrade6 = #xw-huge-fore-upgrade-6;
$ForeUpgrade7 = #xw-huge-fore-upgrade-7;
$ForeCrippledUpgrade1 = #xw-huge-fore-crippled-upgrade-1;
$ForeCrippledUpgrade2 = #xw-huge-fore-crippled-upgrade-2;
$ForeCrippledUpgrade3 = #xw-huge-fore-crippled-upgrade-3;
$ForeCrippledUpgrade4 = #xw-huge-fore-crippled-upgrade-4;
$ForeCrippledUpgrade5 = #xw-huge-fore-crippled-upgrade-5;
$ForeCrippledUpgrade6 = #xw-huge-fore-crippled-upgrade-6;
$ForeCrippledUpgrade7 = #xw-huge-fore-crippled-upgrade-7;
$ForeCost = #xw-huge-fore-cost;
$AftDesignation = #xw-huge-aft-designation;
$AftText = #xw-huge-aft-text;
$AftTextFlavor = #xw-huge-aft-text-flavor;
$AftCrippledText = #xw-huge-aft-crippled-text;
$AftCrippledTextFlavor = #xw-huge-aft-crippled-text-flavor;
$AftPwv = #xw-huge-aft-pwv;
$AftCrippledPwv = #xw-huge-aft-crippled-pwv;
$AftRange = #xw-huge-aft-range;
$AftCrippledRange = #xw-huge-aft-crippled-range;
$AftArc = #xw-huge-aft-arc;
$AftTurret = #xw-huge-aft-turret;
$AftEnergy = #xw-huge-aft-energy;
$AftCrippledEnergy = #xw-huge-aft-crippled-energy;
$AftHull = #xw-huge-aft-hull;
$AftShield = #xw-huge-aft-shield;
$AftRecoverAction = #xw-huge-aft-recover;
$AftReinforceAction = #xw-huge-aft-reinforce;
$AftCoordinateAction = #xw-huge-aft-coordinate;
$AftJamAction = #xw-huge-aft-jam;
$AftLockAction = #xw-huge-aft-lock;
$AftUpgrade1 = #xw-huge-aft-upgrade-1;
$AftUpgrade2 = #xw-huge-aft-upgrade-2;
$AftUpgrade3 = #xw-huge-aft-upgrade-3;
$AftUpgrade4 = #xw-huge-aft-upgrade-4;
$AftUpgrade5 = #xw-huge-aft-upgrade-5;
$AftUpgrade6 = #xw-huge-aft-upgrade-6;
$AftUpgrade7 = #xw-huge-aft-upgrade-7;
$AftCrippledUpgrade1 = #xw-huge-aft-crippled-upgrade-1;
$AftCrippledUpgrade2 = #xw-huge-aft-crippled-upgrade-2;
$AftCrippledUpgrade3 = #xw-huge-aft-crippled-upgrade-3;
$AftCrippledUpgrade4 = #xw-huge-aft-crippled-upgrade-4;
$AftCrippledUpgrade5 = #xw-huge-aft-crippled-upgrade-5;
$AftCrippledUpgrade6 = #xw-huge-aft-crippled-upgrade-6;
$AftCrippledUpgrade7 = #xw-huge-aft-crippled-upgrade-7;
$AftCost = #xw-huge-aft-cost;
$Location = #xw-huge-location;
$DoubleSection = #xw-huge-double;
}
function createInterface( diy, editor ) {
bindings = new Bindings( editor, diy );
// Common Panel
affiliationItems = [];
affiliationItems[0] = ListItem( 'alliance', @xw-affiliation-alliance );
affiliationItems[1] = ListItem( 'resistance', @xw-affiliation-resistance );
affiliationItems[2] = ListItem( 'empire', @xw-affiliation-empire );
affiliationItems[3] = ListItem( 'firstorder', @xw-affiliation-firstorder );
affiliationItems[4] = ListItem( 'scum', @xw-affiliation-scum );
affiliationBox = comboBox( affiliationItems );
bindings.add( 'Affiliation', affiliationBox, [0,1,2,3,4] );
nameField = textField( 'X', 30 );
doubleCheckbox = checkBox( @xw-double-sections );
bindings.add( 'DoubleSection', doubleCheckbox, [0,1,2,3,4,5] );
locationItems = [];
locationItems[0] = ListItem( 'attack-energy', @xw-location-attack-energy );
locationItems[1] = ListItem( 'energy-attack', @xw-location-energy-attack );
locationItems[2] = ListItem( 'none-energy', @xw-location-none-energy );
locationItems[3] = ListItem( 'energy-none', @xw-location-energy-none );
locationBox = comboBox( locationItems );
bindings.add( 'Location', locationBox, [0,1,2,3,4] );
psItems = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
psBox = comboBox( psItems );
bindings.add( 'PilotSkill', psBox, [0,1,2,3,4] );
iconCardPanel = portraitPanel( diy, 4 );
iconCardPanel.panelTitle = @xw-icon-card;
iconTokenPanel = portraitPanel( diy, 5 );
iconTokenPanel.setParentPanel( iconCardPanel );
iconTokenPanel.panelTitle = @xw-icon-token;
commonPanel = new Grid( '', '[min:pref][min:pref,grow][min:pref][min:pref,grow]', '');
commonPanel.setTitle( @xw-info );
commonPanel.place( @xw-affiliation, '', affiliationBox, 'growx, wrap' );
commonPanel.place( @xw-ship, '', nameField, 'span, growx, wrap' );
commonPanel.place( doubleCheckbox, 'span, wrap para' );
commonPanel.place( @xw-location, '', locationBox, 'growx, wrap' );
commonPanel.place( @xw-ps, '', psBox, 'wmin 52, wrap' );
commonPanel.place( iconCardPanel, 'span, growx, wrap' );
commonPanel.place( iconTokenPanel, 'span, growx, wrap' );
commonPanel.editorTabScrolling = true;
// Fore Panel
foreSectionDesignationItems = [ #xw-fore-designation ];
foreSectionDesignationField = autocompletionField( foreSectionDesignationItems );
bindings.add( 'ForeDesignation', foreSectionDesignationField, [0,1,4] );
foreTextArea = textArea( '', 6, 15, true );
bindings.add( 'ForeText', foreTextArea, [0] );
foreTextFlavor = checkBox( @xw-text-flavor );
bindings.add( 'ForeTextFlavor', foreTextFlavor, [0] );
foreCrippledTextArea = textArea( '', 6, 15, true );
bindings.add( 'ForeCrippledText', foreCrippledTextArea, [1] );
foreCrippledTextFlavor = checkBox( @xw-text-flavor );
bindings.add( 'ForeCrippledTextFlavor', foreCrippledTextFlavor, [1] );
symbolsTagTip = tipButton( @xw-symbol-tooltip );
headersTagTip = tipButton( @xw-header-tooltip );
shipsTagTip = tipButton( @xw-ship-tooltip );
foreArcItems = [];
foreArcItems[0] = ListItem( '-', '-' );
foreArcItems[1] = ListItem( 'broadside', @xw-arc-broadside );
foreArcItems[2] = ListItem( 'extendedBroadside', @xw-arc-extended-broadside );
foreArcItems[3] = ListItem( 'front', @xw-arc-front );
foreArcItems[4] = ListItem( 'extendedFront', @xw-arc-extended-front );
foreArcItems[5] = ListItem( 'fullArc', @xw-arc-full );
foreArcBox = comboBox( foreArcItems );
bindings.add( 'ForeArc', foreArcBox, [4] );
foreTurret = checkBox( @xw-turret );
bindings.add( 'ForeTurret', foreTurret, [0,1,4] );
rangeItems = [];
rangeItems[0] = ListItem( '1', '1' );
rangeItems[1] = ListItem( '1-2', '1-2' );
rangeItems[2] = ListItem( '1-3', '1-3' );
rangeItems[3] = ListItem( '1-4', '1-4' );
rangeItems[4] = ListItem( '1-5', '1-5' );
rangeItems[5] = ListItem( '2', '2' );
rangeItems[6] = ListItem( '2-3', '2-3' );
rangeItems[7] = ListItem( '2-4', '2-4' );
rangeItems[8] = ListItem( '2-5', '2-5' );
rangeItems[9] = ListItem( '3', '3' );
rangeItems[10] = ListItem( '3-4', '3-4' );
rangeItems[11] = ListItem( '3-5', '3-5' );
rangeItems[12] = ListItem( '4', '4' );
rangeItems[13] = ListItem( '4-5', '4-5' );
rangeItems[14] = ListItem( '5', '5' );
foreRangeBox = comboBox( rangeItems );
bindings.add( 'ForeRange', foreRangeBox, [0] );
foreCrippledRangeBox = comboBox( rangeItems );
bindings.add( 'ForeCrippledRange', foreCrippledRangeBox, [1] );
pwvItems = ['1', '2', '3', '4', '5', '6', '7', '8'];
forePwvBox = comboBox( pwvItems );
bindings.add( 'ForePwv', forePwvBox, [0,4] );
foreCrippledPwvBox = comboBox( pwvItems );
bindings.add( 'ForeCrippledPwv', foreCrippledPwvBox, [1] );
energyItems = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'];
foreEnergyBox = comboBox( energyItems );
bindings.add( 'ForeEnergy', foreEnergyBox, [0,4] );
foreCrippledEnergyBox = comboBox( energyItems );
bindings.add( 'ForeCrippledEnergy', foreCrippledEnergyBox, [1] );
hullItems = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'];
foreHullBox = comboBox( hullItems );
bindings.add( 'ForeHull', foreHullBox, [0,4] );
shieldItems = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'];
foreShieldBox = comboBox( shieldItems );
bindings.add( 'ForeShield', foreShieldBox, [0,4] );
foreRecoverCheckbox = checkBox( @xw-action-recover );
bindings.add( 'ForeRecoverAction', foreRecoverCheckbox, [0,4] );
foreReinforceCheckbox = checkBox( @xw-action-reinforce );
bindings.add( 'ForeReinforceAction', foreReinforceCheckbox, [0,4] );
foreCoordinateCheckbox = checkBox( @xw-action-coordinate );
bindings.add( 'ForeCoordinateAction', foreCoordinateCheckbox, [0,4] );
foreJamCheckbox = checkBox( @xw-action-jam );
bindings.add( 'ForeJamAction', foreJamCheckbox, [0,4] );
foreLockCheckbox = checkBox( @xw-action-lock );
bindings.add( 'ForeLockAction', foreLockCheckbox, [0,4] );
upgradeItems = [];
upgradeItems[0] = ListItem( '-', '-' );
upgradeItems[1] = ListItem( 'system', @xw-upgrade-system );
upgradeItems[2] = ListItem( 'cannon', @xw-upgrade-cannon );
upgradeItems[3] = ListItem( 'turret', @xw-upgrade-turret );
upgradeItems[4] = ListItem( 'torpedo', @xw-upgrade-torpedo );
upgradeItems[5] = ListItem( 'missile', @xw-upgrade-missile );
upgradeItems[6] = ListItem( 'illicit', @xw-upgrade-illicit );
upgradeItems[7] = ListItem( 'bomb', @xw-upgrade-bomb );
upgradeItems[8] = ListItem( 'crew', @xw-upgrade-crew );
upgradeItems[9] = ListItem( 'hardpoint', @xw-upgrade-hardpoint );
upgradeItems[10] = ListItem( 'team', @xw-upgrade-team );
upgradeItems[11] = ListItem( 'cargo', @xw-upgrade-cargo );
foreUpgradeBox1 = comboBox( upgradeItems );
bindings.add( 'ForeUpgrade1', foreUpgradeBox1, [0,1] );
foreCrippledUpgradeBox1 = checkBox( '' );
bindings.add( 'ForeCrippledUpgrade1', foreCrippledUpgradeBox1, [1] );
foreUpgradeBox2 = comboBox( upgradeItems );
bindings.add( 'ForeUpgrade2', foreUpgradeBox2, [0,1] );
foreCrippledUpgradeBox2 = checkBox( '' );
bindings.add( 'ForeCrippledUpgrade2', foreCrippledUpgradeBox2, [1] );
foreUpgradeBox3 = comboBox( upgradeItems );
bindings.add( 'ForeUpgrade3', foreUpgradeBox3, [0,1] );
foreCrippledUpgradeBox3 = checkBox( '' );
bindings.add( 'ForeCrippledUpgrade3', foreCrippledUpgradeBox3, [1] );
foreUpgradeBox4 = comboBox( upgradeItems );
bindings.add( 'ForeUpgrade4', foreUpgradeBox4, [0,1] );
foreCrippledUpgradeBox4 = checkBox( '' );
bindings.add( 'ForeCrippledUpgrade4', foreCrippledUpgradeBox4, [1] );
foreUpgradeBox5 = comboBox( upgradeItems );
bindings.add( 'ForeUpgrade5', foreUpgradeBox5, [0,1] );
foreCrippledUpgradeBox5 = checkBox( '' );
bindings.add( 'ForeCrippledUpgrade5', foreCrippledUpgradeBox5, [1] );
foreUpgradeBox6 = comboBox( upgradeItems );
bindings.add( 'ForeUpgrade6', foreUpgradeBox6, [0,1] );
foreCrippledUpgradeBox6 = checkBox( '' );
bindings.add( 'ForeCrippledUpgrade6', foreCrippledUpgradeBox6, [1] );
foreUpgradeBox7 = comboBox( upgradeItems );
bindings.add( 'ForeUpgrade7', foreUpgradeBox7, [0,1] );
foreCrippledUpgradeBox7 = checkBox( '' );
bindings.add( 'ForeCrippledUpgrade7', foreCrippledUpgradeBox7, [1] );
foreCostBox = spinner( 1, 200, 1, 20 );
bindings.add( 'ForeCost', foreCostBox, [0] );
forePortrait = portraitPanel( diy, 0 );
forePortrait.panelTitle = 'Healthy Side Fore Section Portrait';
foreCrippledPortrait = portraitPanel( diy, 1 );
foreCrippledPortrait.panelTitle = 'Crippled Side Fore Section Portrait';
forePanel = new Grid( '', '[min:pref][min:pref,grow][min:pref][min:pref,grow]', '');
forePanel.setTitle( @xw-info );
forePanel.place( @xw-designation, '', foreSectionDesignationField, 'span, growx, wrap' );
forePanel.place( @xw-text, 'span 2', foreTextFlavor, 'wrap' );
forePanel.place( foreTextArea, 'span, grow, wrap para' );
forePanel.place( @xw-crippledtext, 'span 2', foreCrippledTextFlavor, 'wrap');
forePanel.place( foreCrippledTextArea, 'span, grow, wrap para' );
forePanel.place( symbolsTagTip, '', headersTagTip, '', shipsTagTip, 'span, grow, wrap para' );
forePanel.place( separator(), 'span, growx, wrap para' );
forePanel.place( @xw-arc, '', foreArcBox, 'wmin 100, span 2, wrap' );
forePanel.place( foreTurret, 'wrap' );
forePanel.place( @xw-pwv, '', forePwvBox, 'wmin 52', @xw-range, '', foreRangeBox, 'wmin 70, wrap' );
forePanel.place( @xw-crippledpwv, '', foreCrippledPwvBox, 'wmin 52', @xw-range, '', foreCrippledRangeBox, 'wmin 70, wrap' );
forePanel.place( @xw-energy, '', foreEnergyBox, 'wmin 52, wrap' );
forePanel.place( @xw-crippledenergy, '', foreCrippledEnergyBox, 'wmin 52, wrap' );
forePanel.place( @xw-hull, '', foreHullBox, 'wmin 52, wrap' );
forePanel.place( @xw-shield, '', foreShieldBox, 'wmin 52, wrap para' );
forePanel.place( separator(), 'span, growx, wrap para' );
forePanel.place( @xw-actions, 'wrap' );
forePanel.place( foreRecoverCheckbox, '', foreReinforceCheckbox, '', foreCoordinateCheckbox, 'wrap' );
forePanel.place( foreJamCheckbox, '', foreLockCheckbox, 'wrap para' );
forePanel.place( separator(), 'span, growx, wrap para' );
forePanel.place( @xw-upgrades, 'wmin 100', @xw-upgrades-crippled, 'wrap' );
forePanel.place( foreUpgradeBox1, 'wmin 100', foreCrippledUpgradeBox1, 'wrap' );
forePanel.place( foreUpgradeBox2, 'wmin 100', foreCrippledUpgradeBox2, 'wrap' );
forePanel.place( foreUpgradeBox3, 'wmin 100', foreCrippledUpgradeBox3, 'wrap' );
forePanel.place( foreUpgradeBox4, 'wmin 100', foreCrippledUpgradeBox4, 'wrap' );
forePanel.place( foreUpgradeBox5, 'wmin 100', foreCrippledUpgradeBox5, 'wrap' );
forePanel.place( foreUpgradeBox6, 'wmin 100', foreCrippledUpgradeBox6, 'wrap' );
forePanel.place( foreUpgradeBox7, 'wmin 100', foreCrippledUpgradeBox7, 'wrap para' );
forePanel.place( separator(), 'span, growx, wrap para' );
forePanel.place( @xw-cost, 'span 2', foreCostBox, 'wmin 100, wrap para' );
forePanel.place( separator(), 'span, growx, wrap para' );
forePanel.place( forePortrait, 'span, growx, wrap' );
forePanel.place( foreCrippledPortrait, 'span, growx, wrap' );
forePanel.editorTabScrolling = true;
// Aft Panel
aftSectionDesignationItems = [ #xw-aft-designation ];
aftSectionDesignationField = autocompletionField( aftSectionDesignationItems );
bindings.add( 'AftDesignation', aftSectionDesignationField, [2,3,4] );
aftTextArea = textArea( '', 6, 15, true );
bindings.add( 'AftText', aftTextArea, [2] );
aftTextFlavor = checkBox( @xw-text-flavor );
bindings.add( 'AftTextFlavor', aftTextFlavor, [2] );
aftCrippledTextArea = textArea( '', 6, 15, true );
bindings.add( 'AftCrippledText', aftCrippledTextArea, [3] );
aftCrippledTextFlavor = checkBox( @xw-text-flavor );
bindings.add( 'AftCrippledTextFlavor', aftCrippledTextFlavor, [3] );
symbolsTagTip2 = tipButton( @xw-symbol-tooltip );
headersTagTip2 = tipButton( @xw-header-tooltip );
shipsTagTip2 = tipButton( @xw-ship-tooltip );
aftArcItems = [];
aftArcItems[0] = ListItem( '-', '-' );
aftArcItems[1] = ListItem( 'broadside', @xw-arc-broadside );
aftArcItems[2] = ListItem( 'extendedBroadside', @xw-arc-extended-broadside );
aftArcItems[3] = ListItem( 'rear', @xw-arc-rear );
aftArcItems[4] = ListItem( 'extendedRear', @xw-arc-extended-rear );
aftArcItems[5] = ListItem( 'fullArc', @xw-arc-full );
aftArcBox = comboBox( aftArcItems );
bindings.add( 'AftArc', aftArcBox, [4] );
aftTurret = checkBox( @xw-turret );
bindings.add( 'AftTurret', aftTurret, [2,3,4] );
aftRangeBox = comboBox( rangeItems );
bindings.add( 'AftRange', aftRangeBox, [2] );
aftCrippledRangeBox = comboBox( rangeItems );
bindings.add( 'AftCrippledRange', aftCrippledRangeBox, [3] );
aftPwvBox = comboBox( pwvItems );
bindings.add( 'AftPwv', aftPwvBox, [2,4] );
aftCrippledPwvBox = comboBox( pwvItems );
bindings.add( 'AftCrippledPwv', aftCrippledPwvBox, [3] );
aftEnergyBox = comboBox( energyItems );
bindings.add( 'AftEnergy', aftEnergyBox, [2,4] );
aftCrippledEnergyBox = comboBox( energyItems );
bindings.add( 'AftCrippledEnergy', aftCrippledEnergyBox, [3] );
aftHullBox = comboBox( hullItems );
bindings.add( 'AftHull', aftHullBox, [2,4] );
aftShieldBox = comboBox( shieldItems );
bindings.add( 'AftShield', aftShieldBox, [2,4] );
aftRecoverCheckbox = checkBox( @xw-action-recover );
bindings.add( 'AftRecoverAction', aftRecoverCheckbox, [2,4] );
aftReinforceCheckbox = checkBox( @xw-action-reinforce );
bindings.add( 'AftReinforceAction', aftReinforceCheckbox, [2,4] );
aftCoordinateCheckbox = checkBox( @xw-action-coordinate );
bindings.add( 'AftCoordinateAction', aftCoordinateCheckbox, [2,4] );
aftJamCheckbox = checkBox( @xw-action-jam );
bindings.add( 'AftJamAction', aftJamCheckbox, [2,4] );
aftLockCheckbox = checkBox( @xw-action-lock );
bindings.add( 'AftLockAction', aftLockCheckbox, [2,4] );
aftUpgradeBox1 = comboBox( upgradeItems );
bindings.add( 'AftUpgrade1', aftUpgradeBox1, [2,3] );
aftCrippledUpgradeBox1 = checkBox( '' );
bindings.add( 'AftCrippledUpgrade1', aftCrippledUpgradeBox1, [3] );
aftUpgradeBox2 = comboBox( upgradeItems );
bindings.add( 'AftUpgrade2', aftUpgradeBox2, [2,3] );
aftCrippledUpgradeBox2 = checkBox( '' );
bindings.add( 'AftCrippledUpgrade2', aftCrippledUpgradeBox2, [3] );
aftUpgradeBox3 = comboBox( upgradeItems );
bindings.add( 'AftUpgrade3', aftUpgradeBox3, [2,3] );
aftCrippledUpgradeBox3 = checkBox( '' );
bindings.add( 'AftCrippledUpgrade3', aftCrippledUpgradeBox3, [3] );
aftUpgradeBox4 = comboBox( upgradeItems );
bindings.add( 'AftUpgrade4', aftUpgradeBox4, [2,3] );
aftCrippledUpgradeBox4 = checkBox( '' );
bindings.add( 'AftCrippledUpgrade4', aftCrippledUpgradeBox4, [3] );
aftUpgradeBox5 = comboBox( upgradeItems );
bindings.add( 'AftUpgrade5', aftUpgradeBox5, [2,3] );
aftCrippledUpgradeBox5 = checkBox( '' );
bindings.add( 'AftCrippledUpgrade5', aftCrippledUpgradeBox5, [3] );
aftUpgradeBox6 = comboBox( upgradeItems );
bindings.add( 'AftUpgrade6', aftUpgradeBox6, [2,3] );
aftCrippledUpgradeBox6 = checkBox( '' );
bindings.add( 'AftCrippledUpgrade6', aftCrippledUpgradeBox6, [3] );
aftUpgradeBox7 = comboBox( upgradeItems );
bindings.add( 'AftUpgrade7', aftUpgradeBox7, [2,3] );
aftCrippledUpgradeBox7 = checkBox( '' );
bindings.add( 'AftCrippledUpgrade7', aftCrippledUpgradeBox7, [3] );
aftCostBox = spinner( 1, 200, 1, 20 );
bindings.add( 'AftCost', aftCostBox, [2] );
aftPortrait = portraitPanel( diy, 2 );
aftPortrait.panelTitle = 'Healthy Side Aft Section Portrait';
aftCrippledPortrait = portraitPanel( diy, 3 );
aftCrippledPortrait.panelTitle = 'Crippled Side Aft Section Portrait';
aftPanel = new Grid( '', '[min:pref][min:pref,grow][min:pref][min:pref,grow]', '');
aftPanel.setTitle( @xw-info );
aftPanel.place( @xw-designation, '', aftSectionDesignationField, 'span, growx, wrap' );
aftPanel.place( @xw-text, 'span 2', aftTextFlavor, 'wrap' );
aftPanel.place( aftTextArea, 'span, grow, wrap para' );
aftPanel.place( @xw-crippledtext, 'span 2', aftCrippledTextFlavor, 'wrap');
aftPanel.place( aftCrippledTextArea, 'span, grow, wrap para' );
aftPanel.place( symbolsTagTip2, '', headersTagTip2, '', shipsTagTip2, 'span, grow, wrap para' );
aftPanel.place( separator(), 'span, growx, wrap para' );
aftPanel.place( @xw-arc, '', aftArcBox, 'wmin 100, span 2, wrap' );
aftPanel.place( aftTurret, 'wrap' );
aftPanel.place( @xw-pwv, '', aftPwvBox, 'wmin 52', @xw-range, '', aftRangeBox, 'wmin 70, wrap' );
aftPanel.place( @xw-crippledpwv, '', aftCrippledPwvBox, 'wmin 52', @xw-range, '', aftCrippledRangeBox, 'wmin 70, wrap' );
aftPanel.place( @xw-energy, '', aftEnergyBox, 'wmin 52, wrap' );
aftPanel.place( @xw-crippledenergy, '', aftCrippledEnergyBox, 'wmin 52, wrap' );
aftPanel.place( @xw-hull, '', aftHullBox, 'wmin 52, wrap' );
aftPanel.place( @xw-shield, '', aftShieldBox, 'wmin 52, wrap para' );
aftPanel.place( separator(), 'span, growx, wrap para' );
aftPanel.place( @xw-actions, 'wrap' );
aftPanel.place( aftRecoverCheckbox, '', aftReinforceCheckbox, '', aftCoordinateCheckbox, 'wrap' );
aftPanel.place( aftJamCheckbox, '', aftLockCheckbox, 'wrap para' );
aftPanel.place( separator(), 'span, growx, wrap para' );
aftPanel.place( @xw-upgrades, 'wmin 100', @xw-upgrades-crippled, 'wrap' );
aftPanel.place( aftUpgradeBox1, 'wmin 100', aftCrippledUpgradeBox1, 'wrap' );
aftPanel.place( aftUpgradeBox2, 'wmin 100', aftCrippledUpgradeBox2, 'wrap' );
aftPanel.place( aftUpgradeBox3, 'wmin 100', aftCrippledUpgradeBox3, 'wrap' );
aftPanel.place( aftUpgradeBox4, 'wmin 100', aftCrippledUpgradeBox4, 'wrap' );
aftPanel.place( aftUpgradeBox5, 'wmin 100', aftCrippledUpgradeBox5, 'wrap' );
aftPanel.place( aftUpgradeBox6, 'wmin 100', aftCrippledUpgradeBox6, 'wrap' );
aftPanel.place( aftUpgradeBox7, 'wmin 100', aftCrippledUpgradeBox7, 'wrap para' );
aftPanel.place( separator(), 'span, growx, wrap para' );
aftPanel.place( @xw-cost, 'span 2', aftCostBox, 'wmin 100, wrap para' );
aftPanel.place( separator(), 'span, growx, wrap para' );
aftPanel.place( aftPortrait, 'span, growx, wrap' );
aftPanel.place( aftCrippledPortrait, 'span, growx, wrap' );
aftPanel.editorTabScrolling = true;
function actionFunction( actionEvent )
{
try {
if( doubleCheckbox.selected ) {
locationBox.setEnabled(true);
foreCrippledTextFlavor.setEnabled(true);
foreCrippledTextArea.setVisible(true);
foreCrippledUpgradeBox1.setEnabled(true);
foreCrippledUpgradeBox2.setEnabled(true);
foreCrippledUpgradeBox3.setEnabled(true);
foreCrippledUpgradeBox4.setEnabled(true);
foreCrippledUpgradeBox5.setEnabled(true);
foreCrippledUpgradeBox6.setEnabled(true);
foreCrippledUpgradeBox7.setEnabled(true);
foreCrippledPortrait.setVisible(true);
aftTextFlavor.setEnabled(true);
aftTextArea.setVisible(true);
aftCrippledTextFlavor.setEnabled(true);
aftCrippledTextArea.setVisible(true);
aftHullBox.setEnabled(true);
aftShieldBox.setEnabled(true);
aftRecoverCheckbox.setEnabled(true);
aftReinforceCheckbox.setEnabled(true);
aftCoordinateCheckbox.setEnabled(true);
aftJamCheckbox.setEnabled(true);
aftLockCheckbox.setEnabled(true);
aftUpgradeBox1.setEnabled(true);
aftUpgradeBox2.setEnabled(true);
aftUpgradeBox3.setEnabled(true);
aftUpgradeBox4.setEnabled(true);
aftUpgradeBox5.setEnabled(true);
aftUpgradeBox6.setEnabled(true);
aftUpgradeBox7.setEnabled(true);
aftCrippledUpgradeBox1.setEnabled(true);
aftCrippledUpgradeBox2.setEnabled(true);
aftCrippledUpgradeBox3.setEnabled(true);
aftCrippledUpgradeBox4.setEnabled(true);
aftCrippledUpgradeBox5.setEnabled(true);
aftCrippledUpgradeBox6.setEnabled(true);
aftCrippledUpgradeBox7.setEnabled(true);
aftCostBox.setEnabled(true);
aftPortrait.setVisible(true);
aftCrippledPortrait.setVisible(true);
if( locationBox.getSelectedItem() == 'attack-energy' ) {
foreTurret.setEnabled(true);
forePwvBox.setEnabled(true);
foreRangeBox.setEnabled(true);
foreCrippledPwvBox.setEnabled(true);
foreCrippledRangeBox.setEnabled(true);
foreEnergyBox.setEnabled(false);
foreCrippledEnergyBox.setEnabled(false);
aftTurret.setEnabled(false);
aftPwvBox.setEnabled(false);
aftRangeBox.setEnabled(false);
aftCrippledPwvBox.setEnabled(false);
aftCrippledRangeBox.setEnabled(false);
aftEnergyBox.setEnabled(true);
aftCrippledEnergyBox.setEnabled(true);
} else if ( locationBox.getSelectedItem() == 'energy-attack' ) {
foreTurret.setEnabled(false);
forePwvBox.setEnabled(false);
foreRangeBox.setEnabled(false);
foreCrippledPwvBox.setEnabled(false);
foreCrippledRangeBox.setEnabled(false);
foreEnergyBox.setEnabled(true);
foreCrippledEnergyBox.setEnabled(true);
aftTurret.setEnabled(true);
aftPwvBox.setEnabled(true);
aftRangeBox.setEnabled(true);
aftCrippledPwvBox.setEnabled(true);
aftCrippledRangeBox.setEnabled(true);
aftEnergyBox.setEnabled(false);
aftCrippledEnergyBox.setEnabled(false);
} else if ( locationBox.getSelectedItem() == 'energy-none' ) {
foreTurret.setEnabled(false);
forePwvBox.setEnabled(false);
foreRangeBox.setEnabled(false);
foreCrippledPwvBox.setEnabled(false);
foreCrippledRangeBox.setEnabled(false);
foreEnergyBox.setEnabled(true);
foreCrippledEnergyBox.setEnabled(true);
aftTurret.setEnabled(false);
aftPwvBox.setEnabled(false);
aftRangeBox.setEnabled(false);
aftCrippledPwvBox.setEnabled(false);
aftCrippledRangeBox.setEnabled(false);
aftEnergyBox.setEnabled(false);
aftCrippledEnergyBox.setEnabled(false);
} else if ( locationBox.getSelectedItem() == 'none-energy' ) {
foreTurret.setEnabled(false);
forePwvBox.setEnabled(false);
foreRangeBox.setEnabled(false);
foreCrippledPwvBox.setEnabled(false);
foreCrippledRangeBox.setEnabled(false);
foreEnergyBox.setEnabled(false);
foreCrippledEnergyBox.setEnabled(false);
aftTurret.setEnabled(false);
aftPwvBox.setEnabled(false);
aftRangeBox.setEnabled(false);
aftCrippledPwvBox.setEnabled(false);
aftCrippledRangeBox.setEnabled(false);
aftEnergyBox.setEnabled(true);
aftCrippledEnergyBox.setEnabled(true);
}
} else {
locationBox.setEnabled(false);
foreCrippledTextFlavor.setEnabled(false);
foreCrippledTextArea.setVisible(false);
foreTurret.setEnabled(false);
forePwvBox.setEnabled(false);
foreRangeBox.setEnabled(false);
foreCrippledPwvBox.setEnabled(false);
foreCrippledRangeBox.setEnabled(false);
foreEnergyBox.setEnabled(true);
foreCrippledEnergyBox.setEnabled(false);
foreCrippledUpgradeBox1.setEnabled(false);
foreCrippledUpgradeBox2.setEnabled(false);
foreCrippledUpgradeBox3.setEnabled(false);
foreCrippledUpgradeBox4.setEnabled(false);
foreCrippledUpgradeBox5.setEnabled(false);
foreCrippledUpgradeBox6.setEnabled(false);
foreCrippledUpgradeBox7.setEnabled(false);
foreCrippledPortrait.setVisible(false);
aftTextFlavor.setEnabled(false);
aftTextArea.setVisible(false);
aftCrippledTextFlavor.setEnabled(false);
aftCrippledTextArea.setVisible(false);
aftTurret.setEnabled(false);
aftPwvBox.setEnabled(false);
aftRangeBox.setEnabled(false);
aftCrippledPwvBox.setEnabled(false);
aftCrippledRangeBox.setEnabled(false);
aftEnergyBox.setEnabled(false);
aftCrippledEnergyBox.setEnabled(false);
aftHullBox.setEnabled(false);
aftShieldBox.setEnabled(false);
aftRecoverCheckbox.setEnabled(false);
aftReinforceCheckbox.setEnabled(false);
aftCoordinateCheckbox.setEnabled(false);
aftJamCheckbox.setEnabled(false);
aftLockCheckbox.setEnabled(false);
aftUpgradeBox1.setEnabled(false);
aftUpgradeBox2.setEnabled(false);
aftUpgradeBox3.setEnabled(false);
aftUpgradeBox4.setEnabled(false);
aftUpgradeBox5.setEnabled(false);
aftUpgradeBox6.setEnabled(false);
aftUpgradeBox7.setEnabled(false);
aftCrippledUpgradeBox1.setEnabled(false);
aftCrippledUpgradeBox2.setEnabled(false);
aftCrippledUpgradeBox3.setEnabled(false);
aftCrippledUpgradeBox4.setEnabled(false);
aftCrippledUpgradeBox5.setEnabled(false);
aftCrippledUpgradeBox6.setEnabled(false);
aftCrippledUpgradeBox7.setEnabled(false);
aftCostBox.setEnabled(false);
aftPortrait.setVisible(false);
aftCrippledPortrait.setVisible(false);
}
} catch( ex ) {
Error.handleUncaught( ex );
}
}
commonPanel.addToEditor( editor, @xw-common, null, null, 0 );
forePanel.addToEditor( editor, @xw-fore, null, null, 1 );
aftPanel.addToEditor( editor, @xw-aft, null, null, 2 );
editor.addFieldPopulationListener( actionFunction );
diy.setNameField( nameField );
bindings.bind();
// Add action listeners
locationBox.addActionListener( actionFunction );
doubleCheckbox.addActionListener( actionFunction );
}
function createFrontPainter( diy, sheet ) {
//============== Ship Token ==============
if( sheet.sheetIndex == 4 ) {
tokenNameBox = Xwing.headingBox( sheet, 6.8 );
return;
}
//============== Front Sheet ==============
if( sheet.sheetIndex != 4 ) {
nameBox = Xwing.headingBox( sheet, 12.5 );
epicBox = Xwing.headingBox( sheet, 12.5 );
abilityTextBox = Xwing.abilityBox( sheet, 8 );
flavorTextBox = Xwing.flavorBox( sheet, 8 );
legalBox = markupBox( sheet );
legalBox.defaultStyle = new TextStyle(
FAMILY, 'Arial',
COLOR, Color(151/255,151/255,151/255),
SIZE, 4
);
legalBox.markupText = '\u00a9LFL \u00a9FFG';
return;
}
}
function createBackPainter( diy, sheet ) {
//============== Ship Token ==============
if( sheet.sheetIndex == 5 ) {
tokenNameBox = Xwing.headingBox( sheet, 6.8 );
return;
}
//============== Front Sheet ==============
if( sheet.sheetIndex != 5 ) {
nameBox = Xwing.headingBox( sheet, 12.5 );
epicBox = Xwing.headingBox( sheet, 12.5 );
abilityTextBox = Xwing.abilityBox( sheet, 8 );
flavorTextBox = Xwing.flavorBox( sheet, 8 );
legalBox = markupBox( sheet );
legalBox.defaultStyle = new TextStyle(
FAMILY, 'Arial',
COLOR, Color(151/255,151/255,151/255),
SIZE, 4
);
legalBox.markupText = '\u00a9LFL \u00a9FFG';
return;
}
}
function paintFront( g, diy, sheet ) {
if( sheet.sheetIndex == 0 ) {
// Fore Card Front Face
if( $$DoubleSection.yesNo ) {
paintCardFaceComponents( g, diy, sheet, 'fore', 'front');
} else {
paintCardFaceComponents( g, diy, sheet, 'single', 'front');
}
} else if( sheet.sheetIndex == 2 ) {
// Aft Card Front Face
if( $$DoubleSection.yesNo ) {
paintCardFaceComponents( g, diy, sheet, 'aft', 'front');
} else {
// Draw nothing
}
} else {
// Ship Token
paintTokenComponents( g, diy, sheet);
}
}
function paintBack( g, diy, sheet ) {
if( sheet.sheetIndex == 1 ) {
// Fore Card Back Face
if( $$DoubleSection.yesNo ) {
paintCardFaceComponents( g, diy, sheet, 'fore', 'back');
} else {
imageTemplate = 'huge-' + Xwing.getPrimaryFaction( $Affiliation ) + '-back-template';
sheet.paintImage( g, imageTemplate, 0, 0);
if( $Affiliation == 'resistance' || $Affiliation == 'firstorder' ) {
imageTemplate = 'huge-' + $Affiliation + '-back-template';
sheet.paintImage( g, imageTemplate, 0, 0);
}
}
} else if( sheet.sheetIndex == 3 ) {
// Aft Card Back Face
if( $$DoubleSection.yesNo ) {
paintCardFaceComponents( g, diy, sheet, 'aft', 'back');
} else {
// Draw nothing
}
} else {
// Ship Token Backside
if( $$DoubleSection.yesNo ) {
imageTemplate = 'huge-double-token-template';
} else {
imageTemplate = 'huge-single-token-template';
}
sheet.paintImage( g, imageTemplate, 0, 0);
}
}
function paintCardFaceComponents( g, diy, sheet, section, side) {
//Draw portrait
target = sheet.getRenderTarget();
portraits[sheet.sheetIndex].paint( g, target );
//Draw template
imageTemplate = 'huge-' + Xwing.getPrimaryFaction( $Affiliation ) + '-' + section + '-template';
sheet.paintImage( g, imageTemplate, 0, 0);
if( $Affiliation == 'resistance' || $Affiliation == 'empire' || $Affiliation == 'firstorder' ) {
imageTemplate = 'huge-' + $Affiliation + '-front-template';
sheet.paintImage( g, imageTemplate, 0, 0);
}
// Draw the name
appendTextToName = '';
if( side == 'back') {
appendTextToName = 'crippled ';
}
if( section == 'fore' ) {
nameBox.markupText = diy.name + ' (' + appendTextToName + $ForeDesignation + ')';
} else if( section == 'aft' ) {
nameBox.markupText = diy.name + ' (' + appendTextToName + $AftDesignation + ')';
} else {
nameBox.markupText = diy.name;
}
nameBox.draw( g, R( section, 'shiptype') );
// Draw the epic icon
epicBox.markupText = '<epic>';
epicBox.draw( g, R( section, 'epic') );
// Draw the ship icon
portraits[4].paint( g, target );
// Draw the Pilot Skill
sheet.drawOutlinedTitle( g, $PilotSkill, R( section, 'ps' ), Xwing.numberFont, 18, 2, Xwing.getColor( 'skill' ), Color.BLACK, sheet.ALIGN_CENTER, true);
// Draw the Primary Weapon/Energy Symbol, Value and Range
if( section == 'single' ) {
symbolTemplate = 'huge-attribute-symbol-energy-template';
symbolRegion = 'huge-fore-attribute-symbol-region';
if( side == 'front' ) {
attributeValue = $ForeEnergy;
} else {
attributeValue = $ForeCrippledEnergy;
}
range = 'no';
attributeColor = Xwing.getColor( 'energy' );
attributeRegion = R( 'fore', 'attribute' );
} else if( section == 'fore' && ( $Location == 'energy-attack' || $Location == 'energy-none' ) ) {
symbolTemplate = 'huge-attribute-symbol-energy-template';
symbolRegion = 'huge-fore-attribute-symbol-region';
if( side == 'front' ) {
attributeValue = $ForeEnergy;
} else {
attributeValue = $ForeCrippledEnergy;
}
range = 'no';
attributeColor = Xwing.getColor( 'energy' );
attributeRegion = R( 'fore', 'attribute' );
} else if( section == 'aft' && ( $Location == 'attack-energy' || $Location == 'none-energy' ) ) {
symbolTemplate = 'huge-attribute-symbol-energy-template';
symbolRegion = 'huge-aft-attribute-symbol-region';
if( side == 'front' ) {
attributeValue = $AftEnergy;
} else {
attributeValue = $AftCrippledEnergy;
}
range = 'no';
attributeColor = Xwing.getColor( 'energy' );
attributeRegion = R( 'aft', 'attribute' );
} else if( section == 'fore' && $Location == 'attack-energy' ) {
if( $$ForeTurret.yesNo ) {
symbolTemplate = 'huge-attribute-symbol-attack-turret-template';
} else {
symbolTemplate = 'huge-attribute-symbol-attack-front-template';
}
symbolRegion = 'huge-fore-attribute-symbol-region';
if( side == 'front' ) {
attributeValue = $ForePwv;
range = $ForeRange;
} else {
attributeValue = $ForeCrippledPwv;
range = $ForeCrippledRange;
}
attributeColor = Xwing.getColor( 'attack' );
attributeRegion = R( 'fore', 'attribute' );
rangeRegion = R( 'fore', 'range' );
rangeBoxTemplate = 'huge-' + Xwing.getPrimaryFaction( $Affiliation ) + '-fore-range-box';
rangeBoxRegion = 'huge-fore-range-box-region';
} else if( section == 'aft' && $Location == 'energy-attack' ) {
if( $$AftTurret.yesNo ) {
symbolTemplate = 'huge-attribute-symbol-attack-turret-template';
} else {
symbolTemplate = 'huge-attribute-symbol-attack-front-template';
}
symbolRegion = 'huge-aft-attribute-symbol-region';
if( side == 'front' ) {
attributeValue = $AftPwv;
range = $AftRange;
} else {
attributeValue = $AftCrippledPwv;
range = $AftCrippledRange;
}
attributeColor = Xwing.getColor( 'attack' );
attributeRegion = R( 'aft', 'attribute');
rangeRegion = R( 'aft', 'range' );
rangeBoxTemplate = 'huge-' + Xwing.getPrimaryFaction( $Affiliation ) + '-aft-range-box';
rangeBoxRegion = 'huge-aft-range-box-region';
} else if( section == 'fore' && $Location == 'none-energy' ) {
symbolTemplate = 'huge-attribute-symbol-attack-front-template';
symbolRegion = 'huge-fore-attribute-symbol-region';
attributeValue = '-';
range = 'no';
attributeColor = Xwing.getColor( 'attack' );
attributeRegion = R( 'fore', 'attribute' );
} else if( section == 'aft' && $Location == 'energy-none' ) {
symbolTemplate = 'huge-attribute-symbol-attack-front-template';
symbolRegion = 'huge-aft-attribute-symbol-region';
attributeValue = '-';
range = 'no';
attributeColor = Xwing.getColor( 'attack' );
attributeRegion = R( 'aft', 'attribute' );
}
if( range != 'no' ) {
sheet.paintImage( g, rangeBoxTemplate, rangeBoxRegion);
sheet.drawOutlinedTitle( g, range, rangeRegion, Xwing.numberFont, 8, 1, Color.WHITE, Color.BLACK, sheet.ALIGN_CENTER, true);
}
sheet.paintImage( g, symbolTemplate, symbolRegion );
sheet.drawOutlinedTitle( g, attributeValue, attributeRegion, Xwing.numberFont, 14, 1, attributeColor, Color.BLACK, sheet.ALIGN_CENTER, true);
// Draw the Agility Value
if( ( section == 'fore' || section == 'single' ) && side == 'back' ) {
agility = '-';
agilityRegion = R( 'fore', 'agi' );
} else if( section == 'aft' && side == 'back' ) {
agility = '-';
agilityRegion = R( 'aft', 'agi' );
} else if( ( section == 'fore' || section == 'single' ) && side == 'front' ) {
agility = '0';
agilityRegion = R( 'fore', 'agi' );
} else {
agility = '0';
agilityRegion = R( 'aft', 'agi' );
}
sheet.drawOutlinedTitle( g, agility, agilityRegion, Xwing.numberFont, 14, 1, Xwing.getColor( 'agility' ), Color.BLACK, sheet.ALIGN_CENTER, true);
// Draw the Hull Value
if( ( section == 'fore' || section == 'single' ) && side == 'back' ) {
hull = '-';
hullRegion = R( 'fore', 'hull' );
} else if( section == 'aft' && side == 'back' ) {
hull = '-';
hullRegion = R( 'aft', 'hull' );
} else if( ( section == 'fore' || section == 'single' ) && side == 'front' ) {
hull = $ForeHull;
hullRegion = R( 'fore', 'hull' );
} else {
hull = $AftHull;
hullRegion = R( 'aft', 'hull' );
}
sheet.drawOutlinedTitle( g, hull, hullRegion, Xwing.numberFont, 14, 1, Xwing.getColor( 'hull' ), Color.BLACK, sheet.ALIGN_CENTER, true);
// Draw the Shield Value
if( ( section == 'fore' || section == 'single' ) && side == 'back' ) {
shield = '-';
shieldRegion = R( 'fore', 'shield' );
} else if( section == 'aft' && side == 'back' ) {
shield = '-';
shieldRegion = R( 'aft', 'shield' );
} else if( ( section == 'fore' || section == 'single' ) && side == 'front' ) {
shield = $ForeShield;
shieldRegion = R( 'fore', 'shield' );
} else {
shield = $AftShield;
shieldRegion = R( 'aft', 'shield' );
}
sheet.drawOutlinedTitle( g, shield, shieldRegion, Xwing.numberFont, 14, 1, Xwing.getColor( 'shield' ), Color.BLACK, sheet.ALIGN_CENTER, true);
// Draw the Squad Point Cost
if( side == 'back' ) {
cost = '-';
} else if( section == 'fore' || section == 'single' ) {
cost = $ForeCost;
} else {
cost = $AftCost;
}
sheet.drawOutlinedTitle( g, cost, R( 'fore', 'cost' ), Xwing.numberFont, 10, 0.5, Color.BLACK, Color.WHITE, sheet.ALIGN_CENTER, true);
// Draw Action Bar
if( side == 'front' ) {
actions = [];
if( section == 'fore' || section == 'single' ) {
if( $$ForeRecoverAction.yesNo ) { actions.push( 'recover' ); }
if( $$ForeReinforceAction.yesNo ) { actions.push( 'reinforce' ); }
if( $$ForeCoordinateAction.yesNo ) { actions.push( 'coordinate' ); }
if( $$ForeJamAction.yesNo ) { actions.push( 'jam' ); }
if( $$ForeLockAction.yesNo ) { actions.push( 'lock' ); }
xbias = 202;
} else if( section == 'aft' ) {
if( $$AftRecoverAction.yesNo ) { actions.push( 'recover' ); }
if( $$AftReinforceAction.yesNo ) { actions.push( 'reinforce' ); }
if( $$AftCoordinateAction.yesNo ) { actions.push( 'coordinate' ); }
if( $$AftJamAction.yesNo ) { actions.push( 'jam' ); }
if( $$AftLockAction.yesNo ) { actions.push( 'lock' ); }
xbias = -28;
}
for( let i = 0; i < actions.length; ++i ) {
// Get a nice distribution of the actions
x = xbias + Math.round( 472 / (actions.length + 1) * ( i + 1 ) );
y = 780;
g.setPaint( Color.BLACK );
sheet.drawTitle(g, Xwing.textToIconChar( actions[i] ), Region( x.toString() + ',' + y.toString() + ',100,100'), Xwing.iconFont, 15, sheet.ALIGN_CENTER);
}
}
// Draw Upgrade Bar
var upgrades = [];
if( section == 'fore' || section == 'single' ) {
if( $ForeUpgrade7 != '-' && ( side != 'back' || $$ForeCrippledUpgrade7.yesNo ) ) { upgrades.push( $ForeUpgrade7 ); }
if( $ForeUpgrade6 != '-' && ( side != 'back' || $$ForeCrippledUpgrade6.yesNo ) ) { upgrades.push( $ForeUpgrade6 ); }
if( $ForeUpgrade5 != '-' && ( side != 'back' || $$ForeCrippledUpgrade5.yesNo ) ) { upgrades.push( $ForeUpgrade5 ); }
if( $ForeUpgrade4 != '-' && ( side != 'back' || $$ForeCrippledUpgrade4.yesNo ) ) { upgrades.push( $ForeUpgrade4 ); }
if( $ForeUpgrade3 != '-' && ( side != 'back' || $$ForeCrippledUpgrade3.yesNo ) ) { upgrades.push( $ForeUpgrade3 ); }
if( $ForeUpgrade2 != '-' && ( side != 'back' || $$ForeCrippledUpgrade2.yesNo ) ) { upgrades.push( $ForeUpgrade2 ); }
if( $ForeUpgrade1 != '-' && ( side != 'back' || $$ForeCrippledUpgrade1.yesNo ) ) { upgrades.push( $ForeUpgrade1 ); }
} else if( section == 'aft' ) {
if( $AftUpgrade7 != '-' && ( side != 'back' || $$AftCrippledUpgrade7.yesNo ) ) { upgrades.push( $AftUpgrade7 ); }
if( $AftUpgrade6 != '-' && ( side != 'back' || $$AftCrippledUpgrade6.yesNo ) ) { upgrades.push( $AftUpgrade6 ); }
if( $AftUpgrade5 != '-' && ( side != 'back' || $$AftCrippledUpgrade5.yesNo ) ) { upgrades.push( $AftUpgrade5 ); }
if( $AftUpgrade4 != '-' && ( side != 'back' || $$AftCrippledUpgrade4.yesNo ) ) { upgrades.push( $AftUpgrade4 ); }
if( $AftUpgrade3 != '-' && ( side != 'back' || $$AftCrippledUpgrade3.yesNo ) ) { upgrades.push( $AftUpgrade3 ); }
if( $AftUpgrade2 != '-' && ( side != 'back' || $$AftCrippledUpgrade2.yesNo ) ) { upgrades.push( $AftUpgrade2 ); }
if( $AftUpgrade1 != '-' && ( side != 'back' || $$AftCrippledUpgrade1.yesNo ) ) { upgrades.push( $AftUpgrade1 ); }
}
for( let i=0; i<upgrades.length; ++i ) {
// Get a nice distribution of the upgrades
if( upgrades.length == 7) {
x = 450 - 51 * ( i );
} else {
x = 450 - 55 * ( i );
}
y = 951;
g.setPaint( Color.BLACK );
g.fillOval( x+2, y+2, 45, 45 );
sheet.drawOutlinedTitle( g, Xwing.textToIconChar( upgrades[i] ), Region( x.toString() + ',' + y.toString() + ',50,50'), Xwing.iconFont, 15, 1, Color.WHITE, Color.BLACK, sheet.ALIGN_CENTER, true);
}
// Draw Legal text
legalBox.drawAsSingleLine( g, R( section, 'legal' ) );
// Draw Crippled Overlay
if( side == 'back' ) {
imageTemplate = 'huge-' + Xwing.getPrimaryFaction( $Affiliation ) + '-' + section + '-action-overlay-template';
sheet.paintImage( g, imageTemplate, 0, 0);
imageTemplate = 'huge-overlay-' + section + '-template';
sheet.paintImage( g, imageTemplate, 0, 0);
}
// Draw the Section Ability/Flavour Text
if( section == 'single' ) {
if( $$ForeTextFlavor.yesNo ) {
flavorTextBox.setPageShape( PageShape.RECTANGLE_SHAPE );
flavorTextBox.markupText = $ForeText;
flavorTextBox.draw( g, R( 'fore', 'text' ) );
} else {
abilityTextBox.setPageShape( PageShape.RECTANGLE_SHAPE );
abilityTextBox.markupText = $ForeText;
abilityTextBox.draw( g, R( 'fore', 'text' ) );
}
} else if( side == 'front' && section == 'fore' ) {
if( $$ForeTextFlavor.yesNo ) {
if( $Location == 'attack-energy' ) {
flavorTextBox.setPageShape( PageShape.CupShape( 98, 0, 597, 0, 0 ) );
} else {
flavorTextBox.setPageShape( PageShape.RECTANGLE_SHAPE );
}
flavorTextBox.markupText = $ForeText;
flavorTextBox.draw( g, R( 'fore', 'text' ) );
} else {
if( $Location == 'attack-energy' ) {
abilityTextBox.setPageShape( PageShape.CupShape( 98, 0, 597, 0, 0 ) );
} else {
abilityTextBox.setPageShape( PageShape.RECTANGLE_SHAPE );
}
abilityTextBox.markupText = $ForeText;
abilityTextBox.draw( g, R( 'fore', 'text' ) );
}
} else if ( side == 'back' && section == 'fore' ) {
if( $$ForeCrippledTextFlavor.yesNo ) {
if( $Location == 'attack-energy' ) {
flavorTextBox.setPageShape( PageShape.CupShape( 98, 0, 597, 0, 0 ) );
} else {
flavorTextBox.setPageShape( PageShape.RECTANGLE_SHAPE );
}
flavorTextBox.markupText = $ForeCrippledText;
flavorTextBox.draw( g, R( 'fore', 'text' ) );
} else {
if( $Location == 'attack-energy' ) {
abilityTextBox.setPageShape( PageShape.CupShape( 98, 0, 597, 0, 0 ) );
} else {
abilityTextBox.setPageShape( PageShape.RECTANGLE_SHAPE );
}
abilityTextBox.markupText = $ForeCrippledText;
abilityTextBox.draw( g, R( 'fore', 'text' ) );
}
} else if( side == 'front' && section == 'aft' ) {
if( $$AftTextFlavor.yesNo ) {
if( $Location == 'energy-attack' ) {
flavorTextBox.setPageShape( PageShape.CupShape( 0, 98, 597, 0, 0 ) );
} else {
flavorTextBox.setPageShape( PageShape.RECTANGLE_SHAPE );
}
flavorTextBox.markupText = $AftText;
flavorTextBox.draw( g, R( 'aft', 'text' ) );
} else {
if( $Location == 'energy-attack' ) {
abilityTextBox.setPageShape( PageShape.CupShape( 0, 98, 597, 0, 0 ) );
} else {
abilityTextBox.setPageShape( PageShape.RECTANGLE_SHAPE );
}
abilityTextBox.markupText = $AftText;
abilityTextBox.draw( g, R( 'aft', 'text' ) );
}
} else if ( side == 'back' && section == 'aft' ) {
if( $$AftCrippledTextFlavor.yesNo ) {
if( $Location == 'energy-attack' ) {
flavorTextBox.setPageShape( PageShape.CupShape( 0, 98, 597, 0, 0 ) );
} else {
flavorTextBox.setPageShape( PageShape.RECTANGLE_SHAPE );
}
flavorTextBox.markupText = $AftCrippledText;
flavorTextBox.draw( g, R( 'aft', 'text' ) );
} else {
if( $Location == 'energy-attack' ) {
abilityTextBox.setPageShape( PageShape.CupShape( 0, 98, 597, 0, 0 ) );
} else {
abilityTextBox.setPageShape( PageShape.RECTANGLE_SHAPE );
}
abilityTextBox.markupText = $AftCrippledText;
abilityTextBox.draw( g, R( 'aft', 'text' ) );
}
}
return;
}
function paintTokenComponents( g, diy, sheet) {
if( $$DoubleSection.yesNo ) {
tokenSize = 'double';
tokenHeight = 2646;
tokenBasicUnit = 472.5;
tokenWidth = 945;
tokenUpperWaistYCoord = 963;
tokenLowerWaistYCoord = 1683;
} else {
tokenSize = 'single';
tokenHeight = 2291;
tokenBasicUnit = 472.5;
tokenWidth = 945;
tokenUpperWaistYCoord = 963;
tokenLowerWaistYCoord = 1328;
}
thickStroke = BasicStroke(7);
normalStroke = BasicStroke(5);
thinStroke = BasicStroke(4);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Draw star-field background
imageTemplate = 'huge-' + tokenSize + '-token-template';
sheet.paintImage( g, imageTemplate, 0, 0);
// Draw fore shaded fire arc area
fireArcArea = ImageUtils.create( tokenWidth, tokenHeight, true );
gTemp = fireArcArea.createGraphics();
gTemp.setPaint( Xwing.getColor( Xwing.getPrimaryFaction( $Affiliation ) ) );
if( $ForeArc == 'broadside' ) {
gTemp.fillPolygon( [0, Math.round(tokenWidth/2), 0], [0, Math.round(tokenBasicUnit), Math.round(tokenBasicUnit*2)], 3 );
gTemp.fillPolygon( [tokenWidth, Math.round(tokenWidth/2), tokenWidth], [0, Math.round(tokenBasicUnit), Math.round(tokenBasicUnit*2)], 3 );
} else if ( $ForeArc == 'extendedBroadside' ) {
gTemp.fillPolygon( [0, Math.round(tokenWidth/2), 0], [0, Math.round(tokenBasicUnit), Math.round(tokenHeight/2)], 3 );
gTemp.fillPolygon( [tokenWidth, Math.round(tokenWidth/2), tokenWidth], [0, Math.round(tokenBasicUnit), Math.round(tokenHeight/2)], 3 );
} else if ( $ForeArc == 'front' ) {
gTemp.fillPolygon( [0, Math.round(tokenWidth/2), tokenWidth], [0, Math.round(tokenBasicUnit), 0], 3 );
} else if ( $ForeArc == 'extendedFront' ) {
gTemp.fillPolygon( [0, 0, Math.round(tokenWidth/2), tokenWidth, tokenWidth], [0, tokenUpperWaistYCoord, Math.round(tokenHeight/2), tokenUpperWaistYCoord, 0], 5 );
} else if ( $ForeArc == 'fullArc' ) {
gTemp.fillPolygon( [0, 0, Math.round(tokenWidth/2), tokenWidth, tokenWidth], [0, Math.round(tokenHeight/2), Math.round(tokenBasicUnit), Math.round(tokenHeight/2), 0], 5 );
}
if( $AftArc == 'broadside' ) {
gTemp.fillPolygon( [0, Math.round(tokenWidth/2), 0], [tokenHeight, Math.round(tokenHeight-tokenBasicUnit), Math.round(tokenHeight-tokenBasicUnit*2)], 3 );
gTemp.fillPolygon( [tokenWidth, Math.round(tokenWidth/2), tokenWidth], [tokenHeight, Math.round(tokenHeight-tokenBasicUnit), Math.round(tokenHeight-tokenBasicUnit*2)], 3 );
} else if ( $AftArc == 'extendedBroadside' ) {
gTemp.fillPolygon( [0, Math.round(tokenWidth/2), 0], [tokenHeight, Math.round(tokenHeight-tokenBasicUnit), Math.round(tokenHeight/2)], 3 );
gTemp.fillPolygon( [tokenWidth, Math.round(tokenWidth/2), tokenWidth], [tokenHeight, Math.round(tokenHeight-tokenBasicUnit), Math.round(tokenHeight/2)], 3 );
} else if ( $AftArc == 'rear' ) {
gTemp.fillPolygon( [0, Math.round(tokenWidth/2), tokenWidth], [tokenHeight, Math.round(tokenHeight-tokenBasicUnit), tokenHeight], 3 );
} else if ( $AftArc == 'extendedRear' ) {
gTemp.fillPolygon( [0, 0, Math.round(tokenWidth/2), tokenWidth, tokenWidth], [tokenHeight, tokenLowerWaistYCoord, Math.round(tokenHeight/2), tokenLowerWaistYCoord, tokenHeight], 5 );
} else if ( $AftArc == 'fullArc' ) {
gTemp.fillPolygon( [0, 0, Math.round(tokenWidth/2), tokenWidth, tokenWidth], [tokenHeight, Math.round(tokenHeight/2), Math.round(tokenHeight-tokenBasicUnit), Math.round(tokenHeight/2), tokenHeight], 5 );
}
fireArcArea = createTranslucentImage( fireArcArea, 0.10);
g.drawImage( fireArcArea, 0, 0, null );
// Draw turret circle
if( ( tokenSize == 'double' && $Location == 'attack-energy' && $$ForeTurret.yesNo ) ) {
g.setPaint( Xwing.getColor( Xwing.getPrimaryFaction( $Affiliation ) ) );
g.setStroke(thinStroke);
diameter = 370;
g.drawArc( Math.round( (tokenWidth-diameter) /2 ), Math.round( tokenBasicUnit-diameter/2 ), diameter, diameter, 7, 322 );
diameter = 316;
g.drawArc( Math.round( (tokenWidth-diameter) /2 ), Math.round( tokenBasicUnit-diameter/2 ), diameter, diameter, 8, 325 );
g.drawPolyline( [ 629, 592, 643, 694, 657 ], [ 452, 452, 531, 452, 452 ], 5 );
g.drawPolyline( [ 613.5, 616, 633, 631 ], [ 546, 541, 565, 568 ], 4 );
} else if ( ( tokenSize == 'double' && $Location == 'energy-attack'&& $$AftTurret.yesNo ) ) {
g.setPaint( Xwing.getColor( Xwing.getPrimaryFaction( $Affiliation ) ) );
g.setStroke(thinStroke);
diameter = 370;
g.drawArc( Math.round( (tokenWidth-diameter) /2 ), Math.round(tokenHeight-tokenBasicUnit-diameter/2), diameter, diameter, 7, 322 );
diameter = 316;
g.drawArc( Math.round( (tokenWidth-diameter) /2 ), Math.round(tokenHeight-tokenBasicUnit-diameter/2), diameter, diameter, 8, 325 );
g.drawPolyline( [ 629, 592, 643, 694, 657 ], [ 2153, 2153, 2232, 2153, 2153 ], 5 );
g.drawPolyline( [ 613.5, 616, 633, 631 ], [ 2247, 2242, 2266, 2269 ], 4 );
}
// Draw stat panel
if( tokenSize == 'double' ) {
sheet.paintImage( g, 'huge-' + Xwing.getPrimaryFaction( $Affiliation ) + '-fore-panel-template', 47, 0);
}
sheet.paintImage( g, 'huge-' + Xwing.getPrimaryFaction( $Affiliation ) + '-aft-panel-template', 47, tokenHeight-230);
// Draw the name
if( tokenSize == 'double' ) {
tokenNameBox.markupText = diy.name + ' (' + $ForeDesignation + ')';
tokenNameBox.draw( g, R( 'fore', 'token-shiptype') );
tokenNameBox.markupText = diy.name + ' (' + $AftDesignation + ')';
tokenNameBox.draw( g, R( 'aft', 'token-shiptype') );
} else {
tokenNameBox.markupText = diy.name;
tokenNameBox.draw( g, R( 'single', 'token-shiptype') );
}
// Draw the ship icon
target = sheet.getRenderTarget();
if( tokenSize == 'double' ) {
portraits[5].paint( g, target );
} else {
iconImage = portraits[5].getImage();
iconScale = portraits[5].getScale();
AT = java.awt.geom.AffineTransform;
tokenTransform = AT.getTranslateInstance(
190 - (iconImage.width*iconScale)/2 + portraits[5].getPanX(),
1809 - (iconImage.height*iconScale)/2 + portraits[5].getPanY() );
tokenTransform.concatenate( AT.getScaleInstance( iconScale, iconScale ) );
g.drawImage( iconImage, tokenTransform, null );
}
// Draw the Pilot Skill
if( tokenSize == 'double' ) {
sheet.drawOutlinedTitle( g, $PilotSkill, R( 'fore' , 'token-ps'), Xwing.numberFont, 18, 2, Xwing.getColor('skill'), Color.BLACK, sheet.ALIGN_CENTER, true);
sheet.drawOutlinedTitle( g, $PilotSkill, R( 'aft', 'token-ps'), Xwing.numberFont, 18, 2, Xwing.getColor('skill'), Color.BLACK, sheet.ALIGN_CENTER, true);
} else {
sheet.drawOutlinedTitle( g, $PilotSkill, R( 'single', 'token-ps'), Xwing.numberFont, 18, 2, Xwing.getColor('skill'), Color.BLACK, sheet.ALIGN_CENTER, true);
}
// Draw the Primary Weapon/Energy Value
if( tokenSize == 'double' ) {
if( $Location == 'attack-energy' ) {
attributeForeValue = $ForePwv;
attributeForeColor = Xwing.getColor( 'attack' );
attributeAftValue = $AftEnergy;
attributeAftColor = Xwing.getColor( 'energy' );
} else if ( $Location == 'energy-attack' ) {
attributeForeValue = $ForeEnergy;
attributeForeColor = Xwing.getColor( 'energy' );
attributeAftValue = $AftPwv;
attributeAftColor = Xwing.getColor( 'attack' );
} else if ( $Location == 'energy-none' ) {
attributeForeValue = $ForeEnergy;
attributeForeColor = Xwing.getColor( 'energy' );
attributeAftValue = '-';
attributeAftColor = Xwing.getColor( 'attack' );
} else if ( $Location == 'none-energy' ) {
attributeForeValue = '-';
attributeForeColor = Xwing.getColor( 'attack' );
attributeAftValue = $AftEnergy;
attributeAftColor = Xwing.getColor( 'energy' );
}
sheet.drawOutlinedTitle( g, attributeForeValue, R( 'fore', 'token-attribute'), Xwing.numberFont, 14, 1, attributeForeColor, Color.BLACK, sheet.ALIGN_CENTER, true);
sheet.drawOutlinedTitle( g, attributeAftValue, R( 'aft', 'token-attribute'), Xwing.numberFont, 14, 1, attributeAftColor, Color.BLACK, sheet.ALIGN_CENTER, true);
} else {
attributeValue = $ForeEnergy;
attributeColor = Xwing.getColor( 'energy' );
sheet.drawOutlinedTitle( g, attributeValue, R( 'single', 'token-attribute'), Xwing.numberFont, 14, 1, attributeColor, Color.BLACK, sheet.ALIGN_CENTER, true);
}
// Draw the Agility Value
if( tokenSize == 'double' ) {
sheet.drawOutlinedTitle( g, '0', R( 'fore', 'token-agi'), Xwing.numberFont, 14, 1, Xwing.getColor( 'agility' ), Color.BLACK, sheet.ALIGN_CENTER, true);
sheet.drawOutlinedTitle( g, '0', R( 'aft', 'token-agi'), Xwing.numberFont, 14, 1, Xwing.getColor( 'agility' ), Color.BLACK, sheet.ALIGN_CENTER, true);
} else {
sheet.drawOutlinedTitle( g, '0', R( 'single', 'token-agi'), Xwing.numberFont, 14, 1, Xwing.getColor( 'agility' ), Color.BLACK, sheet.ALIGN_CENTER, true);
}
// Draw the Hull Value
if( tokenSize == 'double' ) {
sheet.drawOutlinedTitle( g, $ForeHull, R( 'fore', 'token-hull'), Xwing.numberFont, 14, 1, Xwing.getColor( 'hull' ), Color.BLACK, sheet.ALIGN_CENTER, true);
sheet.drawOutlinedTitle( g, $AftHull, R( 'aft', 'token-hull'), Xwing.numberFont, 14, 1, Xwing.getColor( 'hull' ), Color.BLACK, sheet.ALIGN_CENTER, true);
} else {
sheet.drawOutlinedTitle( g, $ForeHull, R( 'single', 'token-hull'), Xwing.numberFont, 14, 1, Xwing.getColor( 'hull' ), Color.BLACK, sheet.ALIGN_CENTER, true);
}
// Draw the Shield Value
if( tokenSize == 'double' ) {
sheet.drawOutlinedTitle( g, $ForeShield, R( 'fore', 'token-shield'), Xwing.numberFont, 14, 1, Xwing.getColor( 'shield' ), Color.BLACK, sheet.ALIGN_CENTER, true);
sheet.drawOutlinedTitle( g, $AftShield, R( 'aft', 'token-shield'), Xwing.numberFont, 14, 1, Xwing.getColor( 'shield' ), Color.BLACK, sheet.ALIGN_CENTER, true);
} else {
sheet.drawOutlinedTitle( g, $ForeShield, R( 'single', 'token-shield'), Xwing.numberFont, 14, 1, Xwing.getColor( 'shield' ), Color.BLACK, sheet.ALIGN_CENTER, true);
}
// Draw center line
g.setPaint( Color(50/255,90/255,190/255 ) );
g.setStroke(thickStroke);
g.drawPolyline( [0, tokenWidth], [Math.round(tokenHeight/2), Math.round(tokenHeight/2)], 2 );
// Draw fire arc lines
g.setPaint( Xwing.getColor( Xwing.getPrimaryFaction( $Affiliation ) ) );
g.setStroke(normalStroke);
if( $ForeArc == 'broadside' ) {
g.drawPolyline( [0, Math.round(tokenWidth/2), 0], [0, Math.round(tokenBasicUnit), Math.round(tokenBasicUnit*2)], 3 );
g.drawPolyline( [tokenWidth, Math.round(tokenWidth/2), tokenWidth], [0, Math.round(tokenBasicUnit), Math.round(tokenBasicUnit*2)], 3 );
} else if ( $ForeArc == 'extendedBroadside' ) {
g.drawPolyline( [0, Math.round(tokenWidth/2), 0], [0, Math.round(tokenBasicUnit), Math.round(tokenHeight/2)], 3 );
g.drawPolyline( [tokenWidth, Math.round(tokenWidth/2), tokenWidth], [0, Math.round(tokenBasicUnit), Math.round(tokenHeight/2)], 3 );
} else if ( $ForeArc == 'front' ) {
g.drawPolyline( [0, Math.round(tokenWidth/2), tokenWidth], [0, Math.round(tokenBasicUnit), 0], 3 );
} else if ( $ForeArc == 'extendedFront' ) {
g.drawPolyline( [0, Math.round(tokenWidth/2), tokenWidth], [tokenUpperWaistYCoord, Math.round(tokenHeight/2), tokenUpperWaistYCoord], 3 );
} else if ( $ForeArc == 'fullArc' ) {
g.drawPolyline( [0, Math.round(tokenWidth/2), tokenWidth], [Math.round(tokenHeight/2), Math.round(tokenBasicUnit), Math.round(tokenHeight/2)], 3 );
}
if( $AftArc == 'broadside' ) {
g.drawPolyline( [0, Math.round(tokenWidth/2), 0], [tokenHeight, Math.round(tokenHeight-tokenBasicUnit), Math.round(tokenHeight-tokenBasicUnit*2)], 3 );
g.drawPolyline( [tokenWidth, Math.round(tokenWidth/2), tokenWidth], [tokenHeight, Math.round(tokenHeight-tokenBasicUnit), Math.round(tokenHeight-tokenBasicUnit*2)], 3 );
} else if ( $AftArc == 'extendedBroadside' ) {
g.drawPolyline( [0, Math.round(tokenWidth/2), 0], [tokenHeight, Math.round(tokenHeight-tokenBasicUnit), Math.round(tokenHeight/2)], 3 );
g.drawPolyline( [tokenWidth, Math.round(tokenWidth/2), tokenWidth], [tokenHeight, Math.round(tokenHeight-tokenBasicUnit), Math.round(tokenHeight/2)], 3 );
} else if ( $AftArc == 'rear' ) {
g.drawPolyline( [0, Math.round(tokenWidth/2), tokenWidth], [tokenHeight, Math.round(tokenHeight-tokenBasicUnit), tokenHeight], 3 );
} else if ( $AftArc == 'extendedRear' ) {
g.drawPolyline( [0, Math.round(tokenWidth/2), tokenWidth], [tokenLowerWaistYCoord, Math.round(tokenHeight/2), tokenLowerWaistYCoord], 3 );
} else if ( $AftArc == 'fullArc' ) {
g.drawPolyline( [0, Math.round(tokenWidth/2), tokenWidth], [Math.round(tokenHeight/2), Math.round(tokenHeight-tokenBasicUnit), Math.round(tokenHeight/2)], 3 );
}
// Draw Action Bar
actions = [];
if( $$ForeRecoverAction.yesNo ) { actions.push( 'recover' ); }
if( $$ForeReinforceAction.yesNo ) { actions.push( 'reinforce' ); }
if( $$ForeCoordinateAction.yesNo ) { actions.push( 'coordinate' ); }
if( $$ForeJamAction.yesNo ) { actions.push( 'jam' ); }
if( $$ForeLockAction.yesNo ) { actions.push( 'lock' ); }
x = 771;
for( let i = 0; i < actions.length; ++i ) {
// Get a nice distribution of the actions
if( tokenSize == 'double' ) {
y = Math.round( ( 353 - 25 * actions.length ) + ( 140 + 50 * actions.length ) / (actions.length + 1) * ( actions.length - i ) );
} else {
y = Math.round( ( 1699 - 25 * actions.length ) + ( 140 + 50 * actions.length ) / (actions.length + 1) * ( actions.length - i ) );
}
sheet.drawOutlinedTitle( g, Xwing.textToIconChar( actions[i] ), Region( x.toString() + ',' + y.toString() + ',100,100'), Xwing.iconFont, 15, 1, Xwing.getColor('imperial'), Color.BLACK, sheet.ALIGN_CENTER, true);
}
if( tokenSize == 'double' ) {
actions = [];
if( $$AftRecoverAction.yesNo ) { actions.push( 'recover' ); }
if( $$AftReinforceAction.yesNo ) { actions.push( 'reinforce' ); }
if( $$AftCoordinateAction.yesNo ) { actions.push( 'coordinate' ); }
if( $$AftJamAction.yesNo ) { actions.push( 'jam' ); }
if( $$AftLockAction.yesNo ) { actions.push( 'lock' ); }
for( let i = 0; i < actions.length; ++i ) {
// Get a nice distribution of the actions
y = Math.round( ( 2054 - 25 * actions.length ) + ( 140 + 50 * actions.length ) / (actions.length + 1) * ( actions.length - i ) );
sheet.drawOutlinedTitle( g, Xwing.textToIconChar( actions[i] ), Region( x.toString() + ',' + y.toString() + ',100,100'), Xwing.iconFont, 15, 1, Xwing.getColor('imperial'), Color.BLACK, sheet.ALIGN_CENTER, true);
}
}
//Draw central cutout circle and ship base cutout rectangles
g.setPaint( Color.WHITE );
cutoutSize = 190;
g.fillOval( Math.round( tokenBasicUnit - cutoutSize/2 ), Math.round( tokenBasicUnit - cutoutSize/2 ), cutoutSize, cutoutSize );
g.fillOval( Math.round( tokenBasicUnit - cutoutSize/2 ), Math.round( tokenHeight - tokenBasicUnit - cutoutSize/2 ), cutoutSize, cutoutSize );
g.fillRect( 0, 0, 47, 963 );
g.fillRect( 0, tokenLowerWaistYCoord, 47, 963 );
g.fillRect( 898, 0, 47, 963 );
g.fillRect( 898, tokenLowerWaistYCoord, 47, 963 );
return;
}
function onClear() {
$Affiliation = 'alliance';
$PilotSkill = '0';
$DoubleSection = 'no';
$Location = 'attack-energy';
$ForeDesignation = 'fore';
$ForeText = '';
$ForeTextFlavor = '';
$ForeCrippledText = '';
$ForeCrippledTextFlavor = '';
$ForePwv = '1';
$ForeCrippledPwv = '1';
$ForeTurret = 'no';
$ForeEnergy = '1';
$ForeCrippledEnergy = '1';
$ForeHull = '1';
$ForeShield = '0';
$ForeArc = '-';
$ForeRange = '1';
$ForeCrippledRange = '1';
$ForeRecoverAction = 'no';
$ForeReinforceAction = 'no';
$ForeCoordinateAction = 'no';
$ForeJamAction = 'no';
$ForeLockAction = 'no';
$ForeUpgrade1 = '-';
$ForeUpgrade2 = '-';
$ForeUpgrade3 = '-';
$ForeUpgrade4 = '-';
$ForeUpgrade5 = '-';
$ForeUpgrade6 = '-';
$ForeUpgrade7 = '-';
$ForeCrippledUpgrade1 = 'no';
$ForeCrippledUpgrade2 = 'no';
$ForeCrippledUpgrade3 = 'no';
$ForeCrippledUpgrade4 = 'no';
$ForeCrippledUpgrade5 = 'no';
$ForeCrippledUpgrade6 = 'no';
$ForeCrippledUpgrade7 = 'no';
$ForeCost = '1';
$AftDesignation = 'aft';
$AftText = '';
$AftTextFlavor = '';
$AftCrippledText = '';
$AftCrippledTextFlavor = '';
$AftPwv = '1';
$AftCrippledPwv = '1';
$AftTurret = 'no';
$AftEnergy = '1';
$AftCrippledEnergy = '1';
$AftHull = '1';
$AftShield = '0';
$AftArc = '-';
$AftRange = '1';
$AftCrippledRange = '1';
$AftRecoverAction = 'no';
$AftReinforceAction = 'no';
$AftCoordinateAction = 'no';
$AftJamAction = 'no';
$AftLockAction = 'no';
$AftUpgrade1 = '-';
$AftUpgrade2 = '-';
$AftUpgrade3 = '-';
$AftUpgrade4 = '-';
$AftUpgrade5 = '-';
$AftUpgrade6 = '-';
$AftUpgrade7 = '-';
$AftCrippledUpgrade1 = 'no';
$AftCrippledUpgrade2 = 'no';
$AftCrippledUpgrade3 = 'no';
$AftCrippledUpgrade4 = 'no';
$AftCrippledUpgrade5 = 'no';
$AftCrippledUpgrade6 = 'no';
$AftCrippledUpgrade7 = 'no';
$AftCost = '1';
}
// These can be used to perform special processing during open/save.
// For example, you can seamlessly upgrade from a previous version
// of the script.
function onRead( diy, ois ) {
if( diy.version < 2 ) {
if( $Affiliation == 'rebel' ) {
$Affiliation = 'alliance';
} else if( $Affiliation == 'imperial' ) {
$Affiliation = 'empire';
}
if( $ForeUpgrade1 == 'none' ) { $ForeUpgrade1 = '-'; }
if( $ForeUpgrade2 == 'none' ) { $ForeUpgrade2 = '-'; }
if( $ForeUpgrade3 == 'none' ) { $ForeUpgrade3 = '-'; }
if( $ForeUpgrade4 == 'none' ) { $ForeUpgrade4 = '-'; }
if( $ForeUpgrade5 == 'none' ) { $ForeUpgrade5 = '-'; }
if( $ForeUpgrade6 == 'none' ) { $ForeUpgrade6 = '-'; }
if( $ForeUpgrade7 == 'none' ) { $ForeUpgrade7 = '-'; }
if( $AftUpgrade1 == 'none' ) { $AftUpgrade1 = '-'; }
if( $AftUpgrade2 == 'none' ) { $AftUpgrade2 = '-'; }
if( $AftUpgrade3 == 'none' ) { $AftUpgrade3 = '-'; }
if( $AftUpgrade4 == 'none' ) { $AftUpgrade4 = '-'; }
if( $AftUpgrade5 == 'none' ) { $AftUpgrade5 = '-'; }
if( $AftUpgrade6 == 'none' ) { $AftUpgrade6 = '-'; }
if( $AftUpgrade7 == 'none' ) { $AftUpgrade7 = '-'; }
if( $ForeArc == 'none' ) { $ForeArc = '-'; }
if( $AftArc == 'none' ) { $AftArc = '-'; }
diy.version = 2;
}
if( diy.version < 3 ) {
$ForeDesignation = 'fore';
$AftDesignation = 'aft';
diy.version = 3;
}
portraits[0] = ois.readObject();
portraits[1] = ois.readObject();
portraits[2] = ois.readObject();
portraits[3] = ois.readObject();
portraits[4] = ois.readObject();
portraits[5] = ois.readObject();
}
function onWrite( diy, oos ) {
oos.writeObject( portraits[0] );
oos.writeObject( portraits[1] );
oos.writeObject( portraits[2] );
oos.writeObject( portraits[3] );
oos.writeObject( portraits[4] );
oos.writeObject( portraits[5] );
}
/**
* createTexturedImage( source, texture )
* Create a new image whose shape (based on translucency) comes
* from <tt>source</tt>, and whose surface is painted using a
* texture. The value of <tt>texture</tt> can be an image, a
* <tt>Color</tt> (in which case the texture is a solid colour),
* or a <tt>Paint</tt>.
*/
function createTexturedImage( source, texture ) {
g = null;
// if texture is a kind of Paint or colour, create a texture image
// using the paint
if( texture instanceof java.awt.Paint ) {
solidTexture = ImageUtils.create( source.width, source.height, true );
try {
g = solidTexture.createGraphics();
g.setPaint( texture );
g.fillRect( 0, 0, source.width, source.height );
texture = solidTexture;
} finally {
if( g ) g.dispose();
g = null;
}
}
dest = ImageUtils.create( source.width, source.height, true );
try {
g = dest.createGraphics();
g.drawImage( source, 0, 0, null );
g.setComposite( java.awt.AlphaComposite.SrcIn );
g.drawImage( texture, 0, 0, null );
} finally {
if( g ) g.dispose();
}
return dest;
}
/**
* createTranslucentImage( source, opacity )
* Create a copy of the source image with an opacity change.
* This is similar to setting the layer opacity in software
* like Photoshop.
*/
function createTranslucentImage( source, opacity ) {
if( opacity >= 1 ) return source;
im = ImageUtils.create( source.width, source.height, true );
if( opacity <= 0 ) return im;
g = im.createGraphics();
try {
g.composite = java.awt.AlphaComposite.SrcOver.derive( opacity );
g.drawImage( source, 0, 0, null );
} finally {
g.dispose();
}
return im;
}
function getShipStat( shipId, stat ) {
key = 'xw-ship-' + shipId + '-' + stat;
if( !Language.getGame().isKeyDefined( key ) ) {
throw new Error( 'shiptype or stat not defined: ' + shipId + stat );
}
return Language.game.get( key );
}
/**
* Returns a region for this component. The nametag is
* the middle part of the region name, without the
* 'char-' prefix or '-region' suffix.
*/
function R( section, nametag, x, y ) {
var value = $('huge-' + section + '-' + nametag + '-region');
if( value == null ) {
throw new Error( 'region not defined: ' + nametag );
}
if( x == null ) {
x = 0;
}
if( y == null ) {
y = 0;
}
var temp = [];
temp = value.split(',');
temp[0] = parseInt(temp[0]) + parseInt(x);
temp[1] = parseInt(temp[1]) + parseInt(y);
temp[0] = temp[0].toString();
temp[1] = temp[1].toString();
value = temp[0] + ',' + temp[1] + ',' + temp[2] + ',' + temp[3];
//return value;
return new Region( value );
}
// This will cause a test component to be created when you run the script
// from a script editor. It doesn't do anything when the script is run
// other ways (e.g., when you choose to create the component by selecting
// it in the New Game Component dialog).
testDIYScript( 'XW' ); | mit |
movio/apidoc | swagger/src/main/scala/me/apidoc/swagger/translators/Body.scala | 667 | package me.apidoc.swagger.translators
import com.bryzek.apidoc.spec.v0.{ models => apidoc }
import io.swagger.models.{ModelImpl, RefModel}
import io.swagger.models.{ parameters => swaggerParams }
object Body {
def apply(
resolver: Resolver,
param: swaggerParams.BodyParameter
): apidoc.Body = {
val bodyType = param.getSchema match {
case m: ModelImpl => m.getType
case m: RefModel => resolver.resolveWithError(m).name
case _ => sys.error("Unsupported body type: " + param.getSchema.getClass)
}
apidoc.Body(
`type` = bodyType,
description = Option(param.getDescription),
deprecation = None
)
}
}
| mit |
prad-a-RuntimeException/semantic-store | src/main/scala/recipestore/ResourceLoader.scala | 1116 | package recipestore
import java.util.ResourceBundle
object AppResource extends Enumeration {
type ResourceName = Value
val TinkerpopResource = Value("tinkerpop")
val TriplestoreResource = Value("triplestore")
val GraphResource = Value("graph")
val LuceneResource = Value("lucene")
}
object ResourceLoader {
private def resourceBundle(key: String) = ResourceBundle.getBundle(key)
val resourceCache: Map[AppResource.Value, ResourceBundle] =
Map(
AppResource.TinkerpopResource -> resourceBundle(AppResource.TinkerpopResource.toString),
AppResource.TriplestoreResource -> resourceBundle(AppResource.TriplestoreResource.toString),
AppResource.GraphResource -> resourceBundle(AppResource.GraphResource.toString),
AppResource.LuceneResource -> resourceBundle(AppResource.LuceneResource.toString)
)
def apply(resource: AppResource.Value, key: String): Option[String] = {
val resourceBundle = resourceCache.getOrElse(resource, null)
if (resourceBundle != null && resourceBundle.containsKey(key)) Option(resourceBundle.getString(key))
else Option.empty
}
} | mit |
DelBianco/TesteSymfony | app/cache/dev/twig/38/3e/078eb846632500e0f1fc0559e58d12e203c7762ae729838ea02075296959.php | 863 | <?php
/* WebProfilerBundle:Profiler:ajax_layout.html.twig */
class __TwigTemplate_383e078eb846632500e0f1fc0559e58d12e203c7762ae729838ea02075296959 extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
'panel' => array($this, 'block_panel'),
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
$this->displayBlock('panel', $context, $blocks);
}
public function block_panel($context, array $blocks = array())
{
echo "";
}
public function getTemplateName()
{
return "WebProfilerBundle:Profiler:ajax_layout.html.twig";
}
public function getDebugInfo()
{
return array ( 20 => 1,);
}
}
| mit |
killyosaur/ag-grid | dist/lib/widgets/touchListener.d.ts | 994 | // Type definitions for ag-grid v13.1.2
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ag-grid/>
import { IEventEmitter } from "../interfaces/iEventEmitter";
import { AgEvent } from "../events";
export interface TapEvent extends AgEvent {
touchStart: Touch;
}
export interface LongTapEvent extends AgEvent {
touchStart: Touch;
}
export declare class TouchListener implements IEventEmitter {
private eElement;
private destroyFuncs;
private moved;
private touching;
private touchStart;
private eventService;
static EVENT_TAP: string;
static EVENT_LONG_TAP: string;
constructor(eElement: HTMLElement);
private getActiveTouch(touchList);
addEventListener(eventType: string, listener: Function): void;
removeEventListener(eventType: string, listener: Function): void;
private onTouchStart(touchEvent);
private onTouchMove(touchEvent);
private onTouchEnd(touchEvent);
destroy(): void;
}
| mit |
LudovicRousseau/Lychee | tests/Feature/UsersTest.php | 6403 | <?php
namespace Tests\Feature;
use AccessControl;
use App\ModelFunctions\SessionFunctions;
use App\Models\Configs;
use Tests\Feature\Lib\AlbumsUnitTest;
use Tests\Feature\Lib\SessionUnitTest;
use Tests\Feature\Lib\UsersUnitTest;
use Tests\TestCase;
class UsersTest extends TestCase
{
public function testSetLogin()
{
/**
* because there is no dependency injection in test cases.
*/
$sessionFunctions = new SessionFunctions();
$sessions_test = new SessionUnitTest();
$clear = false;
$configs = Configs::get();
/*
* Check if password and username are set
*/
if ($configs['password'] == '' && $configs['username'] == '') {
$clear = true;
$sessions_test->set_new($this, 'lychee', 'password', 'true');
$sessions_test->logout($this);
$sessions_test->login($this, 'lychee', 'password', 'true');
$sessions_test->logout($this);
} else {
$this->markTestSkipped('Username and Password are set. We do not bother testing further.');
}
/*
* We check that there are username and password set in the database
*/
$this->assertFalse($sessionFunctions->noLogin());
$sessions_test->login($this, 'foo', 'bar', 'false');
$sessions_test->login($this, 'lychee', 'bar', 'false');
$sessions_test->login($this, 'foo', 'password', 'false');
/*
* If we did set login and password we clear them
*/
if ($clear) {
Configs::set('username', '');
Configs::set('password', '');
}
}
public function testUsers()
{
$sessions_test = new SessionUnitTest();
$users_test = new UsersUnitTest();
$album_tests = new AlbumsUnitTest($this);
/*
* Scenario is as follow
*
* 1. log as admin
* 2. create a user 'test_abcd'
* 3. list users
* 4. check if the user is found
* 5. create a user 'test_abcd' => should return an error: no duplicate username
* 6. change username and password of user
* 7. create a user 'test_abcd2'
* 8. change username to test_abcd => should return an error: no duplicate username
* 9. log out
* 10. log as 'test_abcde'
* 11. try to list users => should fail
* 12. change password without old password => should fail (account is locked)
* 13. change password => should fail (account is locked)
* 14. log out (did not test upload)
*
* 15. log as admin
* 16. unlock account
* 17. log out
*
* 18. log as 'test_abcde'
* 19. try access shared pictures (public)
* 20. try access starred pictures
* 21. try access recent pictures
* 22. change password without old password => should fail
* 23. change password with wrong password => should fail
* 24. change username & password with duplicate username => should fail
* 25. change username & password
* 26. log out
*
* 27. log as 'test_abcde'
* 28. log out
*
* 29. log as admin
* 30. delete user
* 31. log out
*
* 32. log as admin
* 33 get email => should be blank
* 34. update email
* 35. get email
* 36 update email to blank
* 37. log out
*/
// 1
AccessControl::log_as_id(0);
// 2
$users_test->add($this, 'test_abcd', 'test_abcd', '1', '1', 'true');
// 3
$response = $users_test->list($this, 'true');
// 4
$t = json_decode($response->getContent());
$id = end($t)->id;
$response->assertJsonFragment([
'id' => $id,
'username' => 'test_abcd',
'upload' => 1,
'lock' => 1,
]);
// 5
$users_test->add($this, 'test_abcd', 'test_abcd', '1', '1', 'Error: username must be unique');
// 6
$users_test->save($this, $id, 'test_abcde', 'testing', '0', '1', 'true');
// 7
$users_test->add($this, 'test_abcd2', 'test_abcd', '1', '1', 'true');
$response = $users_test->list($this, 'true');
$t = json_decode($response->getContent());
$id2 = end($t)->id;
// 8
$users_test->save($this, $id2, 'test_abcde', 'testing', '0', '1', 'Error: username must be unique');
// 9
$sessions_test->logout($this);
// 10
$sessions_test->login($this, 'test_abcde', 'testing');
// 11
$users_test->list($this, 'false');
// 12
$sessions_test->set_new($this, 'test_abcde', 'testing2', '"Error: Locked account!"');
// 13
$sessions_test->set_old($this, 'test_abcde', 'testing2', 'test_abcde', 'testing2', '"Error: Locked account!"');
// 14
$sessions_test->logout($this);
// 15
AccessControl::log_as_id(0);
// 16
$users_test->save($this, $id, 'test_abcde', 'testing', '0', '0', 'true');
// 17
$sessions_test->logout($this);
// 18
$sessions_test->login($this, 'test_abcde', 'testing');
$sessions_test->init($this, 'true');
// 19
$album_tests->get('public', '', 'true');
// 20
$album_tests->get('starred', '', 'true');
// 21
$album_tests->get('unsorted', '', 'true');
// 22
$sessions_test->set_new($this, 'test_abcde', 'testing2', '"Error: Old username or password entered incorrectly!"');
// 23
$sessions_test->set_old($this, 'test_abcde', 'testing2', 'test_abcde', 'testing2', '"Error: Old username or password entered incorrectly!"');
// 24
$sessions_test->set_old($this, 'test_abcd2', 'testing2', 'test_abcde', 'testing2', '"Error: Username already exists."');
// 25
$sessions_test->set_old($this, 'test_abcdef', 'testing2', 'test_abcde', 'testing', 'true');
// 26
$sessions_test->logout($this);
// 27
$sessions_test->login($this, 'test_abcdef', 'testing2');
// 28
$sessions_test->logout($this);
// 29
AccessControl::log_as_id(0);
// 30
$users_test->delete($this, $id, 'true');
$users_test->delete($this, $id2, 'true');
// those should fail because we do not touch user of ID 0
$users_test->delete($this, '0', 'false', 422);
// those should fail because there are no user with id -1
$users_test->delete($this, '-1', 'false', 422);
$users_test->save($this, '-1', 'toto', 'test', '0', '1', 'false', 422);
// 31
$sessions_test->logout($this);
// 32
AccessControl::log_as_id(0);
$configs = Configs::get();
$store_new_photos_notification = $configs['new_photos_notification'];
Configs::set('new_photos_notification', '1');
// 33
$users_test->get_email($this, '');
// 34
$users_test->update_email($this, '[email protected]', 'true');
// 35
$users_test->get_email($this, '[email protected]');
// 36
$users_test->update_email($this, '', 'true');
// 37
$sessions_test->logout($this);
Configs::set('new_photos_notification', $store_new_photos_notification);
}
}
| mit |
saytam/vela | src/main/java/vela/game/DistanceCalculator.java | 520 | package vela.game;
public class DistanceCalculator {
public static boolean canMove(Unit unit, Position from, Position to) {
int dX = to.getX() - from.getX();
int dY = to.getY() - from.getY();
return unit.getSpeed() >= Math.max(Math.abs(dX), Math.abs(dY));
}
public static boolean canAttack(Unit unit, Position from, Position to) {
int dX = from.getX() - to.getX();
int dY = from.getY() - to.getY();
return 1 == Math.max(Math.abs(dX), Math.abs(dY));
}
}
| mit |
Lilaska/test_electric | src/VyatkinaA/ElectricBundle/VyatkinaAElectricBundle.php | 142 | <?php
namespace VyatkinaA\ElectricBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class VyatkinaAElectricBundle extends Bundle
{
}
| mit |
satoshi-fapamoto/guzl | app/shared/services/reddit.service.ts | 461 | import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
@Injectable()
export class RedditService {
constructor(
private http: Http
) { }
getDetailedRedditPost(permalink) {
return this.http.get('https://www.reddit.com'+permalink+'.json')
.map((res: Response) => res.json());
}
getRealGirlsPosts() {
return this.http.get(`https://www.reddit.com/r/RealGirls/.json`)
.map((res: Response) => res.json());
}
} | mit |
0of/chinesegen | Gruntfile.js | 816 | module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: {
build: {
src: ['dist/']
}
},
eslint: {
target: {
src: ['lib/*.js', 'test/*.js']
}
},
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['./test/**/*.js']
}
},
webpack: require('./webpack.chinesegen')
});
grunt.registerTask('eslint', 'eslint:target');
grunt.registerTask('test', ['eslint:target', 'mochaTest:test']);
grunt.registerTask('build', ['eslint:target', 'mochaTest:test', 'clean', 'webpack']);
require('load-grunt-tasks')(grunt);
}; | mit |
ckjk/Team-Tangor | tangorApp/.meteor/local/build/programs/server/npm-rebuild-args.js | 900 | // Command-line arguments passed to npm when rebuilding binary packages.
var args = [
"rebuild",
// The --no-bin-links flag tells npm not to create symlinks in the
// node_modules/.bin/ directory when rebuilding packages, which helps
// avoid problems like https://github.com/meteor/meteor/issues/7401.
"--no-bin-links",
// The --update-binary flag tells node-pre-gyp to replace previously
// installed local binaries with remote binaries:
// https://github.com/mapbox/node-pre-gyp#options
"--update-binary"
];
// Allow additional flags to be passed via the $METEOR_NPM_REBUILD_FLAGS
// environment variable.
var flags = process.env.METEOR_NPM_REBUILD_FLAGS;
if (flags) {
args = ["rebuild"];
flags.split(/\s+/g).forEach(function (flag) {
if (flag) {
args.push(flag);
}
});
}
exports.get = function () {
// Make a defensive copy.
return args.slice(0);
};
| mit |
IgnatBeresnev/Algorithms | src/main/java/me/beresnev/datastructures/HashMap.java | 9733 | package me.beresnev.datastructures;
import java.util.Objects;
/**
* @author Ignat Beresnev
* @version 1.0
* @since 28.02.17.
*/
public class HashMap<K, V> {
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
private static final int DEFAULT_CAPACITY = 16;
private static final int DEFAULT_THRESHOLD = 12;
private int capacity; // how many items map can hold (table.length)
private int threshold; // default - 75% of capacity, if size=threshold, expand
private int size; // how many elements THERE ARE in the map
private Node[] table;
public HashMap() {
capacity = DEFAULT_CAPACITY;
threshold = DEFAULT_THRESHOLD;
table = new Node[capacity];
}
/**
* Seen in JDK6. Quoting: Applies a supplemental hash function
* to a given hashCode, which defends against poor quality
* hash functions. This is critical because HashMap uses
* power-of-two length hash tables, that otherwise encounter
* collisions for hashCodes that do not differ in lower bits.
* <p>
* Might be slower than current implementation in Java 8
* TODO: Read about this difference and about high/low bits
*
* @param h = object.hashCode()
* @return corrected hash
*/
private static int hash(int h) {
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
/**
* @param hash = hash(object.hashCode())
* @param length capacity of the current table
* @return bucket for certain hash depending on given capacity
*/
private static int indexFor(int hash, int length) {
return hash & (length - 1);
}
/**
* Pretty straight-forward. Get index based on the hash, look at a certain
* bucket, look for key inside the chain. If given key is found, override
* value, if not - add a new node (method addNode)
* TODO: Add null support
*
* @return old value if key was already present, null otherwise
* @see #addNode(int, Object, Object, int) for when we actually insert a new pair
*/
@SuppressWarnings("unchecked")
public V put(K key, V value) {
if (key == null || value == null)
throw new IllegalArgumentException("No null support as for now");
int hash = hash(key.hashCode());
int index = indexFor(hash, capacity);
for (Node<K, V> current = table[index]; current != null; current = current.next) {
if (hash == current.hash && (key == current.key || key.equals(current.key))) {
V oldValue = current.value;
current.value = value;
return oldValue;
}
}
addNode(hash, key, value, index);
return null;
}
/**
* Adds this pair key-value to the beginning of the bucket,
* places oldNode from that bucket right after (next).
* If size >= threshold, we grow.
* TODO: Probably can do something better than oldNode != null
*
* @see #resize(int) for details on how hashMap expands
*/
@SuppressWarnings("unchecked")
private void addNode(int hash, K key, V value, int bucket) {
Node<K, V> oldNode = table[bucket];
Node<K, V> newNode = new Node<>(hash, key, value, oldNode);
table[bucket] = newNode;
if (oldNode != null)
oldNode.previous = newNode;
if (size++ >= threshold)
resize(2 * capacity);
}
/**
* TODO: Do we throw something instead of null?
*
* @return value of the removed node, null otherwise
*/
public V remove(K key) {
if (key == null)
throw new IllegalArgumentException("Null key removal is not permitted");
return removeNode(key);
}
/**
* Based on hash, gets this key's bucket, looks at where the required node is:
* 1) If it's the head (1st element in the bucket), just change the head to next
* 2) If it's the last element, just delete pointer to that element
* 3) Must have both prev and next. Just unlink this element, exchanging pointers.
*
* @return value of the removed node or null if node with key not found
*/
@SuppressWarnings("unchecked")
private V removeNode(K key) {
int hash = hash(key.hashCode());
int index = indexFor(hash, capacity);
Node<K, V> firstTableNode = table[index];
for (Node<K, V> current = firstTableNode; current != null; current = current.next) {
if (hash == current.hash && (key == current.key || key.equals(current.key))) {
if (firstTableNode == current)
table[index] = current.next;
else if (current.next == null)
current.previous.next = null;
else {
current.previous.next = current.next;
current.next.previous = current.previous;
}
size--;
return current.value;
}
}
return null;
}
/**
* @return value of the given key, if present. null otherwise
*/
public V get(K key) {
if (key == null)
throw new IllegalArgumentException("No null support as for now");
Node<K, V> node = getNode(key);
return node == null ? null : node.value;
}
/**
* @return true if node with given key exists, false otherwise
*/
public boolean contains(K key) {
Node<K, V> node = getNode(key);
return node != null;
}
/**
* @return node with the given key, null otherwise
*/
@SuppressWarnings("unchecked")
private Node<K, V> getNode(K key) {
int hash = hash(key.hashCode());
Node<K, V> node = table[indexFor(hash, capacity)];
for (Node<K, V> current = node; current != null; current = current.next) {
if (hash == current.hash && (key == current.key || key.equals(current.key)))
return current;
}
return null;
}
/**
* @return number of elements in the map
*/
public int size() {
return size;
}
/**
* @return true if map size == 0 (that is empty), false otherwise
*/
public boolean isEmpty() {
return size == 0;
}
/**
* When size >= threshold, we need to expand. Start with this method
* Make a new table, transfer the elements, update counters
*
* @param newCapacity x2 of old capacity (table.length)
* @see #transferTo(Node[]) for how we transfer elements to the new table
*/
private void resize(int newCapacity) {
Node[] newTable = new Node[newCapacity];
transferTo(newTable);
table = newTable;
capacity = newCapacity;
threshold = (int) (newCapacity * DEFAULT_LOAD_FACTOR);
}
/**
* Walk through every chain within every bucket in the OLD table,
* starting from the beginning. Unlink elements in the old table to let
* GC do its work. Then get new index for the Node based on new capacity,
* place that node into the new table at that index. BUT! Just in case
* there's already something in that bucket in the new table, we take
* whatever is in that bucket (even null) and link it AFTER current
* element. Then we place that element in the beginning of the new bucket.
*
* @param newTable table to transfer elements into
*/
@SuppressWarnings("unchecked")
private void transferTo(Node[] newTable) {
Node[] oldTable = table;
int newCapacity = newTable.length;
for (int i = 0; i < oldTable.length; i++) { // bucket walking
Node<K, V> current = oldTable[i];
if (current != null) {
oldTable[i] = null; // letting GC do its work
while (current != null) { // chain walking
int index = indexFor(current.hash, newCapacity);
Node<K, V> oldNext = current.next;
// link whatever is in that bucket after this element
// place the element in the beginning of the new bucket
current.next = newTable[index];
newTable[index] = current;
current = oldNext;
}
}
}
}
private static class Node<K, V> {
private final int hash;
private final K key;
private V value;
private Node next;
private Node previous;
/**
* @param hash hashCode of the key
* @param next node that will be linked after this node
*/
private Node(int hash, K key, V value, Node<K, V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Node) {
Node e = ((Node) o);
if (Objects.equals(key, e.key) && Objects.equals(value, e.value))
return true;
}
return false;
}
// overridden just because I've implemented equals
// Standard Java SE HashMap.Entry hashCode() implementation
public int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public String toString() {
return key + "=" + value;
}
}
}
| mit |
Condors/TunisiaMall | vendor/symfony/symfony/src/Symfony/Component/Routing/Generator/UrlGenerator.php | 14509 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Routing\Generator;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Exception\InvalidParameterException;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
use Psr\Log\LoggerInterface;
/**
* UrlGenerator can generate a URL or a path for any route in the RouteCollection
* based on the passed parameters.
*
* @author Fabien Potencier <[email protected]>
* @author Tobias Schultze <http://tobion.de>
*/
class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInterface
{
/**
* @var RouteCollection
*/
protected $routes;
/**
* @var RequestContext
*/
protected $context;
/**
* @var bool|null
*/
protected $strictRequirements = true;
/**
* @var LoggerInterface|null
*/
protected $logger;
/**
* This array defines the characters (besides alphanumeric ones) that will not be percent-encoded in the path segment of the generated URL.
*
* PHP's rawurlencode() encodes all chars except "a-zA-Z0-9-._~" according to RFC 3986. But we want to allow some chars
* to be used in their literal form (reasons below). Other chars inside the path must of course be encoded, e.g.
* "?" and "#" (would be interpreted wrongly as query and fragment identifier),
* "'" and """ (are used as delimiters in HTML).
*/
protected $decodedChars = array(
// the slash can be used to designate a hierarchical structure and we want allow using it with this meaning
// some webservers don't allow the slash in encoded form in the path for security reasons anyway
// see http://stackoverflow.com/questions/4069002/http-400-if-2f-part-of-get-url-in-jboss
'%2F' => '/',
// the following chars are general delimiters in the URI specification but have only special meaning in the authority component
// so they can safely be used in the path in unencoded form
'%40' => '@',
'%3A' => ':',
// these chars are only sub-delimiters that have no predefined meaning and can therefore be used literally
// so URI producing applications can use these chars to delimit subcomponents in a path segment without being encoded for better readability
'%3B' => ';',
'%2C' => ',',
'%3D' => '=',
'%2B' => '+',
'%21' => '!',
'%2A' => '*',
'%7C' => '|',
);
/**
* Constructor.
*
* @param RouteCollection $routes A RouteCollection instance
* @param RequestContext $context The context
* @param LoggerInterface|null $logger A logger instance
*/
public function __construct(RouteCollection $routes, RequestContext $context, LoggerInterface $logger = null)
{
$this->routes = $routes;
$this->context = $context;
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public function setContext(RequestContext $context)
{
$this->context = $context;
}
/**
* {@inheritdoc}
*/
public function getContext()
{
return $this->context;
}
/**
* {@inheritdoc}
*/
public function setStrictRequirements($enabled)
{
$this->strictRequirements = null === $enabled ? null : (bool) $enabled;
}
/**
* {@inheritdoc}
*/
public function isStrictRequirements()
{
return $this->strictRequirements;
}
/**
* {@inheritdoc}
*/
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
{
if (null === $route = $this->routes->get($name)) {
throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
}
// the Route has a cache of its own and is not recompiled as long as it does not get modified
$compiledRoute = $route->compile();
return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $referenceType, $compiledRoute->getHostTokens(), $route->getSchemes());
}
/**
* @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route
* @throws InvalidParameterException When a parameter value for a placeholder is not correct because
* it does not match the requirement
*/
protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array())
{
if (is_bool($referenceType) || is_string($referenceType)) {
@trigger_error('The hardcoded value you are using for the $referenceType argument of the '.__CLASS__.'::generate method is deprecated since version 2.8 and will not be supported anymore in 3.0. Use the constants defined in the UrlGeneratorInterface instead.', E_USER_DEPRECATED);
if (true === $referenceType) {
$referenceType = self::ABSOLUTE_URL;
} elseif (false === $referenceType) {
$referenceType = self::ABSOLUTE_PATH;
} elseif ('relative' === $referenceType) {
$referenceType = self::RELATIVE_PATH;
} elseif ('network' === $referenceType) {
$referenceType = self::NETWORK_PATH;
}
}
$variables = array_flip($variables);
$mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
// all params must be given
if ($diff = array_diff_key($variables, $mergedParams)) {
throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name));
}
$url = '';
$optional = true;
foreach ($tokens as $token) {
if ('variable' === $token[0]) {
if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) {
// check requirement
if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#', $mergedParams[$token[3]])) {
$message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
if ($this->strictRequirements) {
throw new InvalidParameterException($message);
}
if ($this->logger) {
$this->logger->error($message);
}
return;
}
$url = $token[1].$mergedParams[$token[3]].$url;
$optional = false;
}
} else {
// static text
$url = $token[1].$url;
$optional = false;
}
}
if ('' === $url) {
$url = '/';
}
// the contexts base URL is already encoded (see Symfony\Component\HttpFoundation\Request)
$url = strtr(rawurlencode($url), $this->decodedChars);
// the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3
// so we need to encode them as they are not used for this purpose here
// otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route
$url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/'));
if ('/..' === substr($url, -3)) {
$url = substr($url, 0, -2).'%2E%2E';
} elseif ('/.' === substr($url, -2)) {
$url = substr($url, 0, -1).'%2E';
}
$schemeAuthority = '';
if ($host = $this->context->getHost()) {
$scheme = $this->context->getScheme();
if ($requiredSchemes) {
if (!in_array($scheme, $requiredSchemes, true)) {
$referenceType = self::ABSOLUTE_URL;
$scheme = current($requiredSchemes);
}
} elseif (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme !== $req) {
// We do this for BC; to be removed if _scheme is not supported anymore
$referenceType = self::ABSOLUTE_URL;
$scheme = $req;
}
if ($hostTokens) {
$routeHost = '';
foreach ($hostTokens as $token) {
if ('variable' === $token[0]) {
if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#i', $mergedParams[$token[3]])) {
$message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
if ($this->strictRequirements) {
throw new InvalidParameterException($message);
}
if ($this->logger) {
$this->logger->error($message);
}
return;
}
$routeHost = $token[1].$mergedParams[$token[3]].$routeHost;
} else {
$routeHost = $token[1].$routeHost;
}
}
if ($routeHost !== $host) {
$host = $routeHost;
if (self::ABSOLUTE_URL !== $referenceType) {
$referenceType = self::NETWORK_PATH;
}
}
}
if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) {
$port = '';
if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
$port = ':'.$this->context->getHttpPort();
} elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
$port = ':'.$this->context->getHttpsPort();
}
$schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "$scheme://";
$schemeAuthority .= $host.$port;
}
}
if (self::RELATIVE_PATH === $referenceType) {
$url = self::getRelativePath($this->context->getPathInfo(), $url);
} else {
$url = $schemeAuthority.$this->context->getBaseUrl().$url;
}
// add a query string if needed
$extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) {
return $a == $b ? 0 : 1;
});
if ($extra && $query = http_build_query($extra, '', '&')) {
// "/" and "?" can be left decoded for better user experience, see
// http://tools.ietf.org/html/rfc3986#section-3.4
$url .= '?'.strtr($query, array('%2F' => '/'));
}
return $url;
}
/**
* Returns the target path as relative reference from the base path.
*
* Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash.
* Both paths must be absolute and not contain relative parts.
* Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
* Furthermore, they can be used to reduce the link size in documents.
*
* Example target paths, given a base path of "/a/b/c/d":
* - "/a/b/c/d" -> ""
* - "/a/b/c/" -> "./"
* - "/a/b/" -> "../"
* - "/a/b/c/other" -> "other"
* - "/a/x/y" -> "../../x/y"
*
* @param string $basePath The base path
* @param string $targetPath The target path
*
* @return string The relative target path
*/
public static function getRelativePath($basePath, $targetPath)
{
if ($basePath === $targetPath) {
return '';
}
$sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
$targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath);
array_pop($sourceDirs);
$targetFile = array_pop($targetDirs);
foreach ($sourceDirs as $i => $dir) {
if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
unset($sourceDirs[$i], $targetDirs[$i]);
} else {
break;
}
}
$targetDirs[] = $targetFile;
$path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs);
// A reference to the same base directory or an empty subdirectory must be prefixed with "./".
// This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
// as the first segment of a relative-path reference, as it would be mistaken for a scheme name
// (see http://tools.ietf.org/html/rfc3986#section-4.2).
return '' === $path || '/' === $path[0]
|| false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
? "./$path" : $path;
}
}
| mit |
klpdotorg/dubdubdub | apps/common/managers.py | 173 | from django.db.models import Manager
from django.contrib.gis.db.models import GeoManager
class BaseManager(Manager):
pass
class BaseGeoManager(GeoManager):
pass
| mit |
BrettJaner/csla | Source/Csla.Uwp/Properties/AssemblyInfo.cs | 1100 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CSLA .NET for UWP")]
[assembly: AssemblyDescription("CSLA .NET Framework (UWP)")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Marimer LLC")]
[assembly: AssemblyProduct("CSLA .NET")]
[assembly: AssemblyCopyright("Copyright © 2010-16 Marimer LLC")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("4.6.500.0")]
[assembly: AssemblyFileVersion("4.6.500.0")]
[assembly: ComVisible(false)] | mit |
uon-team/uon.gl | shaders/colorid.js | 377 |
module.exports = [
'precision highp float;',
'uniform float LogDepthBufferFar;',
'uniform vec3 CameraPosition;',
'uniform vec4 ObjectID;',
/*'#extension GL_EXT_frag_depth : enable',
'varying float vFragDepth;',*/
'void main() {',
' gl_FragColor = vec4(ObjectID.xyz, 1.0);',
/*' gl_FragDepthEXT = log2(vFragDepth) * LogDepthBufferFar * 0.5;',*/
'}'
].join('\n'); | mit |
ValentinAlexandrovGeorgiev/deal | src/components/add-estate-info/AddEstateInfo.js | 16546 | import React, { Component } from 'react'
import t from 'translations'
import * as ACTIONS from 'actions'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import './addestateinfo.scss'
const ESTATE_TYPES = {
apartament: 'apartament',
house: 'house',
bussiness: 'bussiness',
hotel: 'hotel',
faculty: 'faculty',
sports: 'sports',
field: 'field'
}
class AddEstateInfo extends Component {
constructor() {
super()
this.state = {
readyState: false,
readyClass: false,
quadrature: '',
floor: '',
allFloors: '',
price: '',
buildingYear: '',
moreInfo: '',
buildingType: 'brick',
currency: '€',
estateType: ESTATE_TYPES.apartament,
additionalType: 'one-room',
}
this.handleSubmit = this.handleSubmit.bind(this)
this.handleEdit = this.handleEdit.bind(this)
}
handleSubmit() {
const {
quadrature,
buildingYear,
moreInfo,
floor,
allFloors,
price,
buildingType,
currency,
additionalType,
estateType
} = this.state
this.props.actions.addEstateInformation({
quadrature,
buildingYear,
moreInfo,
floor,
allFloors,
price,
buildingType,
currency,
additionalType,
estateType
})
}
componentWillReceiveProps(nextProps) {
const {
error
} = nextProps
if (error) {
this.startAnimation()
}
}
startAnimation() {
const {
change
} = this.props
this.setState({
readyClass: true
})
setTimeout(() => {
this.setState({
readyState: true
})
change({
activeAddEstateUser: false,
activeAddEstateInfo: false,
activeAddEstateAddress: true
})
}, 2200)
}
handleEdit() {
this.setState({
readyClass: false,
readyState: false
})
}
selectType(type, innerType) {
this.setState({
estateType: type,
additionalType: innerType
})
}
returnType(type) {
if (type === this.state.estateType) {
return 'btn-blue'
}
return ''
}
checkEstateInnerType(type) {
if (type === this.state.additionalType) {
return true
}
return false
}
selectEstateInnerType(type) {
this.setState({
additionalType: type
})
}
handleChangeInput(event, type) {
let object = {}
object[type] = event.target.value
this.setState(object)
}
createInnerTypes() {
const {
estateType
} = this.state
switch(estateType) {
case ESTATE_TYPES.apartament: {
return (
<div>
<label><input onChange={() => this.selectEstateInnerType('one-room')} checked={this.checkEstateInnerType('one-room')} type='radio' value='one-room' name='apartament-type' /> Едностаен </label>
<label><input onChange={() => this.selectEstateInnerType('two-rooms')} checked={this.checkEstateInnerType('two-rooms')} type='radio' value='two-rooms' name='apartament-type' /> Двустаен </label>
<label><input onChange={() => this.selectEstateInnerType('three-rooms')} checked={this.checkEstateInnerType('three-rooms')} type='radio' value='three-rooms' name='apartament-type' /> Тристаен </label>
<label><input onChange={() => this.selectEstateInnerType('four-rooms')} checked={this.checkEstateInnerType('four-rooms')} type='radio' value='four-rooms' name='apartament-type' /> Четиристаен </label>
<label><input onChange={() => this.selectEstateInnerType('many-rooms')} checked={this.checkEstateInnerType('many-rooms')} type='radio' value='many-rooms' name='apartament-type' /> Многостаен </label>
<label><input onChange={() => this.selectEstateInnerType('maisonette')} checked={this.checkEstateInnerType('maisonette')} type='radio' value='maisonette' name='apartament-type' /> Мезонет </label>
<label><input onChange={() => this.selectEstateInnerType('threesonette')} checked={this.checkEstateInnerType('threesonette')} type='radio' value='threesonette' name='apartament-type' /> Тризонет </label>
<label><input onChange={() => this.selectEstateInnerType('room')} checked={this.checkEstateInnerType('room')} type='radio' value='room' name='apartament-type' /> Стая </label>
<label><input onChange={() => this.selectEstateInnerType('atelier')} checked={this.checkEstateInnerType('atelier')} type='radio' value='atelier' name='apartament-type' /> Ателие </label>
</div>
)
}
case ESTATE_TYPES.house: {
return (
<div>
<label><input onChange={() => this.selectEstateInnerType('one-floor')} checked={this.checkEstateInnerType('one-floor')} type='radio' value='one-floor' name='house-type' /> Едноетажна </label>
<label><input onChange={() => this.selectEstateInnerType('two-floors')} checked={this.checkEstateInnerType('two-floors')} type='radio' value='two-floors' name='house-type' /> Двуетажна </label>
<label><input onChange={() => this.selectEstateInnerType('three-floors')} checked={this.checkEstateInnerType('three-floors')} type='radio' value='three-floors' name='house-type' /> Триетажна </label>
<label><input onChange={() => this.selectEstateInnerType('many-floors')} checked={this.checkEstateInnerType('many-floors')} type='radio' value='many-floors' name='house-type' /> Многоетажна </label>
<label><input onChange={() => this.selectEstateInnerType('floor-house')} checked={this.checkEstateInnerType('floor-house')} type='radio' value='floor-house' name='house-type' /> Етаж от къща </label>
<label><input onChange={() => this.selectEstateInnerType('semi-detached')} checked={this.checkEstateInnerType('semi-detached')} type='radio' value='semi-detached' name='house-type' /> На калкан </label>
<label><input onChange={() => this.selectEstateInnerType('whole-house')} checked={this.checkEstateInnerType('whole-house')} type='radio' value='whole-house' name='house-type' /> Самостоятелна </label>
</div>
)
}
case ESTATE_TYPES.hotel: {
return (
<div>
<label><input onChange={() => this.selectEstateInnerType('spa')} checked={this.checkEstateInnerType('spa')} type='radio' value='spa' name='hotel-type' /> Спа</label>
<label><input onChange={() => this.selectEstateInnerType('for-rest')} checked={this.checkEstateInnerType('for-rest')} type='radio' value='for-rest' name='hotel-type' /> Почивни</label>
</div>
)
}
case ESTATE_TYPES.bussiness: {
return (
<div>
<label><input onChange={() => this.selectEstateInnerType('office')} checked={this.checkEstateInnerType('office')} type='radio' value='office' name='bussiness-type' /> Офис </label>
<label><input onChange={() => this.selectEstateInnerType('store')} checked={this.checkEstateInnerType('store')} type='radio' value='store' name='bussiness-type' /> Магазин </label>
<label><input onChange={() => this.selectEstateInnerType('restaurant')} checked={this.checkEstateInnerType('restaurant')} type='radio' value='restaurant' name='bussiness-type' /> Ресторант </label>
</div>
)
}
case ESTATE_TYPES.sports: {
return (
<div>
<label><input onChange={() => this.selectEstateInnerType('fitness')} checked={this.checkEstateInnerType('fitness')} type='radio' value='fitness' name='sports-type' /> Фитнес зала </label>
<label><input onChange={() => this.selectEstateInnerType('gym')} checked={this.checkEstateInnerType('gym')} type='radio' value='gym' name='sports-type' /> Салон </label>
<label><input onChange={() => this.selectEstateInnerType('pool')} checked={this.checkEstateInnerType('pool')} type='radio' value='pool' name='sports-type' /> Басейн </label>
<label><input onChange={() => this.selectEstateInnerType('sport-field')} checked={this.checkEstateInnerType('sport-field')} type='radio' value='sport-field' name='sports-type' /> Игрище </label>
</div>
)
}
case ESTATE_TYPES.faculty: {
return (
<div>
<label><input onChange={() => this.selectEstateInnerType('warehouse')} checked={this.checkEstateInnerType('warehouse')} type='radio' value='warehouse' name='faculty-type' /> Склад</label>
<label><input onChange={() => this.selectEstateInnerType('faculty')} checked={this.checkEstateInnerType('faculty')} type='radio' value='faculty' name='faculty-type' /> Завод</label>
<label><input onChange={() => this.selectEstateInnerType('saloon')} checked={this.checkEstateInnerType('saloon')} type='radio' value='saloon' name='faculty-type' /> Салон</label>
</div>
)
}
case ESTATE_TYPES.field: {
return (
<div>
<label><input onChange={() => this.selectEstateInnerType('land')} checked={this.checkEstateInnerType('land')} type='radio' value='land' name='field-type' /> Земеделска земя</label>
<label><input onChange={() => this.selectEstateInnerType('home-building')} checked={this.checkEstateInnerType('home-building')} type='radio' value='home-building' name='field-type' /> За жилищно строителство</label>
<label><input onChange={() => this.selectEstateInnerType('faculty-building')} checked={this.checkEstateInnerType('faculty-building')} type='radio' value='faculty-building' name='field-type' /> За промишлено строителство</label>
</div>
)
}
}
}
render() {
const {
readyState,
readyClass,
quadrature,
buildingYear,
moreInfo,
floor,
allFloors,
price,
buildingType,
currency,
estateType
} = this.state
const {
error,
active
} = this.props
let activeClass = active ? '' : 'not-active'
const animationClass = readyClass ? 'start-animation' : ''
return (
<div className="add-estate-info__wrapper">
<div className={`${animationClass} info__wrapper`}>
<div className={`shallow-block ${activeClass}`} />
<h3 className='info__title'>Информация за имота</h3>
<div>
<div className='estate_type__wrapper'>
<div className='type-wrapper'>
<button className={`btn ${this.returnType(ESTATE_TYPES.apartament)}`} onClick={() => this.selectType('apartament', 'one-room')}>Апартаменти</button>
</div>
<div className='type-wrapper'>
<button className={`btn ${this.returnType(ESTATE_TYPES.house)}`} onClick={() => this.selectType('house', 'one-floor')}>Къщи</button>
</div>
<div className='type-wrapper'>
<button className={`btn ${this.returnType(ESTATE_TYPES.bussiness)}`} onClick={() => this.selectType('bussiness', 'office')}>Бизнес имоти</button>
</div>
<div className='type-wrapper'>
<button className={`btn ${this.returnType(ESTATE_TYPES.hotel)}`} onClick={() => this.selectType('hotel', 'spa')}>Хотели</button>
</div>
<div className='type-wrapper'>
<button className={`btn ${this.returnType(ESTATE_TYPES.faculty)}`} onClick={() => this.selectType('faculty', 'warehouse')}>Производствени помещения</button>
</div>
<div className='type-wrapper'>
<button className={`btn ${this.returnType(ESTATE_TYPES.sports)}`} onClick={() => this.selectType('sports', 'fitness')}>Спортни съоръжения</button>
</div>
<div className='type-wrapper'>
<button className={`btn ${this.returnType(ESTATE_TYPES.field)}`} onClick={() => this.selectType('field', 'land')}>Парцели</button>
</div>
</div>
<div className='more-type__wrapper'>
{this.createInnerTypes()}
</div>
<div className='floor__wrapper'>
<div className='input-wrapper'>
<label>
Квадратура:
<input onChange={(event) => this.handleChangeInput(event, 'quadrature')} value={quadrature} type='number' />
</label>
</div>
<div className='input-wrapper'>
<label>
Етаж:
<input onChange={(event) => this.handleChangeInput(event, 'floor')} value={floor} type='number' />
</label>
</div>
<div className='input-wrapper'>
<label>
Етажност:
<input onChange={(event) => this.handleChangeInput(event, 'allFloors')} value={allFloors} type='number' />
</label>
</div>
</div>
<div className='price-building__wrapper'>
<div className='input-wrapper'>
<label>
Цена:
<input onChange={(event) => this.handleChangeInput(event, 'price')} value={price} type='number' />
</label>
</div>
<div className='input-wrapper'>
<label>
Валута:
<select value={currency} onChange={(event) => this.handleChangeInput(event, 'currency')}>
<option default value='€'>€</option>
<option value='$'>$</option>
<option value='лв'>лв</option>
<option value='£'>£</option>
</select>
</label>
</div>
<div className='input-wrapper'>
<label>
Вид строителство:
<select value={buildingType} onChange={(event) => this.handleChangeInput(event, 'buildingType')}>
<option default value='brick'>тухла</option>
<option value='panel'>панел</option>
<option value='epk'>ЕПК</option>
<option value='beamworkn'>градоред</option>
<option value='PK'>ПК</option>
</select>
</label>
</div>
<div className='input-wrapper'>
<label>
Година на строителство:
<input onChange={(event) => this.handleChangeInput(event, 'buildingYear')} value={buildingYear} type='number' />
</label>
</div>
</div>
<div className='more__wrapper'>
<div className='input-wrapper'>
<label htmlFor='additional-info'>
Допълнителна информация:
</label>
<textarea onChange={(event) => this.handleChangeInput(event, 'moreInfo')} value={moreInfo} id='additional-info' />
</div>
</div>
</div>
{!!error ?
(
<div>
<p>{error}</p>
</div>
) : null
}
<div className='info-btn__wrapper'>
<button onClick={this.handleSubmit} className='btn btn-big btn-blue'>Продължи</button>
</div>
</div>
{!!readyState ? (
<div className='ready-state'>
<p>Информацията е записана! Продължете със следващата стъпка!</p>
<span onClick={this.handleEdit}>Промени</span>
</div> ) : null
}
</div>
)
}
}
function mapStateToProps(state) {
const props = {
error: state.estate.message
}
return props
}
function mapDispatchToProps(dispatch) {
/* Populated by react-webpack-redux:action */
const actions = ACTIONS
const actionMap = { actions: bindActionCreators(actions, dispatch) }
return actionMap
}
export default connect(mapStateToProps, mapDispatchToProps)(AddEstateInfo)
| mit |
ansas/php-component | src/Component/Collection/Collection.php | 14926 | <?php
/**
* This file is part of the PHP components.
*
* For the full copyright and license information, please view the LICENSE.md file distributed with this source code.
*
* @license MIT License
* @link https://github.com/ansas/php-component
*/
namespace Ansas\Component\Collection;
use Ansas\Util\Arr;
use ArrayAccess;
use ArrayIterator;
use Countable;
use Exception;
use InvalidArgumentException;
use IteratorAggregate;
use Serializable;
use Traversable;
/**
* Class Collection
*
* Making handling of context data a bit easier. Collection can be accessed as array or object. Elements can be
* set / added / retrieved / removed as single elements or bundled as array.
*
* @package Ansas\Component\Collection
* @author Ansas Meyer <[email protected]>
*/
class Collection implements ArrayAccess, IteratorAggregate, Countable, Serializable
{
/** Sort collection by keys (ascending order) */
const SORT_BY_KEYS_ASC = 1;
/** Sort collection by keys (descending order) */
const SORT_BY_KEYS_DESC = 2;
/** Sort collection by values (ascending order) */
const SORT_BY_VALUES_ASC = 4;
/** Sort collection by values (descending order) */
const SORT_BY_VALUES_DESC = 8;
/** has check "array key exists" mode */
const HAS_EXISTS = 1;
/** has check "isset" mode */
const HAS_ISSET = 2;
/** has check "empty" mode */
const HAS_NONEMPTY = 4;
/** has check "string length" mode */
const HAS_LENGTH = 8;
/**
* @var array Holds complete collection data
*/
protected $data = [];
/**
* Collection constructor.
*
* @param array|Traversable $items [optional] The initial items
*/
public function __construct($items = [])
{
$this->replace($items);
}
/**
* Get specified collection item.
*
* @param mixed $key The item key.
*
* @return mixed The item value.
*/
public function __get($key)
{
return $this->get($key);
}
/**
* Check if specified collection item exists.
*
* @param mixed $key The item key.
*
* @return bool
*/
public function __isset($key)
{
return $this->has($key, self::HAS_ISSET);
}
/**
* Set specified collection item.
*
* @param mixed $key The item key.
* @param mixed $value The item value.
*
* @return void
*/
public function __set($key, $value)
{
$this->set($key, $value);
}
/**
* Converts object to string.
*
* @return string
*/
public function __toString()
{
return $this->serialize();
}
/**
* Removes specified collection item.
*
* @param mixed $key The item key.
*
* @return $this
*/
public function __unset($key)
{
return $this->remove($key);
}
/**
* Create new instance.
*
* @param array|Traversable $items [optional] The initial items
*
* @return static
*/
public static function create($items = [])
{
return new static($items);
}
/**
* Adds item to collection for specified key
* (converts item to array if key already exists).
*
* @param mixed $key The item key.
* @param mixed $value The item value to add / set.
* @param int $mode The mode to compare if value exists [optional]
*
* @return $this
*/
public function add($key, $value, $mode = self::HAS_ISSET)
{
if (!$this->has($key, $mode)) {
$this->set($key, $value);
} else {
$key = $this->normalizeKey($key);
$this->data[$key] = (array) $this->data[$key];
$this->data[$key][] = $value;
}
return $this;
}
/**
* Get complete collection as array
* (with original key => value pairs).
*
* @return array All items
*/
public function all()
{
return $this->data;
}
/**
* Appends specified items to collection
* (overwrites existing keys).
*
* @param array|Traversable $items The items to append / overwrite to collection.
*
* @return $this
* @throws InvalidArgumentException
*/
public function append($items)
{
if (!is_array($items) && !$items instanceof Traversable) {
throw new InvalidArgumentException("Argument must be an array or instance of Traversable");
}
foreach ($items as $key => $value) {
$this->set($key, $value);
}
return $this;
}
/**
* Get collection as array.
*
* @return array
*/
public function asArray()
{
return $this->all();
}
/**
* Get collection as json string.
*
* @param int $options [optional] JSON_ constants (e. g. JSON_PRETTY_PRINT)
*
* @return string|false
*/
public function asJson($options = 0)
{
return json_encode($this->all(), $options);
}
/**
* Get collection as object.
*
* @return object
*/
public function asObject()
{
return (object) $this->all();
}
/**
* Clears the collection (remove all items).
*
* @return $this
*/
public function clear()
{
$this->replace([]);
return $this;
}
/**
* Count collection elements.
*
* @return int
*/
public function count()
{
return count($this->data);
}
/**
* Get specified collection item.
*
* @param mixed $key The item key.
* @param mixed $default [optional] The default value (if key does not exist).
* @param int $mode The mode to check if key exists [optional]
*
* @return mixed The item value.
*/
public function get($key, $default = null, $mode = self::HAS_ISSET)
{
if (!$this->has($key, $mode)) {
return $default;
}
$key = $this->normalizeKey($key);
return $this->data[$key];
}
/**
* Create an iterator to be able to traverse items via foreach.
*
* @return ArrayIterator
*/
public function getIterator()
{
return new ArrayIterator($this->data);
}
/**
* Check if specified collection item exists.
*
* @param mixed $key The item key.
* @param int $mode The mode to check if key exists [optional]
*
* @return bool
* @throws InvalidArgumentException
*/
public function has($key, $mode = self::HAS_EXISTS)
{
$key = $this->normalizeKey($key);
switch ($mode) {
case self::HAS_EXISTS:
return array_key_exists($key, $this->data);
case self::HAS_ISSET:
return isset($this->data[$key]);
case self::HAS_NONEMPTY:
return !empty($this->data[$key]);
case self::HAS_LENGTH:
return isset($this->data[$key]) && strlen($this->data[$key]);
default:
throw new InvalidArgumentException("Mode {$mode} not supported");
}
}
/**
* Check if collection is empty.
*
* @return bool
*/
public function isEmpty()
{
return !$this->count();
}
/**
* Get collection keys.
*
* @return array All item keys.
*/
public function keys()
{
return array_keys($this->data);
}
/**
* Check if specified collection item exists.
*
* @param mixed $key The item key.
* @param string $regex
* @param array &$matches [optional]
*
* @return bool
*/
public function matches($key, $regex, &$matches = [])
{
if (!$this->has($key, self::HAS_ISSET)) {
return false;
}
return (bool) preg_match($regex, $this->get($key), $matches);
}
/**
* Get specified collection item.
*
* @param mixed $key The item key.
* @param int $mode The mode to check if key exists [optional]
*
* @return mixed The item value.
* @throws Exception
*/
public function need($key, $mode = self::HAS_ISSET)
{
if (!$this->has($key, $mode)) {
throw new Exception("Key {$key} is required");
}
return $this->get($key);
}
/**
* Check if specified collection item exists.
*
* @param mixed $key The item key.
*
* @return bool
*/
public function offsetExists($key)
{
return $this->has($key, self::HAS_EXISTS);
}
/**
* Get specified collection item.
*
* @param mixed $key The item key.
*
* @return mixed The item value.
*/
public function offsetGet($key)
{
return $this->get($key);
}
/**
* Set specified collection item.
*
* @param mixed $key The item key.
* @param mixed $value The item value.
*
* @return void
*/
public function offsetSet($key, $value)
{
$this->set($key, $value);
}
/**
* Removes specified collection item.
*
* @param mixed $key The item key.
*
* @return void
*/
public function offsetUnset($key)
{
$this->remove($key);
}
/**
* Get filtered collection as array
* (with original key => value pairs).
* $keys can be an array or a comma separated string of keys.
*
* @param mixed $keys The item keys to export.
*
* @return array Filtered items.
*/
public function only($keys)
{
// Convert $keys to array if necessary
if (!is_array($keys)) {
$keys = preg_split("/, */", $keys, -1, PREG_SPLIT_NO_EMPTY);
}
foreach ($keys as $id => $key) {
$keys[$id] = $this->normalizeKey($key);
}
// Compare filter items by provided keys and return new array
return array_intersect_key($this->data, array_flip($keys));
}
/**
* Get specified collection item.
*
* @param array|string $path The path of array keys.
* @param mixed $default [optional] The default value (if key does not exist).
* @param string $glue [optional]
*
* @return mixed The item value.
*/
public function path($path, $default = null, $glue = '.')
{
return Arr::path($this->data, $path, $default, $glue);
}
/**
* Removes specified collection item.
*
* @param mixed $key The item key.
* @param bool $remove [optional] Conditional remove statement.
*
* @return $this
*/
public function remove($key, $remove = true)
{
if ($remove && $this->has($key, self::HAS_EXISTS)) {
$key = $this->normalizeKey($key);
unset($this->data[$key]);
}
return $this;
}
/**
* Removes empty collection items.
*
* @param array $considerEmpty [optional]
*
* @return $this
*/
public function removeEmpty($considerEmpty = [''])
{
foreach ($this->all() as $key => $value) {
if (!is_scalar($value) && !is_null($value)) {
continue;
}
foreach ($considerEmpty as $empty) {
if ($value === $empty) {
$this->remove($key);
break;
}
}
}
return $this;
}
/**
* Replaces the collection with the specified items.
*
* @param array|Traversable $items The items to replace collection with.
*
* @return $this
*/
public function replace($items)
{
$this->data = [];
return $this->append($items);
}
/**
* Convert object into string to make it storable (freeze, store).
*
* @return string
*/
public function serialize()
{
return (string) $this->asJson();
}
/**
* Set specified collection item.
*
* @param mixed $key The item key.
* @param mixed $value The item value.
*
* @return $this
*/
public function set($key, $value)
{
$key = $this->normalizeKey($key);
if (null === $key) {
$this->data[] = $value;
} else {
$this->data[$key] = $value;
}
return $this;
}
/**
* Set specified collection item.
*
* @param mixed $key The item key. [optional]
*
* @return $this
*/
public function trim($key = null)
{
if (null === $key) {
foreach ($this->all() as $key => $value) {
if (is_scalar($value)) {
$this->set($key, trim($value));
}
}
} else {
$value = $this->get($key);
if (is_scalar($value)) {
$this->set($key, trim($value));
}
}
return $this;
}
/**
* Sort collection.
*
* @param int $sortBy Sort by flag (see self::SORT_ constants)
* @param int $sortFlags Sort flags (see PHP SORT_ constants)
*
* @return $this
* @throws InvalidArgumentException
*/
public function sort($sortBy = self::SORT_BY_KEYS_ASC, $sortFlags = SORT_REGULAR)
{
/** @noinspection SpellCheckingInspection */
$sortFunctions = [
self::SORT_BY_KEYS_ASC => 'ksort',
self::SORT_BY_KEYS_DESC => 'krsort',
self::SORT_BY_VALUES_ASC => 'asort',
self::SORT_BY_VALUES_DESC => 'arsort',
];
if (!isset($sortFunctions[$sortBy])) {
throw new InvalidArgumentException("SortBy {$sortBy} not supported");
}
$function = $sortFunctions[$sortBy];
$function($this->data, $sortFlags);
return $this;
}
/**
* Swap / switch values of two keys.
*
* @param mixed $a
* @param mixed $b
*
* @return $this
*/
public function swap($a, $b)
{
$oldA = $this->get($a);
$oldB = $this->get($b);
$this->set($a, $oldB);
$this->set($b, $oldA);
return $this;
}
/**
* Convert string back into object from storage (unfreeze, restore).
*
* @param string $data
*
* @return void
*/
public function unserialize($data)
{
$this->data = json_decode($data);
}
/**
* Get collection values.
*
* @return array All item values.
*/
public function values()
{
return array_values($this->data);
}
/**
* Normalize key.
*
* Useful in child classes to make keys upper case for example.
*
* @param string $key
*
* @return string
*/
protected function normalizeKey($key)
{
return $key;
}
}
| mit |
maestroprog/saw-php | bin/cli.php | 742 | <?php
defined('ENV') or define('ENV', 'UNKNOWN');
if (PHP_SAPI !== 'cli') {
header('HTTP/1.1 503 Service Unavailable');
die(sprintf('<p style="color:red">%s</p>', 'Saw ' . ENV . ' must be run in cli mode.'));
}
$configFile = $argv[1] ?? __DIR__ . '/../config/saw.php';
if (!file_exists($configFile)) {
echo "\033[1;31mSaw " . ENV . " must be configured with special config.\033[0m" . PHP_EOL;
exit(1);
}
$autoloadFiles = [
__DIR__ . '/../vendor/autoload.php',
__DIR__ . '/../../../autoload.php'
];
foreach ($autoloadFiles as $autoloadFile) {
if (file_exists($autoloadFile)) {
/** @noinspection PhpIncludeInspection */
require_once $autoloadFile;
break;
}
}
return $configFile;
| mit |
hawkup/github-stars | angularjs/app/data/user.service.js | 1085 | (function () {
'use strict';
angular
.module('app.data')
.factory('userService', userService);
/* @ngInject */
function userService($q, $auth, $window, githubService) {
var userData = null;
var service = {
checkLoggedIn: checkLoggedIn,
getUser: getUser,
logout: logout,
setUser: setUser,
};
return service;
function checkLoggedIn() {
return $auth.getToken() !== null ? true : false;
}
function getUser() {
var deferred = $q.defer();
if (checkLoggedIn() === false) {
deferred.reject();
} else {
if (userData !== null) {
deferred.resolve(userData);
} else {
githubService.getUser()
.then(function (userData) {
setUser(userData);
deferred.resolve(userData);
});
}
}
return deferred.promise;
}
function logout() {
setUser(null);
$auth.logout();
$window.location.reload();
}
function setUser(data) {
userData = data;
}
}
})();
| mit |
Etonchev/Telerik_CSharpPart1 | 05ConditionalStatements/06_BiggestOfFive/Properties/AssemblyInfo.cs | 1408 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("06_BiggestOfFive")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("06_BiggestOfFive")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d36a1414-56fe-46ae-a97c-734f1f742d3a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
rosd89/sam-node-study | step0_1/app/routes/api/v1/connection/index.js | 680 | const path = '/v1/connection';
const router = require('express').Router();
const {auth} = require('../../../routeMiddleware');
const loginValidation = require('./middleware/loginValidation');
const {validConnection} = require('./validate');
// client salt 가져오기
router.get('/salt', require('./controller/getClientSalt'));
// Create Connection
router.post('/', validConnection, loginValidation, require('./controller/createConnection'));
// 로그인 갱신
router.put('/', validConnection, loginValidation, require('./controller/updateConnection'));
// 로그아웃
router.delete('/', auth, require('./controller/deleteConnection'));
module.exports = {path, router};
| mit |
lambirou/babiphp | system/Http/StreamWrapper.php | 3159 | <?php
/**
* BabiPHP : The flexible PHP Framework
*
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) BabiPHP.
* @link https://github.com/lambirou/babiphp BabiPHP Project
* @license MIT
*
* Not edit this file
*/
namespace BabiPHP\Http;
use \Psr\Http\Message\StreamInterface;
/**
* Converts Guzzle streams into PHP stream resources.
*/
class StreamWrapper
{
/** @var resource */
public $context;
/** @var StreamInterface */
private $stream;
/** @var string r, r+, or w */
private $mode;
/**
* Returns a resource representing the stream.
*
* @param StreamInterface $stream The stream to get a resource for
*
* @return resource
* @throws \InvalidArgumentException if stream is not readable or writable
*/
public static function getResource(StreamInterface $stream)
{
self::register();
if ($stream->isReadable()) {
$mode = $stream->isWritable() ? 'r+' : 'r';
} elseif ($stream->isWritable()) {
$mode = 'w';
} else {
throw new \InvalidArgumentException('The stream must be readable, '
. 'writable, or both.');
}
return fopen('guzzle://stream', $mode, null, stream_context_create([
'guzzle' => ['stream' => $stream]
]));
}
/**
* Registers the stream wrapper if needed
*/
public static function register()
{
if (!in_array('guzzle', stream_get_wrappers())) {
stream_wrapper_register('guzzle', __CLASS__);
}
}
public function stream_open($path, $mode, $options, &$opened_path)
{
$options = stream_context_get_options($this->context);
if (!isset($options['guzzle']['stream'])) {
return false;
}
$this->mode = $mode;
$this->stream = $options['guzzle']['stream'];
return true;
}
public function stream_read($count)
{
return $this->stream->read($count);
}
public function stream_write($data)
{
return (int) $this->stream->write($data);
}
public function stream_tell()
{
return $this->stream->tell();
}
public function stream_eof()
{
return $this->stream->eof();
}
public function stream_seek($offset, $whence)
{
$this->stream->seek($offset, $whence);
return true;
}
public function stream_stat()
{
static $modeMap = [
'r' => 33060,
'r+' => 33206,
'w' => 33188
];
return [
'dev' => 0,
'ino' => 0,
'mode' => $modeMap[$this->mode],
'nlink' => 0,
'uid' => 0,
'gid' => 0,
'rdev' => 0,
'size' => $this->stream->getSize() ?: 0,
'atime' => 0,
'mtime' => 0,
'ctime' => 0,
'blksize' => 0,
'blocks' => 0
];
}
}
| mit |
jvanbrug/cs143sim | cs143sim/errors.py | 1865 | """This module contains all error definitions.
.. autosummary:
InputFileSyntaxError
InputFileUnknownError
MissingAttribute
.. moduleauthor:: Samuel Richerd <[email protected]>
.. moduleauthor:: Jan Van Bruggen <[email protected]>
"""
class InputFileSyntaxError(Exception):
"""InputFileSyntaxError is an `Exception` thrown when an unrecognized syntax
is used in the input file.
:param int line_number: erroneous line of input file
:param str message: error message
"""
def __init__(self, line_number, message):
self.line_number = line_number
self.message = message
def __str__(self):
return ('Input File Syntax Error: (Line ' + str(self.line_number) +
') ' + self.message)
class InputFileUnknownReference(Exception):
"""InputFileUnknownReference is an `Exception` thrown when a link or host makes reference
to an unknown object (Host/Router/Link)
:param int line_number: erroneous line of input file
:param str message: error message
"""
def __init__(self, line_number, message):
self.line_number = line_number
self.message = message
def __str__(self):
return ('InputFileUnknownReference (Line ' + str(self.line_number) +
'): ' + self.message)
class MissingAttribute(Exception):
"""MissingAttribute is an `Exception` designed to notify the user that the
input file is missing information
:param obj_type:
:param obj_id:
:param missing_attr:
"""
def __init__(self, obj_type, obj_id, missing_attr):
self.obj_type = obj_type
self.obj_id = obj_id
self.missing_attr = missing_attr
def __str__(self):
return ('I/O Error: Type ' + self.obj_type + ' (ID: ' + self.obj_id +
') is missing attribute ' + self.missing_attr)
| mit |
qcccs/PhpPalette | src/org/netbeans/modules/filepalette/items/IntegerItem.java | 1976 |
/*
*-----------------------------------------------------------------------------------------
*---This file was generated using Snip - A Snippets Source Code Generator
*---for use with Netbeans Palettes. This project is an expansion of the sample
*---Java Palette by Geertjan Wielenga.
*---Quinsigamond Community College - 2013
*-----------------------------------------------------------------------------------------
*/
package org.netbeans.modules.filepalette.items;
import org.netbeans.modules.filepalette.items.resources.IntegerItemPopup;
import org.openide.text.ActiveEditorDrop;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
/**
* This class gets and sets comments for the code snippet and calls
* the popup or customizer associated with this class.
*/
public class IntegerItem implements ActiveEditorDrop {
private String comment = "";
/**
*
*/
public IntegerItem() {}
private String createBody() {
comment = getComment();
StringBuilder buffer = new StringBuilder();
buffer.append("// ").append(comment).append("\n");
return buffer.toString();
}
/**
*
* @param targetComponent
* @return
*/
public boolean handleTransfer(JTextComponent targetComponent) {
IntegerItemPopup c = new IntegerItemPopup(this, targetComponent);
boolean accept = c.showDialog();
if (accept) {
String body = this.createBody();
try {
FilePaletteUtilities.insert(body, targetComponent);
} catch (BadLocationException ble) {
accept = false;
}
}
return accept;
}
/**
*
* @return Returns a comment.
*/
public String getComment() {
return comment;
}
/**
*
* @param comment
*/
public void setComment(String comment) {
this.comment = comment;
}
}
| mit |
FouadWahabi/medecine-inscription-project | database/seeds/CitySeed.php | 1775 | <?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class CitySeed extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('City')->insert([
'label' => 'Sfax',
'id_Country' => 1
]);
DB::table('City')->insert([
'label' => 'Tunis',
'id_Country' => 1
]);
DB::table('City')->insert([
'label' => 'Mednine',
'id_Country' => 1
]);
DB::table('City')->insert([
'label' => 'Bizert',
'id_Country' => 1
]);
DB::table('City')->insert([
'label' => 'Sousse',
'id_Country' => 1
]);
DB::table('City')->insert([
'label' => 'Mestir',
'id_Country' => 1
]);
DB::table('City')->insert([
'label' => 'Mahdia',
'id_Country' => 1
]);
DB::table('City')->insert([
'label' => 'Nabeul',
'id_Country' => 1
]);
DB::table('City')->insert([
'label' => 'Gabes',
'id_Country' => 1
]);
DB::table('City')->insert([
'label' => 'Tataouin',
'id_Country' => 1
]);
DB::table('City')->insert([
'label' => 'Ben Arous',
'id_Country' => 1
]);
DB::table('City')->insert([
'label' => 'Gafsa',
'id_Country' => 1
]);
DB::table('City')->insert([
'label' => 'Kef',
'id_Country' => 1
]);
DB::table('City')->insert([
'label' => 'Jandouba',
'id_Country' => 1
]);
}
} | mit |
benjholla/SocialMediaToolkit | SocialMediaToolkit/src/utilities/math/Jaccard.java | 447 | package utilities.math;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
public class Jaccard {
public static <T> double jaccardIndex(Collection<T> a, Collection<T> b){
Set<T> setA = new HashSet<T>(a);
Set<T> setB = new HashSet<T>(b);
Set<T> numerator = Sets.intersection(setA, setB);
Set<T> denominator = Sets.union(setA, setB);
return ((double) numerator.size()) / ((double) denominator.size());
}
}
| mit |
AllTheMods/CraftTweaker | CraftTweaker2-MC1120-Main/src/main/java/crafttweaker/mc1120/events/ClientEventHandler.java | 2088 | package crafttweaker.mc1120.events;
import crafttweaker.CraftTweakerAPI;
import crafttweaker.api.formatting.IFormattedText;
import crafttweaker.api.item.IItemStack;
import crafttweaker.api.minecraft.CraftTweakerMC;
import crafttweaker.api.tooltip.IngredientTooltips;
import crafttweaker.mc1120.formatting.IMCFormattedString;
import net.minecraft.client.Minecraft;
import net.minecraft.client.util.RecipeBookClient;
import net.minecraftforge.client.event.GuiOpenEvent;
import net.minecraftforge.event.entity.player.ItemTooltipEvent;
import net.minecraftforge.fml.common.eventhandler.*;
import net.minecraftforge.fml.relauncher.*;
import org.lwjgl.input.Keyboard;
public class ClientEventHandler {
private static boolean alreadyChangedThePlayer = false;
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onItemTooltip(ItemTooltipEvent ev) {
if(!ev.getItemStack().isEmpty()) {
IItemStack itemStack = CraftTweakerMC.getIItemStack(ev.getItemStack());
if(IngredientTooltips.shouldClearToolTip(itemStack)) {
ev.getToolTip().clear();
}
for(IFormattedText tooltip : IngredientTooltips.getTooltips(itemStack)) {
ev.getToolTip().add(((IMCFormattedString) tooltip).getTooltipString());
}
if(!Keyboard.isCreated()) {
return;
}
if(Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) {
for(IFormattedText tooltip : IngredientTooltips.getShiftTooltips(itemStack)) {
ev.getToolTip().add(((IMCFormattedString) tooltip).getTooltipString());
}
}
}
}
@SubscribeEvent
@SideOnly(Side.CLIENT)
public void onGuiOpenEvent(GuiOpenEvent ev){
if (Minecraft.getMinecraft().player != null && !alreadyChangedThePlayer){
alreadyChangedThePlayer = true;
RecipeBookClient.rebuildTable();
CraftTweakerAPI.logInfo("Fixed the RecipeBook");
}
}
}
| mit |
ratimid/SoftUni | C#/TechnologyFundamentals-September2017/ProgrammingFundamentals/10.CSharpDataTypesAndVariables-Exercises/12.RectangleProperties/Properties/AssemblyInfo.cs | 1420 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("12.RectangleProperties")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("12.RectangleProperties")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("531309ef-c3c3-49bc-83b5-c21720c564f2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
Teddy-Zhu/SilentGo | framework/src/main/java/com/silentgo/core/render/support/JsonRender.java | 1651 | package com.silentgo.core.render.support;
import com.silentgo.core.SilentGo;
import com.silentgo.core.exception.AppRenderException;
import com.silentgo.core.render.Render;
import com.silentgo.servlet.http.Request;
import com.silentgo.servlet.http.Response;
import java.io.IOException;
import java.io.PrintWriter;
/**
* Project : silentgo
* com.silentgo.core.render.support
*
* @author <a href="mailto:[email protected]" target="_blank">teddyzhu</a>
* <p>
* Created by teddyzhu on 16/8/22.
*/
public class JsonRender implements Render {
private String encoding;
private String contentType = encoding;
public JsonRender() {
this("utf-8");
}
public JsonRender(String encoding) {
this.encoding = encoding;
this.contentType = "application/json; charset=" + encoding;
}
@Override
public void render(Response response, Request request, Object retVal) throws AppRenderException {
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache , no-store , mag-age=0");
response.setDateHeader("Expires", 0);
response.setContentType(contentType);
PrintWriter writer = null;
try {
writer = response.getWriter();
writer.write(retVal instanceof String ? retVal.toString() : SilentGo.me().json().toJsonString(retVal));
writer.flush();
} catch (IOException e) {
e.printStackTrace();
throw new AppRenderException(e.getMessage());
} finally {
if (writer != null)
writer.close();
}
}
}
| mit |
jugglinmike/es6draft | src/test/scripts/suite/regress/bug3433.js | 425 | /*
* Copyright (c) 2012-2016 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertSame
} = Assert;
// Are %TypedArray% objects supposed to be Concat-Spreadable?
// https://bugs.ecmascript.org/show_bug.cgi?id=3433
var ta1 = new Int8Array(10);
var ta2 = new Int8Array(20);
assertSame(2, [].concat(ta1, ta2).length);
| mit |
andreasdr/tdmecpp | src/libtdme/network/tcpserver/NIOTCPFramingException.cpp | 289 | /**
* @version $Id: 8e9eb0cd83129e11e3ebd8946dc3d4e4b280f449 $
*/
#include <libtdme/network/tcpserver/NIOTCPFramingException.h>
using namespace TDMENetwork;
using namespace std;
NIOTCPFramingException::NIOTCPFramingException(const string &message) throw() : NIOException(message) {
}
| mit |
wp-pwa/wp-pwa | core/client/index.js | 4204 | /* eslint-disable global-require, no-underscore-dangle, import/no-dynamic-require, no-console */
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import { types } from 'mobx-state-tree';
import { AppContainer } from 'react-hot-loader';
import request from 'superagent';
import App from '../components/App';
import { importPromises } from '../components/Universal';
import Store from '../store';
const dev = process.env.NODE_ENV !== 'production';
const analyticsModule = require(`../packages/analytics/${
process.env.MODE
}/client`);
const iframesModule = require(`../packages/iframes/${process.env.MODE}/client`);
const adsModule = require(`../packages/ads/${process.env.MODE}/client`);
const customCssModule = require(`../packages/custom-css/${
process.env.MODE
}/client`);
const oneSignalModule = require(`../packages/one-signal/${
process.env.MODE
}/client`);
const disqusCommentsModule = require(`../packages/disqus-comments/${
process.env.MODE
}/client`);
// Define core modules.
const coreModules = [
{
name: 'analytics',
namespace: 'analytics',
module: analyticsModule,
},
{
name: 'iframes',
namespace: 'iframes',
module: iframesModule,
},
{
name: 'ads',
namespace: 'ads',
module: adsModule,
},
{
name: 'custom-css',
namespace: 'customCss',
module: customCssModule,
},
{
name: 'one-signal',
namespace: 'notifications',
module: oneSignalModule,
},
{
name: 'disqus-comments',
namespace: 'comments',
module: disqusCommentsModule,
},
];
// Get activated packages.
const packages = Object.values(window['wp-pwa'].initialState.build.packages);
let stores = null;
const components = {};
const render = Component => {
ReactDOM.hydrate(
<AppContainer>
<Component
core={coreModules.map(({ name, module }) => ({
name,
Component: module.default,
}))}
packages={packages}
stores={stores}
components={components}
/>
</AppContainer>,
window.document.getElementById('root'),
);
if (!dev)
console.log(`>> Frontity loaded. SiteID: ${stores.build.siteId} <<`);
};
const init = async () => {
// Wait for activated packages.
const pkgEntries = Object.entries(
window['wp-pwa'].initialState.build.packages,
);
const pkgPromises = pkgEntries.map(([namespace, name]) =>
importPromises({ name, namespace }),
);
const pkgModules = await Promise.all(pkgPromises);
const storesProps = {};
const envs = {};
const mapModules = pkg => {
if (pkg.module.Store)
storesProps[pkg.namespace] = types.optional(pkg.module.Store, {});
if (pkg.module.env) envs[pkg.namespace] = pkg.module.env;
if (pkg.module.components)
components[pkg.namespace] = pkg.module.components;
};
// Load MST reducers and server sagas.
coreModules.forEach(mapModules);
pkgModules.forEach(mapModules);
// Create MST Stores
const Stores = Store.props(storesProps);
const { type, id, page } = window['wp-pwa'];
const parsedId = parseInt(id, 10);
stores = Stores.create(window['wp-pwa'].initialState, {
request,
machine: 'server',
...envs,
initialSelectedItem: {
type,
id: Number.isNaN(parsedId) ? id : parsedId,
page: parseInt(page, 10),
},
});
if (dev) {
const makeInspectable = require('mobx-devtools-mst').default;
makeInspectable(stores);
}
// Add both to window
if (typeof window !== 'undefined') window.frontity = { stores, components };
// Start all the client sagas.
stores.clientStarted();
// Start App.
render(App);
// Inform that the client has been rendered.
stores.clientRendered();
// Initializes the afterCSRs.
Object.values(stores).forEach(({ afterCsr }) => {
if (afterCsr) afterCsr();
});
};
if (process.env.NODE_ENV === 'development' && module.hot) {
module.hot.accept('../components/App.js', () => {
const Component = require('../components/App').default;
render(Component);
});
module.hot.accept('../components/Universal.js', () => {
const Component = require('../components/App').default;
render(Component);
});
}
init();
| mit |
InnovateUKGitHub/innovation-funding-service | ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/project/core/repository/ProjectUserRepository.java | 2075 | package org.innovateuk.ifs.project.core.repository;
import org.innovateuk.ifs.project.core.ProjectParticipantRole;
import org.innovateuk.ifs.project.core.domain.ProjectUser;
import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List;
import java.util.Optional;
public interface ProjectUserRepository extends PagingAndSortingRepository<ProjectUser, Long> {
List<ProjectUser> findByProjectId(Long projectId);
List<ProjectUser> findByProjectIdAndRoleIsIn(Long projectId, List<ProjectParticipantRole> role);
List<ProjectUser> findByProjectIdAndUserIdAndRoleIsIn(long projectId, long userId, List<ProjectParticipantRole> role);
ProjectUser findFirstByProjectIdAndUserIdAndRoleIsIn(long projectId, long userId, List<ProjectParticipantRole> role);
List<ProjectUser> findByProjectIdAndOrganisationId(long projectId, long organisationId);
ProjectUser findOneByProjectIdAndUserIdAndOrganisationIdAndRole(long projectId, long userId, long organisationId, ProjectParticipantRole role);
ProjectUser findOneByProjectIdAndUserIdAndOrganisationIdAndRoleIn(long projectId, long userId, long organisationId, List<ProjectParticipantRole> roles);
ProjectUser findFirstByProjectIdAndUserIdAndOrganisationIdAndRoleIn(long projectId, long userId, long organisationId, List<ProjectParticipantRole> roles);
List<ProjectUser> findByProjectIdAndUserIdAndRole(long projectId, long userId, ProjectParticipantRole role);
List<ProjectUser> findByUserId(long userId);
List<ProjectUser> findByProjectIdAndUserId(long projectId, long userId);
List<ProjectUser> findByUserIdAndRole(long userId, ProjectParticipantRole role);
ProjectUser findByProjectIdAndRoleAndUserId(long projectId, ProjectParticipantRole role, long userId);
Optional<ProjectUser> findByProjectIdAndRole(long projectId, ProjectParticipantRole role);
void deleteAllByProjectIdAndOrganisationId(long projectId, long organisationId);
boolean existsByProjectApplicationCompetitionIdAndUserId(long competitionId, long userId);
}
| mit |
reactivesw/customer_server | src/main/java/io/reactivesw/merchant/application/model/action/InternationalUpdateAction.java | 947 | package io.reactivesw.merchant.application.model.action;
/**
* Created by Davis on 17/1/9.
*/
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property =
"action")
@JsonSubTypes( {
@JsonSubTypes.Type(value = SetDefaultCurrencyAction.class, name = "setDefaultCurrency"),
@JsonSubTypes.Type(value = AddSupportCurrencyAction.class, name = "addSupportCurrency"),
@JsonSubTypes.Type(value = RemoveSupportCurrencyAction.class, name = "removeSupportCurrency"),
@JsonSubTypes.Type(value = SetDefaultLanguageAction.class, name = "setDefaultLanguage"),
@JsonSubTypes.Type(value = AddSupportLanguageAction.class, name = "addSupportLanguage"),
@JsonSubTypes.Type(value = RemoveSupportLanguageAction.class, name = "removeSupportLanguage"),
})
public interface InternationalUpdateAction {
}
| mit |
longlongwaytogo/Learning.test | vc_cmd/exe/main.cpp | 102 | #include<stdio.h>
int main()
{
printf("just for fun ,widebright 2007-01-10");
getchar();
return 0;
} | mit |
gedzubo/gee_data_structures | array/randomized_select.rb | 1292 | class Array
def randomized_select(n_element)
array = self.dup
#n_element = n_element - 1
randomized_min_select_method(array, 0, array.length - 1, n_element)
end
protected
def randomized_min_select_method(array, beginning, ending, n_element)
return array[beginning] if beginning == ending
random = randomized_partition(array, beginning, ending)
pivot = random - beginning + 1
if n_element == pivot
return array[random]
elsif n_element < pivot
return randomized_min_select_method(array, beginning, random - 1, n_element)
else
return randomized_min_select_method(array, random + 1, ending, n_element - pivot)
end
end
def randomized_partition(array, beginning, ending)
prng = Random.new
random_index = prng.rand(beginning..ending)
exchange(array, ending, random_index)
partition(array, beginning, ending)
end
def partition(array, beginning, ending)
last = array[ending]
tmp = beginning - 1
(beginning..ending-1).each do |index|
if array[index] <= last
tmp = tmp + 1
exchange(array, tmp, index)
end
end
exchange(array, tmp + 1, ending)
tmp + 1
end
def exchange(array, x, y)
tmp = array[y]
array[y] = array[x]
array[x] = tmp
end
end
| mit |
Duke1/UnrealMedia | UnrealMedia/app/src/androidTest/java/com/qfleng/um/ExampleInstrumentedTest.java | 716 | package com.qfleng.um;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.qfleng.um", appContext.getPackageName());
}
}
| mit |
hal313/chrome-extension-settings-manager | docs/examples/es6/es6-test.js | 2007 | import { SettingsManager } from '../../scripts/SettingsManager.es6.js';
import { SettingsManagerChromeExtensionAdapter } from '../../scripts/SettingsManagerChromeExtensionAdapter.es6.js';
// Create the adapter
var settingsManagerChromeExtensionAdapter = new SettingsManagerChromeExtensionAdapter();
// Create the settings manager instance
var settingsManager = new SettingsManager(settingsManagerChromeExtensionAdapter);
// Start with a load
settingsManager.load(function onLoad(settings) {
// Handle the load response and start a save
onSettingsLoaded(settings);
settingsManager.save({one: 1, two: 'two'}, function onSave() {
// Handle the save response and start another load
onSettingsSaved();
settingsManager.load(function onLoad(settings) {
// Handle the load response and start another save
onSettingsLoaded(settings);
settingsManager.save({three: 3, two: 2}, function onSave() {
// Handle the save response and start another load
onSettingsSaved();
settingsManager.load(function onLoad(settings) {
// Handle the load response
onSettingsLoaded(settings);
}, onError);
}, onError);
}, onError);
}, onError);
}, onError);
// The results element
let resultsElement = document.getElementById('js-results-section');
// Handlers
function onSettingsLoaded(settings) {
let element = document.createElement('code');
element.append(document.createTextNode(`loaded: ${JSON.stringify(settings, null, 2)}\n`));
resultsElement.append(element);
}
function onSettingsSaved() {
let element = document.createElement('code');
element.append(document.createTextNode(`saved\n`));
resultsElement.append(element);
}
function onError(error) {
let element = document.createElement('code');
element.append(document.createTextNode(`error: ${error}\n`));
resultsElement.append(element);
}
| mit |
dscpinheiro/DSW_III | SGH_Khronos/SGH_Khronos.Data/AppContext.cs | 1880 | using System.Data.Entity;
using SGH_Khronos.Data.Mapping;
using SGH_Khronos.Model;
namespace SGH_Khronos.Data
{
public class AppContext : DbContext
{
public DbSet<Hospital> Hospitais { get; set; }
public DbSet<Pessoa> Pessoas { get; set; }
public DbSet<Paciente> Pacientes { get; set; }
public DbSet<Medico> Medicos { get; set; }
public DbSet<Enfermeiro> Enfermeiros { get; set; }
public DbSet<Recepcionista> Recepcionistas { get; set; }
public DbSet<Leito> Leitos { get; set; }
public DbSet<Internacao> Internacoes { get; set; }
public DbSet<EquipeMedica> EquipesMedicas { get; set; }
public DbSet<IndicadorVital> IndicadoresVitais { get; set; }
public DbSet<Acompanhante> Acompanhantes { get; set; }
public DbSet<Acompanhamento> Acompanhamentos { get; set; }
public AppContext() : base("SghKhronosConnection") { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("app");
modelBuilder.Configurations.Add(new HospitalMap());
modelBuilder.Configurations.Add(new PessoaMap());
modelBuilder.Configurations.Add(new PacienteMap());
modelBuilder.Configurations.Add(new MedicoMap());
modelBuilder.Configurations.Add(new EnfermeiroMap());
modelBuilder.Configurations.Add(new RecepcionistaMap());
modelBuilder.Configurations.Add(new LeitoMap());
modelBuilder.Configurations.Add(new InternacaoMap());
modelBuilder.Configurations.Add(new EquipeMedicaMap());
modelBuilder.Configurations.Add(new IndicadorVitalMap());
modelBuilder.Configurations.Add(new AcompanhanteMap());
modelBuilder.Configurations.Add(new AcompanhamentoMap());
}
}
}
| mit |
BrettJaner/csla | Source/Csla.Analyzers/Csla.Analyzers.Tests/EvaluatePropertiesForSimplicityAnalyzerTests.cs | 5969 | using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using System.Threading.Tasks;
namespace Csla.Analyzers.Tests
{
[TestClass]
public sealed class EvaluatePropertiesForSimplicityAnalyzerTests
{
[TestMethod]
public void VerifySupportedDiagnostics()
{
var analyzer = new EvaluatePropertiesForSimplicityAnalyzer();
var diagnostics = analyzer.SupportedDiagnostics;
Assert.AreEqual(1, diagnostics.Length);
var ctorHasParametersDiagnostic = diagnostics.Single(_ => _.Id == Constants.AnalyzerIdentifiers.OnlyUseCslaPropertyMethodsInGetSetRule);
Assert.AreEqual(OnlyUseCslaPropertyMethodsInGetSetRuleConstants.Title, ctorHasParametersDiagnostic.Title.ToString(),
nameof(DiagnosticDescriptor.Title));
Assert.AreEqual(OnlyUseCslaPropertyMethodsInGetSetRuleConstants.Message, ctorHasParametersDiagnostic.MessageFormat.ToString(),
nameof(DiagnosticDescriptor.MessageFormat));
Assert.AreEqual(Constants.Categories.Usage, ctorHasParametersDiagnostic.Category,
nameof(DiagnosticDescriptor.Category));
Assert.AreEqual(DiagnosticSeverity.Warning, ctorHasParametersDiagnostic.DefaultSeverity,
nameof(DiagnosticDescriptor.DefaultSeverity));
}
[TestMethod]
public async Task AnalyzeWhenClassIsNotStereotype()
{
await TestHelpers.RunAnalysisAsync<EvaluatePropertiesForSimplicityAnalyzer>(
$@"Targets\{nameof(EvaluatePropertiesForSimplicityAnalyzerTests)}\{(nameof(this.AnalyzeWhenClassIsNotStereotype))}.cs",
new string[0]);
}
[TestMethod]
public async Task AnalyzeWhenClassHasAbstractProperty()
{
await TestHelpers.RunAnalysisAsync<EvaluatePropertiesForSimplicityAnalyzer>(
$@"Targets\{nameof(EvaluatePropertiesForSimplicityAnalyzerTests)}\{(nameof(this.AnalyzeWhenClassHasAbstractProperty))}.cs",
new string[0]);
}
[TestMethod]
public async Task AnalyzeWhenClassHasStaticProperty()
{
await TestHelpers.RunAnalysisAsync<EvaluatePropertiesForSimplicityAnalyzer>(
$@"Targets\{nameof(EvaluatePropertiesForSimplicityAnalyzerTests)}\{(nameof(this.AnalyzeWhenClassHasStaticProperty))}.cs",
new string[0]);
}
[TestMethod]
public async Task AnalyzeWhenClassHasGetterWithNoMethodCall()
{
await TestHelpers.RunAnalysisAsync<EvaluatePropertiesForSimplicityAnalyzer>(
$@"Targets\{nameof(EvaluatePropertiesForSimplicityAnalyzerTests)}\{(nameof(this.AnalyzeWhenClassHasGetterWithNoMethodCall))}.cs",
new string[0]);
}
[TestMethod]
public async Task AnalyzeWhenClassHasGetterWithMethodCallButIsNotCslaPropertyMethod()
{
await TestHelpers.RunAnalysisAsync<EvaluatePropertiesForSimplicityAnalyzer>(
$@"Targets\{nameof(EvaluatePropertiesForSimplicityAnalyzerTests)}\{(nameof(this.AnalyzeWhenClassHasGetterWithMethodCallButIsNotCslaPropertyMethod))}.cs",
new string[0]);
}
[TestMethod]
public async Task AnalyzeWhenClassHasGetterWithMethodCallAndMultipleStatements()
{
await TestHelpers.RunAnalysisAsync<EvaluatePropertiesForSimplicityAnalyzer>(
$@"Targets\{nameof(EvaluatePropertiesForSimplicityAnalyzerTests)}\{(nameof(this.AnalyzeWhenClassHasGetterWithMethodCallAndMultipleStatements))}.cs",
new[] { Constants.AnalyzerIdentifiers.OnlyUseCslaPropertyMethodsInGetSetRule });
}
[TestMethod]
public async Task AnalyzeWhenClassHasGetterWithMethodCallAndReturnButNoDirectInvocationExpression()
{
await TestHelpers.RunAnalysisAsync<EvaluatePropertiesForSimplicityAnalyzer>(
$@"Targets\{nameof(EvaluatePropertiesForSimplicityAnalyzerTests)}\{(nameof(this.AnalyzeWhenClassHasGetterWithMethodCallAndReturnButNoDirectInvocationExpression))}.cs",
new[] { Constants.AnalyzerIdentifiers.OnlyUseCslaPropertyMethodsInGetSetRule, Constants.AnalyzerIdentifiers.OnlyUseCslaPropertyMethodsInGetSetRule });
}
[TestMethod]
public async Task AnalyzeWhenClassHasGetterWithMethodCallAndReturnAndDirectInvocationExpression()
{
await TestHelpers.RunAnalysisAsync<EvaluatePropertiesForSimplicityAnalyzer>(
$@"Targets\{nameof(EvaluatePropertiesForSimplicityAnalyzerTests)}\{(nameof(this.AnalyzeWhenClassHasGetterWithMethodCallAndReturnAndDirectInvocationExpression))}.cs",
new string[0]);
}
[TestMethod]
public async Task AnalyzeWhenClassHasSetterWithNoMethodCall()
{
await TestHelpers.RunAnalysisAsync<EvaluatePropertiesForSimplicityAnalyzer>(
$@"Targets\{nameof(EvaluatePropertiesForSimplicityAnalyzerTests)}\{(nameof(this.AnalyzeWhenClassHasSetterWithNoMethodCall))}.cs",
new string[0]);
}
[TestMethod]
public async Task AnalyzeWhenClassHasSetterWithMethodCallButIsNotCslaPropertyMethod()
{
await TestHelpers.RunAnalysisAsync<EvaluatePropertiesForSimplicityAnalyzer>(
$@"Targets\{nameof(EvaluatePropertiesForSimplicityAnalyzerTests)}\{(nameof(this.AnalyzeWhenClassHasSetterWithMethodCallButIsNotCslaPropertyMethod))}.cs",
new string[0]);
}
[TestMethod]
public async Task AnalyzeWhenClassHasSetterWithMethodCallAndMultipleStatements()
{
await TestHelpers.RunAnalysisAsync<EvaluatePropertiesForSimplicityAnalyzer>(
$@"Targets\{nameof(EvaluatePropertiesForSimplicityAnalyzerTests)}\{(nameof(this.AnalyzeWhenClassHasSetterWithMethodCallAndMultipleStatements))}.cs",
new[] { Constants.AnalyzerIdentifiers.OnlyUseCslaPropertyMethodsInGetSetRule });
}
[TestMethod]
public async Task AnalyzeWhenClassHasSetterWithMethodCallAndDirectInvocationExpression()
{
await TestHelpers.RunAnalysisAsync<EvaluatePropertiesForSimplicityAnalyzer>(
$@"Targets\{nameof(EvaluatePropertiesForSimplicityAnalyzerTests)}\{(nameof(this.AnalyzeWhenClassHasSetterWithMethodCallAndDirectInvocationExpression))}.cs",
new string[0]);
}
}
}
| mit |
fiber-space/pip | tests/functional/test_install_wheel.py | 14911 | import os
import sys
import pytest
import glob
from tests.lib.path import Path
def test_install_from_future_wheel_version(script, data):
"""
Test installing a future wheel
"""
from tests.lib import TestFailure
package = data.packages.join("futurewheel-3.0-py2.py3-none-any.whl")
result = script.pip('install', package, '--no-index', expect_error=True)
with pytest.raises(TestFailure):
result.assert_installed('futurewheel', without_egg_link=True,
editable=False)
package = data.packages.join("futurewheel-1.9-py2.py3-none-any.whl")
result = script.pip(
'install', package, '--no-index', expect_error=False,
expect_stderr=True,
)
result.assert_installed('futurewheel', without_egg_link=True,
editable=False)
def test_install_from_broken_wheel(script, data):
"""
Test that installing a broken wheel fails properly
"""
from tests.lib import TestFailure
package = data.packages.join("brokenwheel-1.0-py2.py3-none-any.whl")
result = script.pip('install', package, '--no-index', expect_error=True)
with pytest.raises(TestFailure):
result.assert_installed('futurewheel', without_egg_link=True,
editable=False)
def test_install_from_wheel(script, data):
"""
Test installing from a wheel (that has a script)
"""
result = script.pip(
'install', 'has.script==1.0', '--no-index',
'--find-links=' + data.find_links,
expect_error=False,
)
dist_info_folder = script.site_packages / 'has.script-1.0.dist-info'
assert dist_info_folder in result.files_created, (dist_info_folder,
result.files_created,
result.stdout)
script_file = script.bin / 'script.py'
assert script_file in result.files_created
def test_install_from_wheel_with_extras(script, data):
"""
Test installing from a wheel with extras.
"""
result = script.pip(
'install', 'complex-dist[simple]', '--no-index',
'--find-links=' + data.find_links,
expect_error=False,
)
dist_info_folder = script.site_packages / 'complex_dist-0.1.dist-info'
assert dist_info_folder in result.files_created, (dist_info_folder,
result.files_created,
result.stdout)
dist_info_folder = script.site_packages / 'simple.dist-0.1.dist-info'
assert dist_info_folder in result.files_created, (dist_info_folder,
result.files_created,
result.stdout)
def test_install_from_wheel_file(script, data):
"""
Test installing directly from a wheel file.
"""
package = data.packages.join("simple.dist-0.1-py2.py3-none-any.whl")
result = script.pip('install', package, '--no-index', expect_error=False)
dist_info_folder = script.site_packages / 'simple.dist-0.1.dist-info'
assert dist_info_folder in result.files_created, (dist_info_folder,
result.files_created,
result.stdout)
installer = dist_info_folder / 'INSTALLER'
assert installer in result.files_created, (dist_info_folder,
result.files_created,
result.stdout)
with open(script.base_path / installer, 'rb') as installer_file:
installer_details = installer_file.read()
assert installer_details == b'pip\n'
installer_temp = dist_info_folder / 'INSTALLER.pip'
assert installer_temp not in result.files_created, (dist_info_folder,
result.files_created,
result.stdout)
# header installs are broke in pypy virtualenvs
# https://github.com/pypa/virtualenv/issues/510
@pytest.mark.skipif("hasattr(sys, 'pypy_version_info')")
def test_install_from_wheel_with_headers(script, data):
"""
Test installing from a wheel file with headers
"""
package = data.packages.join("headers.dist-0.1-py2.py3-none-any.whl")
result = script.pip('install', package, '--no-index', expect_error=False)
dist_info_folder = script.site_packages / 'headers.dist-0.1.dist-info'
assert dist_info_folder in result.files_created, (dist_info_folder,
result.files_created,
result.stdout)
@pytest.mark.network
def test_install_wheel_with_target(script, data):
"""
Test installing a wheel using pip install --target
"""
script.pip('install', 'wheel')
target_dir = script.scratch_path / 'target'
result = script.pip(
'install', 'simple.dist==0.1', '-t', target_dir,
'--no-index', '--find-links=' + data.find_links,
)
assert Path('scratch') / 'target' / 'simpledist' in result.files_created, (
str(result)
)
@pytest.mark.network
def test_install_wheel_with_target_and_data_files(script, data):
"""
Test for issue #4092. It will be checked that a data_files specification in
setup.py is handled correctly when a wheel is installed with the --target
option.
The setup() for the wheel 'prjwithdatafile-1.0-py2.py3-none-any.whl' is as
follows ::
setup(
name='prjwithdatafile',
version='1.0',
packages=['prjwithdatafile'],
data_files=[
(r'packages1', ['prjwithdatafile/README.txt']),
(r'packages2', ['prjwithdatafile/README.txt'])
]
)
"""
script.pip('install', 'wheel')
target_dir = script.scratch_path / 'prjwithdatafile'
package = data.packages.join("prjwithdatafile-1.0-py2.py3-none-any.whl")
result = script.pip('install', package,
'-t', target_dir,
'--no-index',
expect_error=False)
assert (Path('scratch') / 'prjwithdatafile' / 'packages1' / 'README.txt'
in result.files_created), str(result)
assert (Path('scratch') / 'prjwithdatafile' / 'packages2' / 'README.txt'
in result.files_created), str(result)
assert (Path('scratch') / 'prjwithdatafile' / 'lib' / 'python'
not in result.files_created), str(result)
def test_install_wheel_with_root(script, data):
"""
Test installing a wheel using pip install --root
"""
root_dir = script.scratch_path / 'root'
result = script.pip(
'install', 'simple.dist==0.1', '--root', root_dir,
'--no-index', '--find-links=' + data.find_links,
)
assert Path('scratch') / 'root' in result.files_created
def test_install_wheel_with_prefix(script, data):
"""
Test installing a wheel using pip install --prefix
"""
prefix_dir = script.scratch_path / 'prefix'
result = script.pip(
'install', 'simple.dist==0.1', '--prefix', prefix_dir,
'--no-index', '--find-links=' + data.find_links,
)
if hasattr(sys, "pypy_version_info"):
lib = Path('scratch') / 'prefix' / 'site-packages'
else:
lib = Path('scratch') / 'prefix' / 'lib'
assert lib in result.files_created
def test_install_from_wheel_installs_deps(script, data):
"""
Test can install dependencies of wheels
"""
# 'requires_source' depends on the 'source' project
package = data.packages.join("requires_source-1.0-py2.py3-none-any.whl")
result = script.pip(
'install', '--no-index', '--find-links', data.find_links, package,
)
result.assert_installed('source', editable=False)
def test_install_from_wheel_no_deps(script, data):
"""
Test --no-deps works with wheel installs
"""
# 'requires_source' depends on the 'source' project
package = data.packages.join("requires_source-1.0-py2.py3-none-any.whl")
result = script.pip(
'install', '--no-index', '--find-links', data.find_links, '--no-deps',
package,
)
pkg_folder = script.site_packages / 'source'
assert pkg_folder not in result.files_created
@pytest.mark.network
def test_install_user_wheel(script, virtualenv, data):
"""
Test user install from wheel (that has a script)
"""
virtualenv.system_site_packages = True
script.pip('install', 'wheel')
result = script.pip(
'install', 'has.script==1.0', '--user', '--no-index',
'--find-links=' + data.find_links,
)
egg_info_folder = script.user_site / 'has.script-1.0.dist-info'
assert egg_info_folder in result.files_created, str(result)
script_file = script.user_bin / 'script.py'
assert script_file in result.files_created
def test_install_from_wheel_gen_entrypoint(script, data):
"""
Test installing scripts (entry points are generated)
"""
result = script.pip(
'install', 'script.wheel1a==0.1', '--no-index',
'--find-links=' + data.find_links,
expect_error=False,
)
if os.name == 'nt':
wrapper_file = script.bin / 't1.exe'
else:
wrapper_file = script.bin / 't1'
assert wrapper_file in result.files_created
if os.name != "nt":
assert bool(os.access(script.base_path / wrapper_file, os.X_OK))
def test_install_from_wheel_gen_uppercase_entrypoint(script, data):
"""
Test installing scripts with uppercase letters in entry point names
"""
result = script.pip(
'install', 'console-scripts-uppercase==1.0', '--no-index',
'--find-links=' + data.find_links,
expect_error=False,
)
if os.name == 'nt':
# Case probably doesn't make any difference on NT
wrapper_file = script.bin / 'cmdName.exe'
else:
wrapper_file = script.bin / 'cmdName'
assert wrapper_file in result.files_created
if os.name != "nt":
assert bool(os.access(script.base_path / wrapper_file, os.X_OK))
def test_install_from_wheel_with_legacy(script, data):
"""
Test installing scripts (legacy scripts are preserved)
"""
result = script.pip(
'install', 'script.wheel2a==0.1', '--no-index',
'--find-links=' + data.find_links,
expect_error=False,
)
legacy_file1 = script.bin / 'testscript1.bat'
legacy_file2 = script.bin / 'testscript2'
assert legacy_file1 in result.files_created
assert legacy_file2 in result.files_created
def test_install_from_wheel_no_setuptools_entrypoint(script, data):
"""
Test that when we generate scripts, any existing setuptools wrappers in
the wheel are skipped.
"""
result = script.pip(
'install', 'script.wheel1==0.1', '--no-index',
'--find-links=' + data.find_links,
expect_error=False,
)
if os.name == 'nt':
wrapper_file = script.bin / 't1.exe'
else:
wrapper_file = script.bin / 't1'
wrapper_helper = script.bin / 't1-script.py'
# The wheel has t1.exe and t1-script.py. We will be generating t1 or
# t1.exe depending on the platform. So we check that the correct wrapper
# is present and that the -script.py helper has been skipped. We can't
# easily test that the wrapper from the wheel has been skipped /
# overwritten without getting very platform-dependent, so omit that.
assert wrapper_file in result.files_created
assert wrapper_helper not in result.files_created
def test_skipping_setuptools_doesnt_skip_legacy(script, data):
"""
Test installing scripts (legacy scripts are preserved even when we skip
setuptools wrappers)
"""
result = script.pip(
'install', 'script.wheel2==0.1', '--no-index',
'--find-links=' + data.find_links,
expect_error=False,
)
legacy_file1 = script.bin / 'testscript1.bat'
legacy_file2 = script.bin / 'testscript2'
wrapper_helper = script.bin / 't1-script.py'
assert legacy_file1 in result.files_created
assert legacy_file2 in result.files_created
assert wrapper_helper not in result.files_created
def test_install_from_wheel_gui_entrypoint(script, data):
"""
Test installing scripts (gui entry points are generated)
"""
result = script.pip(
'install', 'script.wheel3==0.1', '--no-index',
'--find-links=' + data.find_links,
expect_error=False,
)
if os.name == 'nt':
wrapper_file = script.bin / 't1.exe'
else:
wrapper_file = script.bin / 't1'
assert wrapper_file in result.files_created
def test_wheel_compiles_pyc(script, data):
"""
Test installing from wheel with --compile on
"""
script.pip(
"install", "--compile", "simple.dist==0.1", "--no-index",
"--find-links=" + data.find_links
)
# There are many locations for the __init__.pyc file so attempt to find
# any of them
exists = [
os.path.exists(script.site_packages_path / "simpledist/__init__.pyc"),
]
exists += glob.glob(
script.site_packages_path / "simpledist/__pycache__/__init__*.pyc"
)
assert any(exists)
def test_wheel_no_compiles_pyc(script, data):
"""
Test installing from wheel with --compile on
"""
script.pip(
"install", "--no-compile", "simple.dist==0.1", "--no-index",
"--find-links=" + data.find_links
)
# There are many locations for the __init__.pyc file so attempt to find
# any of them
exists = [
os.path.exists(script.site_packages_path / "simpledist/__init__.pyc"),
]
exists += glob.glob(
script.site_packages_path / "simpledist/__pycache__/__init__*.pyc"
)
assert not any(exists)
def test_install_from_wheel_uninstalls_old_version(script, data):
# regression test for https://github.com/pypa/pip/issues/1825
package = data.packages.join("simplewheel-1.0-py2.py3-none-any.whl")
result = script.pip('install', package, '--no-index', expect_error=True)
package = data.packages.join("simplewheel-2.0-py2.py3-none-any.whl")
result = script.pip('install', package, '--no-index', expect_error=False)
dist_info_folder = script.site_packages / 'simplewheel-2.0.dist-info'
assert dist_info_folder in result.files_created
dist_info_folder = script.site_packages / 'simplewheel-1.0.dist-info'
assert dist_info_folder not in result.files_created
def test_wheel_compile_syntax_error(script, data):
package = data.packages.join("compilewheel-1.0-py2.py3-none-any.whl")
result = script.pip('install', '--compile', package, '--no-index')
assert 'yield from' not in result.stdout
assert 'SyntaxError: ' not in result.stdout
| mit |
cloudinary/cloudinary_php | src/Transformation/Layer/LayerStackPosition.php | 750 | <?php
/**
* This file is part of the Cloudinary PHP package.
*
* (c) Cloudinary
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cloudinary\Transformation;
/**
* Defines the position of a layer - overlay or underlay.
*
* **Learn more**: <a
* href=https://cloudinary.com/documentation/image_transformations#image_and_text_overlays target="_blank">
* Applying overlays to images</a> |
* <a href=https://cloudinary.com/documentation/video_manipulation_and_delivery#adding_image_overlays target="_blank">
* Applying overlays to videos</a>
*
* @api
*/
class LayerStackPosition
{
const OVERLAY = 'overlay';
const UNDERLAY = 'underlay';
}
| mit |
fzheng/codejam | lib/python2.7/site-packages/notebook/static/notebook/js/outputarea.js | 33201 | // Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
define([
'jquery-ui',
'base/js/utils',
'base/js/security',
'base/js/keyboard',
'notebook/js/mathjaxutils',
'components/marked/lib/marked',
], function($, utils, security, keyboard, mathjaxutils, marked) {
"use strict";
/**
* @class OutputArea
*
* @constructor
*/
var OutputArea = function (options) {
this.selector = options.selector;
this.events = options.events;
this.keyboard_manager = options.keyboard_manager;
this.wrapper = $(options.selector);
this.outputs = [];
this.collapsed = false;
this.scrolled = false;
this.scroll_state = 'auto';
this.trusted = true;
this.clear_queued = null;
if (options.prompt_area === undefined) {
this.prompt_area = true;
} else {
this.prompt_area = options.prompt_area;
}
this.create_elements();
this.style();
this.bind_events();
};
/**
* Class prototypes
**/
OutputArea.prototype.create_elements = function () {
this.element = $("<div/>");
this.collapse_button = $("<div/>");
this.prompt_overlay = $("<div/>");
this.wrapper.append(this.prompt_overlay);
this.wrapper.append(this.element);
this.wrapper.append(this.collapse_button);
};
OutputArea.prototype.style = function () {
this.collapse_button.hide();
this.prompt_overlay.hide();
this.wrapper.addClass('output_wrapper');
this.element.addClass('output');
this.collapse_button.addClass("btn btn-default output_collapsed");
this.collapse_button.attr('title', 'click to expand output');
this.collapse_button.text('. . .');
this.prompt_overlay.addClass('out_prompt_overlay prompt');
this.prompt_overlay.attr('title', 'click to expand output; double click to hide output');
this.collapse();
};
/**
* Should the OutputArea scroll?
* Returns whether the height (in lines) exceeds the current threshold.
* Threshold will be OutputArea.minimum_scroll_threshold if scroll_state=true (manually requested)
* or OutputArea.auto_scroll_threshold if scroll_state='auto'.
* This will always return false if scroll_state=false (scroll disabled).
*
*/
OutputArea.prototype._should_scroll = function () {
var threshold;
if (this.scroll_state === false) {
return false;
} else if (this.scroll_state === true) {
threshold = OutputArea.minimum_scroll_threshold;
} else {
threshold = OutputArea.auto_scroll_threshold;
}
if (threshold <=0) {
return false;
}
// line-height from http://stackoverflow.com/questions/1185151
var fontSize = this.element.css('font-size');
var lineHeight = Math.floor(parseInt(fontSize.replace('px','')) * 1.5);
return (this.element.height() > threshold * lineHeight);
};
OutputArea.prototype.bind_events = function () {
var that = this;
this.prompt_overlay.dblclick(function () { that.toggle_output(); });
this.prompt_overlay.click(function () { that.toggle_scroll(); });
this.element.resize(function () {
// FIXME: Firefox on Linux misbehaves, so automatic scrolling is disabled
if ( utils.browser[0] === "Firefox" ) {
return;
}
// maybe scroll output,
// if it's grown large enough and hasn't already been scrolled.
if (!that.scrolled && that._should_scroll()) {
that.scroll_area();
}
});
this.collapse_button.click(function () {
that.expand();
});
};
OutputArea.prototype.collapse = function () {
if (!this.collapsed) {
this.element.hide();
this.prompt_overlay.hide();
if (this.element.html()){
this.collapse_button.show();
}
this.collapsed = true;
// collapsing output clears scroll state
this.scroll_state = 'auto';
}
};
OutputArea.prototype.expand = function () {
if (this.collapsed) {
this.collapse_button.hide();
this.element.show();
if (this.prompt_area) {
this.prompt_overlay.show();
}
this.collapsed = false;
this.scroll_if_long();
}
};
OutputArea.prototype.toggle_output = function () {
if (this.collapsed) {
this.expand();
} else {
this.collapse();
}
};
OutputArea.prototype.scroll_area = function () {
this.element.addClass('output_scroll');
this.prompt_overlay.attr('title', 'click to unscroll output; double click to hide');
this.scrolled = true;
};
OutputArea.prototype.unscroll_area = function () {
this.element.removeClass('output_scroll');
this.prompt_overlay.attr('title', 'click to scroll output; double click to hide');
this.scrolled = false;
};
/**
* Scroll OutputArea if height exceeds a threshold.
*
* Threshold is OutputArea.minimum_scroll_threshold if scroll_state = true,
* OutputArea.auto_scroll_threshold if scroll_state='auto'.
*
**/
OutputArea.prototype.scroll_if_long = function () {
var should_scroll = this._should_scroll();
if (!this.scrolled && should_scroll) {
// only allow scrolling long-enough output
this.scroll_area();
} else if (this.scrolled && !should_scroll) {
// scrolled and shouldn't be
this.unscroll_area();
}
};
OutputArea.prototype.toggle_scroll = function () {
if (this.scroll_state == 'auto') {
this.scroll_state = !this.scrolled;
} else {
this.scroll_state = !this.scroll_state;
}
if (this.scrolled) {
this.unscroll_area();
} else {
// only allow scrolling long-enough output
this.scroll_if_long();
}
};
// typeset with MathJax if MathJax is available
OutputArea.prototype.typeset = function () {
utils.typeset(this.element);
};
OutputArea.prototype.handle_output = function (msg) {
var json = {};
var msg_type = json.output_type = msg.header.msg_type;
var content = msg.content;
if (msg_type === "stream") {
json.text = content.text;
json.name = content.name;
} else if (msg_type === "display_data") {
json.data = content.data;
json.metadata = content.metadata;
} else if (msg_type === "execute_result") {
json.data = content.data;
json.metadata = content.metadata;
json.execution_count = content.execution_count;
} else if (msg_type === "error") {
json.ename = content.ename;
json.evalue = content.evalue;
json.traceback = content.traceback;
} else {
console.log("unhandled output message", msg);
return;
}
this.append_output(json);
};
OutputArea.output_types = [
'application/javascript',
'text/html',
'text/markdown',
'text/latex',
'image/svg+xml',
'image/png',
'image/jpeg',
'application/pdf',
'text/plain'
];
OutputArea.prototype.validate_mimebundle = function (bundle) {
/** scrub invalid outputs */
if (typeof bundle.data !== 'object') {
console.warn("mimebundle missing data", bundle);
bundle.data = {};
}
if (typeof bundle.metadata !== 'object') {
console.warn("mimebundle missing metadata", bundle);
bundle.metadata = {};
}
var data = bundle.data;
$.map(OutputArea.output_types, function(key){
if (key !== 'application/json' &&
data[key] !== undefined &&
typeof data[key] !== 'string'
) {
console.log("Invalid type for " + key, data[key]);
delete data[key];
}
});
return bundle;
};
OutputArea.prototype.append_output = function (json) {
this.expand();
// Clear the output if clear is queued.
var needs_height_reset = false;
if (this.clear_queued) {
this.clear_output(false);
needs_height_reset = true;
}
var record_output = true;
switch(json.output_type) {
case 'execute_result':
json = this.validate_mimebundle(json);
this.append_execute_result(json);
break;
case 'stream':
// append_stream might have merged the output with earlier stream output
record_output = this.append_stream(json);
break;
case 'error':
this.append_error(json);
break;
case 'display_data':
// append handled below
json = this.validate_mimebundle(json);
break;
default:
console.log("unrecognized output type: " + json.output_type);
this.append_unrecognized(json);
}
// We must release the animation fixed height in a callback since Gecko
// (FireFox) doesn't render the image immediately as the data is
// available.
var that = this;
var handle_appended = function ($el) {
/**
* Only reset the height to automatic if the height is currently
* fixed (done by wait=True flag on clear_output).
*/
if (needs_height_reset) {
that.element.height('');
}
that.element.trigger('resize');
};
if (json.output_type === 'display_data') {
this.append_display_data(json, handle_appended);
} else {
handle_appended();
}
if (record_output) {
this.outputs.push(json);
}
};
OutputArea.prototype.create_output_area = function () {
var oa = $("<div/>").addClass("output_area");
if (this.prompt_area) {
oa.append($('<div/>').addClass('prompt'));
}
return oa;
};
function _get_metadata_key(metadata, key, mime) {
var mime_md = metadata[mime];
// mime-specific higher priority
if (mime_md && mime_md[key] !== undefined) {
return mime_md[key];
}
// fallback on global
return metadata[key];
}
OutputArea.prototype.create_output_subarea = function(md, classes, mime) {
var subarea = $('<div/>').addClass('output_subarea').addClass(classes);
if (_get_metadata_key(md, 'isolated', mime)) {
// Create an iframe to isolate the subarea from the rest of the
// document
var iframe = $('<iframe/>').addClass('box-flex1');
iframe.css({'height':1, 'width':'100%', 'display':'block'});
iframe.attr('frameborder', 0);
iframe.attr('scrolling', 'auto');
// Once the iframe is loaded, the subarea is dynamically inserted
iframe.on('load', function() {
// Workaround needed by Firefox, to properly render svg inside
// iframes, see http://stackoverflow.com/questions/10177190/
// svg-dynamically-added-to-iframe-does-not-render-correctly
this.contentDocument.open();
// Insert the subarea into the iframe
// We must directly write the html. When using Jquery's append
// method, javascript is evaluated in the parent document and
// not in the iframe document. At this point, subarea doesn't
// contain any user content.
this.contentDocument.write(subarea.html());
this.contentDocument.close();
var body = this.contentDocument.body;
// Adjust the iframe height automatically
iframe.height(body.scrollHeight + 'px');
});
// Elements should be appended to the inner subarea and not to the
// iframe
iframe.append = function(that) {
subarea.append(that);
};
return iframe;
} else {
return subarea;
}
};
OutputArea.prototype._append_javascript_error = function (err, element) {
/**
* display a message when a javascript error occurs in display output
*/
var msg = "Javascript error adding output!";
if ( element === undefined ) return;
element
.append($('<div/>').text(msg).addClass('js-error'))
.append($('<div/>').text(err.toString()).addClass('js-error'))
.append($('<div/>').text('See your browser Javascript console for more details.').addClass('js-error'));
};
OutputArea.prototype._safe_append = function (toinsert) {
/**
* safely append an item to the document
* this is an object created by user code,
* and may have errors, which should not be raised
* under any circumstances.
*/
try {
this.element.append(toinsert);
} catch(err) {
console.log(err);
// Create an actual output_area and output_subarea, which creates
// the prompt area and the proper indentation.
var toinsert = this.create_output_area();
var subarea = $('<div/>').addClass('output_subarea');
toinsert.append(subarea);
this._append_javascript_error(err, subarea);
this.element.append(toinsert);
}
// Notify others of changes.
this.element.trigger('changed');
};
OutputArea.prototype.append_execute_result = function (json) {
var n = json.execution_count || ' ';
var toinsert = this.create_output_area();
if (this.prompt_area) {
toinsert.find('div.prompt').addClass('output_prompt').text('Out[' + n + ']:');
}
var inserted = this.append_mime_type(json, toinsert);
if (inserted) {
inserted.addClass('output_result');
}
this._safe_append(toinsert);
// If we just output latex, typeset it.
if ((json.data['text/latex'] !== undefined) ||
(json.data['text/html'] !== undefined) ||
(json.data['text/markdown'] !== undefined)) {
this.typeset();
}
};
OutputArea.prototype.append_error = function (json) {
var tb = json.traceback;
if (tb !== undefined && tb.length > 0) {
var s = '';
var len = tb.length;
for (var i=0; i<len; i++) {
s = s + tb[i] + '\n';
}
s = s + '\n';
var toinsert = this.create_output_area();
var append_text = OutputArea.append_map['text/plain'];
if (append_text) {
append_text.apply(this, [s, {}, toinsert]).addClass('output_error');
}
this._safe_append(toinsert);
}
};
OutputArea.prototype.append_stream = function (json) {
var text = json.text;
if (typeof text !== 'string') {
console.error("Stream output is invalid (missing text)", json);
return false;
}
var subclass = "output_"+json.name;
if (this.outputs.length > 0){
// have at least one output to consider
var last = this.outputs[this.outputs.length-1];
if (last.output_type == 'stream' && json.name == last.name){
// latest output was in the same stream,
// so append directly into its pre tag
// escape ANSI & HTML specials:
last.text = utils.fixCarriageReturn(last.text + json.text);
var pre = this.element.find('div.'+subclass).last().find('pre');
var html = utils.fixConsole(last.text);
html = utils.autoLinkUrls(html);
// The only user content injected with this HTML call is
// escaped by the fixConsole() method.
pre.html(html);
// return false signals that we merged this output with the previous one,
// and the new output shouldn't be recorded.
return false;
}
}
if (!text.replace("\r", "")) {
// text is nothing (empty string, \r, etc.)
// so don't append any elements, which might add undesirable space
// return true to indicate the output should be recorded.
return true;
}
// If we got here, attach a new div
var toinsert = this.create_output_area();
var append_text = OutputArea.append_map['text/plain'];
if (append_text) {
append_text.apply(this, [text, {}, toinsert]).addClass("output_stream " + subclass);
}
this._safe_append(toinsert);
return true;
};
OutputArea.prototype.append_unrecognized = function (json) {
var that = this;
var toinsert = this.create_output_area();
var subarea = $('<div/>').addClass('output_subarea output_unrecognized');
toinsert.append(subarea);
subarea.append(
$("<a>")
.attr("href", "#")
.text("Unrecognized output: " + json.output_type)
.click(function () {
that.events.trigger('unrecognized_output.OutputArea', {output: json});
})
);
this._safe_append(toinsert);
};
OutputArea.prototype.append_display_data = function (json, handle_inserted) {
var toinsert = this.create_output_area();
if (this.append_mime_type(json, toinsert, handle_inserted)) {
this._safe_append(toinsert);
// If we just output latex, typeset it.
if ((json.data['text/latex'] !== undefined) ||
(json.data['text/html'] !== undefined) ||
(json.data['text/markdown'] !== undefined)) {
this.typeset();
}
}
};
OutputArea.safe_outputs = {
'text/plain' : true,
'text/latex' : true,
'image/png' : true,
'image/jpeg' : true
};
OutputArea.prototype.append_mime_type = function (json, element, handle_inserted) {
for (var i=0; i < OutputArea.display_order.length; i++) {
var type = OutputArea.display_order[i];
var append = OutputArea.append_map[type];
if ((json.data[type] !== undefined) && append) {
var value = json.data[type];
if (!this.trusted && !OutputArea.safe_outputs[type]) {
// not trusted, sanitize HTML
if (type==='text/html' || type==='text/svg') {
value = security.sanitize_html(value);
} else {
// don't display if we don't know how to sanitize it
console.log("Ignoring untrusted " + type + " output.");
continue;
}
}
var md = json.metadata || {};
var toinsert = append.apply(this, [value, md, element, handle_inserted]);
// Since only the png and jpeg mime types call the inserted
// callback, if the mime type is something other we must call the
// inserted callback only when the element is actually inserted
// into the DOM. Use a timeout of 0 to do this.
if (['image/png', 'image/jpeg'].indexOf(type) < 0 && handle_inserted !== undefined) {
setTimeout(handle_inserted, 0);
}
this.events.trigger('output_appended.OutputArea', [type, value, md, toinsert]);
return toinsert;
}
}
return null;
};
var append_html = function (html, md, element) {
var type = 'text/html';
var toinsert = this.create_output_subarea(md, "output_html rendered_html", type);
this.keyboard_manager.register_events(toinsert);
toinsert.append(html);
dblclick_to_reset_size(toinsert.find('img'));
element.append(toinsert);
return toinsert;
};
var append_markdown = function(markdown, md, element) {
var type = 'text/markdown';
var toinsert = this.create_output_subarea(md, "output_markdown rendered_html", type);
var text_and_math = mathjaxutils.remove_math(markdown);
var text = text_and_math[0];
var math = text_and_math[1];
marked(text, function (err, html) {
html = mathjaxutils.replace_math(html, math);
toinsert.append(html);
});
dblclick_to_reset_size(toinsert.find('img'));
element.append(toinsert);
return toinsert;
};
var append_javascript = function (js, md, element) {
/**
* We just eval the JS code, element appears in the local scope.
*/
var type = 'application/javascript';
var toinsert = this.create_output_subarea(md, "output_javascript rendered_html", type);
this.keyboard_manager.register_events(toinsert);
element.append(toinsert);
// Fix for ipython/issues/5293, make sure `element` is the area which
// output can be inserted into at the time of JS execution.
element = toinsert;
try {
eval(js);
} catch(err) {
console.log(err);
this._append_javascript_error(err, toinsert);
}
return toinsert;
};
var append_text = function (data, md, element) {
var type = 'text/plain';
var toinsert = this.create_output_subarea(md, "output_text", type);
// escape ANSI & HTML specials in plaintext:
data = utils.fixConsole(data);
data = utils.fixCarriageReturn(data);
data = utils.autoLinkUrls(data);
// The only user content injected with this HTML call is
// escaped by the fixConsole() method.
toinsert.append($("<pre/>").html(data));
element.append(toinsert);
return toinsert;
};
var append_svg = function (svg_html, md, element) {
var type = 'image/svg+xml';
var toinsert = this.create_output_subarea(md, "output_svg", type);
// Get the svg element from within the HTML.
// One svg is supposed, but could embed other nested svgs
var svg = $($('<div \>').html(svg_html).find('svg')[0]);
var svg_area = $('<div />');
var width = svg.attr('width');
var height = svg.attr('height');
svg
.width('100%')
.height('100%');
svg_area
.width(width)
.height(height);
svg_area.append(svg);
toinsert.append(svg_area);
element.append(toinsert);
return toinsert;
};
function dblclick_to_reset_size (img) {
/**
* Double-click on an image toggles confinement to notebook width
*
* img: jQuery element
*/
img.dblclick(function () {
// dblclick toggles *raw* size, disabling max-width confinement.
if (img.hasClass('unconfined')) {
img.removeClass('unconfined');
} else {
img.addClass('unconfined');
}
});
}
var set_width_height = function (img, md, mime) {
/**
* set width and height of an img element from metadata
*/
var height = _get_metadata_key(md, 'height', mime);
if (height !== undefined) img.attr('height', height);
var width = _get_metadata_key(md, 'width', mime);
if (width !== undefined) img.attr('width', width);
if (_get_metadata_key(md, 'unconfined', mime)) {
img.addClass('unconfined');
}
};
var append_png = function (png, md, element, handle_inserted) {
var type = 'image/png';
var toinsert = this.create_output_subarea(md, "output_png", type);
var img = $("<img/>");
if (handle_inserted !== undefined) {
img.on('load', function(){
handle_inserted(img);
});
}
img[0].src = 'data:image/png;base64,'+ png;
set_width_height(img, md, 'image/png');
dblclick_to_reset_size(img);
toinsert.append(img);
element.append(toinsert);
return toinsert;
};
var append_jpeg = function (jpeg, md, element, handle_inserted) {
var type = 'image/jpeg';
var toinsert = this.create_output_subarea(md, "output_jpeg", type);
var img = $("<img/>");
if (handle_inserted !== undefined) {
img.on('load', function(){
handle_inserted(img);
});
}
img[0].src = 'data:image/jpeg;base64,'+ jpeg;
set_width_height(img, md, 'image/jpeg');
dblclick_to_reset_size(img);
toinsert.append(img);
element.append(toinsert);
return toinsert;
};
var append_pdf = function (pdf, md, element) {
var type = 'application/pdf';
var toinsert = this.create_output_subarea(md, "output_pdf", type);
var a = $('<a/>').attr('href', 'data:application/pdf;base64,'+pdf);
a.attr('target', '_blank');
a.text('View PDF');
toinsert.append(a);
element.append(toinsert);
return toinsert;
};
var append_latex = function (latex, md, element) {
/**
* This method cannot do the typesetting because the latex first has to
* be on the page.
*/
var type = 'text/latex';
var toinsert = this.create_output_subarea(md, "output_latex", type);
toinsert.append(latex);
element.append(toinsert);
return toinsert;
};
OutputArea.prototype.append_raw_input = function (msg) {
var that = this;
this.expand();
var content = msg.content;
var area = this.create_output_area();
// disable any other raw_inputs, if they are left around
$("div.output_subarea.raw_input_container").remove();
var input_type = content.password ? 'password' : 'text';
area.append(
$("<div/>")
.addClass("box-flex1 output_subarea raw_input_container")
.append(
$("<pre/>")
.addClass("raw_input_prompt")
.html(utils.fixConsole(content.prompt))
.append(
$("<input/>")
.addClass("raw_input")
.attr('type', input_type)
.attr("size", 47)
.keydown(function (event, ui) {
// make sure we submit on enter,
// and don't re-execute the *cell* on shift-enter
if (event.which === keyboard.keycodes.enter) {
that._submit_raw_input();
return false;
}
})
)
)
);
this.element.append(area);
var raw_input = area.find('input.raw_input');
// Register events that enable/disable the keyboard manager while raw
// input is focused.
this.keyboard_manager.register_events(raw_input);
// Note, the following line used to read raw_input.focus().focus().
// This seemed to be needed otherwise only the cell would be focused.
// But with the modal UI, this seems to work fine with one call to focus().
raw_input.focus();
};
OutputArea.prototype._submit_raw_input = function (evt) {
var container = this.element.find("div.raw_input_container");
var theprompt = container.find("pre.raw_input_prompt");
var theinput = container.find("input.raw_input");
var value = theinput.val();
var echo = value;
// don't echo if it's a password
if (theinput.attr('type') == 'password') {
echo = '········';
}
var content = {
output_type : 'stream',
name : 'stdout',
text : theprompt.text() + echo + '\n'
};
// remove form container
container.parent().remove();
// replace with plaintext version in stdout
this.append_output(content, false);
this.events.trigger('send_input_reply.Kernel', value);
};
OutputArea.prototype.handle_clear_output = function (msg) {
/**
* msg spec v4 had stdout, stderr, display keys
* v4.1 replaced these with just wait
* The default behavior is the same (stdout=stderr=display=True, wait=False),
* so v4 messages will still be properly handled,
* except for the rarely used clearing less than all output.
*/
this.clear_output(msg.content.wait || false);
};
OutputArea.prototype.clear_output = function(wait, ignore_que) {
if (wait) {
// If a clear is queued, clear before adding another to the queue.
if (this.clear_queued) {
this.clear_output(false);
}
this.clear_queued = true;
} else {
// Fix the output div's height if the clear_output is waiting for
// new output (it is being used in an animation).
if (!ignore_que && this.clear_queued) {
var height = this.element.height();
this.element.height(height);
this.clear_queued = false;
}
// Clear all
// Remove load event handlers from img tags because we don't want
// them to fire if the image is never added to the page.
this.element.find('img').off('load');
this.element.html("");
// Notify others of changes.
this.element.trigger('changed');
this.outputs = [];
this.trusted = true;
this.unscroll_area();
return;
}
};
// JSON serialization
OutputArea.prototype.fromJSON = function (outputs, metadata) {
var len = outputs.length;
metadata = metadata || {};
for (var i=0; i<len; i++) {
this.append_output(outputs[i]);
}
if (metadata.collapsed !== undefined) {
if (metadata.collapsed) {
this.collapse();
} else {
this.expand();
}
}
if (metadata.scrolled !== undefined) {
this.scroll_state = metadata.scrolled;
if (metadata.scrolled) {
this.scroll_if_long();
} else {
this.unscroll_area();
}
}
};
OutputArea.prototype.toJSON = function () {
return this.outputs;
};
/**
* Class properties
**/
/**
* Threshold to trigger autoscroll when the OutputArea is resized,
* typically when new outputs are added.
*
* Behavior is undefined if autoscroll is lower than minimum_scroll_threshold,
* unless it is < 0, in which case autoscroll will never be triggered
*
* @property auto_scroll_threshold
* @type Number
* @default 100
*
**/
OutputArea.auto_scroll_threshold = 100;
/**
* Lower limit (in lines) for OutputArea to be made scrollable. OutputAreas
* shorter than this are never scrolled.
*
* @property minimum_scroll_threshold
* @type Number
* @default 20
*
**/
OutputArea.minimum_scroll_threshold = 20;
OutputArea.display_order = [
'application/javascript',
'text/html',
'text/markdown',
'text/latex',
'image/svg+xml',
'image/png',
'image/jpeg',
'application/pdf',
'text/plain'
];
OutputArea.append_map = {
"text/plain" : append_text,
"text/html" : append_html,
"text/markdown": append_markdown,
"image/svg+xml" : append_svg,
"image/png" : append_png,
"image/jpeg" : append_jpeg,
"text/latex" : append_latex,
"application/javascript" : append_javascript,
"application/pdf" : append_pdf
};
return {'OutputArea': OutputArea};
});
| mit |
AlexJCross/Cosmos | Cosmos/Lib.Cosmos/Scenes/Views/BlackHoleView.cs | 377 | namespace Lib.Cosmos.Scenes.Views
{
using Utils;
using ViewControllers;
public class BlackHoleView : SceneViewBase
{
~BlackHoleView()
{
MemoryUtils.LogGc<BlackHoleView>();
}
protected override ISceneViewController GetController()
{
return new BlackHoleViewController(this);
}
}
}
| mit |
alxbl/DebugDiag.Native | DebugDiag.Native.Test/Fixtures/Generators/Map.cs | 3855 | using System.Collections.Generic;
using System.Text;
namespace DebugDiag.Native.Test.Fixtures.Generators
{
/// <summary>
/// Generates an std::Map fixture.
/// </summary>
public class Map : Generator
{
private readonly Generator _childGenerator;
private readonly int _count;
/// <summary>
/// Creates a map of int -> specific element.
/// </summary>
/// <param name="addr">The address at which to dump the map.</param>
/// <param name="count">The number of elements in the map fixture.</param>
/// <param name="child">Generator for the map elements.</param>
// TODO: Should be able to specify the key generator as well.
public Map(ulong addr, int count, Generator child)
{
_childGenerator = child;
_count = count;
Address = addr;
}
public override string GetTypeName()
{
return string.Format("std::map<int,{0},std::less<int>,std::allocator<std::pair<int const ,{0}> > >", _childGenerator.GetTypeName());
}
public override KeyValuePair<string, string> GetTypeInfo()
{
var k = string.Format("dt 0 {0}", GetTypeName());
var v = string.Format(@" +0x000 _Myproxy : Ptr32 std::_Container_proxy
+0x004 _Myhead : Ptr32 std::_Tree_node<std::pair<int const ,{0}>,void *>
+0x008 _Mysize : Uint4B", _childGenerator.GetTypeName());
return new KeyValuePair<string, string>(k, v);
}
public override IEnumerable<KeyValuePair<string, string>> GenerateInternal()
{
// Root of the Map (k, v, and kv are re-used)
var k = string.Format("dt 0x{0:x} {1}", Address, GetTypeName());
var v = string.Format(@" +0x000 _Myproxy : 0xbaadf00d std::_Container_proxy
+0x004 _Myhead : 0xbaadf00d std::_Tree_node<std::pair<int const ,{0}>,void *>
+0x008 _Mysize : {1}", _childGenerator.GetTypeName(), _count);
var kv = new KeyValuePair<string, string>(k, v);
yield return kv;
// Pair Info
k = string.Format("dt 0 std::pair<int const ,{0}>", _childGenerator.GetTypeName());
v = string.Format(@" +0x000 first : Int4B
+0x004 second : {0}", _childGenerator.GetTypeName());
kv = new KeyValuePair<string, string>(k, v);
yield return kv;
k = string.Format("dt 0 std::pair<int const,{0}>", _childGenerator.GetTypeName()); // int const,ValueType without space. Windbg randomly mixes both.
v = string.Format(@" +0x000 first : Int4B
+0x004 second : {0}", _childGenerator.GetTypeName());
kv = new KeyValuePair<string, string>(k, v);
yield return kv;
// Generate children type info.
var children = new StringBuilder();
children.AppendFormat("Size={0}\r\n", _count);
yield return _childGenerator.GetTypeInfo();
// Generate children.
for (ulong i = 0; i < (ulong)_count; ++i)
{
var addr = 0xff0 + i*20;
_childGenerator.Address = addr+4; // !map uses offset manipulation.
children.AppendFormat("0x{0:x}\r\n", addr);
foreach (var fixture in _childGenerator.Generate(false))
{
yield return fixture;
}
}
// Generate the !map output
k = string.Format("!map 0x{0:x}", Address);
v = children.ToString();
kv = new KeyValuePair<string, string>(k, v);
yield return kv;
}
}
}
| mit |
maca88/angular-requirejs-typescript-seed | app/js/main.ts | 862 | /// <reference path='all.ts' />
'use strict';
require.config({
paths: {
angular: '../bower_components/angular/angular',
angularRoute: '../bower_components/angular-route/angular-route',
angularMocks: '../bower_components/angular-mocks/angular-mocks',
text: '../bower_components/requirejs-text/text'
},
shim: {
'angular' : {'exports' : 'angular'},
'angularRoute': ['angular'],
'angularMocks': {
deps:['angular'],
'exports':'angular.mock'
}
},
priority: [
"angular"
]
});
//http://code.angularjs.org/1.2.1/docs/guide/bootstrap#overview_deferred-bootstrap
window.name = "NG_DEFER_BOOTSTRAP!";
require( [
'angular',
'app',
'routes'
], function(angular, app, routes) {
var $html = angular.element(document.getElementsByTagName('html')[0]);
angular.element().ready(function() {
angular.resumeBootstrap([app['name']]);
});
});
| mit |
rockstar3/rails_0133 | config/unicorn.rb | 1299 | # worker_processes 3
# timeout 30
# preload_app true
# before_fork do |server, worker|
# Signal.trap 'TERM' do
# puts 'Unicorn master intercepting TERM and sending myself QUIT instead'
# Process.kill 'QUIT', Process.pid
# end
# defined?(ActiveRecord::Base) and
# ActiveRecord::Base.connection.disconnect!
# end
# after_fork do |server, worker|
# Signal.trap 'TERM' do
# puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to sent QUIT'
# end
# defined?(ActiveRecord::Base) and
# ActiveRecord::Base.establish_connection
# end
##########################
# Set the working application directory
# working_directory "/path/to/your/app"
working_directory "/home/nomessdr/public_html/prelaunch/src"
# Unicorn PID file location
# pid "/path/to/pids/unicorn.pid"
pid "/home/nomessdr/public_html/prelaunch/src/pids/unicorn.pid"
# Path to logs
# stderr_path "/path/to/log/unicorn.log"
# stdout_path "/path/to/log/unicorn.log"
stderr_path "/home/nomessdr/public_html/prelaunch/src/log/unicorn.log"
stdout_path "/home/nomessdr/public_html/prelaunch/src/log/unicorn.log"
# Unicorn socket
listen "/tmp/unicorn.prelaunch.sock"
listen "/tmp/unicorn.prelaunch.sock"
# Number of processes
# worker_processes 4
worker_processes 2
# Time-out
timeout 30 | mit |
sundayz/Restriction-Site-Remover | src/controllers/HomeController.php | 5324 | <?php
class HomeController extends BaseController implements IndexedController
{
public function index()
{
$rsDropdownData = RestrictionSites::getSites();
$this->putData('pageTitle', 'Home');
$this->putData('rsdata', $rsDropdownData);
$this->render('templates/RSR.twig');
}
public function parseDNA()
{
$t1 = microtime(true);
if (Flight::request()->data->dnasequence == null || Flight::request()->data->dnasequence == '')
{
$this->showErrorMessage('A DNA sequence must be provided.');
exit(1);
}
$parser = new InputParser(Flight::request()->data->dnasequence);
$parser->cleanDNA();
if ($parser->getRaw() == '')
{
$this->showErrorMessage('The DNA provided was a malformed format.');
exit(1);
}
$sites = Flight::request()->data->sites;
if (!$sites || count($sites) < 1)
{
$this->showErrorMessage('Please select at least one restriction site to remove.');
exit(1);
}
$dna = $parser->createDNASequence();
// Create an array of Restriction Sites that we will be looking for.
$restrictionSites = array();
if (Flight::request()->data->customtargets)
{
$customParser = new CustomTargetsParser(Flight::request()->data->customtargets);
try
{
$customTargets = $customParser->parseSites();
foreach ($customTargets as $target)
array_push($restrictionSites, $target);
}
catch (RuntimeException $e)
{
$this->showErrorMessage($e->getMessage());
exit(1);
}
}
foreach ($sites as $nucleotides)
{
if ($nucleotides == "all")
{
$restrictionSites = RestrictionSites::getSites(); // Get all the sites. ignore the other input.
break;
}
else if ($nucleotides == "rfc10")
{
RestrictionSites::pushRfc10($restrictionSites);
continue;
}
else if ($nucleotides == "universal")
{
RestrictionSites::pushUniversal($restrictionSites);
continue;
}
$val = RestrictionSites::getSite($nucleotides);
if ($val == null)
continue;
array_push($restrictionSites, $val);
}
if (count($restrictionSites) < 1)
{
$this->showErrorMessage('Please select at least one restriction site to remove.');
exit(1);
}
if (isset(Flight::request()->data->checkcomplements))
{
$temp = array(); // Array of complements.
foreach ($restrictionSites as $site)
array_push($temp, $site->getComplement());
foreach ($temp as $complementSite)
array_push($restrictionSites, $complementSite);
}
try
{
$dna->findRestrictionSites($restrictionSites);
}
catch (ReadingFrameException $e)
{
$this->showErrorMessage($e->getMessage());
exit(1);
}
$dnaresult = $dna->getResult();
// Debug info
$info = array(
'iterations' => $dna->info['iterations'],
'failedmutations' => $dna->info['failedMutations'],
'mutations' => count($dna->info['mutationIndices']),
'checked' => count($restrictionSites),
'found' => $dna->found,
'timetaken' => (microtime(true) - $t1 . ' seconds')
);
if ($dna->info['iterations'] > DNASequence::MAX_ITERATIONS)
{
$this->putData('hasNotice', true);
$this->putData('noticeText', 'The maximum iteration count was hit. Not all sites may have been fully removed.');
}
$this->putData('info', $info);
$this->putData('showDebug', isset(Flight::request()->data->showdebug));
$this->putData('inputdna', $parser->getRaw());
$this->putData('dnaresult', $dnaresult);
$this->putData('pageTitle', 'RSR Results');
$this->putData('sites', $restrictionSites);
$this->render('templates/result.twig');
}
/**
* Creates an alert at the top of the screen, describing the issue.
* @param string $msg The error message to display.
*/
private function showErrorMessage(string $msg)
{
$rsDropdownData = RestrictionSites::getSites(); // Populate dropdown.
$userinput = array( // Preserve user input.
'seq' => Flight::request()->data->dnasequence,
'customtargets' => Flight::request()->data->customtargets
);
$this->putData('userinput', $userinput);
$this->putData('hasError', true);
$this->putData('errorText', $msg);
$this->putData('pageTitle', 'RSR — An Error Has Occurred!');
$this->putData('pageTitle', 'Home');
$this->putData('rsdata', $rsDropdownData);
$this->render('templates/RSR.twig');
}
protected function before() { }
protected function after() { }
}
| mit |
Antione7/Bonnezannonces | app/cache/dev/twig/71/40/f2e94820b2ca10ab1d2b9b8046bbb6740373619766b5ecb8547b7765ad8e.php | 3809 | <?php
/* FOSUserBundle:Security:login.html.twig */
class __TwigTemplate_7140f2e94820b2ca10ab1d2b9b8046bbb6740373619766b5ecb8547b7765ad8e extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
// line 1
try {
$this->parent = $this->env->loadTemplate("FOSUserBundle::layout.html.twig");
} catch (Twig_Error_Loader $e) {
$e->setTemplateFile($this->getTemplateName());
$e->setTemplateLine(1);
throw $e;
}
$this->blocks = array(
'fos_user_content' => array($this, 'block_fos_user_content'),
);
}
protected function doGetParent(array $context)
{
return "FOSUserBundle::layout.html.twig";
}
protected function doDisplay(array $context, array $blocks = array())
{
$this->parent->display($context, array_merge($this->blocks, $blocks));
}
// line 3
public function block_fos_user_content($context, array $blocks = array())
{
// line 4
if ((isset($context["error"]) ? $context["error"] : $this->getContext($context, "error"))) {
// line 5
echo " <div>";
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans((isset($context["error"]) ? $context["error"] : $this->getContext($context, "error")), array(), "FOSUserBundle"), "html", null, true);
echo "</div>
";
}
// line 7
echo "
<form action=\"";
// line 8
echo $this->env->getExtension('routing')->getPath("fos_user_security_check");
echo "\" method=\"post\">
<input type=\"hidden\" name=\"_csrf_token\" value=\"";
// line 9
echo twig_escape_filter($this->env, (isset($context["csrf_token"]) ? $context["csrf_token"] : $this->getContext($context, "csrf_token")), "html", null, true);
echo "\" />
<label for=\"email\">";
// line 11
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("security.login.email", array(), "FOSUserBundle"), "html", null, true);
echo "</label>
<input type=\"text\" id=\"username\" name=\"_username\" value=\"";
// line 12
echo twig_escape_filter($this->env, (isset($context["last_username"]) ? $context["last_username"] : $this->getContext($context, "last_username")), "html", null, true);
echo "\" required=\"required\" />
<label for=\"password\">";
// line 14
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("security.login.password", array(), "FOSUserBundle"), "html", null, true);
echo "</label>
<input type=\"password\" id=\"password\" name=\"_password\" required=\"required\" />
<input type=\"checkbox\" id=\"remember_me\" name=\"_remember_me\" value=\"on\" />
<label for=\"remember_me\">";
// line 18
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("security.login.remember_me", array(), "FOSUserBundle"), "html", null, true);
echo "</label>
<input type=\"submit\" id=\"_submit\" name=\"_submit\" value=\"";
// line 20
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("security.login.submit", array(), "FOSUserBundle"), "html", null, true);
echo "\" />
</form>
";
}
public function getTemplateName()
{
return "FOSUserBundle:Security:login.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 80 => 20, 75 => 18, 68 => 14, 63 => 12, 59 => 11, 54 => 9, 50 => 8, 47 => 7, 41 => 5, 39 => 4, 36 => 3, 11 => 1,);
}
}
| mit |
maichong/alaska | src/alaska/alaska.js | 13019 | // @flow
/* eslint new-cap:0 */
import fs from 'fs';
import _ from 'lodash';
import mime from 'mime-types';
import Koa from 'koa';
// $Flow
import KoaQS from 'koa-qs';
import statuses from 'statuses';
import collie from 'collie';
import Debugger from 'debug';
import depd from 'depd';
import * as utils from './utils';
const debug = Debugger('alaska');
const deprecate = depd('alaska');
/**
* 一般错误
* @class {NormalError}
*/
export class NormalError extends Error {
code: number | void;
constructor(message: string, code?: number) {
super(message);
this.code = code;
}
}
/**
* 严重错误
* @class {PanicError}
*/
export class PanicError extends Error {
code: number | void;
constructor(message: string, code?: number) {
super(message);
this.code = code;
}
}
/**
* 接口关闭
* @type {number}
*/
export const CLOSED = 0;
/**
* 允许所有用户访问接口
*/
export const PUBLIC = 1;
/**
* 允许已经认证的用户访问接口
*/
export const AUTHENTICATED = 2;
/**
* 允许资源所有者访问接口
*/
export const OWNER = 3;
/**
* Alaska主类,通过import获取Alaska实例对象
* ```js
* import alaska from 'alaska';
* ```
*/
class Alaska {
_callbackMode = false;
_app: Koa;
modules: Object;
main: Alaska$Service;
services: {
[id: string]: Alaska$Service
};
_mounts = {};
locales = {};
/**
* 初始化一个新的Alaska实例对象
* @constructor
*/
constructor() {
this.services = {};
collie(this, 'launch');
collie(this, 'loadMiddlewares');
collie(this, 'registerService');
collie(this, 'listen');
}
/**
* 返回当前koa APP对象
* @returns {Koa}
*/
get app(): Koa {
if (!this._app) {
this._app = new Koa();
this._app.env = this.getConfig('env');
this._app.proxy = this.getConfig('proxy');
this._app.subdomainOffset = this.getConfig('subdomainOffset');
KoaQS(this._app);
}
return this._app;
}
/**
* 获取本Alaska实例中注册的Service
* @deprecated
* @param {string} id Service ID
* @return {Service|null}
*/
service(id: string): Alaska$Service {
deprecate('service()');
return this.getService(id);
}
/**
* 获取本Alaska实例中注册的Service
* @since 0.12.0
* @param {string} id Service ID
* @return {Service}
*/
getService(id: string): Alaska$Service {
if (id === 'main') {
return this.main;
}
let service = this.services[id];
if (!_.isObject(service)) {
this.panic(`Can not resolve '${id}' service!`);
}
return service;
}
/**
* 判断是否存在指定Service
* @param {string} id Service ID
* @returns {boolean}
*/
hasService(id: string): boolean {
if (id === 'main' && this.main) {
return true;
}
return _.isObject(this.services[id]);
}
/**
* 注册新的Service
* @param {Service} service Service对象
*/
registerService(service: Alaska$Service) {
if (!this.main) {
this.main = service;
}
this.services[service.id] = service;
}
/**
* 获取当前Alaska实例的主Service配置
* @deprecated
* @param {string} key 配置名
* @param {*} [defaultValue] 默认值
* @returns {*}
*/
config(key: string, defaultValue: any): any {
deprecate('config()');
return this.getConfig(key, defaultValue);
}
/**
* 获取当前Alaska实例的主Service配置
* @since 0.12.0
* @param {string} key 配置名
* @param {*} [defaultValue] 默认值
* @returns {*}
*/
getConfig(key: string, defaultValue: any): any {
return this.main.getConfig(key, defaultValue);
}
/**
* 获取当前主配置的数据库链接
* @returns {mongoose.Connection | null}
*/
get db(): Mongoose$Connection {
return this.main.db;
}
/**
* 监听
*/
async listen(): Promise<void> {
// $Flow
this.listen = utils.resolved;
const alaska = this;
debug('listen');
const mountKeys = Object.keys(this._mounts);
this.app.use(async(ctx, next) => {
const { hostname } = ctx;
for (let point of mountKeys) {
debug('test endpoint', point);
let service = alaska._mounts[point];
if (!service.domain || service.domain === hostname) {
if (ctx.path.startsWith(service.prefix)) {
ctx.service = service;
await service.routes(ctx, next);
return;
}
if (ctx.path + '/' === service.prefix) {
ctx.redirect(service.prefix);
return;
}
}
}
});
if (!this._callbackMode) {
this.app.listen(this.getConfig('port'));
}
}
/**
* 返回 http.createServer() 回调函数
* @returns {Function}
*/
callback(): (req: http$IncomingMessage, res: http$ServerResponse) => void {
this._callbackMode = true;
return this.app.callback();
}
/**
* 加载APP中间件
*/
async loadMiddlewares() {
// $Flow
this.loadMiddlewares = utils.resolved;
// $Flow
const alaska: Alaska$Alaska = this;
const MAIN = this.main;
const { app } = this;
const locales = this.getConfig('locales');
const localeCookieKey = this.getConfig('localeCookieKey');
const localeQueryKey = this.getConfig('localeQueryKey');
const defaultLocale = MAIN.getConfig('defaultLocale');
// $Flow
app.use(async(ctx: Alaska$Context, next) => {
ctx.set('X-Powered-By', 'Alaska');
ctx.alaska = alaska;
ctx.main = MAIN;
ctx.service = MAIN;
ctx.panic = alaska.panic;
ctx.error = alaska.error;
/**
* 发送文件
* @param {string} filePath
* @param {Object} options
*/
ctx.sendfile = async function (filePath, options) {
options = options || {};
let trailingSlash = filePath[filePath.length - 1] === '/';
let { index } = options;
if (index && trailingSlash) filePath += index;
let maxage = options.maxage || options.maxAge || 0;
let hidden = options.hidden || false;
if (!hidden && utils.isHidden(filePath)) return;
let stats;
try {
stats = await utils.statAsync(filePath);
if (stats.isDirectory()) {
if (index) {
filePath += '/' + index;
stats = await utils.statAsync(filePath);
} else {
return;
}
}
} catch (err) {
let notfound = ['ENOENT', 'ENAMETOOLONG', 'ENOTDIR'];
if (notfound.indexOf(err.code) > -1) return;
err.status = 500;
throw err;
}
ctx.set('Last-Modified', stats.mtime.toUTCString());
let lastModified = ctx.headers['if-modified-since'];
if (lastModified) {
try {
let date = new Date(lastModified);
if (date.getTime() === stats.mtime.getTime()) {
ctx.status = 304;
return;
}
} catch (e) {
console.error(e);
}
}
ctx.set('Content-Length', stats.size);
ctx.set('Cache-Control', 'max-age=' + (maxage / 1000 || 0));
ctx.type = options.type || mime.lookup(filePath);
ctx.body = fs.createReadStream(filePath);
};
//toJSON
{
let { toJSON } = ctx;
ctx.toJSON = function () {
let json = toJSON.call(ctx);
json.session = ctx.session || null;
json.state = ctx.state;
json.alaska = ctx.alaska.toJSON();
json.service = ctx.service.toJSON();
return json;
};
}
//切换语言
{
let locale = '';
if (localeQueryKey) {
if (ctx.query[localeQueryKey]) {
locale = ctx.query[localeQueryKey];
if (locales.indexOf(locale) > -1) {
ctx.cookies.set(localeCookieKey, locale, {
maxAge: 365 * 86400 * 1000
});
} else {
locale = '';
}
}
}
if (!locale) {
locale = ctx.cookies.get(localeCookieKey) || '';
}
if (!locale || locales.indexOf(locale) < 0) {
//没有cookie设置
//自动判断
locale = defaultLocale;
let languages = utils.parseAcceptLanguage(ctx.get('accept-language'));
for (let lang of languages) {
if (locales.indexOf(lang) > -1) {
locale = lang;
break;
}
}
}
if (locale) {
ctx.locale = locale;
ctx.state.locale = locale;
}
}
//translate
/**
* 翻译
* @param {string} message 原文
* @param {string} [locale] 目标语言
* @param {Object} [values] 翻译值
* @returns {string} 返回翻译结果
*/
ctx.t = (message, locale, values) => {
if (locale && typeof locale === 'object') {
values = locale;
locale = null;
}
if (!locale) {
// eslint-disable-next-line prefer-destructuring
locale = ctx.locale;
}
return ctx.service.t(message, locale, values);
};
ctx.state.t = ctx.t;
//config
ctx.state.c = (a, b, c) => ctx.service.getConfig(a, b, c);
//env
ctx.state.env = process.env.NODE_ENV || 'production';
/**
* 渲染并显示模板
* @param {string} template 模板文件
* @param {Object} [state] 模板变量
* @returns {Promise<string>} 返回渲染结果
*/
ctx.show = async function (template: string, state?: Object): Promise<string> {
ctx.body = await ctx.service.renderer.renderFile(template, Object.assign({}, ctx.state, state));
return ctx.body;
};
await next();
});
// $Flow
_.map(this.getConfig('middlewares', {}), (item, id) => {
if (!item.id) {
item.id = id;
}
return item;
})
.sort((a, b) => a.sort < b.sort)
.forEach((item: Alaska$Config$middleware) => {
let { id, fn, options } = item;
if (fn && typeof fn.default === 'function') {
fn = fn.default;
}
let name = id || (fn ? fn.name : 'unknown');
debug('middleware', name);
if (!_.isFunction(fn)) {
fn = this.modules.middlewares[id];
if (!fn) {
throw new PanicError(`Middleware '${name}' not found!`);
}
if (_.isObject(fn) && _.isFunction(fn.default)) {
fn = fn.default;
}
}
if (!options) {
options = {};
}
if (id) {
let defaultOptions = this.getConfig(id);
if (_.isObject(defaultOptions)) {
options = utils.merge(_.cloneDeep(defaultOptions), options);
}
}
if (typeof fn === 'function') {
app.use(fn(options));
} else {
throw new PanicError(`Middleware '${name}' is invalid!`);
}
});
}
/**
* 输出Alaska实例JSON调试信息
* @returns {Object}
*/
toJSON(): Object {
return Object.keys(this.services).reduce((res, key) => {
res[key] = this.services[key].toJSON();
return res;
}, {});
}
/**
* 抛出严重错误,并输出调用栈
* @param {string|number|Error} message
* @param {string|number} [code]
*/
panic(message: string | number, code?: number) {
if (!code && typeof message === 'number') {
let msg = statuses[message];
if (msg) {
code = message;
message = msg;
}
}
// $Flow 我们知道message为字符串,但是flow不知道
let error = new PanicError(message);
if (code) {
error.code = code;
}
console.error('Panic ' + error.stack);
throw error;
}
/**
* 抛出普通异常
* @param {string|number|Error} message
* @param {string|number} [code]
*/
error(message: string | number, code?: number) {
if (!code && typeof message === 'number') {
let msg = statuses[message];
if (msg) {
code = message;
message = msg;
}
}
// $Flow 我们知道message为字符串,但是flow不知道
let error = new NormalError(message);
if (code) {
error.code = code;
}
throw error;
}
}
export default new Alaska();
process.on('unhandledRejection', (error) => {
console.error('Unhandled Rejection:', error.stack || error);
let alaska = module.exports.defualt;
if (alaska && alaska.main && alaska.main.getConfig('unhandledRejectionExit') === false) {
return;
}
process.exit(1);
});
exports.utils = utils;
exports.Field = require('./field').default;
exports.Model = require('./model').default;
exports.Sled = require('./sled').default;
exports.Service = require('./service').default;
exports.Renderer = require('./renderer').default;
exports.Driver = require('./driver').default;
| mit |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.