prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>line_echo.rs<|end_file_name|><|fim▁begin|>// notty is a new kind of terminal emulator.
// Copyright (C) 2015 without boats
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
use unicode_width::*;
use Command;
use command::*;
use datatypes::{EchoSettings, Key};
use datatypes::Key::*;
use datatypes::Area::*;
use datatypes::Movement::*;
use datatypes::Direction::*;
pub struct LineEcho {
pub settings: EchoSettings,
position: u32,
len: u32,
}
impl LineEcho {
pub fn new(settings: EchoSettings) -> LineEcho {
LineEcho {
settings: settings,
position: 0,
len: 0,
}
}
pub fn echo(&mut self, key: Key) -> Option<Command> {
match key {
Char(c) if c == self.settings.lerase as char => {
self.len = 0;
wrap(CommandSeries(vec![
Command {
inner: Box::new(Move::new(To(Left, self.position, true)))
as Box<CommandTrait>
},<|fim▁hole|> inner: Box::new(Erase::new(CursorTo(To(Right, self.len, true))))
as Box<CommandTrait>
},
]))
}
Char(c) if c == self.settings.lnext as char => unimplemented!(),
Char(c) if c == self.settings.werase as char => unimplemented!(),
Char(c) if c.width().is_some() => {
self.position += 1;
self.len += 1;
wrap(Put::new_char(c))
}
LeftArrow if self.position != 0 => {
self.position -= 1;
wrap(Move::new(To(Left, 1, true)))
}
RightArrow if self.position != self.len => {
self.position += 1;
wrap(Move::new(To(Right, 1, true)))
}
Enter => {
self.position = 0;
self.len = 0;
wrap(Move::new(NextLine(1)))
}
Backspace if self.position != 0 => {
self.position -= 1;
self.len -= 1;
wrap(CommandSeries(vec![
Command {
inner: Box::new(Move::new(To(Left, 1, false))) as Box<CommandTrait>
},
Command { inner: Box::new(RemoveChars::new(1)) as Box<CommandTrait> },
]))
}
Delete if self.position != self.len => {
self.len -= 1;
wrap(RemoveChars::new(1))
}
Home if self.position != 0 => {
self.position = 0;
wrap(Move::new(To(Left, self.position, true)))
}
End if self.position != self.len => {
let n = self.len - self.position;
self.position = self.len;
wrap(Move::new(To(Right, n, true)))
}
_ => None
}
}
}
fn wrap<T: CommandTrait>(cmd: T) -> Option<Command> {
Some(Command { inner: Box::new(cmd) as Box<CommandTrait> })
}
#[cfg(test)]
mod tests {
use command::*;
use datatypes::EchoSettings;
use datatypes::Key::*;
use datatypes::Area::*;
use datatypes::Movement::*;
use datatypes::Direction::*;
use super::*;
static SETTINGS: EchoSettings = EchoSettings { lerase: 0, lnext: 1, werase: 2 };
#[test]
fn chars() {
let mut echo = LineEcho::new(SETTINGS);
assert_eq!(echo.echo(Char('A')).unwrap().inner.repr(), Put::new_char('A').repr());
assert_eq!(echo.len, 1);
assert_eq!(echo.position, 1);
assert!(echo.echo(Char('\x1b')).is_none());
assert_eq!(echo.len, 1);
assert_eq!(echo.position, 1);
}
#[test]
fn left_arrow() {
let mut echo = LineEcho { settings: SETTINGS, position: 0, len: 0 };
assert!(echo.echo(LeftArrow).is_none());
assert_eq!(echo.len, 0);
assert_eq!(echo.position, 0);
let mut echo = LineEcho { settings: SETTINGS, position: 1, len: 1 };
assert_eq!(echo.echo(LeftArrow).unwrap().inner.repr(), Move::new(To(Left, 1, true)).repr());
assert_eq!(echo.len, 1);
assert_eq!(echo.position, 0);
}
#[test]
fn right_arrow() {
let mut echo = LineEcho { settings: SETTINGS, position: 0, len: 0 };
assert!(echo.echo(RightArrow).is_none());
assert_eq!(echo.len, 0);
assert_eq!(echo.position, 0);
let mut echo = LineEcho { settings: SETTINGS, position: 0, len: 1 };
assert_eq!(echo.echo(RightArrow).unwrap().inner.repr(), Move::new(To(Right, 1, true)).repr());
assert_eq!(echo.len, 1);
assert_eq!(echo.position, 1);
}
#[test]
fn enter() {
let mut echo = LineEcho { settings: SETTINGS, position: 3, len: 3 };
assert_eq!(echo.echo(Enter).unwrap().inner.repr(), Move::new(NextLine(1)).repr());
assert_eq!(echo.len, 0);
assert_eq!(echo.position, 0);
}
#[test]
fn backspace() {
let mut echo = LineEcho { settings: SETTINGS, position: 0, len: 1 };
assert!(echo.echo(Backspace).is_none());
assert_eq!(echo.position, 0);
assert_eq!(echo.len, 1);
let mut echo = LineEcho { settings: SETTINGS, position: 1, len: 1 };
assert!(echo.echo(Backspace).is_some());
assert_eq!(echo.position, 0);
assert_eq!(echo.len, 0);
}
#[test]
fn delete() {
let mut echo = LineEcho { settings: SETTINGS, position: 0, len: 1 };
assert!(echo.echo(Delete).is_some());
assert_eq!(echo.position, 0);
assert_eq!(echo.len, 0);
let mut echo = LineEcho { settings: SETTINGS, position: 1, len: 1 };
assert!(echo.echo(Delete).is_none());
assert_eq!(echo.position, 1);
assert_eq!(echo.len, 1);
}
#[test]
fn home() {
let mut echo = LineEcho { settings: SETTINGS, position: 4, len: 5 };
assert!(echo.echo(Home).is_some());
assert_eq!(echo.position, 0);
assert_eq!(echo.len, 5);
}
#[test]
fn end() {
let mut echo = LineEcho { settings: SETTINGS, position: 4, len: 5 };
assert!(echo.echo(End).is_some());
assert_eq!(echo.position, 5);
assert_eq!(echo.len, 5);
}
}<|fim▁end|> | Command { |
<|file_name|>test_sgpr_regression.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
import os
import random
import unittest
import warnings
from math import exp, pi
import gpytorch
import torch
from gpytorch.distributions import MultivariateNormal
from gpytorch.kernels import InducingPointKernel, RBFKernel, ScaleKernel
from gpytorch.likelihoods import GaussianLikelihood
from gpytorch.means import ConstantMean
from gpytorch.priors import SmoothedBoxPrior
from gpytorch.test.utils import least_used_cuda_device
from gpytorch.utils.warnings import NumericalWarning
from torch import optim
# Simple training data: let's try to learn a sine function,
# but with SGPR
# let's use 100 training examples.
def make_data(cuda=False):
train_x = torch.linspace(0, 1, 100)
train_y = torch.sin(train_x * (2 * pi))
train_y.add_(torch.randn_like(train_y), alpha=1e-2)
test_x = torch.rand(51)
test_y = torch.sin(test_x * (2 * pi))
if cuda:
train_x = train_x.cuda()
train_y = train_y.cuda()
test_x = test_x.cuda()
test_y = test_y.cuda()
return train_x, train_y, test_x, test_y
class GPRegressionModel(gpytorch.models.ExactGP):
def __init__(self, train_x, train_y, likelihood):
super(GPRegressionModel, self).__init__(train_x, train_y, likelihood)
self.mean_module = ConstantMean(prior=SmoothedBoxPrior(-1e-5, 1e-5))
self.base_covar_module = ScaleKernel(RBFKernel(lengthscale_prior=SmoothedBoxPrior(exp(-5), exp(6), sigma=0.1)))
self.covar_module = InducingPointKernel(
self.base_covar_module, inducing_points=torch.linspace(0, 1, 32), likelihood=likelihood
)
def forward(self, x):
mean_x = self.mean_module(x)
covar_x = self.covar_module(x)
return MultivariateNormal(mean_x, covar_x)
class TestSGPRRegression(unittest.TestCase):
def setUp(self):
if os.getenv("UNLOCK_SEED") is None or os.getenv("UNLOCK_SEED").lower() == "false":
self.rng_state = torch.get_rng_state()
torch.manual_seed(0)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(0)
random.seed(0)
def tearDown(self):
if hasattr(self, "rng_state"):
torch.set_rng_state(self.rng_state)
def test_sgpr_mean_abs_error(self):
# Suppress numerical warnings
warnings.simplefilter("ignore", NumericalWarning)
train_x, train_y, test_x, test_y = make_data()
likelihood = GaussianLikelihood()
gp_model = GPRegressionModel(train_x, train_y, likelihood)
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model)
# Optimize the model
gp_model.train()
likelihood.train()
optimizer = optim.Adam(gp_model.parameters(), lr=0.1)
for _ in range(30):
optimizer.zero_grad()
output = gp_model(train_x)
loss = -mll(output, train_y)
loss.backward()
optimizer.step()
for param in gp_model.parameters():
self.assertTrue(param.grad is not None)
self.assertGreater(param.grad.norm().item(), 0)
# Test the model
gp_model.eval()
likelihood.eval()
test_preds = likelihood(gp_model(test_x)).mean
mean_abs_error = torch.mean(torch.abs(test_y - test_preds))
self.assertLess(mean_abs_error.squeeze().item(), 0.05)
def test_sgpr_fast_pred_var(self):
# Suppress numerical warnings<|fim▁hole|>
train_x, train_y, test_x, test_y = make_data()
likelihood = GaussianLikelihood()
gp_model = GPRegressionModel(train_x, train_y, likelihood)
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model)
# Optimize the model
gp_model.train()
likelihood.train()
optimizer = optim.Adam(gp_model.parameters(), lr=0.1)
for _ in range(50):
optimizer.zero_grad()
output = gp_model(train_x)
loss = -mll(output, train_y)
loss.backward()
optimizer.step()
for param in gp_model.parameters():
self.assertTrue(param.grad is not None)
self.assertGreater(param.grad.norm().item(), 0)
# Test the model
gp_model.eval()
likelihood.eval()
with gpytorch.settings.max_preconditioner_size(5), gpytorch.settings.max_cg_iterations(50):
with gpytorch.settings.fast_pred_var(True):
fast_var = gp_model(test_x).variance
fast_var_cache = gp_model(test_x).variance
self.assertLess(torch.max((fast_var_cache - fast_var).abs()), 1e-3)
with gpytorch.settings.fast_pred_var(False):
slow_var = gp_model(test_x).variance
self.assertLess(torch.max((fast_var_cache - slow_var).abs()), 1e-3)
def test_sgpr_mean_abs_error_cuda(self):
# Suppress numerical warnings
warnings.simplefilter("ignore", NumericalWarning)
if not torch.cuda.is_available():
return
with least_used_cuda_device():
train_x, train_y, test_x, test_y = make_data(cuda=True)
likelihood = GaussianLikelihood().cuda()
gp_model = GPRegressionModel(train_x, train_y, likelihood).cuda()
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, gp_model)
# Optimize the model
gp_model.train()
likelihood.train()
optimizer = optim.Adam(gp_model.parameters(), lr=0.1)
optimizer.n_iter = 0
for _ in range(25):
optimizer.zero_grad()
output = gp_model(train_x)
loss = -mll(output, train_y)
loss.backward()
optimizer.n_iter += 1
optimizer.step()
for param in gp_model.parameters():
self.assertTrue(param.grad is not None)
self.assertGreater(param.grad.norm().item(), 0)
# Test the model
gp_model.eval()
likelihood.eval()
test_preds = likelihood(gp_model(test_x)).mean
mean_abs_error = torch.mean(torch.abs(test_y - test_preds))
self.assertLess(mean_abs_error.squeeze().item(), 0.02)
if __name__ == "__main__":
unittest.main()<|fim▁end|> | warnings.simplefilter("ignore", NumericalWarning) |
<|file_name|>filtered_record_array_test.js<|end_file_name|><|fim▁begin|>var Model;
module("Ember.FilteredRecordArray", {
setup: function() {
Model = Ember.Model.extend({
id: Ember.attr(),
name: Ember.attr()
});
Model.adapter = Ember.FixtureAdapter.create();
Model.FIXTURES = [
{id: 1, name: 'Erik'},
{id: 2, name: 'Stefan'},
{id: 'abc', name: 'Charles'}
];
},
teardown: function() { }
});
test("must be created with a modelClass property", function() {
throws(function() {
Ember.FilteredRecordArray.create();
}, /FilteredRecordArrays must be created with a modelClass/);
});
test("must be created with a filterFunction property", function() {
throws(function() {
Ember.FilteredRecordArray.create({modelClass: Model});
}, /FilteredRecordArrays must be created with a filterFunction/);
});
test("must be created with a filterProperties property", function() {
throws(function() {
Ember.FilteredRecordArray.create({modelClass: Model, filterFunction: Ember.K});
}, /FilteredRecordArrays must be created with filterProperties/);
});
test("with a noop filter will return all the loaded records", function() {
expect(1);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: Ember.K,
filterProperties: []
});
equal(recordArray.get('length'), 3, "There are 3 records");
});
<|fim▁hole|>test("with a filter will return only the relevant loaded records", function() {
expect(2);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name') === 'Erik';
},
filterProperties: ['name']
});
equal(recordArray.get('length'), 1, "There is 1 record");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
});
stop();
});
test("loading a record that doesn't match the filter after creating a FilteredRecordArray shouldn't change the content", function() {
expect(2);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name') === 'Erik';
},
filterProperties: ['name']
});
Model.create({id: 3, name: 'Kris'}).save().then(function(record) {
start();
equal(recordArray.get('length'), 1, "There is still 1 record");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
});
stop();
});
stop();
});
test("loading a record that matches the filter after creating a FilteredRecordArray should update the content of it", function() {
expect(3);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name') === 'Erik' || record.get('name') === 'Kris';
},
filterProperties: ['name']
});
Model.create({id: 3, name: 'Kris'}).save().then(function(record) {
start();
equal(recordArray.get('length'), 2, "There are 2 records");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
equal(recordArray.get('lastObject.name'), 'Kris', "The record data matches");
});
stop();
});
stop();
});
test("changing a property that matches the filter should update the FilteredRecordArray to include it", function() {
expect(5);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name').match(/^E/);
},
filterProperties: ['name']
});
equal(recordArray.get('length'), 1, "There is 1 record initially");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
Model.fetch(2).then(function(record) {
start();
record.set('name', 'Estefan');
equal(recordArray.get('length'), 2, "There are 2 records after changing the name");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
equal(recordArray.get('lastObject.name'), 'Estefan', "The record data matches");
});
stop();
});
stop();
});
test("adding a new record and changing a property that matches the filter should update the FilteredRecordArray to include it", function() {
expect(8);
Model.fetch().then(function() {
start();
var recordArray = Ember.FilteredRecordArray.create({
modelClass: Model,
filterFunction: function(record) {
return record.get('name').match(/^E/);
},
filterProperties: ['name']
});
equal(recordArray.get('length'), 1, "There is 1 record initially");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
Model.create({id: 3, name: 'Kris'}).save().then(function(record) {
start();
record.set('name', 'Ekris');
equal(recordArray.get('length'), 2, "There are 2 records after changing the name");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data matches");
equal(recordArray.get('lastObject.name'), 'Ekris', "The record data matches");
record.set('name', 'Eskil');
equal(recordArray.get('length'), 2, "There are still 2 records after changing the name again");
equal(recordArray.get('firstObject.name'), 'Erik', "The record data still matches");
equal(recordArray.get('lastObject.name'), 'Eskil', "The record data still matches");
});
stop();
});
stop();
});<|fim▁end|> | stop();
});
|
<|file_name|>plugin.py<|end_file_name|><|fim▁begin|>import glob, imp
import events
class EventManager:
def __init__(self):
self.Chat_Message_Event = events.ChatMessageEventHandler()
self.Player_Join_Event = events.PlayerJoinEventHandler()
self.Player_Leave_Event = events.PlayerLeaveEventHandler()
self.Player_Move_Event = events.PlayerMoveEventHandler()
self.Command_Event = events.CommandEventHandler()
self.Packet_Recv_Event = events.PacketRecvEventHandler()
class PluginManager:
def __init__(self, server):
self.plugins = {}
self.server = server
<|fim▁hole|> def load_plugins(self):
for plugin in glob.glob("plugins/*_plugin.py"):
plugin_name = plugin[8:-10]
self.plugins[plugin_name] = imp.load_source(plugin_name, plugin)
getattr(self.plugins[plugin_name],plugin_name)(self.server)<|fim▁end|> | |
<|file_name|>roman_numerals.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// force-host
#![crate_type="dylib"]
#![feature(plugin_registrar)]
extern crate syntax;
extern crate rustc;
use syntax::codemap::Span;
use syntax::parse::token;
use syntax::ast::{TokenTree, TtToken};
use syntax::ext::base::{ExtCtxt, MacResult, DummyResult, MacExpr};
use syntax::ext::build::AstBuilder; // trait for expr_usize
use rustc::plugin::Registry;
// WARNING WARNING WARNING WARNING WARNING
// =======================================
//
// This code also appears in src/doc/guide-plugin.md. Please keep
// the two copies in sync! FIXME: have rustdoc read this file
fn expand_rn(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree])
-> Box<MacResult + 'static> {
static NUMERALS: &'static [(&'static str, uint)] = &[
("M", 1000), ("CM", 900), ("D", 500), ("CD", 400),
("C", 100), ("XC", 90), ("L", 50), ("XL", 40),
("X", 10), ("IX", 9), ("V", 5), ("IV", 4),
("I", 1)];
let text = match args {
[TtToken(_, token::Ident(s, _))] => token::get_ident(s).to_string(),
_ => {
cx.span_err(sp, "argument should be a single identifier");
return DummyResult::any(sp);
}
};
let mut text = text.as_slice();
let mut total = 0u;
while !text.is_empty() {
match NUMERALS.iter().find(|&&(rn, _)| text.starts_with(rn)) {
Some(&(rn, val)) => {
total += val;
text = text.slice_from(rn.len());
}
None => {
cx.span_err(sp, "invalid Roman numeral");
return DummyResult::any(sp);
}
}
}
MacExpr::new(cx.expr_usize(sp, total))
}
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("rn", expand_rn);
}<|fim▁end|> | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// |
<|file_name|>user.service.ts<|end_file_name|><|fim▁begin|>export class UserService {
static store(user: any) {
localStorage.setItem('currentUser', user.UserToken);
localStorage.setItem('currentUserDetail', JSON.stringify(user));
}
static token() {
return localStorage.getItem('currentUser');
}
static getUser() {
const data = localStorage.getItem('currentUserDetail');
<|fim▁hole|> if (!data) {
return null;
}
return JSON.parse(data);
}
}<|fim▁end|> | |
<|file_name|>maximum_matching.py<|end_file_name|><|fim▁begin|>"""Weighted maximum matching in general graphs.
The algorithm is taken from "Efficient Algorithms for Finding Maximum
Matching in Graphs" by Zvi Galil, ACM Computing Surveys, 1986.
It is based on the "blossom" method for finding augmenting paths and
the "primal-dual" method for finding a matching of maximum weight, both
due to Jack Edmonds.
Some ideas came from "Implementation of algorithms for maximum matching
on non-bipartite graphs" by H.J. Gabow, Standford Ph.D. thesis, 1973.
A C program for maximum weight matching by Ed Rothberg was used extensively
to validate this new code.
http://jorisvr.nl/article/maximum-matching#ref:4
"""
#
# Changes:
#
# 2013-04-07
# * Added Python 3 compatibility with contributions from Daniel Saunders.
#
# 2008-06-08
# * First release.
#
from __future__ import print_function
# If assigned, DEBUG(str) is called with lots of debug messages.
DEBUG = None
"""def DEBUG(s):
from sys import stderr
print('DEBUG:', s, file=stderr)
"""
# Check delta2/delta3 computation after every substage;
# only works on integer weights, slows down the algorithm to O(n^4).
CHECK_DELTA = False
# Check optimality of solution before returning; only works on integer weights.
CHECK_OPTIMUM = True
def maxWeightMatching(edges, maxcardinality=False):
"""Compute a maximum-weighted matching in the general undirected
weighted graph given by "edges". If "maxcardinality" is true,
only maximum-cardinality matchings are considered as solutions.
Edges is a sequence of tuples (i, j, wt) describing an undirected
edge between vertex i and vertex j with weight wt. There is at most
one edge between any two vertices; no vertex has an edge to itself.
Vertices are identified by consecutive, non-negative integers.
Return a list "mate", such that mate[i] == j if vertex i is
matched to vertex j, and mate[i] == -1 if vertex i is not matched.
This function takes time O(n ** 3)."""
#
# Vertices are numbered 0 .. (nvertex-1).
# Non-trivial blossoms are numbered nvertex .. (2*nvertex-1)
#
# Edges are numbered 0 .. (nedge-1).
# Edge endpoints are numbered 0 .. (2*nedge-1), such that endpoints
# (2*k) and (2*k+1) both belong to edge k.
#
# Many terms used in the comments (sub-blossom, T-vertex) come from
# the paper by Galil; read the paper before reading this code.
#
# Python 2/3 compatibility.
from sys import version as sys_version
if sys_version < '3':
integer_types = (int, long)
else:
integer_types = (int,)
# Deal swiftly with empty graphs.
if not edges:
return [ ]
# Count vertices.
nedge = len(edges)
nvertex = 0
for (i, j, w) in edges:
assert i >= 0 and j >= 0 and i != j
if i >= nvertex:
nvertex = i + 1
if j >= nvertex:
nvertex = j + 1
# Find the maximum edge weight.
maxweight = max(0, max([ wt for (i, j, wt) in edges ]))
# If p is an edge endpoint,
# endpoint[p] is the vertex to which endpoint p is attached.
# Not modified by the algorithm.
endpoint = [ edges[p//2][p%2] for p in range(2*nedge) ]
# If v is a vertex,
# neighbend[v] is the list of remote endpoints of the edges attached to v.
# Not modified by the algorithm.
neighbend = [ [ ] for i in range(nvertex) ]
for k in range(len(edges)):
(i, j, w) = edges[k]
neighbend[i].append(2*k+1)
neighbend[j].append(2*k)
# If v is a vertex,
# mate[v] is the remote endpoint of its matched edge, or -1 if it is single
# (i.e. endpoint[mate[v]] is v's partner vertex).
# Initially all vertices are single; updated during augmentation.
mate = nvertex * [ -1 ]
# If b is a top-level blossom,
# label[b] is 0 if b is unlabeled (free);
# 1 if b is an S-vertex/blossom;
# 2 if b is a T-vertex/blossom.
# The label of a vertex is found by looking at the label of its
# top-level containing blossom.
# If v is a vertex inside a T-blossom,
# label[v] is 2 iff v is reachable from an S-vertex outside the blossom.
# Labels are assigned during a stage and reset after each augmentation.
label = (2 * nvertex) * [ 0 ]
# If b is a labeled top-level blossom,
# labelend[b] is the remote endpoint of the edge through which b obtained
# its label, or -1 if b's base vertex is single.
# If v is a vertex inside a T-blossom and label[v] == 2,
# labelend[v] is the remote endpoint of the edge through which v is
# reachable from outside the blossom.
labelend = (2 * nvertex) * [ -1 ]
# If v is a vertex,
# inblossom[v] is the top-level blossom to which v belongs.
# If v is a top-level vertex, v is itself a blossom (a trivial blossom)
# and inblossom[v] == v.
# Initially all vertices are top-level trivial blossoms.
inblossom = list(range(nvertex))
# If b is a sub-blossom,
# blossomparent[b] is its immediate parent (sub-)blossom.
# If b is a top-level blossom, blossomparent[b] is -1.
blossomparent = (2 * nvertex) * [ -1 ]
# If b is a non-trivial (sub-)blossom,
# blossomchilds[b] is an ordered list of its sub-blossoms, starting with
# the base and going round the blossom.
blossomchilds = (2 * nvertex) * [ None ]
# If b is a (sub-)blossom,
# blossombase[b] is its base VERTEX (i.e. recursive sub-blossom).
blossombase = list(range(nvertex)) + nvertex * [ -1 ]
# If b is a non-trivial (sub-)blossom,
# blossomendps[b] is a list of endpoints on its connecting edges,
# such that blossomendps[b][i] is the local endpoint of blossomchilds[b][i]
# on the edge that connects it to blossomchilds[b][wrap(i+1)].
blossomendps = (2 * nvertex) * [ None ]
# If v is a free vertex (or an unreached vertex inside a T-blossom),
# bestedge[v] is the edge to an S-vertex with least slack,
# or -1 if there is no such edge.
# If b is a (possibly trivial) top-level S-blossom,
# bestedge[b] is the least-slack edge to a different S-blossom,
# or -1 if there is no such edge.
# This is used for efficient computation of delta2 and delta3.
bestedge = (2 * nvertex) * [ -1 ]
# If b is a non-trivial top-level S-blossom,
# blossombestedges[b] is a list of least-slack edges to neighbouring
# S-blossoms, or None if no such list has been computed yet.
# This is used for efficient computation of delta3.
blossombestedges = (2 * nvertex) * [ None ]
# List of currently unused blossom numbers.
unusedblossoms = list(range(nvertex, 2*nvertex))
# If v is a vertex,
# dualvar[v] = 2 * u(v) where u(v) is the v's variable in the dual
# optimization problem (multiplication by two ensures integer values
# throughout the algorithm if all edge weights are integers).
# If b is a non-trivial blossom,
# dualvar[b] = z(b) where z(b) is b's variable in the dual optimization
# problem.
dualvar = nvertex * [ maxweight ] + nvertex * [ 0 ]
# If allowedge[k] is true, edge k has zero slack in the optimization
# problem; if allowedge[k] is false, the edge's slack may or may not
# be zero.
allowedge = nedge * [ False ]
# Queue of newly discovered S-vertices.
queue = [ ]
# Return 2 * slack of edge k (does not work inside blossoms).
def slack(k):
(i, j, wt) = edges[k]
return dualvar[i] + dualvar[j] - 2 * wt
# Generate the leaf vertices of a blossom.
def blossomLeaves(b):
if b < nvertex:
yield b
else:
for t in blossomchilds[b]:
if t < nvertex:
yield t
else:
for v in blossomLeaves(t):
yield v
# Assign label t to the top-level blossom containing vertex w
# and record the fact that w was reached through the edge with
# remote endpoint p.
def assignLabel(w, t, p):
if DEBUG: DEBUG('assignLabel(%d,%d,%d)' % (w, t, p))
b = inblossom[w]
assert label[w] == 0 and label[b] == 0
label[w] = label[b] = t
labelend[w] = labelend[b] = p
bestedge[w] = bestedge[b] = -1
if t == 1:
# b became an S-vertex/blossom; add it(s vertices) to the queue.
queue.extend(blossomLeaves(b))
if DEBUG: DEBUG('PUSH ' + str(list(blossomLeaves(b))))
elif t == 2:
# b became a T-vertex/blossom; assign label S to its mate.
# (If b is a non-trivial blossom, its base is the only vertex
# with an external mate.)
base = blossombase[b]
assert mate[base] >= 0
assignLabel(endpoint[mate[base]], 1, mate[base] ^ 1)
# Trace back from vertices v and w to discover either a new blossom
# or an augmenting path. Return the base vertex of the new blossom or -1.
def scanBlossom(v, w):
if DEBUG: DEBUG('scanBlossom(%d,%d)' % (v, w))
# Trace back from v and w, placing breadcrumbs as we go.
path = [ ]
base = -1
while v != -1 or w != -1:
# Look for a breadcrumb in v's blossom or put a new breadcrumb.
b = inblossom[v]
if label[b] & 4:
base = blossombase[b]
break
assert label[b] == 1
path.append(b)
label[b] = 5
# Trace one step back.
assert labelend[b] == mate[blossombase[b]]
if labelend[b] == -1:
# The base of blossom b is single; stop tracing this path.
v = -1
else:
v = endpoint[labelend[b]]
b = inblossom[v]
assert label[b] == 2
# b is a T-blossom; trace one more step back.
assert labelend[b] >= 0
v = endpoint[labelend[b]]
# Swap v and w so that we alternate between both paths.
if w != -1:
v, w = w, v
# Remove breadcrumbs.
for b in path:
label[b] = 1
# Return base vertex, if we found one.
return base
# Construct a new blossom with given base, containing edge k which
# connects a pair of S vertices. Label the new blossom as S; set its dual
# variable to zero; relabel its T-vertices to S and add them to the queue.
def addBlossom(base, k):
(v, w, wt) = edges[k]
bb = inblossom[base]
bv = inblossom[v]
bw = inblossom[w]
# Create blossom.
b = unusedblossoms.pop()
if DEBUG: DEBUG('addBlossom(%d,%d) (v=%d w=%d) -> %d' % (base, k, v, w, b))
blossombase[b] = base
blossomparent[b] = -1
blossomparent[bb] = b
# Make list of sub-blossoms and their interconnecting edge endpoints.
blossomchilds[b] = path = [ ]
blossomendps[b] = endps = [ ]
# Trace back from v to base.
while bv != bb:
# Add bv to the new blossom.
blossomparent[bv] = b
path.append(bv)
endps.append(labelend[bv])
assert (label[bv] == 2 or
(label[bv] == 1 and labelend[bv] == mate[blossombase[bv]]))
# Trace one step back.
assert labelend[bv] >= 0
v = endpoint[labelend[bv]]
bv = inblossom[v]
# Reverse lists, add endpoint that connects the pair of S vertices.
path.append(bb)
path.reverse()
endps.reverse()
endps.append(2*k)
# Trace back from w to base.
while bw != bb:
# Add bw to the new blossom.
blossomparent[bw] = b
path.append(bw)
endps.append(labelend[bw] ^ 1)
assert (label[bw] == 2 or
(label[bw] == 1 and labelend[bw] == mate[blossombase[bw]]))
# Trace one step back.
assert labelend[bw] >= 0
w = endpoint[labelend[bw]]
bw = inblossom[w]
# Set label to S.
assert label[bb] == 1
label[b] = 1
labelend[b] = labelend[bb]
# Set dual variable to zero.
dualvar[b] = 0
# Relabel vertices.
for v in blossomLeaves(b):
if label[inblossom[v]] == 2:
# This T-vertex now turns into an S-vertex because it becomes
# part of an S-blossom; add it to the queue.
queue.append(v)
inblossom[v] = b
# Compute blossombestedges[b].
bestedgeto = (2 * nvertex) * [ -1 ]
for bv in path:
if blossombestedges[bv] is None:
# This subblossom does not have a list of least-slack edges;
# get the information from the vertices.
nblists = [ [ p // 2 for p in neighbend[v] ]
for v in blossomLeaves(bv) ]
else:
# Walk this subblossom's least-slack edges.
nblists = [ blossombestedges[bv] ]
for nblist in nblists:
for k in nblist:
(i, j, wt) = edges[k]
if inblossom[j] == b:
i, j = j, i
bj = inblossom[j]
if (bj != b and label[bj] == 1 and
(bestedgeto[bj] == -1 or
slack(k) < slack(bestedgeto[bj]))):
bestedgeto[bj] = k
# Forget about least-slack edges of the subblossom.
blossombestedges[bv] = None
bestedge[bv] = -1
blossombestedges[b] = [ k for k in bestedgeto if k != -1 ]
# Select bestedge[b].
bestedge[b] = -1
for k in blossombestedges[b]:
if bestedge[b] == -1 or slack(k) < slack(bestedge[b]):
bestedge[b] = k
if DEBUG: DEBUG('blossomchilds[%d]=' % b + repr(blossomchilds[b]))
# Expand the given top-level blossom.
def expandBlossom(b, endstage):
if DEBUG: DEBUG('expandBlossom(%d,%d) %s' % (b, endstage, repr(blossomchilds[b])))
# Convert sub-blossoms into top-level blossoms.
for s in blossomchilds[b]:
blossomparent[s] = -1
if s < nvertex:
inblossom[s] = s
elif endstage and dualvar[s] == 0:
# Recursively expand this sub-blossom.<|fim▁hole|> else:
for v in blossomLeaves(s):
inblossom[v] = s
# If we expand a T-blossom during a stage, its sub-blossoms must be
# relabeled.
if (not endstage) and label[b] == 2:
# Start at the sub-blossom through which the expanding
# blossom obtained its label, and relabel sub-blossoms untili
# we reach the base.
# Figure out through which sub-blossom the expanding blossom
# obtained its label initially.
assert labelend[b] >= 0
entrychild = inblossom[endpoint[labelend[b] ^ 1]]
# Decide in which direction we will go round the blossom.
j = blossomchilds[b].index(entrychild)
if j & 1:
# Start index is odd; go forward and wrap.
j -= len(blossomchilds[b])
jstep = 1
endptrick = 0
else:
# Start index is even; go backward.
jstep = -1
endptrick = 1
# Move along the blossom until we get to the base.
p = labelend[b]
while j != 0:
# Relabel the T-sub-blossom.
label[endpoint[p ^ 1]] = 0
label[endpoint[blossomendps[b][j-endptrick]^endptrick^1]] = 0
assignLabel(endpoint[p ^ 1], 2, p)
# Step to the next S-sub-blossom and note its forward endpoint.
allowedge[blossomendps[b][j-endptrick]//2] = True
j += jstep
p = blossomendps[b][j-endptrick] ^ endptrick
# Step to the next T-sub-blossom.
allowedge[p//2] = True
j += jstep
# Relabel the base T-sub-blossom WITHOUT stepping through to
# its mate (so don't call assignLabel).
bv = blossomchilds[b][j]
label[endpoint[p ^ 1]] = label[bv] = 2
labelend[endpoint[p ^ 1]] = labelend[bv] = p
bestedge[bv] = -1
# Continue along the blossom until we get back to entrychild.
j += jstep
while blossomchilds[b][j] != entrychild:
# Examine the vertices of the sub-blossom to see whether
# it is reachable from a neighbouring S-vertex outside the
# expanding blossom.
bv = blossomchilds[b][j]
if label[bv] == 1:
# This sub-blossom just got label S through one of its
# neighbours; leave it.
j += jstep
continue
for v in blossomLeaves(bv):
if label[v] != 0:
break
# If the sub-blossom contains a reachable vertex, assign
# label T to the sub-blossom.
if label[v] != 0:
assert label[v] == 2
assert inblossom[v] == bv
label[v] = 0
label[endpoint[mate[blossombase[bv]]]] = 0
assignLabel(v, 2, labelend[v])
j += jstep
# Recycle the blossom number.
label[b] = labelend[b] = -1
blossomchilds[b] = blossomendps[b] = None
blossombase[b] = -1
blossombestedges[b] = None
bestedge[b] = -1
unusedblossoms.append(b)
# Swap matched/unmatched edges over an alternating path through blossom b
# between vertex v and the base vertex. Keep blossom bookkeeping consistent.
def augmentBlossom(b, v):
if DEBUG: DEBUG('augmentBlossom(%d,%d)' % (b, v))
# Bubble up through the blossom tree from vertex v to an immediate
# sub-blossom of b.
t = v
while blossomparent[t] != b:
t = blossomparent[t]
# Recursively deal with the first sub-blossom.
if t >= nvertex:
augmentBlossom(t, v)
# Decide in which direction we will go round the blossom.
i = j = blossomchilds[b].index(t)
if i & 1:
# Start index is odd; go forward and wrap.
j -= len(blossomchilds[b])
jstep = 1
endptrick = 0
else:
# Start index is even; go backward.
jstep = -1
endptrick = 1
# Move along the blossom until we get to the base.
while j != 0:
# Step to the next sub-blossom and augment it recursively.
j += jstep
t = blossomchilds[b][j]
p = blossomendps[b][j-endptrick] ^ endptrick
if t >= nvertex:
augmentBlossom(t, endpoint[p])
# Step to the next sub-blossom and augment it recursively.
j += jstep
t = blossomchilds[b][j]
if t >= nvertex:
augmentBlossom(t, endpoint[p ^ 1])
# Match the edge connecting those sub-blossoms.
mate[endpoint[p]] = p ^ 1
mate[endpoint[p ^ 1]] = p
if DEBUG: DEBUG('PAIR %d %d (k=%d)' % (endpoint[p], endpoint[p^1], p//2))
# Rotate the list of sub-blossoms to put the new base at the front.
blossomchilds[b] = blossomchilds[b][i:] + blossomchilds[b][:i]
blossomendps[b] = blossomendps[b][i:] + blossomendps[b][:i]
blossombase[b] = blossombase[blossomchilds[b][0]]
assert blossombase[b] == v
# Swap matched/unmatched edges over an alternating path between two
# single vertices. The augmenting path runs through edge k, which
# connects a pair of S vertices.
def augmentMatching(k):
(v, w, wt) = edges[k]
if DEBUG: DEBUG('augmentMatching(%d) (v=%d w=%d)' % (k, v, w))
if DEBUG: DEBUG('PAIR %d %d (k=%d)' % (v, w, k))
for (s, p) in ((v, 2*k+1), (w, 2*k)):
# Match vertex s to remote endpoint p. Then trace back from s
# until we find a single vertex, swapping matched and unmatched
# edges as we go.
while 1:
bs = inblossom[s]
assert label[bs] == 1
assert labelend[bs] == mate[blossombase[bs]]
# Augment through the S-blossom from s to base.
if bs >= nvertex:
augmentBlossom(bs, s)
# Update mate[s]
mate[s] = p
# Trace one step back.
if labelend[bs] == -1:
# Reached single vertex; stop.
break
t = endpoint[labelend[bs]]
bt = inblossom[t]
assert label[bt] == 2
# Trace one step back.
assert labelend[bt] >= 0
s = endpoint[labelend[bt]]
j = endpoint[labelend[bt] ^ 1]
# Augment through the T-blossom from j to base.
assert blossombase[bt] == t
if bt >= nvertex:
augmentBlossom(bt, j)
# Update mate[j]
mate[j] = labelend[bt]
# Keep the opposite endpoint;
# it will be assigned to mate[s] in the next step.
p = labelend[bt] ^ 1
if DEBUG: DEBUG('PAIR %d %d (k=%d)' % (s, t, p//2))
# Verify that the optimum solution has been reached.
def verifyOptimum():
if maxcardinality:
# Vertices may have negative dual;
# find a constant non-negative number to add to all vertex duals.
vdualoffset = max(0, -min(dualvar[:nvertex]))
else:
vdualoffset = 0
# 0. all dual variables are non-negative
assert min(dualvar[:nvertex]) + vdualoffset >= 0
assert min(dualvar[nvertex:]) >= 0
# 0. all edges have non-negative slack and
# 1. all matched edges have zero slack;
for k in range(nedge):
(i, j, wt) = edges[k]
s = dualvar[i] + dualvar[j] - 2 * wt
iblossoms = [ i ]
jblossoms = [ j ]
while blossomparent[iblossoms[-1]] != -1:
iblossoms.append(blossomparent[iblossoms[-1]])
while blossomparent[jblossoms[-1]] != -1:
jblossoms.append(blossomparent[jblossoms[-1]])
iblossoms.reverse()
jblossoms.reverse()
for (bi, bj) in zip(iblossoms, jblossoms):
if bi != bj:
break
s += 2 * dualvar[bi]
assert s >= 0
if mate[i] // 2 == k or mate[j] // 2 == k:
assert mate[i] // 2 == k and mate[j] // 2 == k
assert s == 0
# 2. all single vertices have zero dual value;
for v in range(nvertex):
assert mate[v] >= 0 or dualvar[v] + vdualoffset == 0
# 3. all blossoms with positive dual value are full.
for b in range(nvertex, 2*nvertex):
if blossombase[b] >= 0 and dualvar[b] > 0:
assert len(blossomendps[b]) % 2 == 1
for p in blossomendps[b][1::2]:
assert mate[endpoint[p]] == p ^ 1
assert mate[endpoint[p ^ 1]] == p
# Ok.
# Check optimized delta2 against a trivial computation.
def checkDelta2():
for v in range(nvertex):
if label[inblossom[v]] == 0:
bd = None
bk = -1
for p in neighbend[v]:
k = p // 2
w = endpoint[p]
if label[inblossom[w]] == 1:
d = slack(k)
if bk == -1 or d < bd:
bk = k
bd = d
if DEBUG and (bestedge[v] != -1 or bk != -1) and (bestedge[v] == -1 or bd != slack(bestedge[v])):
DEBUG('v=' + str(v) + ' bk=' + str(bk) + ' bd=' + str(bd) + ' bestedge=' + str(bestedge[v]) + ' slack=' + str(slack(bestedge[v])))
assert (bk == -1 and bestedge[v] == -1) or (bestedge[v] != -1 and bd == slack(bestedge[v]))
# Check optimized delta3 against a trivial computation.
def checkDelta3():
bk = -1
bd = None
tbk = -1
tbd = None
for b in range(2 * nvertex):
if blossomparent[b] == -1 and label[b] == 1:
for v in blossomLeaves(b):
for p in neighbend[v]:
k = p // 2
w = endpoint[p]
if inblossom[w] != b and label[inblossom[w]] == 1:
d = slack(k)
if bk == -1 or d < bd:
bk = k
bd = d
if bestedge[b] != -1:
(i, j, wt) = edges[bestedge[b]]
assert inblossom[i] == b or inblossom[j] == b
assert inblossom[i] != b or inblossom[j] != b
assert label[inblossom[i]] == 1 and label[inblossom[j]] == 1
if tbk == -1 or slack(bestedge[b]) < tbd:
tbk = bestedge[b]
tbd = slack(bestedge[b])
if DEBUG and bd != tbd:
DEBUG('bk=%d tbk=%d bd=%s tbd=%s' % (bk, tbk, repr(bd), repr(tbd)))
assert bd == tbd
# Main loop: continue until no further improvement is possible.
for t in range(nvertex):
# Each iteration of this loop is a "stage".
# A stage finds an augmenting path and uses that to improve
# the matching.
if DEBUG: DEBUG('STAGE %d' % t)
# Remove labels from top-level blossoms/vertices.
label[:] = (2 * nvertex) * [ 0 ]
# Forget all about least-slack edges.
bestedge[:] = (2 * nvertex) * [ -1 ]
blossombestedges[nvertex:] = nvertex * [ None ]
# Loss of labeling means that we can not be sure that currently
# allowable edges remain allowable througout this stage.
allowedge[:] = nedge * [ False ]
# Make queue empty.
queue[:] = [ ]
# Label single blossoms/vertices with S and put them in the queue.
for v in range(nvertex):
if mate[v] == -1 and label[inblossom[v]] == 0:
assignLabel(v, 1, -1)
# Loop until we succeed in augmenting the matching.
augmented = 0
while 1:
# Each iteration of this loop is a "substage".
# A substage tries to find an augmenting path;
# if found, the path is used to improve the matching and
# the stage ends. If there is no augmenting path, the
# primal-dual method is used to pump some slack out of
# the dual variables.
if DEBUG: DEBUG('SUBSTAGE')
# Continue labeling until all vertices which are reachable
# through an alternating path have got a label.
while queue and not augmented:
# Take an S vertex from the queue.
v = queue.pop()
if DEBUG: DEBUG('POP v=%d' % v)
assert label[inblossom[v]] == 1
# Scan its neighbours:
for p in neighbend[v]:
k = p // 2
w = endpoint[p]
# w is a neighbour to v
if inblossom[v] == inblossom[w]:
# this edge is internal to a blossom; ignore it
continue
if not allowedge[k]:
kslack = slack(k)
if kslack <= 0:
# edge k has zero slack => it is allowable
allowedge[k] = True
if allowedge[k]:
if label[inblossom[w]] == 0:
# (C1) w is a free vertex;
# label w with T and label its mate with S (R12).
assignLabel(w, 2, p ^ 1)
elif label[inblossom[w]] == 1:
# (C2) w is an S-vertex (not in the same blossom);
# follow back-links to discover either an
# augmenting path or a new blossom.
base = scanBlossom(v, w)
if base >= 0:
# Found a new blossom; add it to the blossom
# bookkeeping and turn it into an S-blossom.
addBlossom(base, k)
else:
# Found an augmenting path; augment the
# matching and end this stage.
augmentMatching(k)
augmented = 1
break
elif label[w] == 0:
# w is inside a T-blossom, but w itself has not
# yet been reached from outside the blossom;
# mark it as reached (we need this to relabel
# during T-blossom expansion).
assert label[inblossom[w]] == 2
label[w] = 2
labelend[w] = p ^ 1
elif label[inblossom[w]] == 1:
# keep track of the least-slack non-allowable edge to
# a different S-blossom.
b = inblossom[v]
if bestedge[b] == -1 or kslack < slack(bestedge[b]):
bestedge[b] = k
elif label[w] == 0:
# w is a free vertex (or an unreached vertex inside
# a T-blossom) but we can not reach it yet;
# keep track of the least-slack edge that reaches w.
if bestedge[w] == -1 or kslack < slack(bestedge[w]):
bestedge[w] = k
if augmented:
break
# There is no augmenting path under these constraints;
# compute delta and reduce slack in the optimization problem.
# (Note that our vertex dual variables, edge slacks and delta's
# are pre-multiplied by two.)
deltatype = -1
delta = deltaedge = deltablossom = None
# Verify data structures for delta2/delta3 computation.
if CHECK_DELTA:
checkDelta2()
checkDelta3()
# Compute delta1: the minumum value of any vertex dual.
if not maxcardinality:
deltatype = 1
delta = min(dualvar[:nvertex])
# Compute delta2: the minimum slack on any edge between
# an S-vertex and a free vertex.
for v in range(nvertex):
if label[inblossom[v]] == 0 and bestedge[v] != -1:
d = slack(bestedge[v])
if deltatype == -1 or d < delta:
delta = d
deltatype = 2
deltaedge = bestedge[v]
# Compute delta3: half the minimum slack on any edge between
# a pair of S-blossoms.
for b in range(2 * nvertex):
if ( blossomparent[b] == -1 and label[b] == 1 and
bestedge[b] != -1 ):
kslack = slack(bestedge[b])
if isinstance(kslack, integer_types):
assert (kslack % 2) == 0
d = kslack // 2
else:
d = kslack / 2
if deltatype == -1 or d < delta:
delta = d
deltatype = 3
deltaedge = bestedge[b]
# Compute delta4: minimum z variable of any T-blossom.
for b in range(nvertex, 2*nvertex):
if ( blossombase[b] >= 0 and blossomparent[b] == -1 and
label[b] == 2 and
(deltatype == -1 or dualvar[b] < delta) ):
delta = dualvar[b]
deltatype = 4
deltablossom = b
if deltatype == -1:
# No further improvement possible; max-cardinality optimum
# reached. Do a final delta update to make the optimum
# verifyable.
assert maxcardinality
deltatype = 1
delta = max(0, min(dualvar[:nvertex]))
# Update dual variables according to delta.
for v in range(nvertex):
if label[inblossom[v]] == 1:
# S-vertex: 2*u = 2*u - 2*delta
dualvar[v] -= delta
elif label[inblossom[v]] == 2:
# T-vertex: 2*u = 2*u + 2*delta
dualvar[v] += delta
for b in range(nvertex, 2*nvertex):
if blossombase[b] >= 0 and blossomparent[b] == -1:
if label[b] == 1:
# top-level S-blossom: z = z + 2*delta
dualvar[b] += delta
elif label[b] == 2:
# top-level T-blossom: z = z - 2*delta
dualvar[b] -= delta
# Take action at the point where minimum delta occurred.
if DEBUG: DEBUG('delta%d=%f' % (deltatype, delta))
if deltatype == 1:
# No further improvement possible; optimum reached.
break
elif deltatype == 2:
# Use the least-slack edge to continue the search.
allowedge[deltaedge] = True
(i, j, wt) = edges[deltaedge]
if label[inblossom[i]] == 0:
i, j = j, i
assert label[inblossom[i]] == 1
queue.append(i)
elif deltatype == 3:
# Use the least-slack edge to continue the search.
allowedge[deltaedge] = True
(i, j, wt) = edges[deltaedge]
assert label[inblossom[i]] == 1
queue.append(i)
elif deltatype == 4:
# Expand the least-z blossom.
expandBlossom(deltablossom, False)
# End of a this substage.
# Stop when no more augmenting path can be found.
if not augmented:
break
# End of a stage; expand all S-blossoms which have dualvar = 0.
for b in range(nvertex, 2*nvertex):
if ( blossomparent[b] == -1 and blossombase[b] >= 0 and
label[b] == 1 and dualvar[b] == 0 ):
expandBlossom(b, True)
# Verify that we reached the optimum solution.
if CHECK_OPTIMUM:
verifyOptimum()
# Transform mate[] such that mate[v] is the vertex to which v is paired.
for v in range(nvertex):
if mate[v] >= 0:
mate[v] = endpoint[mate[v]]
for v in range(nvertex):
assert mate[v] == -1 or mate[mate[v]] == v
return mate<|fim▁end|> | expandBlossom(s, endstage) |
<|file_name|>list_volume_groups_request_response.go<|end_file_name|><|fim▁begin|>// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved.
// This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
// Code generated. DO NOT EDIT.
package core
import (
"k8s.io/autoscaler/cluster-autoscaler/cloudprovider/oci/oci-go-sdk/v43/common"
"net/http"
)
// ListVolumeGroupsRequest wrapper for the ListVolumeGroups operation
//
// See also
//
// Click https://docs.cloud.oracle.com/en-us/iaas/tools/go-sdk-examples/latest/core/ListVolumeGroups.go.html to see an example of how to use ListVolumeGroupsRequest.
type ListVolumeGroupsRequest struct {
// The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the compartment.
CompartmentId *string `mandatory:"true" contributesTo:"query" name:"compartmentId"`
// The name of the availability domain.
// Example: `Uocm:PHX-AD-1`
AvailabilityDomain *string `mandatory:"false" contributesTo:"query" name:"availabilityDomain"`
// For list pagination. The maximum number of results per page, or items to return in a paginated
// "List" call. For important details about how pagination works, see
// List Pagination (https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine).
// Example: `50`
Limit *int `mandatory:"false" contributesTo:"query" name:"limit"`
// For list pagination. The value of the `opc-next-page` response header from the previous "List"
// call. For important details about how pagination works, see
// List Pagination (https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine).
Page *string `mandatory:"false" contributesTo:"query" name:"page"`
// A filter to return only resources that match the given display name exactly.
DisplayName *string `mandatory:"false" contributesTo:"query" name:"displayName"`
// The field to sort by. You can provide one sort order (`sortOrder`). Default order for
// TIMECREATED is descending. Default order for DISPLAYNAME is ascending. The DISPLAYNAME
// sort order is case sensitive.
// **Note:** In general, some "List" operations (for example, `ListInstances`) let you
// optionally filter by availability domain if the scope of the resource type is within a
// single availability domain. If you call one of these "List" operations without specifying
// an availability domain, the resources are grouped by availability domain, then sorted.
SortBy ListVolumeGroupsSortByEnum `mandatory:"false" contributesTo:"query" name:"sortBy" omitEmpty:"true"`
// The sort order to use, either ascending (`ASC`) or descending (`DESC`). The DISPLAYNAME sort order
// is case sensitive.
SortOrder ListVolumeGroupsSortOrderEnum `mandatory:"false" contributesTo:"query" name:"sortOrder" omitEmpty:"true"`
// A filter to only return resources that match the given lifecycle
// state. The state value is case-insensitive.
LifecycleState VolumeGroupLifecycleStateEnum `mandatory:"false" contributesTo:"query" name:"lifecycleState" omitEmpty:"true"`
// Unique Oracle-assigned identifier for the request.
// If you need to contact Oracle about a particular request, please provide the request ID.
OpcRequestId *string `mandatory:"false" contributesTo:"header" name:"opc-request-id"`
// Metadata about the request. This information will not be transmitted to the service, but
// represents information that the SDK will consume to drive retry behavior.
RequestMetadata common.RequestMetadata
}
func (request ListVolumeGroupsRequest) String() string {
return common.PointerString(request)
}
// HTTPRequest implements the OCIRequest interface
func (request ListVolumeGroupsRequest) HTTPRequest(method, path string, binaryRequestBody *common.OCIReadSeekCloser) (http.Request, error) {
return common.MakeDefaultHTTPRequestWithTaggedStruct(method, path, request)
}
// BinaryRequestBody implements the OCIRequest interface
func (request ListVolumeGroupsRequest) BinaryRequestBody() (*common.OCIReadSeekCloser, bool) {
return nil, false
}
// RetryPolicy implements the OCIRetryableRequest interface. This retrieves the specified retry policy.
func (request ListVolumeGroupsRequest) RetryPolicy() *common.RetryPolicy {
return request.RequestMetadata.RetryPolicy
}
// ListVolumeGroupsResponse wrapper for the ListVolumeGroups operation
type ListVolumeGroupsResponse struct {
// The underlying http response
RawResponse *http.Response
// A list of []VolumeGroup instances<|fim▁hole|> // List Pagination (https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine).
OpcNextPage *string `presentIn:"header" name:"opc-next-page"`
// Unique Oracle-assigned identifier for the request. If you need to contact
// Oracle about a particular request, please provide the request ID.
OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
func (response ListVolumeGroupsResponse) String() string {
return common.PointerString(response)
}
// HTTPResponse implements the OCIResponse interface
func (response ListVolumeGroupsResponse) HTTPResponse() *http.Response {
return response.RawResponse
}
// ListVolumeGroupsSortByEnum Enum with underlying type: string
type ListVolumeGroupsSortByEnum string
// Set of constants representing the allowable values for ListVolumeGroupsSortByEnum
const (
ListVolumeGroupsSortByTimecreated ListVolumeGroupsSortByEnum = "TIMECREATED"
ListVolumeGroupsSortByDisplayname ListVolumeGroupsSortByEnum = "DISPLAYNAME"
)
var mappingListVolumeGroupsSortBy = map[string]ListVolumeGroupsSortByEnum{
"TIMECREATED": ListVolumeGroupsSortByTimecreated,
"DISPLAYNAME": ListVolumeGroupsSortByDisplayname,
}
// GetListVolumeGroupsSortByEnumValues Enumerates the set of values for ListVolumeGroupsSortByEnum
func GetListVolumeGroupsSortByEnumValues() []ListVolumeGroupsSortByEnum {
values := make([]ListVolumeGroupsSortByEnum, 0)
for _, v := range mappingListVolumeGroupsSortBy {
values = append(values, v)
}
return values
}
// ListVolumeGroupsSortOrderEnum Enum with underlying type: string
type ListVolumeGroupsSortOrderEnum string
// Set of constants representing the allowable values for ListVolumeGroupsSortOrderEnum
const (
ListVolumeGroupsSortOrderAsc ListVolumeGroupsSortOrderEnum = "ASC"
ListVolumeGroupsSortOrderDesc ListVolumeGroupsSortOrderEnum = "DESC"
)
var mappingListVolumeGroupsSortOrder = map[string]ListVolumeGroupsSortOrderEnum{
"ASC": ListVolumeGroupsSortOrderAsc,
"DESC": ListVolumeGroupsSortOrderDesc,
}
// GetListVolumeGroupsSortOrderEnumValues Enumerates the set of values for ListVolumeGroupsSortOrderEnum
func GetListVolumeGroupsSortOrderEnumValues() []ListVolumeGroupsSortOrderEnum {
values := make([]ListVolumeGroupsSortOrderEnum, 0)
for _, v := range mappingListVolumeGroupsSortOrder {
values = append(values, v)
}
return values
}<|fim▁end|> | Items []VolumeGroup `presentIn:"body"`
// For list pagination. When this header appears in the response, additional pages
// of results remain. For important details about how pagination works, see |
<|file_name|>runner.py<|end_file_name|><|fim▁begin|>"""
Run hugs pipeline.
"""
from __future__ import division, print_function
import os, shutil
from time import time
import mpi4py.MPI as MPI
import schwimmbad
from hugs.pipeline import next_gen_search, find_lsbgs
from hugs.utils import PatchMeta
import hugs
def ingest_data(args):
"""
Write data to database with the master process.
"""
timer = time()
success, sources, meta_data, synth_ids = args
run_name, tract, patch, patch_meta = meta_data
db_ingest = hugs.database.HugsIngest(session, run_name)
if success:
db_ingest.add_all(tract, patch, patch_meta, sources)
if synth_ids is not None:
db_ingest.add_injected_synths(synth_ids)
else:
db_ingest.add_tract(tract)
db_ingest.add_patch(patch, patch_meta)
delta_time = time() - timer
hugs.log.logger.info('time to ingest = {:.2f} seconds'.format(delta_time))
def worker(p):
"""
Workers initialize pipe configuration and run pipeline.
"""
rank = MPI.COMM_WORLD.Get_rank()
if p['seed'] is None:
tract, p1, p2 = p['tract'], int(p['patch'][0]), int(p['patch'][-1])
seed = [int(time()), tract, p1, p2, rank]
else:
seed = p['seed']
config = hugs.PipeConfig(run_name=p['run_name'],
config_fn=p['config_fn'],
random_state=seed,
log_fn=p['log_fn'],
rerun_path=p['rerun_path'])
config.set_patch_id(p['tract'], p['patch'])
config.logger.info('random seed set to {}'.format(seed))
if p['use_old_pipeline']:
results = find_lsbgs.run(config)
else:
results = next_gen_search.run(config, False)
pm = results.hugs_exp.patch_meta
if (results.synths is not None) and results.success:
if len(results.synths) > 0:
synth_ids = results.synths.to_pandas().loc[:, ['synth_id']]
for plane in config.synth_check_masks:
masked = hugs.synths.find_masked_synths(results.synths,
results.exp_clean,
planes=plane)
synth_ids['mask_' + plane.lower()] = masked
else:
synth_ids = None
else:
synth_ids = None
patch_meta = PatchMeta(
x0 = pm.x0,
y0 = pm.y0,
small_frac = pm.small_frac,
cleaned_frac = pm.cleaned_frac,
bright_obj_frac = pm.bright_obj_frac,
good_data_frac = pm.good_data_frac
)
meta_data = [
config.run_name,
config.tract,
config.patch,
patch_meta,
]
if results.success:
df = results.sources.to_pandas()
df['flags'] = df['flags'].astype(int)
else:
df = None
config.reset_mask_planes()
config.logger.info('writing results to database')
return results.success, df, meta_data, synth_ids
if __name__=='__main__':
from argparse import ArgumentParser
from astropy.table import Table
rank = MPI.COMM_WORLD.Get_rank()<|fim▁hole|> # parse command-line arguments
parser = ArgumentParser('Run hugs pipeline')
parser.add_argument('-t', '--tract', type=int, help='HSC tract')
parser.add_argument('-p', '--patch', type=str, help='HSC patch')
parser.add_argument('-c', '--config_fn', help='hugs config file',
default=hugs.utils.default_config_fn)
parser.add_argument('--patches_fn', help='patches file')
parser.add_argument('--use-old-pipeline', action="store_true")
parser.add_argument('-r', '--run_name', type=str, default='hugs-pipe-run')
parser.add_argument('--seed', help='rng seed', default=None)
parser.add_argument('--rerun_path', help='full rerun path', default=None)
parser.add_argument('--overwrite', type=bool,
help='overwrite database', default=True)
group = parser.add_mutually_exclusive_group()
group.add_argument('--ncores', default=1, type=int,
help='Number of processes (uses multiprocessing).')
group.add_argument('--mpi', default=False, action="store_true",
help="Run with MPI.")
args = parser.parse_args()
config_params = hugs.utils.read_config(args.config_fn)
outdir = config_params['hugs_io']
#######################################################################
# run on a single patch
#######################################################################
if args.tract is not None:
assert args.patch is not None
tract, patch = args.tract, args.patch
patches = Table([[tract], [patch]], names=['tract', 'patch'])
run_dir_name = '{}-{}-{}'.format(args.run_name, tract, patch)
outdir = os.path.join(outdir, run_dir_name)
hugs.utils.mkdir_if_needed(outdir)
log_fn = os.path.join(outdir, 'hugs-pipe.log')
patches['outdir'] = outdir
patches['log_fn'] = log_fn
#######################################################################
# OR run on all patches in file
#######################################################################
elif args.patches_fn is not None:
patches = Table.read(args.patches_fn)
if rank==0:
time_label = hugs.utils.get_time_label()
outdir = os.path.join(
outdir, '{}-{}'.format(args.run_name, time_label))
hugs.utils.mkdir_if_needed(outdir)
log_dir = os.path.join(outdir, 'log')
hugs.utils.mkdir_if_needed(log_dir)
log_fn = []
for tract, patch in patches['tract', 'patch']:
fn = os.path.join(log_dir, '{}-{}.log'.format(tract, patch))
log_fn.append(fn)
patches['outdir'] = outdir
patches['log_fn'] = log_fn
else:
print('\n**** must give tract and patch --or-- a patch file ****\n')
parser.print_help()
exit()
patches['rerun_path'] = args.rerun_path
patches['seed'] = args.seed
patches['config_fn'] = args.config_fn
patches['run_name'] = args.run_name
patches['use_old_pipeline'] = args.use_old_pipeline
if rank==0:
# open database session with master process
db_fn = os.path.join(outdir, args.run_name+'.db')
engine = hugs.database.connect(db_fn, args.overwrite)
session = hugs.database.Session()
shutil.copyfile(args.config_fn, os.path.join(outdir, 'config.yml'))
pool = schwimmbad.choose_pool(mpi=args.mpi, processes=args.ncores)
list(pool.map(worker, patches, callback=ingest_data))
pool.close()<|fim▁end|> | |
<|file_name|>ia64-linux.py<|end_file_name|><|fim▁begin|>## Copyright 2001-2007 Virtutech AB
##
## The contents herein are Source Code which are a subset of Licensed
## Software pursuant to the terms of the Virtutech Simics Software
## License Agreement (the "Agreement"), and are being distributed under
## the Agreement. You should have received a copy of the Agreement with
## this Licensed Software; if not, please contact Virtutech for a copy
## of the Agreement prior to using this Licensed Software.
##
## By using this Source Code, you agree to be bound by all of the terms
## of the Agreement, and use of this Source Code is subject to the terms
## the Agreement.
##
## This Source Code and any derivatives thereof are provided on an "as
## is" basis. Virtutech makes no warranties with respect to the Source
## Code or any derivatives thereof and disclaims all implied warranties,
## including, without limitation, warranties of merchantability and
## fitness for a particular purpose and non-infringement.
import string, traceback, sim_core
# ---------------------------------------------------------------------------
#
# read/write cpu registers
#
# ---------------------------------------------------------------------------
r0 = SIM_get_register_number(conf.cpu0, "r0")
nat0 = SIM_get_register_number(conf.cpu0, "r0.nat")
ar_kr6 = SIM_get_register_number(conf.cpu0, "ar.kr6")
def read_gr(regno):
cpu = SIM_current_processor()
return SIM_read_register(cpu, r0 + regno), SIM_read_register(cpu, nat0 + regno)
def read_register(reg):
return SIM_read_register(SIM_current_processor(), SIM_get_register_number(conf.cpu0, reg))
# Signed read
def sread_register(reg):
val = read_register(reg)
if val & 0x8000000000000000L:
val -= 0x10000000000000000L
return val
def read_cr(cr):
return read_register("cr." + cr)
# ---------------------------------------------------------------------------
#
# read/write physical memory
#
# ---------------------------------------------------------------------------
def linux_read_bytes(cpu, address, size):
return cpu.physical_memory.memory[[address, address + size - 1]]
def linux_read_byte(cpu, address):
return linux_read_bytes(cpu, address, 1)[0]
def linux_read_word(cpu, address):
word = linux_read_bytes(cpu, address, 4)
return (word[3] << 24) | (word[2] << 16) | (word[1] << 8) | word[0]
# ---------------------------------------------------------------------------
#
# read logical memory
#
# ---------------------------------------------------------------------------
def linux_read_string(cpu, address, maxlen):
s = ""
try:
while len(s) < maxlen:
p = SIM_logical_to_physical(cpu, 1, address)
c = SIM_read_phys_memory(cpu, p, 1)
if c == 0:
return s
s += char(c)
s += "..."
except:
s += "???"
return s
# ---------------------------------------------------------------------------
#
# system calls
#
# ---------------------------------------------------------------------------
def format_stringbuf(regno):
cpu = SIM_current_processor()
va = SIM_read_register(cpu, r0 + regno)
len = SIM_read_register(cpu, r0 + regno + 1)
s = "0x%x = \"" % va
for i in xrange(0, len):
if i > 64:
return s + "\" ..."
try:
pa = SIM_logical_to_physical(cpu, 1, va + i)
except:
return s + "\" ..."
b = linux_read_byte(cpu, pa)
if b == 9:
s += "\\t"
elif b == 10:
s += "\\n"
elif b == 13:
s += "\\r"
elif b == 92:
s += "\\\\"
elif b >= 32 and b < 127:
s += chr(b)
else:
s += "<%02x>" % b
return s + "\""
def fmt_pipe_ret(regno):
cpu = SIM_current_processor()
fd1 = SIM_read_register(cpu, r0 + 8)
fd2 = SIM_read_register(cpu, r0 + 9)
if fd1 < 0:
return str(fd1)
return "[%d, %d]" % (fd1, fd2)
def fmt_wait4_ret(ignored_regno):
try:
cpu = SIM_current_processor()
s = "%d" % SIM_read_register(cpu, r0 + 8)
statusp = SIM_read_register(cpu, r0 + 33)
rusagep = SIM_read_register(cpu, r0 + 35)
if statusp != 0:
try:
statusp = SIM_logical_to_physical(cpu, 1, statusp)
status = SIM_read_phys_memory(cpu, statusp, 2)
s += " status: %d" % ((status & 0xff00) >> 8)
if status & 0xf7:
s += " signal(%d)" % (status & 0xf7)
except:
s += " status: <not in tlb>"
return s
except:
traceback.print_exc()
def fmt_uname_ret(ignored_regno):
try:
cpu = SIM_current_processor()
lutsp = SIM_read_register(cpu, r0 + 32)
s = "%d" % SIM_read_register(cpu, r0 + 8)
try:
putsp = SIM_logical_to_physical(cpu, 1, lutsp)
except:
return s
sysname = linux_read_string(cpu, lutsp, 65)
nodename = linux_read_string(cpu, lutsp + 65, 65)
release = linux_read_string(cpu, lutsp + 130, 65)
version = linux_read_string(cpu, lutsp + 195, 65)
machine = linux_read_string(cpu, lutsp + 260, 65)
domainname = linux_read_string(cpu, lutsp + 325, 65)
return s + (" { %s, %s, %s, %s, %s, %s }" %
(sysname, nodename, release, version, machine, domainname))
except:
traceback.print_exc()
def fmt_swapflags(regno):
cpu = SIM_current_processor()
swapflags = SIM_read_register(cpu, regno)
s = "%d" % (swapflags & 0x7fff)
if swapflags & 0x8000:
s += "|PREFER"
return s
linux_syscalls = {
1024 : [ "ni_syscall", ""],
1025 : [ "exit", "d:v"],
1026 : [ "read", "dxd:d"],
1027 : [ "write", (["d", format_stringbuf, "d"], "d")],
1028 : [ "open", "sd:d"],
1029 : [ "close", "d:d"],
1030 : [ "creat", "sd:d"],
1031 : [ "link", "ss:d"],
1032 : [ "unlink", "s:d"],
1033 : [ "execve", "sxx:v"],
1034 : [ "chdir", "s:d"],
1035 : [ "fchdir", "d:d"],
1036 : [ "utimes", ""],
1037 : [ "mknod", ""],
1038 : [ "chmod", ""],
1039 : [ "chown", ""],
1040 : [ "lseek", "ddd:d"],
1041 : [ "getpid", ":d"],
1042 : [ "getppid", ""],
1043 : [ "mount", ""],
1044 : [ "umount", ""],
1045 : [ "setuid", ""],
1046 : [ "getuid", ""],
1047 : [ "geteuid", ""],
1048 : [ "ptrace", ""],
1049 : [ "access", "sd:d"],
1050 : [ "sync", ""],
1051 : [ "fsync", ""],
1052 : [ "fdatasync", ""],
1053 : [ "kill", "dd:d"],
1054 : [ "rename", ""],
1055 : [ "mkdir", ""],
1056 : [ "rmdir", ""],
1057 : [ "dup", "d:d"],
1058 : [ "pipe", ("x", fmt_pipe_ret)],
1059 : [ "times", ""],
1060 : [ "brk", "x:x"],
1061 : [ "setgid", ""],
1062 : [ "getgid", ""],
1063 : [ "getegid", ""],
1064 : [ "acct", ""],
1065 : [ "ioctl", "dxx:d"],
1066 : [ "fcntl", "dxx:d"],
1067 : [ "umask", ""],
1068 : [ "chroot", "s:d"],
1069 : [ "ustat", ""],
1070 : [ "dup2", "dd:d"],
1071 : [ "setreuid", ""],
1072 : [ "setregid", ""],
1073 : [ "getresuid", ""],
1074 : [ "setresuid", ""],
1075 : [ "getresgid", ""],
1076 : [ "setresgid", ""],
1077 : [ "getgroups", ""],
1078 : [ "setgroups", ""],
1079 : [ "getpgid", ""],
1080 : [ "setpgid", ""],
1081 : [ "setsid", ""],
1082 : [ "getsid", ""],
1083 : [ "sethostname", ""],
1084 : [ "setrlimit", ""],
1085 : [ "getrlimit", ""],
1086 : [ "getrusage", ""],
1087 : [ "gettimeofday", ""],
1088 : [ "settimeofday", ""],
1089 : [ "select", ""],
1090 : [ "poll", ""],
1091 : [ "symlink", ""],
1092 : [ "readlink", "sxd:d"],
1093 : [ "uselib", ""],
1094 : [ "swapon", (["s", fmt_swapflags], "d")],
1095 : [ "swapoff", "s:d"],
1096 : [ "reboot", ""],
1097 : [ "truncate", ""],
1098 : [ "ftruncate", ""],
1099 : [ "fchmod", ""],
1100 : [ "fchown", ""],
1101 : [ "getpriority", ""],
1102 : [ "setpriority", ""],
1103 : [ "statfs", ""],
1104 : [ "fstatfs", ""],
1106 : [ "semget", ""],
1107 : [ "semop", ""],
1108 : [ "semctl", ""],
1109 : [ "msgget", ""],
1110 : [ "msgsnd", ""],
1111 : [ "msgrcv", ""],
1112 : [ "msgctl", ""],
1113 : [ "shmget", ""],
1114 : [ "shmat", ""],
1115 : [ "shmdt", ""],
1116 : [ "shmctl", ""],
1117 : [ "syslog", ""],
1118 : [ "setitimer", ""],
1119 : [ "getitimer", ""],
1120 : [ "old_stat", ""],
1121 : [ "old_lstat", ""],
1122 : [ "old_fstat", ""],
1123 : [ "vhangup", ""],
1124 : [ "lchown", ""],
1125 : [ "vm86", ""],
1126 : [ "wait4", ("dxdx", fmt_wait4_ret)],
1127 : [ "sysinfo", ""],
1128 : [ "clone", "xxxx:d"],
1129 : [ "setdomainname", ""],
1130 : [ "uname", ("x", fmt_uname_ret)],
1131 : [ "adjtimex", ""],
1132 : [ "create_module", ""],
1133 : [ "init_module", ""],
1134 : [ "delete_module", ""],
1135 : [ "get_kernel_syms", ""],
1136 : [ "query_module", ""],
1137 : [ "quotactl", ""],
1138 : [ "bdflush", ""],
1139 : [ "sysfs", ""],
1140 : [ "personality", ""],
1141 : [ "afs_syscall", ""],
1142 : [ "setfsuid", ""],
1143 : [ "setfsgid", ""],
1144 : [ "getdents", ""],
1145 : [ "flock", ""],
1146 : [ "readv", ""],
1147 : [ "writev", ""],
1148 : [ "pread", ""],
1149 : [ "pwrite", ""],
1150 : [ "_sysctl", ""],
1151 : [ "mmap", "xxdxxx:x"],
1152 : [ "munmap", "xx:d"],
1153 : [ "mlock", ""],
1154 : [ "mlockall", ""],
1155 : [ "mprotect", ""],
1156 : [ "mremap", ""],
1157 : [ "msync", ""],
1158 : [ "munlock", ""],
1159 : [ "munlockall", ""],
1160 : [ "sched_getparam", ""],<|fim▁hole|> 1164 : [ "sched_yield", ""],
1165 : [ "sched_get_priority_max", ""],
1166 : [ "sched_get_priority_min", ""],
1167 : [ "sched_rr_get_interval", ""],
1168 : [ "nanosleep", ""],
1169 : [ "nfsservctl", ""],
1170 : [ "prctl", ""],
1172 : [ "mmap2", ""],
1173 : [ "pciconfig_read", ""],
1174 : [ "pciconfig_write", ""],
1175 : [ "perfmonctl", ""],
1176 : [ "sigaltstack", ""],
1177 : [ "rt_sigaction", "dxxd:d"],
1178 : [ "rt_sigpending", "xd:d"],
1179 : [ "rt_sigprocmask", "dxxd:d"],
1180 : [ "rt_sigqueueinfo", "ddx:d"],
1181 : [ "rt_sigreturn", ""],
1182 : [ "rt_sigsuspend", ""],
1183 : [ "rt_sigtimedwait", "xxxd:d"],
1184 : [ "getcwd", ""],
1185 : [ "capget", ""],
1186 : [ "capset", ""],
1187 : [ "sendfile", ""],
1188 : [ "getpmsg", ""],
1189 : [ "putpmsg", ""],
1190 : [ "socket", "ddd:d"],
1191 : [ "bind", ""],
1192 : [ "connect", ""],
1193 : [ "listen", ""],
1194 : [ "accept", ""],
1195 : [ "getsockname", ""],
1196 : [ "getpeername", ""],
1197 : [ "socketpair", ""],
1198 : [ "send", ""],
1199 : [ "sendto", ""],
1200 : [ "recv", ""],
1201 : [ "recvfrom", ""],
1202 : [ "shutdown", ""],
1203 : [ "setsockopt", ""],
1204 : [ "getsockopt", ""],
1205 : [ "sendmsg", ""],
1206 : [ "recvmsg", ""],
1207 : [ "pivot_root", ""],
1208 : [ "mincore", ""],
1209 : [ "madvise", ""],
1210 : [ "stat", "sx:d"],
1211 : [ "lstat", "sx:d"],
1212 : [ "fstat", "dx:d"],
1213 : [ "clone2", ""],
1214 : [ "getdents64", ""],
}
# ---------------------------------------------------------------------------
#
# read data from current task_struct
#
# ---------------------------------------------------------------------------
task_name_offset = 0x57a
task_pid_offset = 0xcc
def current_task(cpu):
return SIM_read_register(cpu, ar_kr6)
def current_comm():
comm = linux_read_bytes(read_register("ar.kr6") + task_name_offset, 16)
name = ""
for c in comm:
if c == 0:
break
name += chr(c)
return name
def current_process(cpu, task = None):
if not task:
task = SIM_read_register(cpu, ar_kr6)
try:
pid = SIM_read_phys_memory(cpu, task + task_pid_offset, 4)
comm = linux_read_bytes(cpu, task + task_name_offset, 16)
name = ""
for c in comm:
if c == 0:
break
name += chr(c)
return pid, name
except sim_core.SimExc_Memory:
return None, None
# ---------------------------------------------------------------------------
#
# parse system call name and arguments
#
# ---------------------------------------------------------------------------
def string_argument(regno):
cpu = SIM_current_processor()
va, nat = read_gr(regno)
if nat:
return "NaT"
s = "\""
for i in xrange(0, 64):
try:
pa = SIM_logical_to_physical(cpu, 1, va + i)
except:
return "0x%x" % va
b = linux_read_byte(cpu, pa)
if b == 0:
return s + "\""
elif b == 9:
s += "\\t"
elif b == 10:
s += "\\n"
elif b == 13:
s += "\\r"
elif b >= 32:
s += chr(b)
else:
s += "<%02x>"
return s + "\""
def int_argument(regno):
i, nat = read_gr(regno)
if nat:
return "NaT"
if i & 0x8000000000000000L:
i -= 0x10000000000000000L
return "%d" % i
def uint_argument(regno):
i, nat = read_gr(regno)
if nat:
return "NaT"
return "%d" % i
def hex_argument(regno):
addr, nat = read_gr(regno)
if nat:
return "NaT"
return "0x%x" % addr
def format_reg(regno, fmt):
try:
if fmt == 'd':
return int_argument(regno)
if fmt == 'u':
return uint_argument(regno)
if fmt == 'x':
return hex_argument(regno)
if fmt == 's':
return string_argument(regno)
return fmt(regno)
except sim_core.SimExc_Index:
return "<can't read r%d>" % regno
except TypeError:
traceback.print_exc()
raise "Unknown format element: %s" % fmt
def format_params(params):
s = ""
for i in range(0, len(params)):
if i != 0:
s += ", "
s += format_reg(32 + i, params[i])
return s
# ---------------------------------------------------------------------------
#
# handle break instruction
#
# ---------------------------------------------------------------------------
pre_syscall = 0
post_syscall = 0
# To get around a misfeature in Simics' hap callback handling, we have to store
# references to all data that is sent as callback data in
# SIM_hap_add_callback_index. We do this in this dictionary.
hap_data = { }
def post_syscall_hap(sc, obj, type, bp_id, dummy1, dummy2):
name, params, retfmt, task = sc
cpu = SIM_current_processor()
# Same context?
if task != current_task(cpu):
return
# print "post_syscall_hap(%s, %s, %s, %s, %s)" % (sc, type, bp_id, dummy1, dummy2)
SIM_delete_breakpoint(bp_id)
SIM_hap_delete_callback("Core_Breakpoint", post_syscall_hap, sc);
del hap_data[bp_id]
if not retfmt:
ret = "??"
else:
ret = format_reg(8, retfmt)
pid, comm = current_process(cpu)
print "[%s] %d [%d:%s] %s(%s) -> %s" % (cpu.name, SIM_cycle_count(cpu),
pid, comm,
name, format_params(params), ret)
def syscall():
global pids, pid_default, ia64_linux_loaded
cpu = SIM_current_processor()
pid, comm = current_process(cpu)
if not pids.get(pid, pid_default):
return
try:
r15 = read_register("r15")
sc = linux_syscalls[r15]
except:
print "<--- syscall() failed --->"
else:
name = sc[0]
if not sc[1]:
params = []
retfmt = None
elif type(sc[1]) == type(""):
[params, retfmt] = sc[1].split(":")
else:
params,retfmt = sc[1]
if pre_syscall:
print "[%s] %d [%d:%s] %s(%s)" % (cpu.name, SIM_cycle_count(cpu),
pid, comm,
name, format_params(params))
if not pre_syscall and post_syscall and retfmt == "v":
# Give at least some indication
print "[%s] %d [%d:%s] %s(%s) -> no return" % (cpu.name, SIM_cycle_count(cpu),
pid, comm,
name, format_params(params))
if len(sc) > 2:
for fn in sc[2]:
fn(r15)
if post_syscall and retfmt != "v":
iip = read_cr("iip")
isr_ei = (read_register("cr.isr") >> 41) & 0x3
if isr_ei == 2:
next_ip = iip + 16
else:
next_ip = iip + isr_ei + 1
ia64_linux_loaded = 1
context = SIM_get_object("primary-context")
id = SIM_breakpoint(context, Sim_Break_Virtual, 4, next_ip, 1, 0);
data = (name, params, retfmt, current_task(cpu))
hap_data[id] = data
hap_id = SIM_hap_add_callback_index("Core_Breakpoint", post_syscall_hap, data, id);
def install_syscall_callback(syscall, fn):
if len(linux_syscalls[syscall]) > 2:
linux_syscalls[syscall][2] += [fn]
else:
linux_syscalls[syscall] += [ [fn] ]
def break_instruction():
iim = read_cr("iim")
if iim == 0x100000 and (pre_syscall or post_syscall):
syscall()
elif iim == 0:
print "break 0 @ %d" % SIM_cycle_count(SIM_current_processor())
pids = {}
pid_default = 1
def syscall_trace_cmd(mode, incl, excl):
global pre_syscall, post_syscall, pids, pid_default
if mode == "enter" or mode == "both":
pre_syscall = 1
else:
pre_syscall = 0
if mode == "exit" or mode == "both":
post_syscall = 1
else:
post_syscall = 0
pids = {}
try:
if incl:
for k in incl.split(","): pids[int(k)] = 1
if excl:
for k in excl.split(","): pids[int(k)] = 0
except:
print "Bad pid list"
if incl and excl:
print "Redundant use of incl"
if incl:
pid_default = 0
else:
pid_default = 1
def syscall_mode_expander(comp):
return get_completions(comp, ["off", "enter", "exit", "both"])
new_command("syscall-trace", syscall_trace_cmd,
[arg(str_t, "mode", expander = syscall_mode_expander),
arg(str_t, "include-pids", "?"),
arg(str_t, "exclude-pids", "?")],
type = "linux commands",
short = "enable or disable syscall tracing",
doc = """
Set the syscall trace mode.
""")
# ---------------------------------------------------------------------------
#
# examine the page table
#
# ---------------------------------------------------------------------------
def ptwalk(addr):
cpu,_ = get_cpu()
vrn = addr >> 61
rr = cpu.rr[vrn]
rr_ps = (rr>>2) & 0x3f
pt_entries = 1L << (rr_ps - 3)
pgd = cpu.ar[7]
print "rr_ps: 0x%x" % rr_ps
ptd_index = (addr >> rr_ps) & (pt_entries - 1)
pmd_index = (addr >> (rr_ps + rr_ps-3)) & (pt_entries - 1)
pgd_index = ((addr >> (rr_ps + rr_ps-3 + rr_ps-3)) & ((pt_entries>>3) - 1) |
(vrn << (rr_ps - 6)))
print "pgd_index: 0x%x" % pgd_index
print "pmd_index: 0x%x" % pmd_index
print "ptd_index: 0x%x" % ptd_index
print "pgd: 0x%x" % pgd
pmd = SIM_read_phys_memory(cpu, pgd + 8*pgd_index, 8)
print "pmd = pgd[0x%x}: 0x%x" % (pgd_index, pmd)
ptd = SIM_read_phys_memory(cpu, pmd + 8*pmd_index, 8)
print "ptd = pmd[0x%x}: 0x%x" % (pmd_index, ptd)
pte = SIM_read_phys_memory(cpu, ptd + 8*ptd_index, 8)
print "pte = ptd[0x%x]: 0x%x" % (ptd_index, pte)
# ---------------------------------------------------------------------------
#
# handle illegal instruction
#
# ---------------------------------------------------------------------------
def exception_hap(data, cpu, exception):
if exception == 33:
print "Illegal instruction exception"
SIM_break_simulation("Illegal instruction")
elif exception == 35:
break_instruction()
return 0
# This is to allow us to reload ia64-linux.py
try:
if ia64_linux_loaded:
pass
except:
print "installing linux callbacks"
ia64_linux_loaded = 1
SIM_hap_add_callback("Core_Exception", exception_hap, None)<|fim▁end|> | 1161 : [ "sched_setparam", ""],
1162 : [ "sched_getscheduler", ""],
1163 : [ "sched_setscheduler", ""], |
<|file_name|>_helpers.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#<|fim▁hole|># limitations under the License.
def strip_region_tags(sample_text):
"""Remove blank lines and region tags from sample text"""
magic_lines = [
line for line in sample_text.split("\n") if len(line) > 0 and "# [" not in line
]
return "\n".join(magic_lines)<|fim▁end|> | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and |
<|file_name|>98.py<|end_file_name|><|fim▁begin|>test = "test of the localtime() function"
import time
times = [ 0, 100000, int (time.time()) ]
filedata = """
{$
for (i, %(times)s) {
locals { v : localtime(i) }
print ("${v[0]} ${v[1]} ${v[2]} ${v[3]} ${v[4]} ");
}
$}
""" % { "times" : times }
# in publand, localtime(0) should give the time now
times[0] = int (time.time())
outcome_v = []
for i in times:
lt = time.localtime (i)<|fim▁hole|>outcome = " ".join ([ str (i) for i in outcome_v ])<|fim▁end|> | outcome_v += [ lt.tm_year, lt.tm_mon, lt.tm_mday, lt.tm_hour, lt.tm_min ]
|
<|file_name|>dom_html_html_element.rs<|end_file_name|><|fim▁begin|>// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::DOMElement;
use crate::DOMEventTarget;
use crate::DOMHTMLElement;
use crate::DOMNode;
use crate::DOMObject;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
glib::wrapper! {
pub struct DOMHTMLHtmlElement(Object<ffi::WebKitDOMHTMLHtmlElement, ffi::WebKitDOMHTMLHtmlElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget;
match fn {
type_ => || ffi::webkit_dom_html_html_element_get_type(),
}
}
pub const NONE_DOMHTML_HTML_ELEMENT: Option<&DOMHTMLHtmlElement> = None;
pub trait DOMHTMLHtmlElementExt: 'static {
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_html_html_element_get_version")]
fn version(&self) -> Option<glib::GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_html_html_element_set_version")]
fn set_version(&self, value: &str);
fn connect_property_version_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}
<|fim▁hole|> fn version(&self) -> Option<glib::GString> {
unsafe {
from_glib_full(ffi::webkit_dom_html_html_element_get_version(
self.as_ref().to_glib_none().0,
))
}
}
fn set_version(&self, value: &str) {
unsafe {
ffi::webkit_dom_html_html_element_set_version(
self.as_ref().to_glib_none().0,
value.to_glib_none().0,
);
}
}
fn connect_property_version_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_version_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::WebKitDOMHTMLHtmlElement,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMHTMLHtmlElement>,
{
let f: &F = &*(f as *const F);
f(&DOMHTMLHtmlElement::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::version\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_version_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
}
impl fmt::Display for DOMHTMLHtmlElement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("DOMHTMLHtmlElement")
}
}<|fim▁end|> | impl<O: IsA<DOMHTMLHtmlElement>> DOMHTMLHtmlElementExt for O { |
<|file_name|>array_strings_are_equal.py<|end_file_name|><|fim▁begin|>from typing import List
class Solution:
def arrayStringsAreEqualV1(self, word1: List[str], word2: List[str]) -> bool:
return "".join(word1) == "".join(word2)
def arrayStringsAreEqualV2(self, word1: List[str], word2: List[str]) -> bool:
def generator(word: List[str]):
for s in word:
for c in s:
yield c
yield None
for c1, c2 in zip(generator(word1), generator(word2)):<|fim▁hole|> return True
# TESTS
for word1, word2, expected in [
(["ab", "c"], ["a", "bc"], True),
(["a", "cb"], ["ab", "c"], False),
(["abc", "d", "defg"], ["abcddefg"], True),
]:
sol = Solution()
actual = sol.arrayStringsAreEqualV1(word1, word2)
print("Array strings", word1, "and", word2, "are equal ->", actual)
assert actual == expected
assert sol.arrayStringsAreEqualV1(word1, word2) == expected<|fim▁end|> | if c1 != c2:
return False |
<|file_name|>AgreeItem.web.js<|end_file_name|><|fim▁begin|>'use strict';
Object.defineProperty(exports, "__esModule", {
value: true<|fim▁hole|>
var _defineProperty3 = _interopRequireDefault(_defineProperty2);
var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);
var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');
var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);
var _inherits2 = require('babel-runtime/helpers/inherits');
var _inherits3 = _interopRequireDefault(_inherits2);
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _classnames = require('classnames');
var _classnames2 = _interopRequireDefault(_classnames);
var _Checkbox = require('./Checkbox.web');
var _Checkbox2 = _interopRequireDefault(_Checkbox);
var _getDataAttr = require('../_util/getDataAttr');
var _getDataAttr2 = _interopRequireDefault(_getDataAttr);
var _omit = require('omit.js');
var _omit2 = _interopRequireDefault(_omit);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var __assign = undefined && undefined.__assign || Object.assign || function (t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
}
return t;
};
var AgreeItem = function (_React$Component) {
(0, _inherits3["default"])(AgreeItem, _React$Component);
function AgreeItem() {
(0, _classCallCheck3["default"])(this, AgreeItem);
return (0, _possibleConstructorReturn3["default"])(this, _React$Component.apply(this, arguments));
}
AgreeItem.prototype.render = function render() {
var _classNames;
var _props = this.props,
prefixCls = _props.prefixCls,
style = _props.style,
className = _props.className;
var wrapCls = (0, _classnames2["default"])((_classNames = {}, (0, _defineProperty3["default"])(_classNames, prefixCls + '-agree', true), (0, _defineProperty3["default"])(_classNames, className, className), _classNames));
return _react2["default"].createElement("div", __assign({}, (0, _getDataAttr2["default"])(this.props), { className: wrapCls, style: style }), _react2["default"].createElement(_Checkbox2["default"], __assign({}, (0, _omit2["default"])(this.props, ['style']), { className: prefixCls + '-agree-label' })));
};
return AgreeItem;
}(_react2["default"].Component);
exports["default"] = AgreeItem;
AgreeItem.defaultProps = {
prefixCls: 'am-checkbox'
};
module.exports = exports['default'];<|fim▁end|> | });
exports["default"] = undefined;
var _defineProperty2 = require('babel-runtime/helpers/defineProperty'); |
<|file_name|>LoginActivity.java<|end_file_name|><|fim▁begin|>package com.habitrpg.android.habitica.ui.activities;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TableRow;
import android.widget.TextView;
import com.amplitude.api.Amplitude;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.habitrpg.android.habitica.APIHelper;
import com.habitrpg.android.habitica.HostConfig;
import com.habitrpg.android.habitica.R;
import com.habitrpg.android.habitica.callbacks.HabitRPGUserCallback;
import com.habitrpg.android.habitica.prefs.scanner.IntentIntegrator;
import com.habitrpg.android.habitica.prefs.scanner.IntentResult;
import com.magicmicky.habitrpgwrapper.lib.models.HabitRPGUser;
import com.magicmicky.habitrpgwrapper.lib.models.UserAuthResponse;
import org.json.JSONException;
import org.json.JSONObject;
import butterknife.Bind;
import butterknife.BindString;
import butterknife.ButterKnife;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
/**
* @author Mickael Goubin
*/
public class LoginActivity extends AppCompatActivity
implements Callback<UserAuthResponse>,HabitRPGUserCallback.OnUserReceived {
private final static String TAG_ADDRESS="address";
private final static String TAG_USERID="user";
private final static String TAG_APIKEY="key";
private APIHelper mApiHelper;
public String mTmpUserToken;
public String mTmpApiToken;
public Boolean isRegistering;
private Menu menu;
@BindString(R.string.SP_address_default)
String apiAddress;
//private String apiAddress;
//private String apiAddress = "http://192.168.2.155:8080/"; // local testing
private CallbackManager callbackManager;
@Bind(R.id.login_btn)
Button mLoginNormalBtn;
@Bind(R.id.PB_AsyncTask)
ProgressBar mProgressBar;
@Bind(R.id.username)
EditText mUsernameET;
@Bind(R.id.password)
EditText mPasswordET;
@Bind(R.id.email)
EditText mEmail;
@Bind(R.id.confirm_password)
EditText mConfirmPassword;
@Bind(R.id.email_row)
TableRow mEmailRow;
@Bind(R.id.confirm_password_row)
TableRow mConfirmPasswordRow;
@Bind(R.id.login_button)
LoginButton mFacebookLoginBtn;
@Bind(R.id.forgot_pw_tv)
TextView mForgotPWTV;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
//Set default values to avoid null-responses when requesting unedited settings
PreferenceManager.setDefaultValues(this, R.xml.preferences_account_details, false);
PreferenceManager.setDefaultValues(this, R.xml.preferences_fragment, false);
ButterKnife.bind(this);
mLoginNormalBtn.setOnClickListener(mLoginNormalClick);
mFacebookLoginBtn.setReadPermissions("user_friends");
mForgotPWTV.setOnClickListener(mForgotPWClick);
SpannableString content = new SpannableString(mForgotPWTV.getText());
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
mForgotPWTV.setText(content);
callbackManager = CallbackManager.Factory.create();
mFacebookLoginBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
mApiHelper.connectSocial(accessToken.getUserId(), accessToken.getToken(), LoginActivity.this);
}
@Override
public void onCancel() {
Log.d("FB Login", "Cancelled");
}
@Override
public void onError(FacebookException exception) {
Log.e("FB Login", "Error", exception);
}
});
HostConfig hc= PrefsActivity.fromContext(this);
if(hc ==null) {
hc = new HostConfig(apiAddress, "80", "", "");
}
mApiHelper = new APIHelper(hc);
this.isRegistering = true;
JSONObject eventProperties = new JSONObject();
try {
eventProperties.put("eventAction", "navigate");
eventProperties.put("eventCategory", "navigation");
eventProperties.put("hitType", "pageview");
eventProperties.put("page", this.getClass().getSimpleName());
} catch (JSONException exception) {
}
Amplitude.getInstance().logEvent("navigate", eventProperties);
}
private void resetLayout() {
if (this.isRegistering) {
if (this.mEmailRow.getVisibility() == View.GONE) {
expand(this.mEmailRow);
}
if (this.mConfirmPasswordRow.getVisibility() == View.GONE) {
expand(this.mConfirmPasswordRow);
}
} else {
if (this.mEmailRow.getVisibility() == View.VISIBLE) {
collapse(this.mEmailRow);
}
if (this.mConfirmPasswordRow.getVisibility() == View.VISIBLE) {
collapse(this.mConfirmPasswordRow);
}
}
}
private View.OnClickListener mLoginNormalClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
mProgressBar.setVisibility(View.VISIBLE);
if (isRegistering) {
String username, email,password,cpassword;
username = String.valueOf(mUsernameET.getText()).trim();
email = String.valueOf(mEmail.getText()).trim();
password = String.valueOf(mPasswordET.getText());
cpassword = String.valueOf(mConfirmPassword.getText());
if (username.length() == 0 || password.length() == 0 || email.length() == 0 || cpassword.length() == 0) {
showValidationError(R.string.login_validation_error_fieldsmissing);
return;
}
mApiHelper.registerUser(username,email,password, cpassword, LoginActivity.this);
} else {
String username,password;
username = String.valueOf(mUsernameET.getText()).trim();
password = String.valueOf(mPasswordET.getText());
if (username.length() == 0 || password.length() == 0) {
showValidationError(R.string.login_validation_error_fieldsmissing);
return;
}
mApiHelper.connectUser(username,password, LoginActivity.this);
}
}
};
private View.OnClickListener mForgotPWClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
String url = getString(R.string.SP_address_default);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
};
public static void expand(final View v) {
v.setVisibility(View.VISIBLE);
}
public static void collapse(final View v) {
v.setVisibility(View.GONE);
}
private void startMainActivity() {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
private void startSetupActivity() {
Intent intent = new Intent(LoginActivity.this, SetupActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
private void toggleRegistering() {
this.isRegistering = !this.isRegistering;
this.setRegistering();
}
private void setRegistering() {
MenuItem menuItem = menu.findItem(R.id.action_toggleRegistering);
if (this.isRegistering) {
this.mLoginNormalBtn.setText(getString(R.string.register_btn));
menuItem.setTitle(getString(R.string.login_btn));
mUsernameET.setHint(R.string.username);
mPasswordET.setImeOptions(EditorInfo.IME_ACTION_NEXT);
} else {
this.mLoginNormalBtn.setText(getString(R.string.login_btn));
menuItem.setTitle(getString(R.string.register_btn));
mUsernameET.setHint(R.string.email_username);
mPasswordET.setImeOptions(EditorInfo.IME_ACTION_DONE);
}
this.resetLayout();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
callbackManager.onActivityResult(requestCode, resultCode, intent);
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
try {
Log.d("scanresult", scanResult.getContents());
this.parse(scanResult.getContents());
} catch(Exception e) {
Log.e("scanresult", "Could not parse scanResult", e);
}
}
}
private void parse(String contents) {
String adr,user,key;
try {
JSONObject obj;
obj = new JSONObject(contents);
adr = obj.getString(TAG_ADDRESS);
user = obj.getString(TAG_USERID);
key = obj.getString(TAG_APIKEY);
Log.d("", "adr" + adr + " user:" + user + " key" + key);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
boolean ans = editor.putString(getString(R.string.SP_address), adr)
.putString(getString(R.string.SP_APIToken), key)
.putString(getString(R.string.SP_userID), user)
.commit();
if(!ans) {
throw new Exception("PB_string_commit");
}
startMainActivity();
} catch (JSONException e) {
showSnackbar(getString(R.string.ERR_pb_barcode));
e.printStackTrace();
} catch(Exception e) {
if("PB_string_commit".equals(e.getMessage())) {
showSnackbar(getString(R.string.ERR_pb_barcode));
}
}
}
private void showSnackbar(String content)
{
Snackbar snackbar = Snackbar
.make(this.findViewById(R.id.login_linear_layout), content, Snackbar.LENGTH_LONG);
View snackbarView = snackbar.getView();
snackbarView.setBackgroundColor(Color.RED);//change Snackbar's background color;
snackbar.show(); // Don’t forget to show!
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
this.menu = menu;
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_toggleRegistering:
toggleRegistering();
break;
}
return super.onOptionsItemSelected(item);
}
private void afterResults() {
mProgressBar.setVisibility(View.INVISIBLE);
}
@Override
public void success(UserAuthResponse userAuthResponse, Response response) {
try {
saveTokens(userAuthResponse.getToken(), userAuthResponse.getId());
} catch (Exception e) {
e.printStackTrace();
}
if (this.isRegistering) {
this.startSetupActivity();
} else {
JSONObject eventProperties = new JSONObject();
try {
eventProperties.put("eventAction", "lofin");
eventProperties.put("eventCategory", "behaviour");
eventProperties.put("hitType", "event");
} catch (JSONException exception) {
}
Amplitude.getInstance().logEvent("login", eventProperties);
this.startMainActivity();
}
}
private void saveTokens(String api, String user) throws Exception {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);
SharedPreferences.Editor editor = prefs.edit();
boolean ans = editor.putString(getString(R.string.SP_APIToken), api)
.putString(getString(R.string.SP_userID), user)
.putString(getString(R.string.SP_address),getString(R.string.SP_address_default))
.commit();
if(!ans) {
throw new Exception("PB_string_commit");
}
}
@Override
public void failure(RetrofitError error) {
mProgressBar.setVisibility(View.GONE);
}
@Override
public void onUserReceived(HabitRPGUser user) {
try {
saveTokens(mTmpApiToken, mTmpUserToken);<|fim▁hole|> }
this.startMainActivity();
}
@Override
public void onUserFail() {
mProgressBar.setVisibility(View.GONE);
showSnackbar(getString(R.string.unknown_error));
}
private void showValidationError(int resourceMessageString) {
mProgressBar.setVisibility(View.GONE);
new android.support.v7.app.AlertDialog.Builder(this)
.setTitle(R.string.login_validation_error_title)
.setMessage(resourceMessageString)
.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(R.drawable.ic_warning_black)
.show();
}
}<|fim▁end|> | } catch (Exception e) {
e.printStackTrace(); |
<|file_name|>u8.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Operations and constants for unsigned 8-bits integers (`u8` type)
#![unstable]
#![doc(primitive = "u8")]
use from_str::FromStr;
use num::{ToStrRadix, FromStrRadix};
use num::strconv;
use option::Option;
use slice::ImmutableVector;<|fim▁hole|>pub use core::u8::{BITS, BYTES, MIN, MAX};
uint_module!(u8)<|fim▁end|> | use string::String;
|
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>import numpy as np
import torch
import time
from torch.autograd import Variable
'''
fast beam search
'''
def repackage_hidden(h):
"""Wraps hidden states in new Variables, to detach them from their history."""
if type(h) == Variable:
return Variable(h.data)
else:
return tuple(repackage_hidden(v) for v in h)
def tensor_transformer(seq0, batch_size, beam_size):
seq = seq0.unsqueeze(2)
seq = seq.repeat(1, 1, beam_size, 1)
seq = seq.contiguous().view(batch_size, beam_size*beam_size, seq.size(3))
return seq
'''
First beam search
'''
def fast_beam_search_1(
model_emb,
model_s2s,
src_text_rep,
vocab2id,
batch_size,<|fim▁hole|> trg_len,
encoder_hy,
hidden_,
h_attn_new,
p_gen_new,
past_attn_new,
pt_idx
):
(h0_new, c0_new) = hidden_
beam_seq = Variable(torch.LongTensor(
batch_size, beam_size, trg_len+1).fill_(vocab2id['<pad>'])).cuda()
beam_seq[:, :, 0] = vocab2id['<s>']
beam_prb = torch.FloatTensor(batch_size, beam_size).fill_(0.0)
last_wd = Variable(torch.LongTensor(
batch_size, beam_size, 1).fill_(vocab2id['<s>'])).cuda()
beam_h_attn = Variable(torch.FloatTensor(
trg_len, batch_size, beam_size, h_attn_new.size(1)).fill_(0.0)).cuda()
for j in range(trg_len):
last_emb = model_emb(last_wd.view(-1, 1))
output_s2s, (h0, c0), h_attn, past_attn = model_s2s.forward_onestep_decoder1(
j,
last_emb,
(h0_new, c0_new),
h_attn_new,
encoder_hy,
p_gen_new,
past_attn_new,
pt_idx
)
p_gen_new.fill_(0.0)
(h0, c0) = repackage_hidden((h0, c0))
prob, wds = output_s2s.data.topk(k=beam_size)
prob = prob.view(batch_size, beam_size, prob.size(1), prob.size(2))
wds = wds.view(batch_size, beam_size, wds.size(1), wds.size(2))
if j == 0:
beam_prb = prob[:, 0, 0]
beam_seq[:, :, 1] = wds[:, 0, 0]
last_wd = Variable(wds[:, 0, 0].unsqueeze(2).clone()).cuda()
h0_new = h0
c0_new = c0
h_attn_new = h_attn
past_attn_new = past_attn
beam_h_attn[j] = h_attn_new.view(batch_size, beam_size, h_attn_new.size(-1))
continue
cand_seq = tensor_transformer(beam_seq, batch_size, beam_size)
cand_seq[:, :, j+1] = wds.squeeze(2).view(batch_size, -1)
cand_last_wd = wds.squeeze(2).view(batch_size, -1)
cand_prob = beam_prb.unsqueeze(1).repeat(1, beam_size, 1).transpose(1,2)
cand_prob += prob[:, :, 0]
cand_prob = cand_prob.contiguous().view(batch_size, beam_size*beam_size)
h0_new = h0_new.view(batch_size, beam_size, h0_new.size(-1))
c0_new = c0_new.view(batch_size, beam_size, c0_new.size(-1))
h_attn_new = h_attn_new.view(batch_size, beam_size, h_attn_new.size(-1))
past_attn_new = past_attn_new.view(batch_size, beam_size, past_attn_new.size(-1))
h0 = h0.view(batch_size, beam_size, h0.size(-1))
h0 = tensor_transformer(h0, batch_size, beam_size)
c0 = c0.view(batch_size, beam_size, c0.size(-1))
c0 = tensor_transformer(c0, batch_size, beam_size)
h_attn = h_attn.view(batch_size, beam_size, h_attn.size(-1))
h_attn = tensor_transformer(h_attn, batch_size, beam_size)
past_attn = past_attn.view(batch_size, beam_size, past_attn.size(-1))
past_attn = tensor_transformer(past_attn, batch_size, beam_size)
tmp_prb, tmp_idx = cand_prob.topk(k=beam_size, dim=1)
for x in range(batch_size):
for b in range(beam_size):
last_wd[x, b] = cand_last_wd[x, tmp_idx[x, b]]
beam_seq[x, b] = cand_seq[x, tmp_idx[x, b]]
beam_prb[x, b] = tmp_prb[x, b]
h0_new[x, b] = h0[x, tmp_idx[x, b]]
c0_new[x, b] = c0[x, tmp_idx[x, b]]
h_attn_new[x, b] = h_attn[x, tmp_idx[x, b]]
past_attn_new[x, b] = past_attn[x, tmp_idx[x, b]]
beam_h_attn[j] = h_attn_new
h0_new = h0_new.view(-1, h0_new.size(-1))
c0_new = c0_new.view(-1, c0_new.size(-1))
h_attn_new = h_attn_new.view(-1, h_attn_new.size(-1))
past_attn_new = past_attn_new.view(-1, past_attn_new.size(-1))
return beam_seq, beam_prb, beam_h_attn
'''
second beam search
'''
def fast_beam_search_2(
model_emb,
model_s2s,
src_text_rep,
vocab2id,
batch_size,
beam_size,
trg_len,
encoder_hy,
hidden_,
h_attn21_new,
h_attn22_new,
p_gen21_new,
past_attn21_new,
past_attn22_new,
beam_h_attn1,
pt_idx
):
(h0_new, c0_new) = hidden_
beam_seq = Variable(torch.LongTensor(batch_size, beam_size, trg_len+1).fill_(vocab2id['<pad>'])).cuda()
beam_seq[:, :, 0] = vocab2id['<s>']
beam_prb = torch.FloatTensor(batch_size, beam_size).fill_(0.0)
last_wd = Variable(torch.LongTensor(batch_size, beam_size, 1).fill_(vocab2id['<s>'])).cuda()
for j in range(trg_len):
last_emb = model_emb(last_wd.view(-1, 1))
output_s2s, (h0, c0), h_attn21, h_attn22, past_attn21, past_attn22 = model_s2s.forward_onestep_decoder2(
j,
last_emb,
(h0_new, c0_new),
h_attn21_new,
h_attn22_new,
encoder_hy,
p_gen21_new,
past_attn21_new,
past_attn22_new,
beam_h_attn1,
pt_idx
)
p_gen21_new.fill_(0.0)
(h0, c0) = repackage_hidden((h0, c0))
prob, wds = output_s2s.data.topk(k=beam_size)
prob = prob.view(batch_size, beam_size, prob.size(1), prob.size(2))
wds = wds.view(batch_size, beam_size, wds.size(1), wds.size(2))
if j == 0:
beam_prb = prob[:, 0, 0]
beam_seq[:, :, 1] = wds[:, 0, 0]
last_wd = Variable(wds[:, 0, 0].unsqueeze(2).clone()).cuda()
h0_new = h0
c0_new = c0
h_attn21_new = h_attn21
h_attn22_new = h_attn22
past_attn21_new = past_attn21
past_attn22_new = past_attn22
continue
cand_seq = tensor_transformer(beam_seq, batch_size, beam_size)
cand_seq[:, :, j+1] = wds.squeeze(2).view(batch_size, -1)
cand_last_wd = wds.squeeze(2).view(batch_size, -1)
cand_prob = beam_prb.unsqueeze(1).repeat(1, beam_size, 1).transpose(1,2)
cand_prob += prob[:, :, 0]
cand_prob = cand_prob.contiguous().view(batch_size, beam_size*beam_size)
h0_new = h0_new.view(batch_size, beam_size, h0_new.size(-1))
c0_new = c0_new.view(batch_size, beam_size, c0_new.size(-1))
h_attn21_new = h_attn21_new.view(batch_size, beam_size, h_attn21_new.size(-1))
h_attn22_new = h_attn22_new.view(batch_size, beam_size, h_attn22_new.size(-1))
past_attn21_new = past_attn21_new.view(batch_size, beam_size, past_attn21_new.size(-1))
past_attn22_new = past_attn22_new.view(batch_size, beam_size, past_attn22_new.size(-1))
h0 = h0.view(batch_size, beam_size, h0.size(-1))
h0 = tensor_transformer(h0, batch_size, beam_size)
c0 = c0.view(batch_size, beam_size, c0.size(-1))
c0 = tensor_transformer(c0, batch_size, beam_size)
h_attn21 = h_attn21.view(batch_size, beam_size, h_attn21.size(-1))
h_attn21 = tensor_transformer(h_attn21, batch_size, beam_size)
h_attn22 = h_attn22.view(batch_size, beam_size, h_attn22.size(-1))
h_attn22 = tensor_transformer(h_attn22, batch_size, beam_size)
past_attn21 = past_attn21.view(batch_size, beam_size, past_attn21.size(-1))
past_attn21 = tensor_transformer(past_attn21, batch_size, beam_size)
past_attn22 = past_attn22.view(batch_size, beam_size, past_attn22.size(-1))
past_attn22 = tensor_transformer(past_attn22, batch_size, beam_size)
tmp_prb, tmp_idx = cand_prob.topk(k=beam_size, dim=1)
for x in range(batch_size):
for b in range(beam_size):
last_wd[x, b] = cand_last_wd[x, tmp_idx[x, b]]
beam_seq[x, b] = cand_seq[x, tmp_idx[x, b]]
beam_prb[x, b] = tmp_prb[x, b]
h0_new[x, b] = h0[x, tmp_idx[x, b]]
c0_new[x, b] = c0[x, tmp_idx[x, b]]
h_attn21_new[x, b] = h_attn21[x, tmp_idx[x, b]]
h_attn22_new[x, b] = h_attn22[x, tmp_idx[x, b]]
past_attn21_new[x, b] = past_attn21[x, tmp_idx[x, b]]
past_attn22_new[x, b] = past_attn22[x, tmp_idx[x, b]]
h0_new = h0_new.view(-1, h0_new.size(-1))
c0_new = c0_new.view(-1, c0_new.size(-1))
h_attn21_new = h_attn21_new.view(-1, h_attn21_new.size(-1))
h_attn22_new = h_attn22_new.view(-1, h_attn22_new.size(-1))
past_attn21_new = past_attn21_new.view(-1, past_attn21_new.size(-1))
past_attn22_new = past_attn22_new.view(-1, past_attn22_new.size(-1))
return beam_seq, beam_prb<|fim▁end|> | beam_size, |
<|file_name|>models.py<|end_file_name|><|fim▁begin|><|fim▁hole|>
def __init__(self, id_zone, name, region, description):
self.id = id_zone
self.name = name
self.region = region
self.description = description<|fim▁end|> | class Zone: |
<|file_name|>FilterByProbe.cpp<|end_file_name|><|fim▁begin|>#include "FilterByProbe.h"
#include "ProbeEvents.h"
#include "ProbeGlCalls.h"
#include "mmcore/CoreInstance.h"
#include "mmcore/EventCall.h"
#include "mmcore_gl/FlagCallsGL.h"
#include "mmcore_gl/utility/ShaderSourceFactory.h"
#include "probe/CallKDTree.h"
#include "probe/ProbeCalls.h"
#include "probe/ProbeCollection.h"
namespace megamol {
namespace probe_gl {
FilterByProbe::FilterByProbe()
: m_version(0)
, m_probe_selection()
, m_probes_slot("getProbes", "")
, m_kd_tree_slot("getKDTree", "")
, m_event_slot("getEvents", "")
, m_readFlagsSlot("getReadFlags", "")
, m_writeFlagsSlot("getWriteFlags", "") {
this->m_probes_slot.SetCompatibleCall<probe::CallProbesDescription>();
this->MakeSlotAvailable(&this->m_probes_slot);
this->m_kd_tree_slot.SetCompatibleCall<probe::CallKDTreeDescription>();
this->MakeSlotAvailable(&this->m_kd_tree_slot);
this->m_event_slot.SetCompatibleCall<megamol::core::CallEventDescription>();
this->MakeSlotAvailable(&this->m_event_slot);
this->m_readFlagsSlot.SetCompatibleCall<core_gl::FlagCallRead_GLDescription>();
this->MakeSlotAvailable(&this->m_readFlagsSlot);
this->m_writeFlagsSlot.SetCompatibleCall<core_gl::FlagCallWrite_GLDescription>();
this->MakeSlotAvailable(&this->m_writeFlagsSlot);
}
FilterByProbe::~FilterByProbe() {
this->Release();
}
bool FilterByProbe::create() {
try {
// create shader program
m_setFlags_prgm = std::make_unique<GLSLComputeShader>();
m_filterAll_prgm = std::make_unique<GLSLComputeShader>();
m_filterNone_prgm = std::make_unique<GLSLComputeShader>();
vislib_gl::graphics::gl::ShaderSource setFlags_src;
vislib_gl::graphics::gl::ShaderSource filterAll_src;
vislib_gl::graphics::gl::ShaderSource filterNone_src;
auto ssf =
std::make_shared<core_gl::utility::ShaderSourceFactory>(instance()->Configuration().ShaderDirectories());
if (!ssf->MakeShaderSource("FilterByProbe::setFlags", setFlags_src))
return false;
if (!m_setFlags_prgm->Compile(setFlags_src.Code(), setFlags_src.Count()))
return false;
if (!m_setFlags_prgm->Link())
return false;
if (!ssf->MakeShaderSource("FilterByProbe::filterAll", filterAll_src))
return false;
if (!m_filterAll_prgm->Compile(filterAll_src.Code(), filterAll_src.Count()))
return false;
if (!m_filterAll_prgm->Link())
return false;
if (!ssf->MakeShaderSource("FilterByProbe::filterNone", filterNone_src))
return false;
if (!m_filterNone_prgm->Compile(filterNone_src.Code(), filterNone_src.Count()))
return false;
if (!m_filterNone_prgm->Link())
return false;
} catch (vislib_gl::graphics::gl::AbstractOpenGLShader::CompileException ce) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(megamol::core::utility::log::Log::LEVEL_ERROR,
"Unable to compile shader (@%s): %s\n",
vislib_gl::graphics::gl::AbstractOpenGLShader::CompileException::CompileActionName(ce.FailedAction()),
ce.GetMsgA());
return false;
} catch (vislib::Exception e) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(
megamol::core::utility::log::Log::LEVEL_ERROR, "Unable to compile shader: %s\n", e.GetMsgA());
return false;
} catch (...) {
megamol::core::utility::log::Log::DefaultLog.WriteMsg(
megamol::core::utility::log::Log::LEVEL_ERROR, "Unable to compile shader: Unknown exception\n");
return false;
}
return true;
}
void FilterByProbe::release() {
m_setFlags_prgm.reset();
m_filterAll_prgm.reset();
}
bool FilterByProbe::GetExtents(core_gl::view::CallRender3DGL& call) {
return true;
}
bool FilterByProbe::Render(core_gl::view::CallRender3DGL& call) {
probe::CallProbes* pc = this->m_probes_slot.CallAs<probe::CallProbes>();
if (pc == NULL)
return false;
if (!(*pc)(0))
return false;
if (pc->hasUpdate()) {
auto probes = pc->getData();
m_probe_selection.resize(probes->getProbeCount());
}
// query kd tree data
auto ct = this->m_kd_tree_slot.CallAs<probe::CallKDTree>();
if (ct == nullptr)
return false;
if (!(*ct)(0))
return false;
// check for pending events
auto call_event_storage = this->m_event_slot.CallAs<core::CallEvent>();
if (call_event_storage != NULL) {
if ((!(*call_event_storage)(0)))
return false;
auto event_collection = call_event_storage->getData();
auto probes = pc->getData();
// process pobe clear selection events
{
auto pending_clearselection_events = event_collection->get<ProbeClearSelection>();
if (!pending_clearselection_events.empty()) {
std::fill(m_probe_selection.begin(), m_probe_selection.end(), false);
}
}
// process probe selection events
{
auto pending_select_events = event_collection->get<ProbeSelect>();
for (auto& evt : pending_select_events) {
m_probe_selection[evt.obj_id] = true;
}
}
// process probe deselection events
{
auto pending_deselect_events = event_collection->get<ProbeDeselect>();
for (auto& evt : pending_deselect_events) {
m_probe_selection[evt.obj_id] = false;
}
}
// process probe exclusive selection events
{
auto pending_selectExclusive_events = event_collection->get<ProbeSelectExclusive>();
if (!pending_selectExclusive_events.empty()) {
std::fill(m_probe_selection.begin(), m_probe_selection.end(), false);
m_probe_selection[pending_selectExclusive_events.back().obj_id] = true;
}
}
// process probe selection toggle events
{
auto pending_select_events = event_collection->get<ProbeSelectToggle>();
for (auto& evt : pending_select_events) {
m_probe_selection[evt.obj_id] = m_probe_selection[evt.obj_id] == true ? false : true;
}
}
// process clear filter events
{
auto pending_clearselection_events = event_collection->get<DataClearFilter>();
for (auto& evt : pending_clearselection_events) {
auto readFlags = m_readFlagsSlot.CallAs<core_gl::FlagCallRead_GL>();
auto writeFlags = m_writeFlagsSlot.CallAs<core_gl::FlagCallWrite_GL>();
if (readFlags != nullptr && writeFlags != nullptr) {
(*readFlags)(core_gl::FlagCallWrite_GL::CallGetData);
if (readFlags->hasUpdate()) {
this->m_version = readFlags->version();
}
++m_version;
auto flag_data = readFlags->getData();
{
m_filterNone_prgm->Enable();
auto flag_cnt = static_cast<GLuint>(flag_data->flags->getByteSize() / sizeof(GLuint));
glUniform1ui(m_filterNone_prgm->ParameterLocation("flag_cnt"), flag_cnt);
flag_data->flags->bind(1);
m_filterNone_prgm->Dispatch(static_cast<int>(std::ceil(flag_cnt / 64.0f)), 1, 1);
::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
m_filterNone_prgm->Disable();
}
writeFlags->setData(readFlags->getData(), m_version);
(*writeFlags)(core_gl::FlagCallWrite_GL::CallGetData);
}
}
}
// process probe selection events
{
auto pending_filter_event = event_collection->get<DataFilterByProbeSelection>();
if (!pending_filter_event.empty()) {
// TODO get corresponding data points from kd-tree
auto tree = ct->getData();
std::vector<uint32_t> indices;
for (size_t probe_idx = 0; probe_idx < m_probe_selection.size(); ++probe_idx) {
if (m_probe_selection[probe_idx] == true) {
// TODO get probe
auto generic_probe = probes->getGenericProbe(probe_idx);
auto visitor = [&tree, &indices](auto&& arg) {
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, probe::Vec4Probe> || std::is_same_v<T, probe::FloatProbe>) {
auto position = arg.m_position;
auto direction = arg.m_direction;
auto begin = arg.m_begin;
auto end = arg.m_end;
auto samples_per_probe = arg.getSamplingResult()->samples.size();
auto sample_step = end / static_cast<float>(samples_per_probe);
auto radius = sample_step * 2.0; // sample_radius_factor;
for (int j = 0; j < samples_per_probe; j++) {
pcl::PointXYZ sample_point;
sample_point.x = position[0] + j * sample_step * direction[0];
sample_point.y = position[1] + j * sample_step * direction[1];
sample_point.z = position[2] + j * sample_step * direction[2];
std::vector<float> k_distances;
std::vector<uint32_t> k_indices;
auto num_neighbors =
tree->radiusSearch(sample_point, arg.m_sample_radius, k_indices, k_distances);
if (num_neighbors == 0) {
num_neighbors = tree->nearestKSearch(sample_point, 1, k_indices, k_distances);
}
indices.insert(indices.end(), k_indices.begin(), k_indices.end());
} // end num samples per probe
}
};
std::visit(visitor, generic_probe);
}
}<|fim▁hole|> auto readFlags = m_readFlagsSlot.CallAs<core_gl::FlagCallRead_GL>();
auto writeFlags = m_writeFlagsSlot.CallAs<core_gl::FlagCallWrite_GL>();
if (readFlags != nullptr && writeFlags != nullptr) {
(*readFlags)(core_gl::FlagCallWrite_GL::CallGetData);
if (readFlags->hasUpdate()) {
this->m_version = readFlags->version();
}
++m_version;
auto flag_data = readFlags->getData();
auto kdtree_ids =
std::make_unique<glowl::BufferObject>(GL_SHADER_STORAGE_BUFFER, indices, GL_DYNAMIC_DRAW);
if (!indices.empty()) {
m_filterAll_prgm->Enable();
auto flag_cnt = static_cast<GLuint>(flag_data->flags->getByteSize() / sizeof(GLuint));
glUniform1ui(m_filterAll_prgm->ParameterLocation("flag_cnt"), flag_cnt);
flag_data->flags->bind(1);
m_filterAll_prgm->Dispatch(static_cast<int>(std::ceil(flag_cnt / 64.0f)), 1, 1);
::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
m_filterAll_prgm->Disable();
m_setFlags_prgm->Enable();
glUniform1ui(m_setFlags_prgm->ParameterLocation("id_cnt"), static_cast<GLuint>(indices.size()));
kdtree_ids->bind(0);
flag_data->flags->bind(1);
m_setFlags_prgm->Dispatch(static_cast<int>(std::ceil(indices.size() / 64.0f)), 1, 1);
::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
m_setFlags_prgm->Disable();
}
writeFlags->setData(readFlags->getData(), m_version);
(*writeFlags)(core_gl::FlagCallWrite_GL::CallGetData);
}
}
}
// process probe selection events
{
auto pending_filter_event = event_collection->get<DataFilterByProbingDepth>();
if (!pending_filter_event.empty()) {
// TODO get corresponding data points from kd-tree
auto tree = ct->getData();
std::vector<uint32_t> indices;
for (size_t probe_idx = 0; probe_idx < m_probe_selection.size(); ++probe_idx) {
auto generic_probe = probes->getGenericProbe(probe_idx);
auto visitor = [&tree, &indices, &pending_filter_event](auto&& arg) {
using T = std::decay_t<decltype(arg)>;
if constexpr (std::is_same_v<T, probe::Vec4Probe> || std::is_same_v<T, probe::FloatProbe>) {
auto position = arg.m_position;
auto direction = arg.m_direction;
auto begin = arg.m_begin;
auto end = arg.m_end;
auto samples_per_probe = arg.getSamplingResult()->samples.size();
auto sample_step = end / static_cast<float>(samples_per_probe);
auto radius = sample_step * 2.0; // sample_radius_factor;
float depth = std::min(end, pending_filter_event.back().depth);
//float depth = pending_filter_event.back().depth;
pcl::PointXYZ sample_point;
sample_point.x = position[0] + depth * direction[0];
sample_point.y = position[1] + depth * direction[1];
sample_point.z = position[2] + depth * direction[2];
std::vector<float> k_distances;
std::vector<uint32_t> k_indices;
auto num_neighbors =
tree->radiusSearch(sample_point, arg.m_sample_radius, k_indices, k_distances);
if (num_neighbors == 0) {
num_neighbors = tree->nearestKSearch(sample_point, 1, k_indices, k_distances);
}
indices.insert(indices.end(), k_indices.begin(), k_indices.end());
}
};
std::visit(visitor, generic_probe);
}
// TODO set flags
auto readFlags = m_readFlagsSlot.CallAs<core_gl::FlagCallRead_GL>();
auto writeFlags = m_writeFlagsSlot.CallAs<core_gl::FlagCallWrite_GL>();
if (readFlags != nullptr && writeFlags != nullptr) {
(*readFlags)(core_gl::FlagCallWrite_GL::CallGetData);
if (readFlags->hasUpdate()) {
this->m_version = readFlags->version();
}
++m_version;
auto flag_data = readFlags->getData();
auto kdtree_ids =
std::make_unique<glowl::BufferObject>(GL_SHADER_STORAGE_BUFFER, indices, GL_DYNAMIC_DRAW);
if (!indices.empty()) {
m_filterAll_prgm->Enable();
auto flag_cnt = static_cast<GLuint>(flag_data->flags->getByteSize() / sizeof(GLuint));
glUniform1ui(m_filterAll_prgm->ParameterLocation("flag_cnt"), flag_cnt);
flag_data->flags->bind(1);
m_filterAll_prgm->Dispatch(static_cast<int>(std::ceil(flag_cnt / 64.0f)), 1, 1);
::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
m_filterAll_prgm->Disable();
m_setFlags_prgm->Enable();
glUniform1ui(m_setFlags_prgm->ParameterLocation("id_cnt"), static_cast<GLuint>(indices.size()));
kdtree_ids->bind(0);
flag_data->flags->bind(1);
m_setFlags_prgm->Dispatch(static_cast<int>(std::ceil(indices.size() / 64.0f)), 1, 1);
::glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
m_setFlags_prgm->Disable();
}
writeFlags->setData(readFlags->getData(), m_version);
(*writeFlags)(core_gl::FlagCallWrite_GL::CallGetData);
}
}
}
}
return true;
}
void FilterByProbe::PreRender(core_gl::view::CallRender3DGL& call) {}
} // namespace probe_gl
} // namespace megamol<|fim▁end|> |
// TODO set flags |
<|file_name|>angular-desktop-notification-tests.ts<|end_file_name|><|fim▁begin|>import * as angular from 'angular';
angular
.module('app', ['ngDesktopNotification'])
.config(['desktopNotificationProvider', (desktopNotificationProvider: angular.desktopNotification.IDesktopNotificationProvider) => {
desktopNotificationProvider.config({
autoClose: true,
duration: 5,
showOnPageHidden: false,
});
}])
.controller('AppController', ['desktopNotification', (desktopNotification: angular.desktopNotification.IDesktopNotificationService) => {
// Check support and permission
const isNotificationSupported = desktopNotification.isSupported();
const currentNotificationPermission = desktopNotification.currentPermission();
if (currentNotificationPermission === desktopNotification.permissions.granted) {
// Permission granted
}
<|fim▁hole|> desktopNotification.requestPermission().then(
// Permission granted
(permission) => {
// Show notification
desktopNotification.show(
"Notification title",
{
tag: "tag",
body: "Notification body",
icon: "https://www.iconurl.com/icon-name.icon-extension",
onClick: () => {
// Notification clicked
}
});
},
() => {
// No permission granted
});
}]);<|fim▁end|> | // Request permission |
<|file_name|>issue-5521.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::collections::HashMap;
use std::gc::Gc;<|fim▁hole|><|fim▁end|> |
pub type map = Gc<HashMap<uint, uint>>; |
<|file_name|>0042_auto_20170507_2352.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-07 23:52
from __future__ import unicode_literals<|fim▁hole|>from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tableaubord', '0041_auto_20170507_2344'),
]
operations = [
migrations.AlterField(
model_name='evenement',
name='dateheure',
field=models.DateTimeField(default=datetime.datetime(2017, 5, 7, 23, 52, 53, 961581), verbose_name='Date/heure evenement '),
),
]<|fim▁end|> |
import datetime |
<|file_name|>bitcoin_lt.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="lt" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About GlobalDenomination</source>
<translation>Apie GlobalDenomination</translation>
</message>
<message>
<location line="+39"/>
<source><b>GlobalDenomination</b> version</source>
<translation><b>GlobalDenomination</b> versija</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>Tai eksperimentinė programa.
Platinama pagal MIT/X11 licenciją, kurią rasite faile COPYING arba http://www.opensource.org/licenses/mit-license.php.
Šiame produkte yra OpenSSL projekto kuriamas OpenSSL Toolkit (http://www.openssl.org/), Eric Young parašyta kriptografinė programinė įranga bei Thomas Bernard sukurta UPnP programinė įranga.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The GlobalDenomination developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adresų knygelė</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Spragtelėkite, kad pakeistumėte adresą arba žymę</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Sukurti naują adresą</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopijuoti esamą adresą į mainų atmintį</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Naujas adresas</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your GlobalDenomination 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>Tai yra jūsų GlobalDenomination adresai mokėjimų gavimui. Galite duoti skirtingus adresus atskiriems siuntėjams, kad galėtumėte sekti, kas jums moka.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Kopijuoti adresą</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Rodyti &QR kodą</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a GlobalDenomination address</source>
<translation>Pasirašykite žinutę, kad įrodytume, jog esate GlobalDenomination adreso savininkas</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Registruoti praneši&mą</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified GlobalDenomination address</source>
<translation>Patikrinkite žinutę, jog įsitikintumėte, kad ją pasirašė nurodytas GlobalDenomination adresas</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Tikrinti žinutę</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Trinti</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your GlobalDenomination addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Kopijuoti ž&ymę</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Keisti</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Eksportuoti adresų knygelės duomenis</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kableliais išskirtas failas (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Eksportavimo klaida</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Nepavyko įrašyti į failą %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Žymė</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresas</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(nėra žymės)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Slaptafrazės dialogas</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Įvesti slaptafrazę</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nauja slaptafrazė</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Pakartokite naują slaptafrazę</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<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>Įveskite naują piniginės slaptafrazę.<br/>Prašome naudoti slaptafrazę iš <b> 10 ar daugiau atsitiktinių simbolių</b> arba <b>aštuonių ar daugiau žodžių</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Užšifruoti piniginę</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Ši operacija reikalauja jūsų piniginės slaptafrazės jai atrakinti.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Atrakinti piniginę</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Ši operacija reikalauja jūsų piniginės slaptafrazės jai iššifruoti.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Iššifruoti piniginę</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Pakeisti slaptafrazę</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Įveskite seną ir naują piniginės slaptafrazes.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Patvirtinkite piniginės užšifravimą</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR GlobalDenominationS</b>!</source>
<translation>Dėmesio: jei užšifruosite savo piniginę ir pamesite slaptafrazę, jūs<b>PRARASITE VISUS SAVO GlobalDenominationUS</b>! </translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Ar tikrai norite šifruoti savo piniginę?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Įspėjimas: įjungtas Caps Lock klavišas!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Piniginė užšifruota</translation>
</message>
<message>
<location line="-56"/>
<source>GlobalDenomination will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your GlobalDenominations from being stolen by malware infecting your computer.</source>
<translation>GlobalDenomination dabar užsidarys šifravimo proceso pabaigai. Atminkite, kad piniginės šifravimas negali pilnai apsaugoti GlobalDenominationų vagysčių kai tinkle esančios kenkėjiškos programos patenka į jūsų kompiuterį.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Nepavyko užšifruoti piniginę</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Dėl vidinės klaidos nepavyko užšifruoti piniginę.Piniginė neužšifruota.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Įvestos slaptafrazės nesutampa.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Nepavyko atrakinti piniginę</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Neteisingai įvestas slaptažodis piniginės iššifravimui.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Nepavyko iššifruoti piniginės</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Piniginės slaptažodis sėkmingai pakeistas.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Pasirašyti ži&nutę...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Sinchronizavimas su tinklu ...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Apžvalga</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Rodyti piniginės bendrą apžvalgą</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Sandoriai</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Apžvelgti sandorių istoriją</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Redaguoti išsaugotus adresus bei žymes</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Parodyti adresų sąraša mokėjimams gauti</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Išeiti</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Išjungti programą</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about GlobalDenomination</source>
<translation>Rodyti informaciją apie GlobalDenomination</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Apie &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Rodyti informaciją apie Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Parinktys...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Užšifruoti piniginę...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Backup piniginę...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Keisti slaptafrazę...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a GlobalDenomination address</source>
<translation>Siųsti monetas GlobalDenomination adresui</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for GlobalDenomination</source>
<translation>Keisti GlobalDenomination konfigūracijos galimybes</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Daryti piniginės atsarginę kopiją</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Pakeisti slaptafrazę naudojamą piniginės užšifravimui</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Derinimo langas</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Atverti derinimo ir diagnostikos konsolę</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Tikrinti žinutę...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>GlobalDenomination</source>
<translation>GlobalDenomination</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Piniginė</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About GlobalDenomination</source>
<translation>&Apie GlobalDenomination</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Rodyti / Slėpti</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your GlobalDenomination addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified GlobalDenomination addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Failas</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Nustatymai</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Pagalba</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Kortelių įrankinė</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testavimotinklas]</translation>
</message>
<message>
<location line="+47"/>
<source>GlobalDenomination client</source>
<translation>GlobalDenomination klientas</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to GlobalDenomination network</source>
<translation><numerusform>%n GlobalDenomination tinklo aktyvus ryšys</numerusform><numerusform>%n GlobalDenomination tinklo aktyvūs ryšiai</numerusform><numerusform>%n GlobalDenomination tinklo aktyvūs ryšiai</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<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="-140"/>
<source>Up to date</source>
<translation>Atnaujinta</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Vejamasi...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Patvirtinti sandorio mokestį</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Sandoris nusiųstas</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Ateinantis sandoris</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Data: %1
Suma: %2
Tipas: %3
Adresas: %4</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>URI apdorojimas</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid GlobalDenomination address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Piniginė <b>užšifruota</b> ir šiuo metu <b>atrakinta</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Piniginė <b>užšifruota</b> ir šiuo metu <b>užrakinta</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. GlobalDenomination can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Tinklo įspėjimas</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Keisti adresą</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>Ž&ymė</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Žymė yra susieta su šios adresų knygelęs turiniu</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adresas</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>Adresas yra susietas su šios adresų knygelęs turiniu. Tai gali būti keičiama tik siuntimo adresams.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Naujas gavimo adresas</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Naujas siuntimo adresas</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Keisti gavimo adresą</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Keisti siuntimo adresą</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Įvestas adresas „%1“ jau yra adresų knygelėje.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid GlobalDenomination address.</source>
<translation>Įvestas adresas „%1“ nėra galiojantis GlobalDenomination adresas.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Nepavyko atrakinti piniginės.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Naujo rakto generavimas nepavyko.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>GlobalDenomination-Qt</source>
<translation>GlobalDenomination-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versija</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Naudojimas:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>komandinės eilutės parametrai</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Naudotoji sąsajos parametrai</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Nustatyti kalbą, pavyzdžiui "lt_LT" (numatyta: sistemos kalba)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Paleisti sumažintą</translation>
</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>Parinktys</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Pagrindinės</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>&Mokėti sandorio mokestį</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start GlobalDenomination after logging in to the system.</source>
<translation>Automatiškai paleisti Bitkoin programą įjungus sistemą.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start GlobalDenomination on system login</source>
<translation>&Paleisti GlobalDenomination programą su window sistemos paleidimu</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Tinklas</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the GlobalDenomination client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Automatiškai atidaryti GlobalDenomination kliento prievadą maršrutizatoriuje. Tai veikia tik tada, kai jūsų maršrutizatorius palaiko UPnP ir ji įjungta.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Persiųsti prievadą naudojant &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the GlobalDenomination network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Jungtis į Bitkoin tinklą per socks proxy (pvz. jungiantis per Tor)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Jungtis per SOCKS tarpinį serverį:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Tarpinio serverio &IP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Tarpinio serverio IP adresas (pvz. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Prievadas:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Tarpinio serverio preivadas (pvz, 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &versija:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Tarpinio serverio SOCKS versija (pvz., 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Langas</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Po programos lango sumažinimo rodyti tik programos ikoną.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&M sumažinti langą bet ne užduočių juostą</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>Uždarant langą neuždaryti programos. Kai ši parinktis įjungta, programa bus uždaryta tik pasirinkus meniu komandą Baigti.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>&Sumažinti uždarant</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Rodymas</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Naudotojo sąsajos &kalba:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting GlobalDenomination.</source>
<translation>Čia gali būti nustatyta naudotojo sąsajos kalba. Šis nustatymas įsigalios iš naujo paleidus GlobalDenomination.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Vienetai, kuriais rodyti sumas:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Rodomų ir siunčiamų monetų kiekio matavimo vienetai</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show GlobalDenomination addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Rodyti adresus sandorių sąraše</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&Gerai</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Atšaukti</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Pritaikyti</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>numatyta</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Įspėjimas</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting GlobalDenomination.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Nurodytas tarpinio serverio adresas negalioja.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Forma</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the GlobalDenomination network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Balansas:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Nepatvirtinti:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Piniginė</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Nepribrendę:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Naujausi sandoriai</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Jūsų einamasis balansas</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Iš viso sandorių, įskaitant tuos kurie dar turi būti patvirtinti, ir jie dar nėra įskaičiuotii į einamosios sąskaitos balansą</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start GlobalDenomination: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR kodo dialogas</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Prašau išmokėti</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Suma:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Žymė:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Žinutė:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>Į&rašyti kaip...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Klaida, koduojant URI į QR kodą.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Įvesta suma neteisinga, prašom patikrinti.</translation>
</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>Įrašyti QR kodą</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG paveikslėliai (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Kliento pavadinimas</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>nėra</translation>
</message>
<message><|fim▁hole|> <source>Client version</source>
<translation>Kliento versija</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Informacija</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Naudojama OpenSSL versija</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Paleidimo laikas</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Tinklas</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Prisijungimų kiekis</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Testnete</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blokų grandinė</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Dabartinis blokų skaičius</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Paskutinio bloko laikas</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Atverti</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Komandinės eilutės parametrai</translation>
</message>
<message>
<location line="+7"/>
<source>Show the GlobalDenomination-Qt help message to get a list with possible GlobalDenomination command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Rodyti</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsolė</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Kompiliavimo data</translation>
</message>
<message>
<location line="-104"/>
<source>GlobalDenomination - Debug window</source>
<translation>GlobalDenomination - Derinimo langas</translation>
</message>
<message>
<location line="+25"/>
<source>GlobalDenomination Core</source>
<translation>GlobalDenomination branduolys</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Derinimo žurnalo failas</translation>
</message>
<message>
<location line="+7"/>
<source>Open the GlobalDenomination 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>Išvalyti konsolę</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the GlobalDenomination 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 type="unfinished"/>
</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="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Siųsti monetas</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Siųsti keliems gavėjams vienu metu</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&A Pridėti gavėją</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Pašalinti visus sandorio laukus</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Išvalyti &viską</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Balansas:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Patvirtinti siuntimo veiksmą</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Siųsti</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> to %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Patvirtinti monetų siuntimą</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Ar tikrai norite siųsti %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> ir </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Negaliojantis gavėjo adresas. Patikrinkite.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Apmokėjimo suma turi būti didesnė nei 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Suma viršija jūsų balansą.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Jei pridedame sandorio mokestį %1 bendra suma viršija jūsų balansą.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Rastas adreso dublikatas.</translation>
</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>Klaida: sandoris buvo atmestas.Tai gali įvykti, jei kai kurios monetos iš jūsų piniginėje jau buvo panaudotos, pvz. jei naudojote wallet.dat kopiją ir monetos buvo išleistos kopijoje, bet nepažymėtos kaip skirtos išleisti čia.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Forma</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Su&ma:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Mokėti &gavėjui:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Įveskite žymę šiam adresui kad galėtumėte įtraukti ją į adresų knygelę</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>Ž&ymė:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Pasirinkite adresą iš adresų knygelės</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Įvesti adresą iš mainų atminties</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>Pašalinti šį gavėją</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a GlobalDenomination address (e.g. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</source>
<translation>Įveskite bitkoinų adresą (pvz. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Pasirašyti žinutę</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</source>
<translation>Įveskite bitkoinų adresą (pvz. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Pasirinkite adresą iš adresų knygelės</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Įvesti adresą iš mainų atminties</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>Įveskite pranešimą, kurį norite pasirašyti čia</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this GlobalDenomination address</source>
<translation>Registruotis žinute įrodymuii, kad turite šį adresą</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Išvalyti &viską</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Patikrinti žinutę</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</source>
<translation>Įveskite bitkoinų adresą (pvz. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified GlobalDenomination address</source>
<translation>Patikrinkite žinutę, jog įsitikintumėte, kad ją pasirašė nurodytas GlobalDenomination adresas</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a GlobalDenomination address (e.g. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</source>
<translation>Įveskite bitkoinų adresą (pvz. H7QEPyCg1Yv3UZUALDha9bNYXuYbfMe9Lp)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Spragtelėkite "Registruotis žinutę" tam, kad gauti parašą</translation>
</message>
<message>
<location line="+3"/>
<source>Enter GlobalDenomination signature</source>
<translation>Įveskite GlobalDenomination parašą</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Įvestas adresas negalioja.</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>Prašom patikrinti adresą ir bandyti iš naujo.</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>Piniginės atrakinimas atšauktas.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Žinutės pasirašymas nepavyko.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Žinutė pasirašyta.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Nepavyko iškoduoti parašo.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Prašom patikrinti parašą ir bandyti iš naujo.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Parašas neatitinka žinutės.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Žinutės tikrinimas nepavyko.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Žinutė patikrinta.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The GlobalDenomination developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testavimotinklas]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Atidaryta iki %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/neprisijungęs</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/nepatvirtintas</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 patvirtinimų</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Būsena</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Šaltinis</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Sugeneruotas</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Nuo</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Kam</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>savo adresas</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>žymė</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Kreditas</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>nepriimta</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debitas</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Sandorio mokestis</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Neto suma</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Žinutė</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Komentaras</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Sandorio ID</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 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>Išgautos monetos turi sulaukti 120 blokų, kol jos gali būti naudojamos. Kai sukūrėte šį bloką, jis buvo transliuojamas tinkle ir turėjo būti įtrauktas į blokų grandinę. Jei nepavyksta patekti į grandinę, bus pakeista į "nepriėmė", o ne "vartojamas". Tai kartais gali atsitikti, jei kitas mazgas per keletą sekundžių sukuria bloką po jūsų bloko.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Derinimo informacija</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Sandoris</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Suma</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>tiesa</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>netiesa</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, transliavimas dar nebuvo sėkmingas</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>nežinomas</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Sandorio detelės</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Šis langas sandorio detalų aprašymą</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipas</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adresas</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Suma</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Atidaryta iki %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Atjungta (%1 patvirtinimai)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Nepatvirtintos (%1 iš %2 patvirtinimų)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Patvirtinta (%1 patvirtinimai)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Šis blokas negautas nė vienu iš mazgų ir matomai nepriimtas</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Išgauta bet nepriimta</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Gauta su</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Gauta iš</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Siųsta </translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Mokėjimas sau</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Išgauta</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>nepasiekiama</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Sandorio būklė. Užvedus pelės žymeklį ant šios srities matysite patvirtinimų skaičių.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Sandorio gavimo data ir laikas</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Sandorio tipas.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Sandorio paskirties adresas</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Suma pridėta ar išskaičiuota iš balanso</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Visi</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Šiandien</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Šią savaitę</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Šį mėnesį</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Paskutinį mėnesį</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Šiais metais</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Intervalas...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Gauta su</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Išsiųsta</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Skirta sau</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Išgauta</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Kita</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Įveskite adresą ar žymę į paiešką</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimali suma</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopijuoti adresą</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopijuoti žymę</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopijuoti sumą</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Taisyti žymę</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Rodyti sandėrio detales</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Sandorio duomenų eksportavimas</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kableliais atskirtų duomenų failas (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Patvirtintas</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Data</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipas</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Žymė</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adresas</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Suma</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Eksportavimo klaida</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Neįmanoma įrašyti į failą %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Grupė:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>skirta</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Siųsti monetas</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<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>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>GlobalDenomination version</source>
<translation>GlobalDenomination versija</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Naudojimas:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or GlobalDenominationd</source>
<translation>Siųsti komandą serveriui arba GlobalDenominationd</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Komandų sąrašas</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Suteikti pagalba komandai</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Parinktys:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: GlobalDenomination.conf)</source>
<translation>Nurodyti konfigūracijos failą (pagal nutylėjimąt: GlobalDenomination.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: GlobalDenominationd.pid)</source>
<translation>Nurodyti pid failą (pagal nutylėjimą: GlobalDenominationd.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Nustatyti duomenų aplanką</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9348 or testnet: 19348)</source>
<translation>Sujungimo klausymas prijungčiai <port> (pagal nutylėjimą: 9348 arba testnet: 19348)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Palaikyti ne daugiau <n> jungčių kolegoms (pagal nutylėjimą: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Atjungimo dėl netinkamo kolegų elgesio riba (pagal nutylėjimą: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Sekundžių kiekis eikiamas palaikyti ryšį dėl lygiarangių nestabilumo (pagal nutylėjimą: 86.400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9347 or testnet: 19347)</source>
<translation>Klausymas JSON-RPC sujungimui prijungčiai <port> (pagal nutylėjimą: 9347 or testnet: 19347)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Priimti komandinę eilutę ir JSON-RPC komandas</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Dirbti fone kaip šešėlyje ir priimti komandas</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Naudoti testavimo tinklą</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=GlobalDenominationrpc
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 "GlobalDenomination Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<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="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. GlobalDenomination is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Įspėjimas: -paytxfee yra nustatytas per didelis. Tai sandorio mokestis, kurį turėsite mokėti, jei siųsite sandorį.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong GlobalDenomination will not work properly.</source>
<translation>Įspėjimas: Patikrinkite, kad kompiuterio data ir laikas yra teisingi.Jei Jūsų laikrodis neteisingai nustatytas GlobalDenomination, veiks netinkamai.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Prisijungti tik prie nurodyto mazgo</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Neteisingas tor adresas: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maksimalus buferis priėmimo sujungimui <n>*1000 bitų (pagal nutylėjimą: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maksimalus buferis siuntimo sujungimui <n>*1000 bitų (pagal nutylėjimą: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Išvesti papildomą derinimo informaciją. Numanomi visi kiti -debug* parametrai</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Išvesti papildomą tinklo derinimo informaciją</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Prideėti laiko žymę derinimo rezultatams</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the GlobalDenomination Wiki for SSL setup instructions)</source>
<translation>SSL opcijos (žr.e GlobalDenomination Wiki for SSL setup instructions)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Siųsti atsekimo/derinimo info į konsolę vietoj debug.log failo</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Siųsti sekimo/derinimo info derintojui</translation>
</message>
<message>
<location line="+5"/>
<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="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Nustatyti sujungimo trukmę milisekundėmis (pagal nutylėjimą: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Bandymas naudoti UPnP struktūra klausymosi prievadui (default: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Bandymas naudoti UPnP struktūra klausymosi prievadui (default: 1 when listening)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Vartotojo vardas JSON-RPC jungimuisi</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Slaptažodis JSON-RPC sujungimams</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Leisti JSON-RPC tik iš nurodytų IP adresų</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Siųsti komandą mazgui dirbančiam <ip> (pagal nutylėjimą: 127.0.0.1)</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Atnaujinti piniginę į naujausią formatą</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Nustatyti rakto apimties dydį <n> (pagal nutylėjimą: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Ieškoti prarastų piniginės sandorių blokų grandinėje</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Naudoti OpenSSL (https) jungimuisi JSON-RPC </translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Serverio sertifikato failas (pagal nutylėjimą: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Serverio privatus raktas (pagal nutylėjimą: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Priimtini šifrai (pagal nutylėjimą: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Pagelbos žinutė</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Nepavyko susieti šiame kompiuteryje prievado %s (bind returned error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Jungtis per socks tarpinį serverį</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Leisti DNS paiešką sujungimui ir mazgo pridėjimui</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Užkraunami adresai...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation> wallet.dat pakrovimo klaida, wallet.dat sugadintas</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of GlobalDenomination</source>
<translation> wallet.dat pakrovimo klaida, wallet.dat reikalauja naujasnės GlobalDenomination versijos</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart GlobalDenomination to complete</source>
<translation>Piniginė turi būti prrašyta: įvykdymui perkraukite GlobalDenomination</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation> wallet.dat pakrovimo klaida</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Neteisingas proxy adresas: '%s'</translation>
</message>
<message>
<location line="+56"/>
<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="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Neteisinga suma -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Neteisinga suma</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Nepakanka lėšų</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Įkeliamas blokų indeksas...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Pridėti mazgą prie sujungti su and attempt to keep the connection open</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. GlobalDenomination is probably already running.</source>
<translation>Nepavyko susieti šiame kompiuteryje prievado %s. GlobalDenomination tikriausiai jau veikia.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Įtraukti mokestį už kB siunčiamiems sandoriams</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Užkraunama piniginė...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Peržiūra</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Įkėlimas baigtas</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Klaida</translation>
</message>
<message>
<location line="-31"/>
<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><|fim▁end|> | <location line="-217"/> |
<|file_name|>kmers.go<|end_file_name|><|fim▁begin|>// Copyright © 2018-2021 Wei Shen <[email protected]>
//
// 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 sketches
var base2bit = [256]uint64{
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 0, 1, 1, 0, 4, 4, 2, 0, 4, 4, 2, 4, 0, 0, 4,
4, 4, 0, 1, 3, 3, 0, 0, 4, 1, 4, 4, 4, 4, 4, 4,
4, 0, 1, 1, 0, 4, 4, 2, 0, 4, 4, 2, 4, 0, 0, 4,
4, 4, 0, 1, 3, 3, 0, 0, 4, 1, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,<|fim▁hole|>var bit2base = [4]byte{'A', 'C', 'G', 'T'}<|fim▁end|> | }
|
<|file_name|>BuildMetadataServiceException.java<|end_file_name|><|fim▁begin|>package org.flysnow.cloud.buildmeta.ui.resteasy.exception;
import java.io.Serializable;
public class BuildMetadataServiceException extends RuntimeException implements Serializable {
private static final long serialVersionUID = 7786141544419367058L;
public BuildMetadataServiceException(){
super();
}
public BuildMetadataServiceException(String message, Throwable cause){
super(message, cause);<|fim▁hole|> }
public BuildMetadataServiceException(String msg){
super(msg);
}
}<|fim▁end|> | }
public BuildMetadataServiceException(Throwable cause){
super(cause); |
<|file_name|>project.py<|end_file_name|><|fim▁begin|># Copyright 2014 Dietrich Epp.
# This file is part of SGLib. SGLib is licensed under the terms of the
# 2-clause BSD license. For more information, see LICENSE.txt.
import uuid as uuid_module
import xml.etree.ElementTree as etree
from ..util import indent_xml
from ..error import ConfigError
import io
import os
Element = etree.Element
SubElement = etree.SubElement
XMLNS = 'http://schemas.microsoft.com/developer/msbuild/2003'
def condition(variant):
return "'$(Configuration)|$(Platform)'=='{}'".format(variant)
SOURCE_TYPES = {kk: (n, v) for n, (k, v) in enumerate([
('c c++', 'ClCompile'),
('h h++', 'ClInclude'),
('rc', 'ResourceCompile'),
('vcxproj', 'ProjectReference'),
]) for kk in k.split()}
def proj_import(root, path):
SubElement(root, 'Import', {'Project': path})
def emit_properties(*, element, props, var=None):
for k, v in sorted(props.items()):
if isinstance(v, list):
assert var is not None
vs = '{};{}({})'.format(';'.join(v), var, k)
elif isinstance(v, bool):
vs = str(v).lower()
elif isinstance(v, str):
vs = v
else:
raise TypeError('unexpected property type: {}'.format(type(v)))
SubElement(element, k).text = vs
TYPE_CPP = uuid_module.UUID('8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942')
class Project(object):
"""A Visual Studio project."""
__slots__ = [
# The project name.
'name',
# Path to the project file.
'path',
# The project type UUID.
'type',
# The project UUID.
'uuid',
# Map from solution (config, platform) to project (config, platform).
'configs',
# List of project dependencies (other projects).
'dependencies',
]
@property
def sourcetype(self):
return 'vcxproj'
def emit(self):
"""Emit project files if necessary."""
class UserProject(Project):
"""A user-generated Visual Studio project."""
__slots__ = [
# Contents of the project file.
'_data_project',
# Contents of the filter file.
'_data_filter',
# Contents of the user file.
'_data_user',
]
def emit(self):
"""Emit project files if necessary."""
with open(self.name + '.vcxproj', 'wb') as fp:
fp.write(self._data_project)
with open(self.name + '.vcxproj.filters', 'wb') as fp:
fp.write(self._data_filter)
with open(self.name + '.vcxproj.user', 'wb') as fp:
fp.write(self._data_user)
def read_project(*, path, configs):
"""Read a Visual Studio project."""<|fim▁hole|>
def get_uuid():
gtag = etree.QName(XMLNS, 'PropertyGroup')
ptag = etree.QName(XMLNS, 'ProjectGuid')
for gelem in doc.getroot():
if gelem.tag == gtag:
for pelem in gelem:
if pelem.tag == ptag:
return uuid_module.UUID(pelem.text)
raise ConfigError('could not detect project UUID: {}'.format(path))
def get_configs():
gtag = etree.QName(XMLNS, 'ItemGroup')
itag = etree.QName(XMLNS, 'ProjectConfiguration')
ctag = etree.QName(XMLNS, 'Configuration')
ptag = etree.QName(XMLNS, 'Platform')
configs = []
for gelem in doc.getroot():
if (gelem.tag != gtag or
gelem.attrib.get('Label') != 'ProjectConfigurations'):
continue
for ielem in gelem:
if ielem.tag != itag:
continue
cfg = None
plat = None
for pelem in ielem:
if pelem.tag == ctag:
cfg = pelem.text
elif pelem.tag == ptag:
plat = pelem.text
if cfg is None or plat is None:
raise ConfigError(
'could not parse project configurations')
configs.append((cfg, plat))
return configs
obj = Project()
obj.name = os.path.splitext(os.path.basename(path))[0]
obj.path = path
obj.type = TYPE_CPP
obj.uuid = get_uuid()
obj.configs = configs
obj.dependencies = []
return obj
def xml_data(root):
indent_xml(root)
return etree.tostring(root, encoding='UTF-8')
def create_project(*, name, sources, uuid, variants, props, arguments):
"""Create a Visual Studio project.
name: the project name.
sources: list of source files in the project.
uuid: the project UUID.
variants: list of "config|arch" variants.
props: map from "config|arch" to map from group to prop dict.
arguments: default arguments for debugging.
"""
def create_project():
root = Element('Project', {
'xmlns': XMLNS,
'ToolsVersion': '12.0',
'DefaultTargets': 'Build',
})
cfgs = SubElement(
root, 'ItemGroup', {'Label': 'ProjectConfigurations'})
for variant in variants:
pc = SubElement(
cfgs, 'ProjectConfiguration', {'Include': variant})
configuration, platform = variant.split('|')
SubElement(pc, 'Configuration').text = configuration
SubElement(pc, 'Platform').text = platform
del cfgs, variant, configuration, platform, pc
pg = SubElement(root, 'PropertyGroup', {'Label': 'Globals'})
SubElement(pg, 'Keyword').text = 'Win32Proj'
SubElement(pg, 'ProjectGuid').text = \
'{{{}}}'.format(str(uuid).upper())
# RootNamespace
del pg
proj_import(root, '$(VCTargetsPath)\\Microsoft.Cpp.Default.props')
for variant in variants:
emit_properties(
element=SubElement(root, 'PropertyGroup', {
'Condition': condition(variant),
'Label': 'Configuration',
}),
props=props[variant]['Config'])
del variant
proj_import(root, '$(VCTargetsPath)\\Microsoft.Cpp.props')
SubElement(root, 'ImportGroup', {'Label': 'ExtensionSettings'})
for variant in variants:
ig = SubElement(root, 'ImportGroup', {
'Label': 'PropertySheets',
'Condition': condition(variant),
})
path = '$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props'
i = SubElement(ig, 'Import', {
'Project': path,
'Condition': "exists('{}')".format(path),
'Label': 'LocalAppDataPlatform',
})
del variant, ig, path, i
SubElement(root, 'PropertyGroup', {'Label': 'UserMacros'})
for variant in variants:
emit_properties(
element=SubElement(root, 'PropertyGroup', {
'Condition': condition(variant),
}),
props=props[variant]['VC'],
var='$')
del variant
for variant in variants:
ig = SubElement(root, 'ItemDefinitionGroup', {
'Condition': condition(variant),
})
for group in ('ClCompile', 'Link'):
emit_properties(
element=SubElement(ig, group),
props=props[variant][group],
var='%')
del variant, ig, group
groups = {}
for source in sources:
try:
index, tag = SOURCE_TYPES[source.sourcetype]
except KeyError:
raise ConfigError(
'cannot add file to executable: {}'.format(source.path))
try:
group = groups[index]
except KeyError:
group = Element('ItemGroup')
groups[index] = group
src = SubElement(group, tag, {'Include': source.path})
if tag == 'ProjectReference':
SubElement(src, 'Project').text = \
'{{{}}}'.format(str(source.uuid).upper())
del source, index, tag, group, src
for n, elt in sorted(groups.items()):
root.append(elt)
del n, elt
proj_import(root, '$(VCTargetsPath)\\Microsoft.Cpp.targets')
SubElement(root, 'ImportGroup', {'Label': 'ExtensionTargets'})
return root
def create_filter():
filters = set()
root = Element('Project', {
'xmlns': XMLNS,
'ToolsVersion': '12.0',
})
groups = {}
for source in sources:
index, tag = SOURCE_TYPES[source.sourcetype]
if tag == 'ProjectReference':
continue
try:
group = groups[index]
except KeyError:
group = Element('ItemGroup')
groups[index] = group
elt = SubElement(group, tag, {'Include': source.path})
dirname, basename = os.path.split(source.path)
if not dirname:
continue
filter = dirname
SubElement(elt, 'Filter').text = filter
while filter and filter not in filters:
filters.add(filter)
filter = os.path.dirname(filter)
for n, elt in sorted(groups.items()):
root.append(elt)
fgroup = SubElement(root, 'ItemGroup')
for filter in sorted(filters):
elt = SubElement(fgroup, 'Filter', {'Include': filter})
SubElement(elt, 'UniqueIdentifier').text = \
'{{{}}}'.format(str(uuid_module.uuid4()).upper())
return root
def convert_arg(arg):
return '"{}"'.format(arg)
def create_user():
root = Element('Project', {
'xmlns': XMLNS,
'ToolsVersion': '12.0',
})
args = ' '.join(convert_arg(arg) for arg in arguments)
for variant in variants:
pg = SubElement(root, 'PropertyGroup', {
'Condition': condition(variant),
})
SubElement(pg, 'LocalDebuggerCommandArguments').text = args
SubElement(pg, 'DebuggerFlavor').text = 'WindowsLocalDebugger'
epath = props[variant]['Debug'].get('Path', ())
if epath:
SubElement(pg, 'LocalDebuggerEnvironment').text = \
'PATH=%PATH%;' + ';'.join(epath)
return root
def create_object():
configs = set(x.split('|')[0] for x in variants)
obj = UserProject()
obj.name = name
obj.path = name + '.vcxproj'
obj.type = TYPE_CPP
obj.uuid = uuid
obj.configs = {c: c for c in configs}
obj.dependencies = [source for source in sources
if source.sourcetype == 'vcxproj']
obj._data_project = xml_data(create_project())
obj._data_filter = xml_data(create_filter())
obj._data_user = xml_data(create_user())
return obj
return create_object()<|fim▁end|> | if os.path.splitext(path)[1] != '.vcxproj':
raise UserError('invalid Visual Studio project extension')
with open(path, 'rb') as fp:
doc = etree.parse(fp) |
<|file_name|>gps_l1_ca_kf_tracking.cc<|end_file_name|><|fim▁begin|>/*!
* \file gps_l1_ca_kf_tracking.cc
* \brief Implementation of an adapter of a DLL + Kalman carrier
* tracking loop block for GPS L1 C/A signals
* \author Javier Arribas, 2018. jarribas(at)cttc.es
* \author Jordi Vila-Valls 2018. jvila(at)cttc.es
* \author Carles Fernandez-Prades 2018. cfernandez(at)cttc.es
*
* Reference:
* J. Vila-Valls, P. Closas, M. Navarro and C. Fernández-Prades,
* "Are PLLs Dead? A Tutorial on Kalman Filter-based Techniques for Digital
* Carrier Synchronization", IEEE Aerospace and Electronic Systems Magazine,
* Vol. 32, No. 7, pp. 28–45, July 2017. DOI: 10.1109/MAES.2017.150260
*
* -----------------------------------------------------------------------------
*
* GNSS-SDR is a Global Navigation Satellite System software-defined receiver.
* This file is part of GNSS-SDR.
*
* Copyright (C) 2010-2020 (see AUTHORS file for a list of contributors)
* SPDX-License-Identifier: GPL-3.0-or-later
*
* -----------------------------------------------------------------------------
*/
#include "gps_l1_ca_kf_tracking.h"
#include "GPS_L1_CA.h"
#include "configuration_interface.h"
#include "gnss_sdr_flags.h"<|fim▁hole|>GpsL1CaKfTracking::GpsL1CaKfTracking(
const ConfigurationInterface* configuration, const std::string& role,
unsigned int in_streams, unsigned int out_streams) : role_(role), in_streams_(in_streams), out_streams_(out_streams)
{
DLOG(INFO) << "role " << role;
// ################# CONFIGURATION PARAMETERS ########################
const std::string default_item_type("gr_complex");
std::string item_type = configuration->property(role + ".item_type", default_item_type);
int order = configuration->property(role + ".order", 2);
int fs_in_deprecated = configuration->property("GNSS-SDR.internal_fs_hz", 2048000);
int fs_in = configuration->property("GNSS-SDR.internal_fs_sps", fs_in_deprecated);
bool dump = configuration->property(role + ".dump", false);
float dll_bw_hz = configuration->property(role + ".dll_bw_hz", static_cast<float>(2.0));
if (FLAGS_dll_bw_hz != 0.0)
{
dll_bw_hz = static_cast<float>(FLAGS_dll_bw_hz);
}
float early_late_space_chips = configuration->property(role + ".early_late_space_chips", static_cast<float>(0.5));
const std::string default_dump_filename("./track_ch");
std::string dump_filename = configuration->property(role + ".dump_filename", default_dump_filename);
const auto vector_length = static_cast<int>(std::round(fs_in / (GPS_L1_CA_CODE_RATE_CPS / GPS_L1_CA_CODE_LENGTH_CHIPS)));
bool bce_run = configuration->property(role + ".bce_run", false);
unsigned int bce_ptrans = configuration->property(role + ".p_transient", 0);
unsigned int bce_strans = configuration->property(role + ".s_transient", 0);
int bce_nu = configuration->property(role + ".bce_nu", 0);
int bce_kappa = configuration->property(role + ".bce_kappa", 0);
// ################# MAKE TRACKING GNURadio object ###################
if (item_type == "gr_complex")
{
item_size_ = sizeof(gr_complex);
tracking_ = gps_l1_ca_kf_make_tracking_cc(
order,
fs_in,
vector_length,
dump,
dump_filename,
dll_bw_hz,
early_late_space_chips,
bce_run,
bce_ptrans,
bce_strans,
bce_nu,
bce_kappa);
}
else
{
item_size_ = 0;
LOG(WARNING) << item_type << " unknown tracking item type.";
}
channel_ = 0;
DLOG(INFO) << "tracking(" << tracking_->unique_id() << ")";
if (in_streams_ == 0)
{
in_streams_ = 1;
// Avoid compiler warning
}
if (out_streams_ == 0)
{
out_streams_ = 1;
// Avoid compiler warning
}
}
void GpsL1CaKfTracking::stop_tracking()
{
}
void GpsL1CaKfTracking::start_tracking()
{
tracking_->start_tracking();
}
/*
* Set tracking channel unique ID
*/
void GpsL1CaKfTracking::set_channel(unsigned int channel)
{
channel_ = channel;
tracking_->set_channel(channel);
}
void GpsL1CaKfTracking::set_gnss_synchro(Gnss_Synchro* p_gnss_synchro)
{
tracking_->set_gnss_synchro(p_gnss_synchro);
}
void GpsL1CaKfTracking::connect(gr::top_block_sptr top_block)
{
if (top_block)
{ /* top_block is not null */
};
// nothing to connect, now the tracking uses gr_sync_decimator
}
void GpsL1CaKfTracking::disconnect(gr::top_block_sptr top_block)
{
if (top_block)
{ /* top_block is not null */
};
// nothing to disconnect, now the tracking uses gr_sync_decimator
}
gr::basic_block_sptr GpsL1CaKfTracking::get_left_block()
{
return tracking_;
}
gr::basic_block_sptr GpsL1CaKfTracking::get_right_block()
{
return tracking_;
}<|fim▁end|> | #include <glog/logging.h>
|
<|file_name|>invenio_2013_06_24_new_bibsched_status_table.py<|end_file_name|><|fim▁begin|><|fim▁hole|># Copyright (C) 2012 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# Invenio is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
from invenio.legacy.dbquery import run_sql
depends_on = ['invenio_release_1_1_0']
def info():
return "New bibsched status (schSTATUS) table"
def do_upgrade():
run_sql("""CREATE TABLE IF NOT EXISTS schSTATUS (
name varchar(50),
value mediumblob,
PRIMARY KEY (name)
) ENGINE=MyISAM
""")
def estimate():
return 1<|fim▁end|> | # -*- coding: utf-8 -*-
#
# This file is part of Invenio. |
<|file_name|>sim.py<|end_file_name|><|fim▁begin|>""" Pymulator simulation objects """
import json
import datetime
from .serialize import PandasNumpyEncoderMixIn, hook
def importmodel(s):
"""
Import model from string s specifying a callable. The string has the
following structure:
package[.package]*.model[:function]
For example:
foo.bar.mod:func
Will be imported as
from foo.bar.mod import func
TODO: unbound class method
"""
mname, fname = s.split(':')
mod = __import__(mname, globals(), locals(), (fname,), 0)
f = getattr(mod, fname)
if not callable(f):
raise ValueError("Model is not callable")
return f
def funstr(fun):
if not callable(fun):
raise ValueError("Not a callable: {}".format(fun))
return '{x.__module__}:{x.__qualname__}'.format(x=fun)
class Sim(object):
"""
Simulation configuration. Includes information abou:
- parameter spans
- model callable
- model outputs
- results
- PRNG seed / internal state
This class mainly for correct JSON serialization/deserialization of the above information.
"""
def __init__(self, modelstr, spans, outputs, seed=None):
self.spans = spans
self.model = modelstr
self.outputs = outputs
self.timestamp = datetime.datetime.now()
self.seed = seed
def __eq__(self, other):
def _(obj):
d = dict(obj.__dict__)
return (d, d.pop('results', None), d.pop('state', None))
return all(map(all, _(self), _(other)))
def _getspans(self):
return dict(self._spans)
def _setspans(self, spans):
if not hasattr(self, '_spans'):
self._spans= {}
for argument, vals_or_range in spans.items():
self._spans[str(argument)] = list(vals_or_range)
def _delspans(self):
self._spans.clear()
spans = property(_getspans, _setspans, _delspans, doc="Simulation spans")
def _getmodel(self):
return self._f
def _setmodel(self, f_or_str):
if isinstance(f_or_str, str):
self._modelstr = f_or_str
self._f = importmodel(f_or_str)
elif callable(f_or_str):
self._modelstr = funstr(f_or_str)
self._f = f_or_str
else:
raise ValueError('Neither a callable nor a string: {}'.format(f_or_str))
def _delmodel(self):
del self._f
del self._modelstr
model = property(_getmodel, _setmodel, _delmodel, "Simulation model")
def _setoutputs(self, outputs):
self._outputs = list(map(str, outputs))
def _getoutputs(self):
return list(self._outputs)
def _deloutput(self):
self._outputs.clear()
outputs = property(_getoutputs, _setoutputs, _deloutput, "Model outputs")
def todict(self):
d = {
'spans': self.spans,
'model': funstr(self.model),
'timestamp': str(self.timestamp),
'outputs': self.outputs
}
if hasattr(self, 'results'):
d['results'] = self.results
if hasattr(self, 'seed'):
d['seed'] = self.seed
if hasattr(self, 'state'):
d['state'] = self.state
return d
def dumps(self):
return json.dumps(self.todict(), cls=PandasNumpyEncoderMixIn, indent=4)
def dump(self, path):
with open(path, 'w') as f:
f.write(self.dumps())<|fim▁hole|> def load(self, path):
with open(path) as f:
return self.loads(f.read())<|fim▁end|> |
def loads(self, s):
return json.loads(s, hook=hook)
|
<|file_name|>App.js<|end_file_name|><|fim▁begin|>// App.js
import React from 'react';
import { browserHistory } from 'react-router';
// import components
import NavBar from './navbar/components/NavBar';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {}
this.getComponentsXHR = this.getComponentsXHR.bind(this);<|fim▁hole|> this.getPostsXHR = this.getPostsXHR.bind(this);
this.sendPostsToStore = this.sendPostsToStore.bind(this);
}
componentDidMount() {
this.getComponentsXHR();
this.getPostsXHR();
let token = localStorage.getItem('token');
if(!token) {
this.checkUser();
}
}
checkUser() {
let that = this;
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if(xhr.status === 200 && xhr.readyState === 4) {
that.handleUserData(JSON.parse(xhr.responseText));
}
}
xhr.open('GET', '/api/users');
xhr.send();
}
handleUserData(userData) {
if(userData.length === 0) {
browserHistory.push('/signup')
}
}
getComponentsXHR() {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if(xhr.status === 200 && xhr.readyState === 4) {
this.sendComponentsToStore(JSON.parse(xhr.responseText));
}
}
xhr.open('GET', '/api/plugins');
xhr.send();
}
sendComponentsToStore(pluginData) {
let plugins = [];
pluginData.forEach(plugin => {
plugins.push(plugin);
})
this.props.getComponents(plugins);
}
getPostsXHR() {
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if(xhr.status === 200 && xhr.readyState === 4) {
this.sendPostsToStore(JSON.parse(xhr.responseText));
}
}
xhr.open('GET', '/api/posts');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send();
}
sendPostsToStore(postData) {
let posts = {};
postData.forEach(post => {
posts[post._id] = post;
})
this.props.getPosts(posts);
}
logoutUser() {
localStorage.removeItem('token');
localStorage.removeItem('userId')
}
render() {
return (
<div>
<NavBar hasToken={this.props.user} logoutUser={this.logoutUser} />
<div className="container-fluid">
{React.cloneElement(this.props.children, this.props)}
</div>
</div>
)
}
}<|fim▁end|> | this.checkUser = this.checkUser.bind(this);
this.sendComponentsToStore = this.sendComponentsToStore.bind(this); |
<|file_name|>generate.py<|end_file_name|><|fim▁begin|>import resume.models as rmod
import random
import logging
from django.http import HttpResponse
from datetime import date
logger = logging.getLogger('default')
def generate(request):
cs_objs = rmod.Department.objects.filter(shortname='cs')
if len(cs_objs) == 0:
logger.info('created cs dept')
cs = rmod.Department(name='Computer Science', shortname='cs', lastChange=0,\
headerImage='', logoImage='', resumeImage='', headerBgImage='',\
brandColor='blue', contactName='Donald Knuth', contactEmail='[email protected]',\
techEmail='[email protected]')
cs.save()
else:
logger.info('used pre-existing cs dept')
cs = cs_objs[0]
ct_objs = rmod.ComponentType.objects.filter(short='ta')
if len(ct_objs) == 0:
logger.info('created component type')
ct = rmod.ComponentType(type='contactlong', name='type a', short='ta', department=cs)
ct.save()
else:
logger.info('used existing component type')
ct = ct_objs[0]
ct_objs = rmod.ComponentType.objects.filter(short='stmt')
if len(ct_objs) == 0:
logger.info('created component type')
ct = rmod.ComponentType(type='statement', name='Research Statement', short='stmt', department=cs)
ct.save()
else:
logger.info('used existing component type')
ct = ct_objs[0]
auth_objs = rmod.AuthInfo.objects.all()
if len(auth_objs) == 0:
return HttpResponse("No auth_info objects to use")
auth = auth_objs[0]
pos_objs = rmod.ApplicantPosition.objects.filter(name='pos1')
if len(pos_objs) == 0:
logger.info('created app position')
pos = rmod.ApplicantPosition(department=cs, name='pos1', shortform='p1',\
autoemail=False)
pos.save()
else:
logger.info('used existing app position')
pos = pos_objs[0]
a_objs = rmod.Applicant.objects.filter(auth=auth)
if len(a_objs) == 0:
logger.error('ERROR: created applicant')
a = rmod.Applicant(auth=auth, firstname='john', lastname='doe', country='usa',\
department=cs, position=pos)<|fim▁hole|> a.save()
else:
logger.info('used existing applicant')
a = a_objs[0]
c_objs = rmod.Component.objects.filter(applicant=a)
if len(c_objs) == 0:
logger.info('created component')
c = rmod.Component(applicant=a, type=ct, value='component 1', lastSubmitted=0,\
department=cs)
c.save()
else:
logger.info('used existing component')
c = c_objs[0]
reviewer_objs = rmod.Reviewer.objects.filter(auth=auth)
if len(reviewer_objs) == 0:
logger.info('created reviewer')
reviewer = rmod.Reviewer(auth=auth, department=cs)
reviewer.save()
else:
logger.info('used existing reviewer')
reviewer = reviewer_objs[0]
review_objs = rmod.Review.objects.filter(applicant=a)
if len(review_objs) == 0:
logger.info('created review')
review = rmod.Review(applicant=a, reviewer=reviewer, advocate='advocate',\
comments='this shit sucks', draft=False, department=cs)
review.save()
else:
logger.info('used existing review')
review = review_objs[0]
area_objs = rmod.Area.objects.filter(department=cs)
if len(area_objs) < 2:
a = rmod.Area(name='area two', abbr='a2', department=cs)
a.save()
a = rmod.Area(name='area one', abbr='a1', department=cs)
a.save()
score_cats = rmod.ScoreCategory.objects.filter(department=cs)
if len(score_cats) == 0:
sc = rmod.ScoreCategory(name='Awesomeness Level', shortform='AL', department=cs)
sc.save()
else:
sc = score_cats[0]
score_vals = rmod.ScoreValue.objects.filter(department=cs)
if len(score_vals) == 0:
for i in range(5):
sv = rmod.ScoreValue(category=sc, number=i, explanation='%d level of awesome' % i,\
department=cs)
sv.save()
return HttpResponse('OK')<|fim▁end|> | |
<|file_name|>letter_count.py<|end_file_name|><|fim▁begin|>def LetterCount(str):
words = str.split(" ")
result_word = ""<|fim▁hole|> for word in words:
word_map = {}
for ch in word:
if ch in word_map:
word_map[ch] += 1
else:
word_map[ch] = 1
max_key = max(word_map.iterkeys(), key=lambda k: word_map[k])
if letter_count < word_map[max_key] and word_map[max_key] > 1:
letter_count = word_map[max_key]
result_word = word
return result_word if letter_count > 1 else -1
print LetterCount("Hello apple pie")
print LetterCount("No words")<|fim▁end|> | letter_count = 0 |
<|file_name|>16_gzip.go<|end_file_name|><|fim▁begin|>package main
import (
"compress/gzip"
"fmt"
"io/ioutil"
"os"
)
func main() {
fpath := "test.tar.gz"
if err := toGzip("Hello World!", fpath); err != nil {
panic(err)
}
if tb, err := toBytes(fpath); err != nil {
panic(err)
} else {
fmt.Println(fpath, ":", string(tb))
// test.tar.gz : Hello World!
}
os.Remove(fpath)
}
// exec.Command("gzip", "-f", fpath).Run()
func toGzip(txt, fpath string) error {<|fim▁hole|> if err != nil {
return err
}
}
defer f.Close()
gw := gzip.NewWriter(f)
if _, err := gw.Write([]byte(txt)); err != nil {
return err
}
gw.Close()
gw.Flush()
return nil
}
func toBytes(fpath string) ([]byte, error) {
f, err := os.OpenFile(fpath, os.O_RDONLY, 0444)
if err != nil {
return nil, err
}
defer f.Close()
fz, err := gzip.NewReader(f)
if err != nil {
return nil, err
}
defer fz.Close()
// or JSON
// http://jmoiron.net/blog/crossing-streams-a-love-letter-to-ioreader/
s, err := ioutil.ReadAll(fz)
if err != nil {
return nil, err
}
return s, nil
}<|fim▁end|> | f, err := os.OpenFile(fpath, os.O_RDWR|os.O_TRUNC, 0777)
if err != nil {
f, err = os.Create(fpath) |
<|file_name|>rte.py<|end_file_name|><|fim▁begin|># coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_HTTPError
from ..utils import (
float_or_none,
parse_iso8601,
str_or_none,
try_get,
unescapeHTML,
url_or_none,
ExtractorError,
)
class RteBaseIE(InfoExtractor):
def _real_extract(self, url):
item_id = self._match_id(url)
info_dict = {}
formats = []
ENDPOINTS = (
'https://feeds.rasset.ie/rteavgen/player/playlist?type=iptv&format=json&showId=',
'http://www.rte.ie/rteavgen/getplaylist/?type=web&format=json&id=',
)
for num, ep_url in enumerate(ENDPOINTS, start=1):
try:
data = self._download_json(ep_url + item_id, item_id)
except ExtractorError as ee:
if num < len(ENDPOINTS) or formats:
continue
if isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404:
error_info = self._parse_json(ee.cause.read().decode(), item_id, fatal=False)
if error_info:
raise ExtractorError(
'%s said: %s' % (self.IE_NAME, error_info['message']),
expected=True)
raise
# NB the string values in the JSON are stored using XML escaping(!)
show = try_get(data, lambda x: x['shows'][0], dict)
if not show:
continue
if not info_dict:
title = unescapeHTML(show['title'])
description = unescapeHTML(show.get('description'))
thumbnail = show.get('thumbnail')
duration = float_or_none(show.get('duration'), 1000)
timestamp = parse_iso8601(show.get('published'))
info_dict = {
'id': item_id,
'title': title,
'description': description,
'thumbnail': thumbnail,
'timestamp': timestamp,
'duration': duration,
}
mg = try_get(show, lambda x: x['media:group'][0], dict)
if not mg:
continue
if mg.get('url'):
m = re.match(r'(?P<url>rtmpe?://[^/]+)/(?P<app>.+)/(?P<playpath>mp4:.*)', mg['url'])
if m:
m = m.groupdict()
formats.append({
'url': m['url'] + '/' + m['app'],
'app': m['app'],
'play_path': m['playpath'],
'player_url': url,
'ext': 'flv',
'format_id': 'rtmp',
})
if mg.get('hls_server') and mg.get('hls_url'):
formats.extend(self._extract_m3u8_formats(
mg['hls_server'] + mg['hls_url'], item_id, 'mp4',
entry_protocol='m3u8_native', m3u8_id='hls', fatal=False))
if mg.get('hds_server') and mg.get('hds_url'):
formats.extend(self._extract_f4m_formats(
mg['hds_server'] + mg['hds_url'], item_id,
f4m_id='hds', fatal=False))
mg_rte_server = str_or_none(mg.get('rte:server'))
mg_url = str_or_none(mg.get('url'))
if mg_rte_server and mg_url:
hds_url = url_or_none(mg_rte_server + mg_url)
if hds_url:
formats.extend(self._extract_f4m_formats(
hds_url, item_id, f4m_id='hds', fatal=False))
self._sort_formats(formats)
info_dict['formats'] = formats
return info_dict
class RteIE(RteBaseIE):
IE_NAME = 'rte'
IE_DESC = 'Raidió Teilifís Éireann TV'
_VALID_URL = r'https?://(?:www\.)?rte\.ie/player/[^/]{2,3}/show/[^/]+/(?P<id>[0-9]+)'
_TEST = {
'url': 'http://www.rte.ie/player/ie/show/iwitness-862/10478715/',
'md5': '4a76eb3396d98f697e6e8110563d2604',
'info_dict': {
'id': '10478715',
'ext': 'mp4',
'title': 'iWitness',
'thumbnail': r're:^https?://.*\.jpg$',
'description': 'The spirit of Ireland, one voice and one minute at a time.',
'duration': 60.046,
'upload_date': '20151012',
'timestamp': 1444694160,
},
}
class RteRadioIE(RteBaseIE):
IE_NAME = 'rte:radio'
IE_DESC = 'Raidió Teilifís Éireann radio'
# Radioplayer URLs have two distinct specifier formats,
# the old format #!rii=<channel_id>:<id>:<playable_item_id>:<date>:
# the new format #!rii=b<channel_id>_<id>_<playable_item_id>_<date>_
# where the IDs are int/empty, the date is DD-MM-YYYY, and the specifier may be truncated.
# An <id> uniquely defines an individual recording, and is the only part we require.
_VALID_URL = r'https?://(?:www\.)?rte\.ie/radio/utils/radioplayer/rteradioweb\.html#!rii=(?:b?[0-9]*)(?:%3A|:|%5F|_)(?P<id>[0-9]+)'
_TESTS = [{
# Old-style player URL; HLS and RTMPE formats
'url': 'http://www.rte.ie/radio/utils/radioplayer/rteradioweb.html#!rii=16:10507902:2414:27-12-2015:',
'md5': 'c79ccb2c195998440065456b69760411',
'info_dict': {
'id': '10507902',
'ext': 'mp4',
'title': 'Gloria',
'thumbnail': r're:^https?://.*\.jpg$',
'description': 'md5:9ce124a7fb41559ec68f06387cabddf0',
'timestamp': 1451203200,<|fim▁hole|> 'upload_date': '20151227',
'duration': 7230.0,
},
}, {
# New-style player URL; RTMPE formats only
'url': 'http://rte.ie/radio/utils/radioplayer/rteradioweb.html#!rii=b16_3250678_8861_06-04-2012_',
'info_dict': {
'id': '3250678',
'ext': 'flv',
'title': 'The Lyric Concert with Paul Herriott',
'thumbnail': r're:^https?://.*\.jpg$',
'description': '',
'timestamp': 1333742400,
'upload_date': '20120406',
'duration': 7199.016,
},
'params': {
# rtmp download
'skip_download': True,
},
}]<|fim▁end|> | |
<|file_name|>tag.go<|end_file_name|><|fim▁begin|>package models
import (
"github.com/coopernurse/gorp"
"time"
)
type Tag struct {
Id int `db:"id"`
<|fim▁hole|>}
func (this *Tag) PreInsert(s gorp.SqlExecutor) error {
this.CreatedTime = time.Now()
return nil
}<|fim▁end|> | Name string `db:"name"`
Count int `db:"count"`
CreatedTime time.Time `db:"created_time"`
|
<|file_name|>core.py<|end_file_name|><|fim▁begin|>"""
#;+
#; NAME:
#; galaxy.core
#; Version 1.0
#;<|fim▁hole|>#;-
#;------------------------------------------------------------------------------
"""
from __future__ import print_function, absolute_import, division, unicode_literals
import os, copy, sys
import numpy as np
from astropy import units as u
from astropy.io import ascii
from astropy.coordinates import SkyCoord
from xastropy.xutils import xdebug as xdb
# Class for LLS Absorption Lines
class Galaxy(object):
"""A Galaxy Class
Attributes:
name: string
Name(s)
z: float
Adopted redshift
coord: Coordinates
mstar: float
Stellar mass (MsolMass)
"""
# Initialize with a .dat file
def __init__(self, ra=None, dec=None, z=0.):
self.z = z
# Coord
if ra is None:
ras = '00 00 00'
else:
ras = str(ra)
if dec is None:
decs = '+00 00 00'
else:
decs = str(dec)
self.coord = SkyCoord(ras, decs, 'icrs', unit=(u.hour, u.deg))
# Name
self.name = ('J'+
self.coord.ra.to_string(unit=u.hour,sep='',pad=True)+
self.coord.dec.to_string(sep='',pad=True,alwayssign=True))
# #############
def __repr__(self):
return ('[Galaxy: {:s} {:s} {:s}, z={:g}]'.format(
self.name,
self.coord.ra.to_string(unit=u.hour,sep=':',pad=True),
self.coord.dec.to_string(sep=':',pad=True),
self.z) )
## #################################
## #################################
## TESTING
## #################################
if __name__ == '__main__':
# Instantiate
gal = Galaxy()
print(gal)<|fim▁end|> | #; PURPOSE:
#; Core routines for galaxy analysis
#; 29-Nov-2014 by JXP |
<|file_name|>make.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
import subprocess
import os
import time
import platform
import glob
import shutil
import csbuild
from csbuild import log
csbuild.Toolchain("gcc").Compiler().SetCppStandard("c++11")
csbuild.Toolchain("gcc").SetCxxCommand("clang++")
csbuild.Toolchain("gcc").Compiler().AddWarnFlags("all", "extra", "ctor-dtor-privacy", "overloaded-virtual", "init-self", "missing-include-dirs", "switch-default", "no-switch-enum", "undef", "no-old-style-cast")
csbuild.DisablePrecompile()
csbuild.AddOption("--with-mongo", action="store", help="Path to mongo include directory. If not specified, mongo will not be built.", nargs="?", default=None, const="/usr")
csbuild.AddOption("--with-boost", action="store", help="Path to boost include directory. If not specified, mongo will not be built.", nargs="?", default=None, const="/usr")
csbuild.AddOption("--no-threads", action="store_true", help="Build without thread support")
csbuild.AddOption("--no-exceptions", action="store_true", help="Build without exception support")
csbuild.AddOption("--no-unit-tests", action="store_true", help="Don't automatically run unit tests as part of build")
csbuild.SetHeaderInstallSubdirectory("sprawl/{project.name}")
csbuild.SetUserData("subdir", platform.system())
if platform.system() == "Darwin":
csbuild.Toolchain("gcc").AddDefines("_XOPEN_SOURCE");
csbuild.Toolchain("gcc").SetCppStandardLibrary("libc++")
csbuild.SetOutputDirectory("lib/{project.userData.subdir}/{project.activeToolchainName}/{project.outputArchitecture}/{project.targetName}")
csbuild.SetIntermediateDirectory("Intermediate/{project.userData.subdir}/{project.activeToolchainName}/{project.outputArchitecture}/{project.targetName}/{project.name}")
csbuild.Toolchain("msvc").AddCompilerFlags(
"/fp:fast",
"/wd\"4530\"",
"/wd\"4067\"",
"/wd\"4351\"",
"/constexpr:steps1000000",
)
if not csbuild.GetOption("no_threads"):
csbuild.Toolchain("gcc", "ios", "android").AddCompilerFlags("-pthread")<|fim▁hole|> csbuild.Toolchain("msvc").AddCompilerFlags("/EHsc")
@csbuild.project("collections", "collections")
def collections():
csbuild.SetOutput("libsprawl_collections", csbuild.ProjectType.StaticLibrary)
csbuild.EnableHeaderInstall()
@csbuild.project("tag", "tag")
def collections():
csbuild.SetOutput("libsprawl_tag", csbuild.ProjectType.StaticLibrary)
csbuild.EnableHeaderInstall()
@csbuild.project("if", "if")
def collections():
csbuild.SetOutput("libsprawl_if", csbuild.ProjectType.StaticLibrary)
csbuild.EnableHeaderInstall()
@csbuild.project("network", "network")
def network():
csbuild.SetOutput("libsprawl_network", csbuild.ProjectType.StaticLibrary)
csbuild.EnableOutputInstall()
csbuild.EnableHeaderInstall()
@csbuild.project("serialization", "serialization")
def serialization():
csbuild.SetOutput("libsprawl_serialization", csbuild.ProjectType.StaticLibrary)
csbuild.AddExcludeDirectories("serialization/mongo")
csbuild.EnableOutputInstall()
csbuild.EnableHeaderInstall()
@csbuild.project("time", "time")
def timeProject():
csbuild.SetOutput("libsprawl_time", csbuild.ProjectType.StaticLibrary)
csbuild.Toolchain("gcc").AddExcludeFiles("time/*_windows.cpp")
if platform.system() == "Darwin":
csbuild.Toolchain("gcc").AddExcludeFiles("time/*_linux.cpp")
else:
csbuild.Toolchain("gcc").AddExcludeFiles("time/*_osx.cpp")
csbuild.Toolchain("msvc").AddExcludeFiles("time/*_linux.cpp", "time/*_osx.cpp")
csbuild.EnableOutputInstall()
csbuild.EnableHeaderInstall()
@csbuild.project("filesystem", "filesystem")
def filesystem():
csbuild.SetOutput("libsprawl_filesystem", csbuild.ProjectType.StaticLibrary)
csbuild.Toolchain("gcc").AddExcludeFiles("filesystem/*_windows.cpp")
csbuild.Toolchain("msvc").AddExcludeFiles("filesystem/*_linux.cpp")
csbuild.EnableOutputInstall()
csbuild.EnableHeaderInstall()
@csbuild.project("threading", "threading")
def threading():
csbuild.SetOutput("libsprawl_threading", csbuild.ProjectType.StaticLibrary)
if platform.system() != "Darwin":
@csbuild.scope(csbuild.ScopeDef.Final)
def finalScope():
csbuild.Toolchain("gcc").Linker().AddLinkerFlags("-pthread")
csbuild.Toolchain("gcc").AddExcludeFiles("threading/*_windows.cpp")
if platform.system() == "Darwin":
csbuild.Toolchain("gcc").AddExcludeFiles("threading/event_linux.cpp")
else:
csbuild.Toolchain("gcc").AddExcludeFiles("threading/event_osx.cpp")
csbuild.Toolchain("msvc").AddExcludeFiles(
"threading/*_linux.cpp",
"threading/*_osx.cpp"
)
csbuild.EnableOutputInstall()
csbuild.EnableHeaderInstall()
MongoDir = csbuild.GetOption("with_mongo")
BoostDir = csbuild.GetOption("with_boost")
if (not MongoDir) ^ (not BoostDir):
log.LOG_ERROR("Both mongo and boost directories must be specified to build MongoSerializer.");
csbuild.Exit(1)
if MongoDir and BoostDir:
MongoDir = os.path.abspath(MongoDir)
BoostDir = os.path.abspath(BoostDir)
@csbuild.project("serialization-mongo", "serialization/mongo")
def serialization():
csbuild.SetOutput("libsprawl_serialization-mongo", csbuild.ProjectType.StaticLibrary)
csbuild.AddDefines("BOOST_ALL_NO_LIB")
csbuild.AddIncludeDirectories(
"./serialization",
os.path.join(MongoDir, "include"),
os.path.join(BoostDir, "include")
)
csbuild.AddLibraryDirectories(
os.path.join(MongoDir, "lib"),
os.path.join(BoostDir, "lib")
)
csbuild.SetHeaderInstallSubdirectory("sprawl/serialization")
csbuild.EnableOutputInstall()
csbuild.EnableHeaderInstall()
@csbuild.project("memory", "memory")
def memory():
csbuild.SetOutput("libsprawl_memory", csbuild.ProjectType.StaticLibrary)
csbuild.EnableHeaderInstall()
@csbuild.project("string", "string")
def string():
csbuild.SetOutput("libsprawl_string", csbuild.ProjectType.StaticLibrary)
csbuild.EnableOutputInstall()
csbuild.EnableHeaderInstall()
@csbuild.project("hash", "hash")
def hash():
csbuild.SetOutput("libsprawl_hash", csbuild.ProjectType.StaticLibrary)
csbuild.EnableOutputInstall()
csbuild.EnableHeaderInstall()
@csbuild.project("logging", "logging")
def logging():
csbuild.SetOutput("libsprawl_logging", csbuild.ProjectType.StaticLibrary)
@csbuild.scope(csbuild.ScopeDef.Final)
def finalScope():
if platform.system() != "Darwin":
csbuild.Toolchain("gcc").AddLibraries(
"bfd",
)
csbuild.Toolchain("msvc").AddLibraries(
"DbgHelp"
)
csbuild.Toolchain("gcc").AddExcludeFiles("logging/*_windows.cpp")
if platform.system() == "Darwin":
csbuild.Toolchain("gcc").AddExcludeFiles("logging/*_linux.cpp")
else:
csbuild.Toolchain("gcc").AddExcludeFiles("logging/*_osx.cpp")
csbuild.Toolchain("msvc").AddExcludeFiles(
"logging/*_linux.cpp",
"logging/*_osx.cpp"
)
csbuild.EnableOutputInstall()
csbuild.EnableHeaderInstall()
@csbuild.project("common", "common")
def common():
csbuild.SetOutput("libsprawl_common", csbuild.ProjectType.StaticLibrary)
csbuild.EnableHeaderInstall()
UnitTestDepends = ["serialization", "string", "hash", "time", "threading", "filesystem", "logging"]
if MongoDir:
UnitTestDepends.append("serialization-mongo")
@csbuild.project("UnitTests", "UnitTests", UnitTestDepends)
def UnitTests():
csbuild.DisableChunkedBuild()
csbuild.SetOutput("SprawlUnitTest")
csbuild.SetOutputDirectory("bin/{project.userData.subdir}/{project.activeToolchainName}/{project.outputArchitecture}/{project.targetName}")
csbuild.EnableOutputInstall()
csbuild.AddIncludeDirectories(
"UnitTests/gtest",
"UnitTests/gtest/include",
)
csbuild.Toolchain("gcc").Compiler().AddWarnFlags("no-undef", "no-switch-enum", "no-missing-field-initializers")
csbuild.AddExcludeFiles(
"UnitTests/gtest/src/gtest-death-test.cc",
"UnitTests/gtest/src/gtest-filepath.cc",
"UnitTests/gtest/src/gtest-internal-inl.h",
"UnitTests/gtest/src/gtest-port.cc",
"UnitTests/gtest/src/gtest-printers.cc",
"UnitTests/gtest/src/gtest-test-part.cc",
"UnitTests/gtest/src/gtest-typed-test.cc",
"UnitTests/gtest/src/gtest.cc",
)
if MongoDir:
csbuild.AddIncludeDirectories(
"./serialization",
os.path.join(MongoDir, "include"),
os.path.join(BoostDir, "include")
)
csbuild.AddLibraryDirectories(
os.path.join(MongoDir, "lib"),
os.path.join(BoostDir, "lib")
)
csbuild.AddLibraries(
"mongoclient",
"boost_filesystem",
"boost_system",
"boost_thread",
"boost_program_options",
"ssl",
"crypto",
)
csbuild.Toolchain("gcc").AddLibraries("pthread")
csbuild.Toolchain("gcc").AddCompilerFlags("-pthread")
csbuild.AddDefines("WITH_MONGO")
else:
csbuild.AddExcludeFiles(
"UnitTests/UnitTests_MongoReplicable.cpp",
)
@csbuild.project("QueueTests", "QueueTests", ["time", "threading"])
def UnitTests():
csbuild.DisableChunkedBuild()
csbuild.SetOutput("QueueTests")
csbuild.SetOutputDirectory("bin/{project.userData.subdir}/{project.activeToolchainName}/{project.outputArchitecture}/{project.targetName}")
csbuild.EnableOutputInstall()
csbuild.Toolchain("gcc").Compiler().AddWarnFlags("no-undef", "no-switch-enum", "no-missing-field-initializers")
csbuild.AddIncludeDirectories("QueueTests/ext/include")
csbuild.AddLibraryDirectories("QueueTests/ext/lib/{project.userData.subdir}-{project.outputArchitecture}")
csbuild.AddExcludeDirectories("QueueTests/ext")
csbuild.AddLibraries("tbb")
if platform.system() == "Windows":
@csbuild.postMakeStep
def postMake(project):
for f in glob.glob("QueueTests/ext/lib/{project.userData.subdir}-{project.outputArchitecture}/*".format(project=project)):
basename = os.path.basename(f)
dest = os.path.join(project.outputDir, basename)
if not os.path.exists(dest):
print("Copying {} to {}".format(f, dest))
shutil.copyfile(f, dest)<|fim▁end|> |
if csbuild.GetOption("no_exceptions"):
csbuild.Toolchain("gcc", "ios", "android").AddCompilerFlags("-fno-exceptions")
else: |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::marker::PhantomData;
use std::sync::Arc;
use async_trait::async_trait;
use edenapi::BlockingResponse;
use edenapi::EdenApi;
use edenapi::EdenApiError;
use edenapi::Response;
use edenapi_types::EdenApiServerError;
use edenapi_types::FileResponse;
use edenapi_types::FileSpec;
use edenapi_types::TreeAttributes;
use edenapi_types::TreeEntry;
use types::Key;
use crate::datastore::HgIdMutableDeltaStore;
use crate::datastore::RemoteDataStore;
use crate::historystore::HgIdMutableHistoryStore;
use crate::historystore::RemoteHistoryStore;
use crate::remotestore::HgIdRemoteStore;
use crate::types::StoreKey;
mod data;
mod history;
use data::EdenApiDataStore;
use history::EdenApiHistoryStore;
/// Convenience aliases for file and tree stores.
pub type EdenApiFileStore = EdenApiRemoteStore<File>;
pub type EdenApiTreeStore = EdenApiRemoteStore<Tree>;
/// A shim around an EdenAPI client that implements the various traits of
/// Mercurial's storage layer, allowing a type that implements `EdenApi` to be
/// used alongside other Mercurial data and history stores.
///
/// Note that this struct does not allow for data fetching on its own, because
/// it does not contain a mutable store into which to write the fetched data.
/// Use the methods from the `HgIdRemoteStore` trait to provide an appropriate
/// mutable store.
#[derive(Clone)]
pub struct EdenApiRemoteStore<T> {
client: Arc<dyn EdenApi>,
_phantom: PhantomData<T>,
}
impl<T: EdenApiStoreKind> EdenApiRemoteStore<T> {
/// Create a new EdenApiRemoteStore using the given EdenAPI client.
///
/// The current design of the storage layer also requires a distinction
/// between stores that provide file data and stores that provide tree data.
/// (This is because both kinds of data are fetched via the `prefetch()`
/// method from the `RemoteDataStore` trait.)
///
/// The kind of data fetched by a store can be specified via a marker type;
/// in particular, `File` or `Tree`. For example, a store that fetches file
/// data would be created as follows:<|fim▁hole|> /// ```
pub fn new(client: Arc<dyn EdenApi>) -> Arc<Self> {
Arc::new(Self {
client,
_phantom: PhantomData,
})
}
}
impl HgIdRemoteStore for EdenApiRemoteStore<File> {
fn datastore(
self: Arc<Self>,
store: Arc<dyn HgIdMutableDeltaStore>,
) -> Arc<dyn RemoteDataStore> {
Arc::new(EdenApiDataStore::new(self, store))
}
fn historystore(
self: Arc<Self>,
store: Arc<dyn HgIdMutableHistoryStore>,
) -> Arc<dyn RemoteHistoryStore> {
Arc::new(EdenApiHistoryStore::new(self, store))
}
}
impl HgIdRemoteStore for EdenApiRemoteStore<Tree> {
fn datastore(
self: Arc<Self>,
store: Arc<dyn HgIdMutableDeltaStore>,
) -> Arc<dyn RemoteDataStore> {
Arc::new(EdenApiDataStore::new(self, store))
}
fn historystore(
self: Arc<Self>,
_store: Arc<dyn HgIdMutableHistoryStore>,
) -> Arc<dyn RemoteHistoryStore> {
unimplemented!("EdenAPI does not support fetching tree history")
}
}
/// Marker type indicating that the store fetches file data.
pub enum File {}
/// Marker type indicating that the store fetches tree data.
pub enum Tree {}
impl EdenApiFileStore {
pub fn files_blocking(
&self,
keys: Vec<Key>,
) -> Result<BlockingResponse<FileResponse>, EdenApiError> {
BlockingResponse::from_async(self.client.files(keys))
}
pub fn files_attrs_blocking(
&self,
reqs: Vec<FileSpec>,
) -> Result<BlockingResponse<FileResponse>, EdenApiError> {
BlockingResponse::from_async(self.client.files_attrs(reqs))
}
pub async fn files_attrs(
&self,
reqs: Vec<FileSpec>,
) -> Result<Response<FileResponse>, EdenApiError> {
self.client.files_attrs(reqs).await
}
}
impl EdenApiTreeStore {
pub fn trees_blocking(
&self,
keys: Vec<Key>,
attributes: Option<TreeAttributes>,
) -> Result<BlockingResponse<Result<TreeEntry, EdenApiServerError>>, EdenApiError> {
BlockingResponse::from_async(self.client.trees(keys, attributes))
}
}
/// Trait that provides a common interface for calling the `files` and `trees`
/// methods on an EdenAPI client.
#[async_trait]
pub trait EdenApiStoreKind: Send + Sync + 'static {
async fn prefetch_files(
_client: Arc<dyn EdenApi>,
_keys: Vec<Key>,
) -> Result<Response<FileResponse>, EdenApiError> {
unimplemented!("fetching files not supported for this store")
}
async fn prefetch_trees(
_client: Arc<dyn EdenApi>,
_keys: Vec<Key>,
_attributes: Option<TreeAttributes>,
) -> Result<Response<Result<TreeEntry, EdenApiServerError>>, EdenApiError> {
unimplemented!("fetching trees not supported for this store")
}
}
#[async_trait]
impl EdenApiStoreKind for File {
async fn prefetch_files(
client: Arc<dyn EdenApi>,
keys: Vec<Key>,
) -> Result<Response<FileResponse>, EdenApiError> {
client.files(keys).await
}
}
#[async_trait]
impl EdenApiStoreKind for Tree {
async fn prefetch_trees(
client: Arc<dyn EdenApi>,
keys: Vec<Key>,
attributes: Option<TreeAttributes>,
) -> Result<Response<Result<TreeEntry, EdenApiServerError>>, EdenApiError> {
client.trees(keys, attributes).await
}
}
/// Return only the HgId keys from the given iterator.
/// EdenAPI cannot fetch content-addressed LFS blobs.
fn hgid_keys<'a>(keys: impl IntoIterator<Item = &'a StoreKey>) -> Vec<Key> {
keys.into_iter()
.filter_map(|k| match k {
StoreKey::HgId(k) => Some(k.clone()),
StoreKey::Content(..) => None,
})
.collect()
}<|fim▁end|> | ///
/// ```rust,ignore
/// let store = EdenApiStore::<File>::new(edenapi); |
<|file_name|>base.py<|end_file_name|><|fim▁begin|>import abc
import datetime
import decimal
import functools
import json
import uuid
import pytz
import msgpack
import six
from lymph.utils import Undefined
@six.add_metaclass(abc.ABCMeta)
class ExtensionTypeSerializer(object):
@abc.abstractmethod
def serialize(self, obj):
raise NotImplementedError
@abc.abstractmethod
def deserialize(self, obj):
raise NotImplementedError
class DatetimeSerializer(ExtensionTypeSerializer):
format = '%Y-%m-%dT%H:%M:%SZ'
def serialize(self, obj):
result = obj.strftime(self.format)
if obj.tzinfo:
return str(obj.tzinfo), result
return result
def deserialize(self, obj):
try:
tzinfo, obj = obj
except ValueError:
tzinfo = None
result = datetime.datetime.strptime(obj, self.format)
if not tzinfo:
return result
return pytz.timezone(tzinfo).localize(result)
class DateSerializer(ExtensionTypeSerializer):
format = '%Y-%m-%d'
def serialize(self, obj):
return obj.strftime(self.format)
def deserialize(self, obj):
return datetime.datetime.strptime(obj, self.format).date()
class TimeSerializer(ExtensionTypeSerializer):
format = '%H:%M:%SZ'
def serialize(self, obj):
return obj.strftime(self.format)
def deserialize(self, obj):
return datetime.datetime.strptime(obj, self.format).time()
class StrSerializer(ExtensionTypeSerializer):
def __init__(self, factory):
self.factory = factory
def serialize(self, obj):
return str(obj)
def deserialize(self, obj):
return self.factory(obj)
class SetSerializer(ExtensionTypeSerializer):
def serialize(self, obj):
return list(obj)<|fim▁hole|> def deserialize(self, obj):
return set(obj)
class UndefinedSerializer(ExtensionTypeSerializer):
def serialize(self, obj):
return ''
def deserialize(self, obj):
return Undefined
_extension_type_serializers = {
'datetime': DatetimeSerializer(),
'date': DateSerializer(),
'time': TimeSerializer(),
'Decimal': StrSerializer(decimal.Decimal),
'UUID': StrSerializer(uuid.UUID),
'set': SetSerializer(),
'UndefinedType': UndefinedSerializer(),
}
class BaseSerializer(object):
def __init__(self, dumps=None, loads=None, load=None, dump=None):
self._dumps = dumps
self._loads = loads
self._load = load
self._dump = dump
def dump_object(self, obj):
obj_type = type(obj)
serializer = _extension_type_serializers.get(obj_type.__name__)
if serializer:
obj = {
'__type__': obj_type.__name__,
'_': serializer.serialize(obj),
}
elif hasattr(obj, '_lymph_dump_'):
obj = obj._lymph_dump_()
return obj
def load_object(self, obj):
obj_type = obj.get('__type__')
if obj_type:
serializer = _extension_type_serializers.get(obj_type)
return serializer.deserialize(obj['_'])
return obj
def dumps(self, obj):
return self._dumps(obj, default=self.dump_object)
def loads(self, s):
return self._loads(s, object_hook=self.load_object)
def dump(self, obj, f):
return self._dump(obj, f, default=self.dump_object)
def load(self, f):
return self._load(f, object_hook=self.load_object)
msgpack_serializer = BaseSerializer(
dumps=functools.partial(msgpack.dumps, use_bin_type=True),
loads=functools.partial(msgpack.loads, encoding='utf-8'),
dump=functools.partial(msgpack.dump, use_bin_type=True),
load=functools.partial(msgpack.load, encoding='utf-8'),
)
json_serializer = BaseSerializer(dumps=json.dumps, loads=json.loads, dump=json.dump, load=json.load)<|fim▁end|> | |
<|file_name|>expanded_signature.rs<|end_file_name|><|fim▁begin|>/// Docs
#[cfg(test)]
/// More Docs
pub const unsafe extern "C" fn foo<T, U, V>(
x: T,
y: u32,
z: u64
) -> (
u32,
u64,
u64
) where T: Clone,<|fim▁hole|>{
92
}
fn main() {
<caret>foo()
}<|fim▁end|> | U: Debug,
V: Display |
<|file_name|>spf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tests/spf.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of the project nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.<|fim▁hole|>#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import unittest
from king_phisher import testing
from king_phisher import spf
class SPFTests(testing.KingPhisherTestCase):
@testing.skip_if_offline
def test_spf_check_host(self):
s = spf.SenderPolicyFramework('1.2.3.4', 'king-phisher.com')
check_host_result = s.check_host()
self.assertIsNotNone(check_host_result)
self.assertEqual(check_host_result, 'fail')
self.assertEqual(spf.check_host('1.2.3.4', 'king-phisher.com'), 'fail')
@testing.skip_if_offline
def test_spf_evaluate_mechanism(self):
s = spf.SenderPolicyFramework('1.2.3.4', 'doesnotexist.king-phisher.com')
eval_mech = lambda m, r: s._evaluate_mechanism(s.ip_address, s.domain, s.sender, m, r)
self.assertTrue(eval_mech('all', None))
self.assertTrue(eval_mech('exists', '%{d2}'))
self.assertTrue(eval_mech('ip4', '1.2.3.0/24'))
self.assertTrue(eval_mech('ip4', '1.2.3.4'))
self.assertFalse(eval_mech('ip4', '1.1.1.0/24'))
def test_spf_evaluate_mechanism_permerror(self):
s = spf.SenderPolicyFramework('1.2.3.4', 'doesnotexist.king-phisher.com')
eval_mech = lambda m, r: s._evaluate_mechanism(s.ip_address, s.domain, s.sender, m, r)
with self.assertRaises(spf.SPFPermError):
eval_mech('ip4', 'thisisnotanetwork')
with self.assertRaises(spf.SPFPermError):
eval_mech('ip6', 'thisisnotanetwork')
with self.assertRaises(spf.SPFPermError):
eval_mech('fake', None)
def test_spf_evaluate_mechanism_temperror(self):
s = spf.SenderPolicyFramework('1.2.3.4', 'doesnotexist.king-phisher.com')
eval_mech = lambda m, r: s._evaluate_mechanism(s.ip_address, s.domain, s.sender, m, r)
with self.assertRaises(spf.SPFTempError):
eval_mech('a', None)
with self.assertRaises(spf.SPFTempError):
eval_mech('exists', None)
with self.assertRaises(spf.SPFTempError):
eval_mech('mx', None)
def test_spf_nonexistent_domain(self):
s = spf.SenderPolicyFramework('1.2.3.4', 'doesnotexist.king-phisher.com')
self.assertIsNone(s.check_host())
self.assertIsNone(spf.check_host('1.2.3.4', 'doesnotexist.king-phisher.com'))
def test_spf_rfc7208_macro_expansion(self):
spf_records = [('all', '-', None)]
s = spf.SenderPolicyFramework('192.0.2.3', 'email.example.com', '[email protected]', spf_records=spf_records)
expand_macro = lambda m: s.expand_macros(m, '192.0.2.3', 'email.example.com', '[email protected]')
self.assertEqual(expand_macro('%{s}'), '[email protected]')
self.assertEqual(expand_macro('%{o}'), 'email.example.com')
self.assertEqual(expand_macro('%{d}'), 'email.example.com')
self.assertEqual(expand_macro('%{d4}'), 'email.example.com')
self.assertEqual(expand_macro('%{d3}'), 'email.example.com')
self.assertEqual(expand_macro('%{d2}'), 'example.com')
self.assertEqual(expand_macro('%{d1}'), 'com')
self.assertEqual(expand_macro('%{dr}'), 'com.example.email')
self.assertEqual(expand_macro('%{d2r}'), 'example.email')
self.assertEqual(expand_macro('%{l}'), 'strong-bad')
self.assertEqual(expand_macro('%{l-}'), 'strong.bad')
self.assertEqual(expand_macro('%{lr}'), 'strong-bad')
self.assertEqual(expand_macro('%{lr-}'), 'bad.strong')
self.assertEqual(expand_macro('%{l1r-}'), 'strong')
self.assertEqual(expand_macro('%{ir}.%{v}._spf.%{d2}'), '3.2.0.192.in-addr._spf.example.com')
self.assertEqual(expand_macro('%{lr-}.lp._spf.%{d2}'), 'bad.strong.lp._spf.example.com')
self.assertEqual(expand_macro('%{lr-}.lp.%{ir}.%{v}._spf.%{d2}'), 'bad.strong.lp.3.2.0.192.in-addr._spf.example.com')
self.assertEqual(expand_macro('%{ir}.%{v}.%{l1r-}.lp._spf.%{d2}'), '3.2.0.192.in-addr.strong.lp._spf.example.com')
self.assertEqual(expand_macro('%{d2}.trusted-domains.example.net'), 'example.com.trusted-domains.example.net')
def test_spf_record_unparse(self):
self.assertEqual(spf.record_unparse(('all', '+', None)), 'all')
self.assertEqual(spf.record_unparse(('all', '-', None)), '-all')
self.assertEqual(spf.record_unparse(('include', '+', '_spf.wonderland.com')), 'include:_spf.wonderland.com')
self.assertEqual(spf.record_unparse(('ip4', '+', '10.0.0.0/24')), 'ip4:10.0.0.0/24')
if __name__ == '__main__':
unittest.main()<|fim▁end|> | |
<|file_name|>parse_clipped_alignment.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import sys
from modules.ClipRead import *
import os
if __name__ == '__main__':
from optparse import OptionParser
usage = "usage: ./%prog [options] data_file"
parser = OptionParser(usage=usage)
parser.add_option("-v", "--verbose", action = 'store_true', default = False, help="verbose output")
parser.add_option("-t", "--tag", default = 'gtfar', type='string', help="tag data")
(options, args) = parser.parse_args()
if len(args)==1:
try:
fileType = args[0].split(".")[-1]
fileHandle = open(args[0])
ClipReads = ClipReads(fileHandle,fileType,options.tag)
while ClipReads.fileOpen:<|fim▁hole|> ClipReads.printData()
except IOError:
sys.exit()
else:
parser.print_help()
print ""
print "Example Usage: ./parse_alignment.py mymapping.sam -p myexonicoutput"
sys.exit(2)<|fim▁end|> | ClipReads.getNextRead() |
<|file_name|>expr-copy.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn f(arg: &mut A) {
arg.a = 100;
}
struct A { a: int }
pub fn main() {
let mut x = A {a: 10};
f(&mut x);<|fim▁hole|> x.a = 20;
let mut y = x;
f(&mut y);
assert_eq!(x.a, 20);
}<|fim▁end|> | assert_eq!(x.a, 100); |
<|file_name|>directions.py<|end_file_name|><|fim▁begin|># Copyright (c) 2015, Lars Tingelstad
# All rights reserved.
#
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of pyversor nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Operations on directions in 3D conformal geometric algebra."""
from __pyversor__.c3d.directions import (<|fim▁hole|><|fim▁end|> | DirectionVector, DirectionBivector, DirectionTrivector) |
<|file_name|>PartialDSLContentAssistParser.java<|end_file_name|><|fim▁begin|>/*
* generated by Xtext
*/
package co.edu.uniandes.mono.gesco.ui.contentassist.antlr;<|fim▁hole|>
import java.util.Collection;
import java.util.Collections;
import org.eclipse.xtext.AbstractRule;
import org.eclipse.xtext.ui.codetemplates.ui.partialEditing.IPartialContentAssistParser;
import org.eclipse.xtext.ui.editor.contentassist.antlr.FollowElement;
import org.eclipse.xtext.ui.editor.contentassist.antlr.internal.AbstractInternalContentAssistParser;
import org.eclipse.xtext.util.PolymorphicDispatcher;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
@SuppressWarnings("restriction")
public class PartialDSLContentAssistParser extends DSLParser implements IPartialContentAssistParser {
private AbstractRule rule;
public void initializeFor(AbstractRule rule) {
this.rule = rule;
}
@Override
protected Collection<FollowElement> getFollowElements(AbstractInternalContentAssistParser parser) {
if (rule == null || rule.eIsProxy())
return Collections.emptyList();
String methodName = "entryRule" + rule.getName();
PolymorphicDispatcher<Collection<FollowElement>> dispatcher =
new PolymorphicDispatcher<Collection<FollowElement>>(methodName, 0, 0, Collections.singletonList(parser));
dispatcher.invoke();
return parser.getFollowElements();
}
}<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2009 Shikhar Bhushan
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from errors import OperationError, TimeoutExpiredError, MissingCapabilityError
from rpc import RPC, RPCReply, RPCError, RaiseMode
# rfc4741 ops
from retrieve import Get, GetConfig, GetReply
from edit import EditConfig, CopyConfig, DeleteConfig, Validate, Commit, DiscardChanges
from session import CloseSession, KillSession
from lock import Lock, Unlock, LockContext
# others...
from flowmon import PoweroffMachine, RebootMachine
__all__ = [<|fim▁hole|> 'RPCReply',
'RPCError',
'RaiseMode',
'Get',
'GetConfig',
'GetReply',
'EditConfig',
'CopyConfig',
'Validate',
'Commit',
'DiscardChanges',
'DeleteConfig',
'Lock',
'Unlock',
'PoweroffMachine',
'RebootMachine',
'LockContext',
'CloseSession',
'KillSession',
'OperationError',
'TimeoutExpiredError',
'MissingCapabilityError'
]<|fim▁end|> | 'RPC', |
<|file_name|>coverers.py<|end_file_name|><|fim▁begin|>"""
Coverers of the filtrated space
"""
from __future__ import print_function
from sklearn.base import BaseEstimator, TransformerMixin
import numpy as np
class HyperRectangleCoverer(BaseEstimator, TransformerMixin):
""" Covers the space using overlapping hyperectangles
Parameters
----------
intervals: integer or list of integers
number of intervals in each filtered space dimension, if an integer
is specified the same number is used in all dimensions.
overlap: float or list of floats
fraction of overlap between hyperectangles in each space dimension,
if a single float is specified the same overlap is used in all
dimensions.
Attributes
----------
"""
def __init__(self, intervals=10, overlap=0.5):
self.intervals = intervals
self.overlap = overlap
def fit(self, X, y=None):
""" Creates the space covering for the input data
It creates a hyperectangle covering of the multidimensional space of X.
Parameters
----------
X: array-like, shape=(n_samples, n_features)
Data which will be covered.
"""
if y is not None:
raise ValueError("y value will not be used")
if np.iterable(self.intervals):
if len(self.intervals) != X.shape[1]:
raise ValueError("length of intervals not matches X dimension")
else:
intervals = np.array(self.intervals, dtype=int)
else:
intervals = np.full((X.shape[1]), self.intervals, dtype=int)
if np.iterable(self.overlap):
if len(self.overlap) != X.shape[1]:
raise ValueError("length of overlap not matches X dimension")
else:
overlap = np.array(self.overlap, dtype=float)
else:
overlap = np.full((X.shape[1]), self.overlap, dtype=float)
# partition each dimension, incluiding last point
bbs, ws = zip(*[np.linspace(*min_max_num, endpoint=True, retstep=True)
for min_max_num in
zip(np.min(X, axis=0),
np.max(X, axis=0), intervals + 1)])
# get cover lower and upper bounds
self.lowerbounds = np.array(np.meshgrid(*[bb[:-1] - shift for
bb, shift in
zip(bbs, ws * overlap)])) \
.T.reshape(-1, X.shape[1])
self.upperbounds = np.array(np.meshgrid(*[bb[1:] + shift for
bb, shift in
zip(bbs, ws * overlap)])) \
.T.reshape(-1, X.shape[1])
return self
def transform(self, X, y=None):
""" Returns boolean array of space partition membership
Returns a (n_samples, n_partitions) boolean array whose elements
are true when the sample (row) is a member of each space partition
(column). This will be used to filter in the clustering space.
Parameters
----------
X: array-like, shape=(n_samples, n_features)
Data which will be partition in hyperectangles.
Returns
-------
m_matrix: boolean array, shape=(n_samples, n_partitions)<|fim▁hole|> """
if y is not None:
raise ValueError("y value will not be used")
return np.logical_and(
np.all(X[:, :, np.newaxis] > self.lowerbounds.T, axis=1),
np.all(X[:, :, np.newaxis] < self.upperbounds.T, axis=1))
def overlap_matrix(self):
""" Returns a boolean array with the overlaps between space partitions
Returns a (n_partitions, n_partitions) boolean array whose elements
are true when there is overlap between the i and j partitions, only
upper triangle is filled (rest is False).
Returns
-------
overlap_matrix: boolean array, shape=(n_partitions, n_partitions)
Boolean matrix of overlaping between partitions, only the upper
triangle is filled and the rest is False.
"""
overlap_matrix = None
i_min_leq_j_min = self.lowerbounds[
:, :, np.newaxis] <= self.lowerbounds.T
i_max_geq_j_min = self.upperbounds[
:, :, np.newaxis] >= self.lowerbounds.T
overlap_matrix = np.all((i_min_leq_j_min, i_max_geq_j_min), axis=0)
overlap_matrix = np.any((overlap_matrix, overlap_matrix.T), axis=0)
overlap_matrix = np.all(overlap_matrix, axis=1)
# only upper triagular filled
np.fill_diagonal(overlap_matrix, False)
return np.triu(overlap_matrix)<|fim▁end|> | Boolean matrix of sample membership to each partition
|
<|file_name|>header.js<|end_file_name|><|fim▁begin|>angular.module('mean.system').controller('HeaderController', ['$scope', 'Global', function ($scope, Global) {
$scope.global = Global;
$scope.menu = [<|fim▁hole|> "title": "buckets",
"link": "buckets"
},
{
"title": "users",
"link": "musers"
},
{
"title": "logs",
"link": "logs"
}
];
$scope.isCollapsed = false;
}]);<|fim▁end|> | { |
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.shortcuts import redirect
from django.shortcuts import render
from django.views.decorators.cache import never_cache
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.decorators import login_required
from registration.backends import get_backend
def register(request, backend='default', template_name='registration/registration_form.html'):
backend = get_backend(backend)
# determine is registration is currently allowed. the ``request`` object
# is passed which can be used to selectively disallow registration based on
# the user-agent
if not backend.registration_allowed(request):
return redirect(*backend.registration_closed_redirect(request))
form_class = backend.get_registration_form_class(request)
if request.method == 'POST':
form = form_class(request.POST, request.FILES)
if form.is_valid():
user = backend.register(request, form)
return redirect(backend.post_registration_redirect(request, user))
else:
form = form_class()
return render(request, template_name, {'form': form})
@never_cache
def verify(request, backend='default', template_name='registration/registration_verify.html', **kwargs):
backend = get_backend(backend)
profile = backend.get_profile(request, **kwargs)
if profile:
# check to see if moderation for this profile is required and whether or
# not it is a verified account.
if backend.moderation_required(request, profile):
moderation_required = True
backend.verify(request, profile, **kwargs)
else:
moderation_required = False
# attempt to activate this user
backend.activate(request, profile, **kwargs)
else:
moderation_required = None
return render(request, template_name, {
'profile': profile,
'moderation_required': moderation_required,
})
@never_cache
@login_required()
def moderate(request, backend='default', template_name='registration/registration_moderate.html', **kwargs):
backend = get_backend(backend)
profile = backend.get_profile(request, **kwargs)
form_class = backend.get_moderation_form_class(request)
if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
backend.moderate(request, form, profile, **kwargs)
return redirect(backend.post_moderation_redirect(request, profile))
else:
form = form_class()
return render(request, template_name, {
'form': form,
'profile': profile,
})
@permission_required('registration.change_registrationprofile')
@login_required()
def moderate_list(request, backend='default', template_name='registration/registration_moderate_list.html'):
backend = get_backend(backend)
profiles = backend.get_unmoderated_profiles(request)
return render(request, template_name, {
'profiles': profiles,<|fim▁hole|><|fim▁end|> | }) |
<|file_name|>app.py<|end_file_name|><|fim▁begin|># -*- coding: utf8 -*-
import os
import os.path
import flask
import flask_assets
import flask_sqlalchemy
from .cross_domain_app import CrossDomainApp
from zeeguu.util.configuration import load_configuration_or_abort
import sys
if sys.version_info[0] < 3:
raise "Must be using Python 3"
# *** Starting the App *** #
app = CrossDomainApp(__name__)
<|fim▁hole|>load_configuration_or_abort(app, 'ZEEGUU_WEB_CONFIG',
['HOST', 'PORT', 'DEBUG', 'SECRET_KEY', 'MAX_SESSION',
'SMTP_SERVER', 'SMTP_USERNAME', 'SMTP_PASSWORD',
'INVITATION_CODES'])
# The zeeguu.model module relies on an app being injected from outside
# ----------------------------------------------------------------------
import zeeguu
zeeguu.app = app
import zeeguu.model
assert zeeguu.model
# -----------------
from .account import account
app.register_blueprint(account)
from .exercises import exercises
app.register_blueprint(exercises)
from zeeguu_exercises import ex_blueprint
app.register_blueprint(ex_blueprint, url_prefix="/practice")
from umr import umrblue
app.register_blueprint(umrblue, url_prefix="/read")
env = flask_assets.Environment(app)
env.cache = app.instance_path
env.directory = os.path.join(app.instance_path, "gen")
env.url = "/gen"
env.append_path(os.path.join(
os.path.dirname(os.path.abspath(__file__)), "static"
), "/static")
# create the instance folder and return the path
def instance_path(app):
path = os.path.join(app.instance_path, "gen")
try:
os.makedirs(path)
except Exception as e:
print(("exception" + str(e)))
if not os.path.isdir(path):
raise
return path
instance = flask.Blueprint("instance", __name__, static_folder=instance_path(app))
app.register_blueprint(instance)<|fim▁end|> | |
<|file_name|>bitcoin_be_BY.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="be_BY" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Shopzcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+39"/>
<source><b>Shopzcoin</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 Shopzcoin 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 type="unfinished"/>
</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 Shopzcoin 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 type="unfinished"/>
</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 Shopzcoin 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 type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Verify a message to ensure it was signed with a specified Shopzcoin 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 type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Edit</source>
<translation type="unfinished"/>
</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)</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>болей васьмі слоў</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>Shopzcoin 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 type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+280"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</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 Shopzcoin</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</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 Shopzcoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+45"/>
<source>Modify configuration options for Shopzcoin</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>Зрабіце копію гаманца ў іншае месца</translation>
</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 type="unfinished"/>
</message>
<message>
<location line="-200"/>
<source>Shopzcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+178"/>
<source>&About Shopzcoin</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 type="unfinished"/>
</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>Shopzcoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to Shopzcoin 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>Дата: %1
Колькасць: %2
Тып: %3
Адрас: %4
</translation>
</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 Shopzcoin 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. Shopzcoin 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 type="unfinished"/>
</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>Капіяваць ID транзакцыі</translation>
</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 Shopzcoin 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>Shopzcoin-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 type="unfinished"/>
</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 type="unfinished"/>
</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 Shopzcoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Shopzcoin 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 type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Shopzcoin 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 type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the Shopzcoin 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 type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Shopzcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show Shopzcoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</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 Shopzcoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</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 Shopzcoin 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 type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</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 Shopzcoin-Qt help message to get a list with possible Shopzcoin 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>Shopzcoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Shopzcoin 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 Shopzcoin 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 type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-33"/>
<source>Welcome to the Shopzcoin 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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+22"/>
<location line="+86"/>
<location line="+86"/>
<location line="+32"/>
<source>0.00 BC</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 type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Balance:</source>
<translation>Баланс:</translation>
</message>
<message>
<location line="+16"/>
<source>123.456 BC</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 type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-173"/>
<source>Enter a Shopzcoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</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 type="unfinished"/>
</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 Shopzcoin 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. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</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 Shopzcoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</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 type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</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 type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Shopzcoin 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 type="unfinished"/>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</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. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Shopzcoin 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 Shopzcoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Shopzcoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+19"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 20 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 type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</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>Плацёж самому сабе</translation>
</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>Капіяваць ID транзакцыі</translation>
</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)</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>ID</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>Shopzcoin 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 shopzcoind</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: shopzcoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: shopzcoind.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>Пазначыць памер кэшу базы звестак у мегабайтах (тыпова: 25)</translation>
</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: 7867 or testnet: 17867)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Трымаць не больш за <n> злучэнняў на асобу (зыходна: 125)</translation>
</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: 7868 or testnet: 17868)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Прымаць камандны радок і JSON-RPC каманды</translation>
</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>Запусціць у фоне як дэман і прымаць каманды</translation>
</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 Shopzcoin 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>Слаць trace/debug звесткі ў кансоль замест файла 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=shopzcoinrpc
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 "Shopzcoin 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>Выканаць каманду калі лепшы блок зменіцца (%s замяняецца на хэш блока)</translation>
</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>Абнавіць гаманец на новы фармат</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Устанавіць памер фонда ключоў у <n> (тыпова: 100)</translation>
</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>Прыватны ключ сервера (зыходна: 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 type="unfinished"/>
</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. Shopzcoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-98"/>
<source>Shopzcoin</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>Памылка загрузкі wallet.dat: гаманец пашкоджаны</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of Shopzcoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart Shopzcoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>Памылка загрузкі wallet.dat</translation>
</message>
<message>
<location line="-16"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</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><|fim▁hole|> <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>Памылковая колькасць</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Недастаткова сродкаў</translation>
</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. Shopzcoin 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><|fim▁end|> | <translation type="unfinished"/>
</message>
<message> |
<|file_name|>scheduler_bind.cc<|end_file_name|><|fim▁begin|>#include <luabind/luabind.hpp>
#include "scheduler.h"
namespace graphic
{
void Scheduler::bind(lua_State *L)
{
using namespace luabind;
module_(L, "graphic")<|fim▁hole|> .def("flush", &Scheduler::flush)
.def("get_visible_calls_count", &Scheduler::get_visible_calls_count)
.def("get_invisible_calls_count", &Scheduler::get_invisible_calls_count)
];
}
}<|fim▁end|> | [
class_<Scheduler, SchedulerPtr >("Scheduler")
.def(constructor<RendererPtr const &>())
.def("add", &Scheduler::add) |
<|file_name|>ig-client.error.ts<|end_file_name|><|fim▁begin|>import { CustomError } from 'ts-custom-error';
export class IgClientError extends CustomError {
constructor(message = 'Instagram API error was made.') {
super(message);
// Fix for ts-custom-error. Otherwise console.error will show JSON instead of just stack trace<|fim▁hole|> value: new.target.name,
enumerable: false,
});
}
}<|fim▁end|> | Object.defineProperty(this, 'name', { |
<|file_name|>logger.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
import logging
import logging.handlers
def setupLogger(log_path, verbose):
logger = logging.getLogger('hive')
logger.setLevel(logging.DEBUG)
logger.propagate = False
fh = logging.handlers.TimedRotatingFileHandler(log_path, when="midnight", backupCount=5)
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
if verbose:
ch.setLevel(logging.DEBUG)
else:
ch.setLevel(logging.ERROR)
<|fim▁hole|> formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# Add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)<|fim▁end|> |
# create formatter and add it to the handlers
|
<|file_name|>MySQLScriptExecuteWizard.java<|end_file_name|><|fim▁begin|>/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([email protected])
* Copyright (C) 2011-2012 Eugene Fradkin ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.ext.mysql.tools;
import org.jkiss.dbeaver.ext.mysql.MySQLConstants;
import org.jkiss.dbeaver.ext.mysql.MySQLDataSourceProvider;
import org.jkiss.dbeaver.ext.mysql.MySQLMessages;
import org.jkiss.dbeaver.ext.mysql.MySQLServerHome;
import org.jkiss.dbeaver.ext.mysql.model.MySQLCatalog;
import org.jkiss.dbeaver.ui.dialogs.tools.AbstractScriptExecuteWizard;
import org.jkiss.dbeaver.utils.RuntimeUtils;
import org.jkiss.utils.CommonUtils;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
class MySQLScriptExecuteWizard extends AbstractScriptExecuteWizard<MySQLCatalog, MySQLCatalog> {
enum LogLevel {
Normal,
Verbose,
Debug
}
private LogLevel logLevel;
private boolean noBeep;
private boolean isImport;
private MySQLScriptExecuteWizardPageSettings mainPage;
public MySQLScriptExecuteWizard(MySQLCatalog catalog, boolean isImport)
{
super(Collections.singleton(catalog), isImport ? MySQLMessages.tools_script_execute_wizard_db_import : MySQLMessages.tools_script_execute_wizard_execute_script);
this.isImport = isImport;
this.logLevel = LogLevel.Normal;
this.noBeep = true;
this.mainPage = new MySQLScriptExecuteWizardPageSettings(this);
}
public LogLevel getLogLevel()
{
return logLevel;
}
public void setLogLevel(LogLevel logLevel)
{
this.logLevel = logLevel;
}
public boolean isImport()
{
return isImport;
}
@Override
public boolean isVerbose()
{
return logLevel == LogLevel.Verbose || logLevel == LogLevel.Debug;
}
@Override
public void addPages()
{
addPage(mainPage);
super.addPages();
}
@Override
public void fillProcessParameters(List<String> cmd, MySQLCatalog arg) throws IOException
{
String dumpPath = RuntimeUtils.getHomeBinary(getClientHome(), MySQLConstants.BIN_FOLDER, "mysql").getAbsolutePath(); //$NON-NLS-1$
cmd.add(dumpPath);
if (logLevel == LogLevel.Debug) {
cmd.add("--debug-info"); //$NON-NLS-1$
}
if (noBeep) {
cmd.add("--no-beep"); //$NON-NLS-1$
}
}
@Override
protected void setupProcessParameters(ProcessBuilder process) {
if (!CommonUtils.isEmpty(getToolUserPassword())) {
process.environment().put(MySQLConstants.ENV_VARIABLE_MYSQL_PWD, getToolUserPassword());
}
}
@Override
public MySQLServerHome findServerHome(String clientHomeId)
{
return MySQLDataSourceProvider.getServerHome(clientHomeId);
}
@Override
public Collection<MySQLCatalog> getRunInfo() {
return getDatabaseObjects();
}
<|fim▁hole|> List<String> cmd = MySQLToolScript.getMySQLToolCommandLine(this, arg);
cmd.add(arg.getName());
return cmd;
}
}<|fim▁end|> | @Override
protected List<String> getCommandLine(MySQLCatalog arg) throws IOException
{
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .lattice import default_optics_mode
from .lattice import energy
from .accelerator import default_vchamber_on
from .accelerator import default_radiation_on
from .accelerator import accelerator_data
from .accelerator import create_accelerator<|fim▁hole|>from .families import get_section_name_mapping
# -- default accelerator values for TS_V03 --
lattice_version = accelerator_data['lattice_version']<|fim▁end|> |
from .families import get_family_data
from .families import family_mapping |
<|file_name|>macro-repeat.rs<|end_file_name|><|fim▁begin|>macro_rules! mac {
( $($v:tt)* ) => {
$v
//~^ ERROR still repeating at this depth
//~| ERROR still repeating at this depth
};<|fim▁hole|> mac!(1);
}<|fim▁end|> | }
fn main() {
mac!(0); |
<|file_name|>script.py<|end_file_name|><|fim▁begin|>"""
Name : Stegano Extract and Read File From Image
Created By : Agus Makmun (Summon Agus)
Blog : bloggersmart.net - python.web.id
License : GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
Documentation : https://github.com/agusmakmun/Some-Examples-of-Simple-Python-Script/
"""
import os
import time, zipfile
class scureImage(object):
def _secure(self, image, zipfile, new_image):
return os.system("cat "+image+" "+zipfile+" > "+new_image)
def _openScure(self, new_image):
return os.system("unzip "+new_image)
def _stegano(self, zipFile):
archive = zipfile.ZipFile(zipFile, 'r')
list_name = archive.namelist()
print "[+] This list of files in the image."
print "+---------------------------------------+"
print " ", list_name
print "+---------------------------------------+"
file_open = raw_input("[+] Type file want to read.\n[+] >>> ")
try:
print "[+] This content of { "+file_open+" }"
print "+---------------------------------------+"
print archive.read(file_open)
print "+---------------------------------------+\n"
except KeyError:
print "[-] Uppss, {", file_open, "} is not found at this file."
print "[-] Please check again!"
def main(self):
print "\n\tWelcome to Python Scure Image { STEGANO METHOD }"
print "[+] Please choice this options:"
print " 1. Saved files in image."
print " 2. Extract files from image."
print " 3. Stegano read file from image.\n"
mome = scureImage()
choice = raw_input("[+] >>> ")
if choice == "1":
print os.listdir(".")
img = raw_input("[+] Type Image file that will save your archive.\n[+] >>> ")
zip = raw_input("[+] Type your Zip file: ")
new_img = raw_input("[+] Type New Image that will save your zip: ")
mome._secure(img, zip, new_img)
print os.listdir(".")
elif choice == "2":
print os.listdir(".")<|fim▁hole|> time.sleep(2)
print os.listdir(".")
elif choice == "3":
print os.listdir(".")
zipName = raw_input("[+] Type Image where your file was saved.\n[+] >>> ")
try:
mome._stegano(zipName)
except IOError:
print "[-] Uppss, {", zipName, "} is not image or not found at this directory."
print "[-] Please check again!"
if __name__ == "__main__":
mome = scureImage()
mome.main()<|fim▁end|> | new_img = raw_input("[+] Type Image that will going to Extract all files.\n[+] >>> ")
mome._openScure(new_img) |
<|file_name|>unittestbase.py<|end_file_name|><|fim▁begin|># This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
import mock
import os
from configman import ConfigurationManager<|fim▁hole|>from socorro.unittest.testbase import TestCase
class ElasticSearchTestCase(TestCase):
"""Base class for Elastic Search related unit tests. """
def get_config_context(self, es_index=None):
mock_logging = mock.Mock()
storage_config = \
crashstorage.ElasticSearchCrashStorage.get_required_config()
middleware_config = MiddlewareApp.get_required_config()
middleware_config.add_option('logger', default=mock_logging)
values_source = {
'logger': mock_logging,
'resource.elasticsearch.elasticsearch_default_index': 'socorro_integration_test',
'resource.elasticsearch.elasticsearch_index': 'socorro_integration_test',
'resource.elasticsearch.backoff_delays': [1],
'resource.elasticsearch.elasticsearch_timeout': 5,
'resource.postgresql.database_name': 'socorro_integration_test'
}
if es_index:
values_source['resource.elasticsearch.elasticsearch_index'] = es_index
config_manager = ConfigurationManager(
[storage_config, middleware_config],
app_name='testapp',
app_version='1.0',
app_description='app description',
values_source_list=[os.environ, values_source],
argv_source=[],
)
return config_manager.get_config()<|fim▁end|> |
from socorro.external.elasticsearch import crashstorage
from socorro.middleware.middleware_app import MiddlewareApp |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>"""
.. module: lemur.authorizations.models
:platform: unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Netflix Secops <[email protected]>
"""
from sqlalchemy import Column, Integer, String
from sqlalchemy_utils import JSONType
from lemur.database import db<|fim▁hole|>
class Authorization(db.Model):
__tablename__ = "pending_dns_authorizations"
id = Column(Integer, primary_key=True, autoincrement=True)
account_number = Column(String(128))
domains = Column(JSONType)
dns_provider_type = Column(String(128))
options = Column(JSONType)
@property
def plugin(self):
return plugins.get(self.plugin_name)
def __repr__(self):
return "Authorization(id={id})".format(id=self.id)
def __init__(self, account_number, domains, dns_provider_type, options=None):
self.account_number = account_number
self.domains = domains
self.dns_provider_type = dns_provider_type
self.options = options<|fim▁end|> |
from lemur.plugins.base import plugins
|
<|file_name|>0007_robouser_magnetic.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
<|fim▁hole|>
class Migration(migrations.Migration):
dependencies = [
('robocrm', '0006_auto_20141005_1800'),
]
operations = [
migrations.AddField(
model_name='robouser',
name='magnetic',
field=models.CharField(max_length=9, null=True, blank=True),
preserve_default=True,
),
]<|fim▁end|> | |
<|file_name|>github-profile.actions.ts<|end_file_name|><|fim▁begin|>import { GithubUserDto } from 'api/github/github-api.types'
import { action, ActionsUnion } from 'common/redux/action-utils'
export const githubProfileActions = {
loadStart: action('@githubProfile.loadStart').withPayload<{
username: string<|fim▁hole|> loadError: action('@githubProfile.loadError').withPayload<object>(),
}
export type GithubProfileAction = ActionsUnion<typeof githubProfileActions><|fim▁end|> | }>(),
loadSuccess: action('@githubProfile.loadSuccess').withPayload<GithubUserDto>(), |
<|file_name|>proxysocket.go<|end_file_name|><|fim▁begin|>/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package winuserspace
import (
"fmt"
"io"
"net"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/miekg/dns"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/klog"
"k8s.io/kubernetes/pkg/proxy"
"k8s.io/kubernetes/pkg/util/ipconfig"
"k8s.io/utils/exec"
)
const (
// Kubernetes DNS suffix search list
// TODO: Get DNS suffix search list from docker containers.
// --dns-search option doesn't work on Windows containers and has been
// fixed recently in docker.
// Kubernetes cluster domain
clusterDomain = "cluster.local"
// Kubernetes service domain
serviceDomain = "svc." + clusterDomain
// Kubernetes default namespace domain
namespaceServiceDomain = "default." + serviceDomain
// Kubernetes DNS service port name
dnsPortName = "dns"
// DNS TYPE value A (a host address)
dnsTypeA uint16 = 0x01
// DNS TYPE value AAAA (a host IPv6 address)
dnsTypeAAAA uint16 = 0x1c
// DNS CLASS value IN (the Internet)
dnsClassInternet uint16 = 0x01
)
// Abstraction over TCP/UDP sockets which are proxied.
type proxySocket interface {
// Addr gets the net.Addr for a proxySocket.
Addr() net.Addr
// Close stops the proxySocket from accepting incoming connections.
// Each implementation should comment on the impact of calling Close
// while sessions are active.
Close() error
// ProxyLoop proxies incoming connections for the specified service to the service endpoints.
ProxyLoop(service ServicePortPortalName, info *serviceInfo, proxier *Proxier)
// ListenPort returns the host port that the proxySocket is listening on
ListenPort() int
}
func newProxySocket(protocol v1.Protocol, ip net.IP, port int) (proxySocket, error) {
host := ""
if ip != nil {
host = ip.String()
}
switch strings.ToUpper(string(protocol)) {
case "TCP":
listener, err := net.Listen("tcp", net.JoinHostPort(host, strconv.Itoa(port)))
if err != nil {
return nil, err
}
return &tcpProxySocket{Listener: listener, port: port}, nil
case "UDP":
addr, err := net.ResolveUDPAddr("udp", net.JoinHostPort(host, strconv.Itoa(port)))
if err != nil {
return nil, err
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
return nil, err
}
return &udpProxySocket{UDPConn: conn, port: port}, nil
case "SCTP":
return nil, fmt.Errorf("SCTP is not supported for user space proxy")
}
return nil, fmt.Errorf("unknown protocol %q", protocol)
}
// How long we wait for a connection to a backend in seconds
var endpointDialTimeout = []time.Duration{250 * time.Millisecond, 500 * time.Millisecond, 1 * time.Second, 2 * time.Second}
// tcpProxySocket implements proxySocket. Close() is implemented by net.Listener. When Close() is called,
// no new connections are allowed but existing connections are left untouched.
type tcpProxySocket struct {
net.Listener
port int
}
func (tcp *tcpProxySocket) ListenPort() int {
return tcp.port
}
func tryConnect(service ServicePortPortalName, srcAddr net.Addr, protocol string, proxier *Proxier) (out net.Conn, err error) {
sessionAffinityReset := false
for _, dialTimeout := range endpointDialTimeout {
servicePortName := proxy.ServicePortName{
NamespacedName: types.NamespacedName{
Namespace: service.Namespace,
Name: service.Name,
},
Port: service.Port,
}
endpoint, err := proxier.loadBalancer.NextEndpoint(servicePortName, srcAddr, sessionAffinityReset)
if err != nil {
klog.Errorf("Couldn't find an endpoint for %s: %v", service, err)
return nil, err
}
klog.V(3).Infof("Mapped service %q to endpoint %s", service, endpoint)
// TODO: This could spin up a new goroutine to make the outbound connection,
// and keep accepting inbound traffic.
outConn, err := net.DialTimeout(protocol, endpoint, dialTimeout)
if err != nil {
if isTooManyFDsError(err) {
panic("Dial failed: " + err.Error())
}
klog.Errorf("Dial failed: %v", err)
sessionAffinityReset = true
continue
}
return outConn, nil
}
return nil, fmt.Errorf("failed to connect to an endpoint.")
}
func (tcp *tcpProxySocket) ProxyLoop(service ServicePortPortalName, myInfo *serviceInfo, proxier *Proxier) {
for {
if !myInfo.isAlive() {
// The service port was closed or replaced.
return
}
// Block until a connection is made.
inConn, err := tcp.Accept()
if err != nil {
if isTooManyFDsError(err) {
panic("Accept failed: " + err.Error())
}
if isClosedError(err) {
return
}
if !myInfo.isAlive() {
// Then the service port was just closed so the accept failure is to be expected.
return
}
klog.Errorf("Accept failed: %v", err)
continue
}
klog.V(3).Infof("Accepted TCP connection from %v to %v", inConn.RemoteAddr(), inConn.LocalAddr())
outConn, err := tryConnect(service, inConn.(*net.TCPConn).RemoteAddr(), "tcp", proxier)
if err != nil {
klog.Errorf("Failed to connect to balancer: %v", err)
inConn.Close()
continue
}
// Spin up an async copy loop.
go proxyTCP(inConn.(*net.TCPConn), outConn.(*net.TCPConn))
}
}
// proxyTCP proxies data bi-directionally between in and out.
func proxyTCP(in, out *net.TCPConn) {
var wg sync.WaitGroup
wg.Add(2)
klog.V(4).Infof("Creating proxy between %v <-> %v <-> %v <-> %v",
in.RemoteAddr(), in.LocalAddr(), out.LocalAddr(), out.RemoteAddr())
go copyBytes("from backend", in, out, &wg)
go copyBytes("to backend", out, in, &wg)
wg.Wait()
}
func copyBytes(direction string, dest, src *net.TCPConn, wg *sync.WaitGroup) {
defer wg.Done()
klog.V(4).Infof("Copying %s: %s -> %s", direction, src.RemoteAddr(), dest.RemoteAddr())
n, err := io.Copy(dest, src)
if err != nil {
if !isClosedError(err) {
klog.Errorf("I/O error: %v", err)
}
}
klog.V(4).Infof("Copied %d bytes %s: %s -> %s", n, direction, src.RemoteAddr(), dest.RemoteAddr())
dest.Close()
src.Close()
}
// udpProxySocket implements proxySocket. Close() is implemented by net.UDPConn. When Close() is called,
// no new connections are allowed and existing connections are broken.
// TODO: We could lame-duck this ourselves, if it becomes important.
type udpProxySocket struct {
*net.UDPConn
port int
}
func (udp *udpProxySocket) ListenPort() int {
return udp.port
}
func (udp *udpProxySocket) Addr() net.Addr {
return udp.LocalAddr()
}
// Holds all the known UDP clients that have not timed out.
type clientCache struct {
mu sync.Mutex
clients map[string]net.Conn // addr string -> connection
}
func newClientCache() *clientCache {
return &clientCache{clients: map[string]net.Conn{}}
}
// DNS query client classified by address and QTYPE
type dnsClientQuery struct {
clientAddress string
dnsQType uint16
}
// Holds DNS client query, the value contains the index in DNS suffix search list,
// the original DNS message and length for the same client and QTYPE
type dnsClientCache struct {
mu sync.Mutex
clients map[dnsClientQuery]*dnsQueryState
}
type dnsQueryState struct {
searchIndex int32
msg *dns.Msg
}
func newDNSClientCache() *dnsClientCache {
return &dnsClientCache{clients: map[dnsClientQuery]*dnsQueryState{}}
}
func packetRequiresDNSSuffix(dnsType, dnsClass uint16) bool {
return (dnsType == dnsTypeA || dnsType == dnsTypeAAAA) && dnsClass == dnsClassInternet
}
func isDNSService(portName string) bool {
return portName == dnsPortName
}
func appendDNSSuffix(msg *dns.Msg, buffer []byte, length int, dnsSuffix string) (int, error) {
if msg == nil || len(msg.Question) == 0 {
return length, fmt.Errorf("DNS message parameter is invalid")
}
// Save the original name since it will be reused for next iteration
origName := msg.Question[0].Name
if dnsSuffix != "" {
msg.Question[0].Name += dnsSuffix + "."
}
mbuf, err := msg.PackBuffer(buffer)
msg.Question[0].Name = origName
if err != nil {
klog.Warningf("Unable to pack DNS packet. Error is: %v", err)
return length, err
}
if &buffer[0] != &mbuf[0] {
return length, fmt.Errorf("Buffer is too small in packing DNS packet")
}
return len(mbuf), nil
}
func recoverDNSQuestion(origName string, msg *dns.Msg, buffer []byte, length int) (int, error) {
if msg == nil || len(msg.Question) == 0 {
return length, fmt.Errorf("DNS message parameter is invalid")
}
if origName == msg.Question[0].Name {
return length, nil<|fim▁hole|> }
msg.Question[0].Name = origName
if len(msg.Answer) > 0 {
msg.Answer[0].Header().Name = origName
}
mbuf, err := msg.PackBuffer(buffer)
if err != nil {
klog.Warningf("Unable to pack DNS packet. Error is: %v", err)
return length, err
}
if &buffer[0] != &mbuf[0] {
return length, fmt.Errorf("Buffer is too small in packing DNS packet")
}
return len(mbuf), nil
}
func processUnpackedDNSQueryPacket(
dnsClients *dnsClientCache,
msg *dns.Msg,
host string,
dnsQType uint16,
buffer []byte,
length int,
dnsSearch []string) int {
if dnsSearch == nil || len(dnsSearch) == 0 {
klog.V(1).Infof("DNS search list is not initialized and is empty.")
return length
}
// TODO: handle concurrent queries from a client
dnsClients.mu.Lock()
state, found := dnsClients.clients[dnsClientQuery{host, dnsQType}]
if !found {
state = &dnsQueryState{0, msg}
dnsClients.clients[dnsClientQuery{host, dnsQType}] = state
}
dnsClients.mu.Unlock()
index := atomic.SwapInt32(&state.searchIndex, state.searchIndex+1)
// Also update message ID if the client retries due to previous query time out
state.msg.MsgHdr.Id = msg.MsgHdr.Id
if index < 0 || index >= int32(len(dnsSearch)) {
klog.V(1).Infof("Search index %d is out of range.", index)
return length
}
length, err := appendDNSSuffix(msg, buffer, length, dnsSearch[index])
if err != nil {
klog.Errorf("Append DNS suffix failed: %v", err)
}
return length
}
func processUnpackedDNSResponsePacket(
svrConn net.Conn,
dnsClients *dnsClientCache,
msg *dns.Msg,
rcode int,
host string,
dnsQType uint16,
buffer []byte,
length int,
dnsSearch []string) (bool, int) {
var drop bool
var err error
if dnsSearch == nil || len(dnsSearch) == 0 {
klog.V(1).Infof("DNS search list is not initialized and is empty.")
return drop, length
}
dnsClients.mu.Lock()
state, found := dnsClients.clients[dnsClientQuery{host, dnsQType}]
dnsClients.mu.Unlock()
if found {
index := atomic.SwapInt32(&state.searchIndex, state.searchIndex+1)
if rcode != 0 && index >= 0 && index < int32(len(dnsSearch)) {
// If the response has failure and iteration through the search list has not
// reached the end, retry on behalf of the client using the original query message
drop = true
length, err = appendDNSSuffix(state.msg, buffer, length, dnsSearch[index])
if err != nil {
klog.Errorf("Append DNS suffix failed: %v", err)
}
_, err = svrConn.Write(buffer[0:length])
if err != nil {
if !logTimeout(err) {
klog.Errorf("Write failed: %v", err)
}
}
} else {
length, err = recoverDNSQuestion(state.msg.Question[0].Name, msg, buffer, length)
if err != nil {
klog.Errorf("Recover DNS question failed: %v", err)
}
dnsClients.mu.Lock()
delete(dnsClients.clients, dnsClientQuery{host, dnsQType})
dnsClients.mu.Unlock()
}
}
return drop, length
}
func processDNSQueryPacket(
dnsClients *dnsClientCache,
cliAddr net.Addr,
buffer []byte,
length int,
dnsSearch []string) (int, error) {
msg := &dns.Msg{}
if err := msg.Unpack(buffer[:length]); err != nil {
klog.Warningf("Unable to unpack DNS packet. Error is: %v", err)
return length, err
}
// Query - Response bit that specifies whether this message is a query (0) or a response (1).
if msg.MsgHdr.Response == true {
return length, fmt.Errorf("DNS packet should be a query message")
}
// QDCOUNT
if len(msg.Question) != 1 {
klog.V(1).Infof("Number of entries in the question section of the DNS packet is: %d", len(msg.Question))
klog.V(1).Infof("DNS suffix appending does not support more than one question.")
return length, nil
}
// ANCOUNT, NSCOUNT, ARCOUNT
if len(msg.Answer) != 0 || len(msg.Ns) != 0 || len(msg.Extra) != 0 {
klog.V(1).Infof("DNS packet contains more than question section.")
return length, nil
}
dnsQType := msg.Question[0].Qtype
dnsQClass := msg.Question[0].Qclass
if packetRequiresDNSSuffix(dnsQType, dnsQClass) {
host, _, err := net.SplitHostPort(cliAddr.String())
if err != nil {
klog.V(1).Infof("Failed to get host from client address: %v", err)
host = cliAddr.String()
}
length = processUnpackedDNSQueryPacket(dnsClients, msg, host, dnsQType, buffer, length, dnsSearch)
}
return length, nil
}
func processDNSResponsePacket(
svrConn net.Conn,
dnsClients *dnsClientCache,
cliAddr net.Addr,
buffer []byte,
length int,
dnsSearch []string) (bool, int, error) {
var drop bool
msg := &dns.Msg{}
if err := msg.Unpack(buffer[:length]); err != nil {
klog.Warningf("Unable to unpack DNS packet. Error is: %v", err)
return drop, length, err
}
// Query - Response bit that specifies whether this message is a query (0) or a response (1).
if msg.MsgHdr.Response == false {
return drop, length, fmt.Errorf("DNS packet should be a response message")
}
// QDCOUNT
if len(msg.Question) != 1 {
klog.V(1).Infof("Number of entries in the response section of the DNS packet is: %d", len(msg.Answer))
return drop, length, nil
}
dnsQType := msg.Question[0].Qtype
dnsQClass := msg.Question[0].Qclass
if packetRequiresDNSSuffix(dnsQType, dnsQClass) {
host, _, err := net.SplitHostPort(cliAddr.String())
if err != nil {
klog.V(1).Infof("Failed to get host from client address: %v", err)
host = cliAddr.String()
}
drop, length = processUnpackedDNSResponsePacket(svrConn, dnsClients, msg, msg.MsgHdr.Rcode, host, dnsQType, buffer, length, dnsSearch)
}
return drop, length, nil
}
func (udp *udpProxySocket) ProxyLoop(service ServicePortPortalName, myInfo *serviceInfo, proxier *Proxier) {
var buffer [4096]byte // 4KiB should be enough for most whole-packets
var dnsSearch []string
if isDNSService(service.Port) {
dnsSearch = []string{"", namespaceServiceDomain, serviceDomain, clusterDomain}
execer := exec.New()
ipconfigInterface := ipconfig.New(execer)
suffixList, err := ipconfigInterface.GetDNSSuffixSearchList()
if err == nil {
for _, suffix := range suffixList {
dnsSearch = append(dnsSearch, suffix)
}
}
}
for {
if !myInfo.isAlive() {
// The service port was closed or replaced.
break
}
// Block until data arrives.
// TODO: Accumulate a histogram of n or something, to fine tune the buffer size.
n, cliAddr, err := udp.ReadFrom(buffer[0:])
if err != nil {
if e, ok := err.(net.Error); ok {
if e.Temporary() {
klog.V(1).Infof("ReadFrom had a temporary failure: %v", err)
continue
}
}
klog.Errorf("ReadFrom failed, exiting ProxyLoop: %v", err)
break
}
// If this is DNS query packet
if isDNSService(service.Port) {
n, err = processDNSQueryPacket(myInfo.dnsClients, cliAddr, buffer[:], n, dnsSearch)
if err != nil {
klog.Errorf("Process DNS query packet failed: %v", err)
}
}
// If this is a client we know already, reuse the connection and goroutine.
svrConn, err := udp.getBackendConn(myInfo.activeClients, myInfo.dnsClients, cliAddr, proxier, service, myInfo.timeout, dnsSearch)
if err != nil {
continue
}
// TODO: It would be nice to let the goroutine handle this write, but we don't
// really want to copy the buffer. We could do a pool of buffers or something.
_, err = svrConn.Write(buffer[0:n])
if err != nil {
if !logTimeout(err) {
klog.Errorf("Write failed: %v", err)
// TODO: Maybe tear down the goroutine for this client/server pair?
}
continue
}
err = svrConn.SetDeadline(time.Now().Add(myInfo.timeout))
if err != nil {
klog.Errorf("SetDeadline failed: %v", err)
continue
}
}
}
func (udp *udpProxySocket) getBackendConn(activeClients *clientCache, dnsClients *dnsClientCache, cliAddr net.Addr, proxier *Proxier, service ServicePortPortalName, timeout time.Duration, dnsSearch []string) (net.Conn, error) {
activeClients.mu.Lock()
defer activeClients.mu.Unlock()
svrConn, found := activeClients.clients[cliAddr.String()]
if !found {
// TODO: This could spin up a new goroutine to make the outbound connection,
// and keep accepting inbound traffic.
klog.V(3).Infof("New UDP connection from %s", cliAddr)
var err error
svrConn, err = tryConnect(service, cliAddr, "udp", proxier)
if err != nil {
return nil, err
}
if err = svrConn.SetDeadline(time.Now().Add(timeout)); err != nil {
klog.Errorf("SetDeadline failed: %v", err)
return nil, err
}
activeClients.clients[cliAddr.String()] = svrConn
go func(cliAddr net.Addr, svrConn net.Conn, activeClients *clientCache, dnsClients *dnsClientCache, service ServicePortPortalName, timeout time.Duration, dnsSearch []string) {
defer runtime.HandleCrash()
udp.proxyClient(cliAddr, svrConn, activeClients, dnsClients, service, timeout, dnsSearch)
}(cliAddr, svrConn, activeClients, dnsClients, service, timeout, dnsSearch)
}
return svrConn, nil
}
// This function is expected to be called as a goroutine.
// TODO: Track and log bytes copied, like TCP
func (udp *udpProxySocket) proxyClient(cliAddr net.Addr, svrConn net.Conn, activeClients *clientCache, dnsClients *dnsClientCache, service ServicePortPortalName, timeout time.Duration, dnsSearch []string) {
defer svrConn.Close()
var buffer [4096]byte
for {
n, err := svrConn.Read(buffer[0:])
if err != nil {
if !logTimeout(err) {
klog.Errorf("Read failed: %v", err)
}
break
}
drop := false
if isDNSService(service.Port) {
drop, n, err = processDNSResponsePacket(svrConn, dnsClients, cliAddr, buffer[:], n, dnsSearch)
if err != nil {
klog.Errorf("Process DNS response packet failed: %v", err)
}
}
if !drop {
err = svrConn.SetDeadline(time.Now().Add(timeout))
if err != nil {
klog.Errorf("SetDeadline failed: %v", err)
break
}
n, err = udp.WriteTo(buffer[0:n], cliAddr)
if err != nil {
if !logTimeout(err) {
klog.Errorf("WriteTo failed: %v", err)
}
break
}
}
}
activeClients.mu.Lock()
delete(activeClients.clients, cliAddr.String())
activeClients.mu.Unlock()
}<|fim▁end|> | |
<|file_name|>CompositeModelSelectionListener.java<|end_file_name|><|fim▁begin|>/* ###
* IP: GHIDRA
* REVIEWED: YES
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ghidra.app.plugin.core.compositeeditor;
/**
* Composite Viewer Model component selection change listener interface.
*/<|fim▁hole|> void selectionChanged();
}<|fim▁end|> | public interface CompositeModelSelectionListener {
/**
* Called to indicate the model's component selection has changed.
*/ |
<|file_name|>BuiltInCallable.java<|end_file_name|><|fim▁begin|>package com.stuffwithstuff.magpie.interpreter.builtin;
import com.stuffwithstuff.magpie.interpreter.Interpreter;
import com.stuffwithstuff.magpie.interpreter.Obj;<|fim▁hole|>public interface BuiltInCallable {
Obj invoke(Interpreter interpreter, Obj thisObj, Obj arg);
}<|fim▁end|> | |
<|file_name|>test_hive_stats.py<|end_file_name|><|fim▁begin|>#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import os
import re
import unittest
from collections import OrderedDict
from unittest.mock import patch
import pytest
from airflow.exceptions import AirflowException
from airflow.providers.apache.hive.operators.hive_stats import HiveStatsCollectionOperator
from tests.providers.apache.hive import DEFAULT_DATE, DEFAULT_DATE_DS, TestHiveEnvironment
from tests.test_utils.mock_hooks import MockHiveMetastoreHook, MockMySqlHook, MockPrestoHook
class _FakeCol:
def __init__(self, col_name, col_type):
self.name = col_name
self.type = col_type
fake_col = _FakeCol('col', 'string')
class TestHiveStatsCollectionOperator(TestHiveEnvironment):
def setUp(self):
self.kwargs = dict(
table='table',
partition=dict(col='col', value='value'),
metastore_conn_id='metastore_conn_id',
presto_conn_id='presto_conn_id',
mysql_conn_id='mysql_conn_id',
task_id='test_hive_stats_collection_operator',
)
super().setUp()
def test_get_default_exprs(self):
col = 'col'
default_exprs = HiveStatsCollectionOperator(**self.kwargs).get_default_exprs(col, None)
assert default_exprs == {(col, 'non_null'): f'COUNT({col})'}
def test_get_default_exprs_excluded_cols(self):
col = 'excluded_col'
self.kwargs.update(dict(excluded_columns=[col]))
default_exprs = HiveStatsCollectionOperator(**self.kwargs).get_default_exprs(col, None)
assert default_exprs == {}
def test_get_default_exprs_number(self):
col = 'col'
for col_type in ['double', 'int', 'bigint', 'float']:
default_exprs = HiveStatsCollectionOperator(**self.kwargs).get_default_exprs(col, col_type)
assert default_exprs == {
(col, 'avg'): f'AVG({col})',
(col, 'max'): f'MAX({col})',
(col, 'min'): f'MIN({col})',
(col, 'non_null'): f'COUNT({col})',
(col, 'sum'): f'SUM({col})',
}
def test_get_default_exprs_boolean(self):
col = 'col'
col_type = 'boolean'
default_exprs = HiveStatsCollectionOperator(**self.kwargs).get_default_exprs(col, col_type)
assert default_exprs == {
(col, 'false'): f'SUM(CASE WHEN NOT {col} THEN 1 ELSE 0 END)',
(col, 'non_null'): f'COUNT({col})',
(col, 'true'): f'SUM(CASE WHEN {col} THEN 1 ELSE 0 END)',
}
def test_get_default_exprs_string(self):
col = 'col'
col_type = 'string'
default_exprs = HiveStatsCollectionOperator(**self.kwargs).get_default_exprs(col, col_type)
assert default_exprs == {
(col, 'approx_distinct'): f'APPROX_DISTINCT({col})',
(col, 'len'): f'SUM(CAST(LENGTH({col}) AS BIGINT))',
(col, 'non_null'): f'COUNT({col})',
}
@patch('airflow.providers.apache.hive.operators.hive_stats.json.dumps')
@patch('airflow.providers.apache.hive.operators.hive_stats.MySqlHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.PrestoHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.HiveMetastoreHook')
def test_execute(self, mock_hive_metastore_hook, mock_presto_hook, mock_mysql_hook, mock_json_dumps):
mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols = [fake_col]
mock_mysql_hook.return_value.get_records.return_value = False
hive_stats_collection_operator = HiveStatsCollectionOperator(**self.kwargs)
hive_stats_collection_operator.execute(context={})
mock_hive_metastore_hook.assert_called_once_with(
metastore_conn_id=hive_stats_collection_operator.metastore_conn_id
)
mock_hive_metastore_hook.return_value.get_table.assert_called_once_with(
table_name=hive_stats_collection_operator.table
)
mock_presto_hook.assert_called_once_with(presto_conn_id=hive_stats_collection_operator.presto_conn_id)
mock_mysql_hook.assert_called_once_with(hive_stats_collection_operator.mysql_conn_id)
mock_json_dumps.assert_called_once_with(hive_stats_collection_operator.partition, sort_keys=True)
field_types = {
col.name: col.type for col in mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols
}
exprs = {('', 'count'): 'COUNT(*)'}
for col, col_type in list(field_types.items()):
exprs.update(hive_stats_collection_operator.get_default_exprs(col, col_type))
exprs = OrderedDict(exprs)
rows = [
(
hive_stats_collection_operator.ds,
hive_stats_collection_operator.dttm,
hive_stats_collection_operator.table,
mock_json_dumps.return_value,
)
+ (r[0][0], r[0][1], r[1])
for r in zip(exprs, mock_presto_hook.return_value.get_first.return_value)
]
mock_mysql_hook.return_value.insert_rows.assert_called_once_with(
table='hive_stats',
rows=rows,
target_fields=[
'ds',
'dttm',
'table_name',
'partition_repr',
'col',
'metric',
'value',
],
)
@patch('airflow.providers.apache.hive.operators.hive_stats.json.dumps')
@patch('airflow.providers.apache.hive.operators.hive_stats.MySqlHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.PrestoHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.HiveMetastoreHook')
def test_execute_with_assignment_func(
self, mock_hive_metastore_hook, mock_presto_hook, mock_mysql_hook, mock_json_dumps
):
def assignment_func(col, _):
return {(col, 'test'): f'TEST({col})'}
self.kwargs.update(dict(assignment_func=assignment_func))
mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols = [fake_col]
mock_mysql_hook.return_value.get_records.return_value = False
hive_stats_collection_operator = HiveStatsCollectionOperator(**self.kwargs)
hive_stats_collection_operator.execute(context={})
field_types = {
col.name: col.type for col in mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols
}
exprs = {('', 'count'): 'COUNT(*)'}
for col, col_type in list(field_types.items()):
exprs.update(hive_stats_collection_operator.assignment_func(col, col_type))
exprs = OrderedDict(exprs)
rows = [
(
hive_stats_collection_operator.ds,
hive_stats_collection_operator.dttm,
hive_stats_collection_operator.table,
mock_json_dumps.return_value,
)
+ (r[0][0], r[0][1], r[1])
for r in zip(exprs, mock_presto_hook.return_value.get_first.return_value)
]<|fim▁hole|> 'ds',
'dttm',
'table_name',
'partition_repr',
'col',
'metric',
'value',
],
)
@patch('airflow.providers.apache.hive.operators.hive_stats.json.dumps')
@patch('airflow.providers.apache.hive.operators.hive_stats.MySqlHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.PrestoHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.HiveMetastoreHook')
def test_execute_with_assignment_func_no_return_value(
self, mock_hive_metastore_hook, mock_presto_hook, mock_mysql_hook, mock_json_dumps
):
def assignment_func(_, __):
pass
self.kwargs.update(dict(assignment_func=assignment_func))
mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols = [fake_col]
mock_mysql_hook.return_value.get_records.return_value = False
hive_stats_collection_operator = HiveStatsCollectionOperator(**self.kwargs)
hive_stats_collection_operator.execute(context={})
field_types = {
col.name: col.type for col in mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols
}
exprs = {('', 'count'): 'COUNT(*)'}
for col, col_type in list(field_types.items()):
exprs.update(hive_stats_collection_operator.get_default_exprs(col, col_type))
exprs = OrderedDict(exprs)
rows = [
(
hive_stats_collection_operator.ds,
hive_stats_collection_operator.dttm,
hive_stats_collection_operator.table,
mock_json_dumps.return_value,
)
+ (r[0][0], r[0][1], r[1])
for r in zip(exprs, mock_presto_hook.return_value.get_first.return_value)
]
mock_mysql_hook.return_value.insert_rows.assert_called_once_with(
table='hive_stats',
rows=rows,
target_fields=[
'ds',
'dttm',
'table_name',
'partition_repr',
'col',
'metric',
'value',
],
)
@patch('airflow.providers.apache.hive.operators.hive_stats.MySqlHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.PrestoHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.HiveMetastoreHook')
def test_execute_no_query_results(self, mock_hive_metastore_hook, mock_presto_hook, mock_mysql_hook):
mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols = [fake_col]
mock_mysql_hook.return_value.get_records.return_value = False
mock_presto_hook.return_value.get_first.return_value = None
with pytest.raises(AirflowException):
HiveStatsCollectionOperator(**self.kwargs).execute(context={})
@patch('airflow.providers.apache.hive.operators.hive_stats.json.dumps')
@patch('airflow.providers.apache.hive.operators.hive_stats.MySqlHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.PrestoHook')
@patch('airflow.providers.apache.hive.operators.hive_stats.HiveMetastoreHook')
def test_execute_delete_previous_runs_rows(
self, mock_hive_metastore_hook, mock_presto_hook, mock_mysql_hook, mock_json_dumps
):
mock_hive_metastore_hook.return_value.get_table.return_value.sd.cols = [fake_col]
mock_mysql_hook.return_value.get_records.return_value = True
hive_stats_collection_operator = HiveStatsCollectionOperator(**self.kwargs)
hive_stats_collection_operator.execute(context={})
sql = f"""
DELETE FROM hive_stats
WHERE
table_name='{hive_stats_collection_operator.table}' AND
partition_repr='{mock_json_dumps.return_value}' AND
dttm='{hive_stats_collection_operator.dttm}';
"""
mock_mysql_hook.return_value.run.assert_called_once_with(sql)
@unittest.skipIf(
'AIRFLOW_RUNALL_TESTS' not in os.environ, "Skipped because AIRFLOW_RUNALL_TESTS is not set"
)
@patch(
'airflow.providers.apache.hive.operators.hive_stats.HiveMetastoreHook',
side_effect=MockHiveMetastoreHook,
)
def test_runs_for_hive_stats(self, mock_hive_metastore_hook):
mock_mysql_hook = MockMySqlHook()
mock_presto_hook = MockPrestoHook()
with patch(
'airflow.providers.apache.hive.operators.hive_stats.PrestoHook', return_value=mock_presto_hook
):
with patch(
'airflow.providers.apache.hive.operators.hive_stats.MySqlHook', return_value=mock_mysql_hook
):
op = HiveStatsCollectionOperator(
task_id='hive_stats_check',
table="airflow.static_babynames_partitioned",
partition={'ds': DEFAULT_DATE_DS},
dag=self.dag,
)
op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True)
select_count_query = (
"SELECT COUNT(*) AS __count "
"FROM airflow.static_babynames_partitioned "
"WHERE ds = '2015-01-01';"
)
mock_presto_hook.get_first.assert_called_with(hql=select_count_query)
expected_stats_select_query = (
"SELECT 1 "
"FROM hive_stats "
"WHERE table_name='airflow.static_babynames_partitioned' "
" AND partition_repr='{\"ds\": \"2015-01-01\"}' "
" AND dttm='2015-01-01T00:00:00+00:00' "
"LIMIT 1;"
)
raw_stats_select_query = mock_mysql_hook.get_records.call_args_list[0][0][0]
actual_stats_select_query = re.sub(r'\s{2,}', ' ', raw_stats_select_query).strip()
assert expected_stats_select_query == actual_stats_select_query
insert_rows_val = [
(
'2015-01-01',
'2015-01-01T00:00:00+00:00',
'airflow.static_babynames_partitioned',
'{"ds": "2015-01-01"}',
'',
'count',
['val_0', 'val_1'],
)
]
mock_mysql_hook.insert_rows.assert_called_with(
table='hive_stats',
rows=insert_rows_val,
target_fields=[
'ds',
'dttm',
'table_name',
'partition_repr',
'col',
'metric',
'value',
],
)<|fim▁end|> | mock_mysql_hook.return_value.insert_rows.assert_called_once_with(
table='hive_stats',
rows=rows,
target_fields=[ |
<|file_name|>test_ioctl.rs<|end_file_name|><|fim▁begin|>#![allow(dead_code)]
// Simple tests to ensure macro generated fns compile
ioctl!(do_bad with 0x1234);
ioctl!(none do_none with 0, 0);
ioctl!(read read_test with 0, 0; u32);
ioctl!(write write_test with 0, 0; u64);
ioctl!(readwrite readwrite_test with 0, 0; u64);
ioctl!(read buf readbuf_test with 0, 0; u32);
ioctl!(write buf writebuf_test with 0, 0; u32);
ioctl!(readwrite buf readwritebuf_test with 0, 0; u32);
// See C code for source of values for op calculations (does NOT work for mips/powerpc):
// https://gist.github.com/posborne/83ea6880770a1aef332e
//
// TODO: Need a way to compute these constants at test time. Using precomputed
// values is fragile and needs to be maintained.
#[cfg(any(target_os = "linux", target_os = "android"))]
mod linux {
#[test]
fn test_op_none() {
if cfg!(any(target_arch = "mips", target_arch="powerpc")){
assert_eq!(io!(b'q', 10), 0x2000710A);
assert_eq!(io!(b'a', 255), 0x200061FF);
} else {
assert_eq!(io!(b'q', 10), 0x0000710A);
assert_eq!(io!(b'a', 255), 0x000061FF);
}
}
#[test]
fn test_op_write() {
if cfg!(any(target_arch = "mips", target_arch="powerpc")){
assert_eq!(iow!(b'z', 10, 1), 0x80017A0A);
assert_eq!(iow!(b'z', 10, 512), 0x82007A0A);
} else {
assert_eq!(iow!(b'z', 10, 1), 0x40017A0A);
assert_eq!(iow!(b'z', 10, 512), 0x42007A0A);
}
}
#[cfg(target_pointer_width = "64")]
#[test]
fn test_op_write_64() {
assert_eq!(iow!(b'z', 10, (1 as u64) << 32), 0x40007A0A);
}
#[test]
fn test_op_read() {
if cfg!(any(target_arch = "mips", target_arch="powerpc")){
assert_eq!(ior!(b'z', 10, 1), 0x40017A0A);
assert_eq!(ior!(b'z', 10, 512), 0x42007A0A);
} else {
assert_eq!(ior!(b'z', 10, 1), 0x80017A0A);
assert_eq!(ior!(b'z', 10, 512), 0x82007A0A);
}
}
#[cfg(target_pointer_width = "64")]
#[test]
fn test_op_read_64() {
assert_eq!(ior!(b'z', 10, (1 as u64) << 32), 0x80007A0A);
}
#[test]
fn test_op_read_write() {
assert_eq!(iorw!(b'z', 10, 1), 0xC0017A0A);
assert_eq!(iorw!(b'z', 10, 512), 0xC2007A0A);
}
#[cfg(target_pointer_width = "64")]
#[test]
fn test_op_read_write_64() {
assert_eq!(iorw!(b'z', 10, (1 as u64) << 32), 0xC0007A0A);
}
}
#[cfg(any(target_os = "macos",
target_os = "ios",
target_os = "netbsd",
target_os = "openbsd",
target_os = "freebsd",
target_os = "dragonfly"))]
mod bsd {
#[test]
fn test_op_none() {
assert_eq!(io!(b'q', 10), 0x2000710A);
assert_eq!(io!(b'a', 255), 0x200061FF);
}
#[test]
fn test_op_write() {
assert_eq!(iow!(b'z', 10, 1), 0x80017A0A);
assert_eq!(iow!(b'z', 10, 512), 0x82007A0A);
}
#[cfg(target_pointer_width = "64")]
#[test]
fn test_op_write_64() {
assert_eq!(iow!(b'z', 10, (1 as u64) << 32), 0x80007A0A);
}
#[test]
fn test_op_read() {
assert_eq!(ior!(b'z', 10, 1), 0x40017A0A);
assert_eq!(ior!(b'z', 10, 512), 0x42007A0A);
}
#[cfg(target_pointer_width = "64")]
#[test]
fn test_op_read_64() {<|fim▁hole|>
#[test]
fn test_op_read_write() {
assert_eq!(iorw!(b'z', 10, 1), 0xC0017A0A);
assert_eq!(iorw!(b'z', 10, 512), 0xC2007A0A);
}
#[cfg(target_pointer_width = "64")]
#[test]
fn test_op_read_write_64() {
assert_eq!(iorw!(b'z', 10, (1 as u64) << 32), 0xC0007A0A);
}
}<|fim▁end|> | assert_eq!(ior!(b'z', 10, (1 as u64) << 32), 0x40007A0A);
} |
<|file_name|>titanium_hu.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="hu" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Titanium</source>
<translation>A Titaniumról</translation>
</message>
<message>
<location line="+39"/>
<source><b>Titanium</b> version</source>
<translation><b>Titanium</b> verzió</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
Ez egy kísérleti program.
MIT/X11 szoftverlicenc alatt kiadva, lásd a mellékelt fájlt COPYING vagy http://www.opensource.org/licenses/mit-license.php.
Ez a termék az OpenSSL Project által lett kifejlesztve az OpenSSL Toolkit (http://www.openssl.org/) és kriptográfiai szoftvertben való felhasználásra, írta Eric Young ([email protected]) és UPnP szoftver, írta Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Dr. Kimoto Chan</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Címjegyzék</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Dupla-kattintás a cím vagy a címke szerkesztéséhez</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Új cím létrehozása</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>A kiválasztott cím másolása a vágólapra</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Új cím</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Titanium 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>Ezekkel a Titanium-címekkel fogadhatod kifizetéseket. Érdemes lehet minden egyes kifizető számára külön címet létrehozni, hogy könnyebben nyomon követhesd, kitől kaptál már pénzt.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Cím másolása</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>&QR kód mutatása</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Titanium 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 type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Jelenlegi nézet exportálása fájlba</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Titanium address</source>
<translation>Üzenet ellenőrzése, hogy valóban a megjelölt Titanium címekkel van-e aláírva.</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>Üzenet ellenőrzése</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Törlés</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Titanium addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Címke &másolása</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>Sz&erkesztés</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Címjegyzék adatainak exportálása</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Vesszővel elválasztott fájl (*. csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Hiba exportálás közben</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>%1 nevű fájl nem írható.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Címke</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Cím</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(nincs címke)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Kulcsszó párbeszédablak</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Add meg a jelszót</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Új jelszó</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Új jelszó újra</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<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>Írd be az új jelszót a tárcához.<br/>Használj legalább 10<br/>véletlenszerű karaktert</b> vagy <b>legalább nyolc szót</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Tárca kódolása</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>A tárcád megnyitásához a műveletnek szüksége van a tárcád jelszavára.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Tárca megnyitása</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>A tárcád dekódolásához a műveletnek szüksége van a tárcád jelszavára.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Tárca dekódolása</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Jelszó megváltoztatása</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Írd be a tárca régi és új jelszavát.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Biztosan kódolni akarod a tárcát?</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR TITANIUMS</b>!</source>
<translation>Figyelem: Ha kódolod a tárcát, és elveszíted a jelszavad, akkor <b>AZ ÖSSZES TITANIUMODAT IS EL FOGOD VESZÍTENI!</b></translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Biztosan kódolni akarod a tárcát?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>FONTOS: A pénztárca-fájl korábbi mentéseit ezzel az új, titkosított pénztárca-fájllal kell helyettesíteni. Biztonsági okokból a pénztárca-fájl korábbi titkosítás nélküli mentései haszontalanná válnak amint elkezdi használni az új, titkosított pénztárcát.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Tárca kódolva</translation>
</message>
<message>
<location line="-56"/>
<source>Titanium will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your titaniums from being stolen by malware infecting your computer.</source>
<translation>Titanium will close now to finish the encryption process. Ne feledd, hogy a tárca titkosítása sem nyújt teljes védelmet az adathalász programok fertőzésével szemben.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Tárca kódolása sikertelen.</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Tárca kódolása belső hiba miatt sikertelen. A tárcád nem lett kódolva.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>A megadott jelszavak nem egyeznek.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Tárca megnyitása sikertelen</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Hibás jelszó.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Dekódolás sikertelen.</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Jelszó megváltoztatva.</translation>
</message>
</context>
<context>
<name>TitaniumGUI</name>
<message>
<location filename="../titaniumgui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Üzenet aláírása...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Szinkronizálás a hálózattal...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Áttekintés</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Tárca általános áttekintése</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Tranzakciók</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Tranzakciótörténet megtekintése</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Tárolt címek és címkék listájának szerkesztése</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Kiizetést fogadó címek listája</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Kilépés</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Kilépés</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Titanium</source>
<translation>Információk a Titaniumról</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>A &Qt-ról</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Információk a Qt ról</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opciók...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>Tárca &kódolása...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Bisztonsági másolat készítése a Tárcáról</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>Jelszó &megváltoztatása...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>A blokkok importálása lemezről...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>A blokkok lemezen történő ujraindexelése...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Titanium address</source>
<translation>Érmék küldése megadott címre</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Titanium</source>
<translation>Titanium konfigurációs opciók</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Biztonsági másolat készítése a Tárcáról egy másik helyre</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Tárcakódoló jelszó megváltoztatása</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Debug ablak</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Hibakereső és diagnosztikai konzol megnyitása</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>Üzenet &valódiságának ellenőrzése</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Titanium</source>
<translation>Titanium</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Tárca</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Titanium</source>
<translation>&A Titaniumról</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>A pénztárcájához tartozó privát kulcsok titkosítása</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Titanium addresses to prove you own them</source>
<translation>Üzenet aláírása a Titanium címmel, amivel bizonyítja, hogy a cím az ön tulajdona.</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Titanium addresses</source>
<translation>Annak ellenőrzése, hogy az üzenetek valóban a megjelölt Titanium címekkel vannak-e alaírva</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Fájl</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Beállítások</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Súgó</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Fül eszköztár</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[teszthálózat]</translation>
</message>
<message>
<location line="+47"/>
<source>Titanium client</source>
<translation>Titanium kliens</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Titanium network</source>
<translation><numerusform>%n aktív kapcsolat a Titanium-hálózattal</numerusform><numerusform>%n aktív kapcsolat a Titanium-hálózattal</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>A tranzakció-történet %1 blokkja feldolgozva.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<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 numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<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="-140"/>
<source>Up to date</source>
<translation>Naprakész</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Frissítés...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Tranzakciós díj jóváhagyása</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Tranzakció elküldve.</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Beérkező tranzakció</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Dátum: %1
Összeg: %2
Típus: %3
Cím: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Titanium address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Tárca <b>kódolva</b> és jelenleg <b>nyitva</b>.</translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Tárca <b>kódolva</b> és jelenleg <b>zárva</b>.</translation>
</message>
<message>
<location filename="../titanium.cpp" line="+111"/>
<source>A fatal error occurred. Titanium can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Cím szerkesztése</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>Cím&ke</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>A címhez tartozó címke</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Cím</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>Az ehhez a címjegyzék-bejegyzéshez tartozó cím. Ez csak a küldő címeknél módosítható.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Új fogadó cím</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Új küldő cím</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Fogadó cím szerkesztése</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Küldő cím szerkesztése</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>A megadott "%1" cím már szerepel a címjegyzékben.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Titanium address.</source>
<translation>A megadott "%1" cím nem egy érvényes Titanium-cím.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Tárca feloldása sikertelen</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Új kulcs generálása sikertelen</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Titanium-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>verzió</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Használat:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>parancssoros opciók</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>UI opciók</translation>
</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>Indítás lekicsinyítve
</translation>
</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>Opciók</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Fő</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Tranzakciós &díj fizetése</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Titanium after logging in to the system.</source>
<translation>Induljon el a Titanium a számítógép bekapcsolásakor</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Titanium on system login</source>
<translation>&Induljon el a számítógép bekapcsolásakor</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Titanium client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>A Titanium-kliens portjának automatikus megnyitása a routeren. Ez csak akkor működik, ha a routered támogatja az UPnP-t és az engedélyezve is van rajta.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>&UPnP port-feltérképezés</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Titanium network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>SOCKS proxyn keresztüli csatlakozás a Titanium hálózatához (pl. Tor-on keresztüli csatlakozás esetén)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Csatlakozás SOCKS proxyn keresztül:</translation>
</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>Proxy IP címe (pl.: 127.0.0.1)</translation>
</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>Proxy portja (pl.: 9050)</translation>
</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 type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Kicsinyítés után csak eszköztár-ikont mutass</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Kicsinyítés a tálcára az eszköztár helyett</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>Az alkalmazásból való kilépés helyett az eszköztárba kicsinyíti az alkalmazást az ablak bezárásakor. Ez esetben az alkalmazás csak a Kilépés menüponttal zárható be.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>K&icsinyítés záráskor</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Megjelenítés</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Titanium.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Mértékegység:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Válaszd ki az interfészen és érmék küldésekor megjelenítendő alapértelmezett alegységet.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Titanium addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Címek megjelenítése a tranzakciólistában</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>Megszakítás</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>Alkalmazás</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>alapértelmezett</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Figyelem</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Titanium.</source>
<translation>Ez a beállítás a Titanium ujraindítása után lép érvénybe.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Űrlap</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Titanium network after a connection is established, but this process has not completed yet.</source>
<translation>A kijelzett információ lehet, hogy elavult. A pénztárcája automatikusan szinkronizálja magát a Titanium hálózattal miután a kapcsolat létrejön, de ez e folyamat még nem fejeződött be.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Egyenleg:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Megerősítetlen:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Tárca</translation>
</message>
<message>
<location line="+107"/>
<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="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Legutóbbi tranzakciók</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Aktuális egyenleged</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Még megerősítésre váró, a jelenlegi egyenlegbe be nem számított tranzakciók</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>Nincs szinkronban.</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start titanium: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR kód párbeszédablak</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Fizetés kérése</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Összeg:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Címke:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Üzenet:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>Mentés má&sként</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Hiba lépett fel az URI QR kóddá alakításakor</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>A megadott összeg nem érvényes. Kérem ellenőrizze.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>A keletkezett URI túl hosszú, próbálja meg csökkenteni a cimkeszöveg / üzenet méretét.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>QR kód mentése</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG Képfájlok (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Kliens néve</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation>Nem elérhető</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Kliens verzió</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Információ</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Bekapcsolás ideje</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Hálózat</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Kapcsolatok száma</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Teszthálózaton</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blokklánc</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Aktuális blokkok száma</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Becsült összes blokk</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Utolsó blokk ideje</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Megnyitás</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Titanium-Qt help message to get a list with possible Titanium 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>&Konzol</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Fordítás dátuma</translation>
</message>
<message>
<location line="-104"/>
<source>Titanium - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Titanium Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/><|fim▁hole|> <translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Titanium 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>Konzol törlése</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Titanium 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>Navigálhat a fel és le nyilakkal, és <b>Ctrl-L</b> -vel törölheti a képernyőt.</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="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Érmék küldése</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Küldés több címzettnek egyszerre</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Címzett hozzáadása</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Az összes tranzakciós mező eltávolítása</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Mindent &töröl</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Egyenleg:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 TTN</source>
<translation>123.456 TTN</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>Küldés megerősítése</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Küldés</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> %2-re (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Küldés megerősítése</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Valóban el akarsz küldeni %1-t?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> és</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>A címzett címe érvénytelen, kérlek, ellenőrizd.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>A fizetendő összegnek nagyobbnak kell lennie 0-nál.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Nincs ennyi titanium az egyenlegeden.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>A küldeni kívánt összeg és a %1 tranzakciós díj együtt meghaladja az egyenlegeden rendelkezésedre álló összeget.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Többször szerepel ugyanaz a cím. Egy küldési műveletben egy címre csak egyszer lehet küldeni.</translation>
</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>Hiba: a tranzakciót elutasították. Ezt az okozhatja, ha már elköltöttél valamennyi érmét a tárcádból például ha a wallet.dat-od egy másolatát használtad, és így az elköltés csak abban lett jelölve, de itt nem.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Űrlap</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Összeg:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Címzett:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>Milyen címkével kerüljön be ez a cím a címtáradba?
</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>Címke:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Válassz egy címet a címjegyzékből</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Cím beillesztése a vágólapról</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>Címzett eltávolítása</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Titanium address (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Adj meg egy Titanium-címet (pl.: MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L )</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>Üzenet aláírása...</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Aláírhat a címeivel üzeneteket, amivel bizonyíthatja, hogy a címek az önéi. Vigyázzon, hogy ne írjon alá semmi félreérthetőt, mivel a phising támadásokkal megpróbálhatják becsapni, hogy az azonosságát átírja másokra. Csak olyan részletes állításokat írjon alá, amivel egyetért.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Adj meg egy Titanium-címet (pl.: MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L )</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Válassz egy címet a címjegyzékből</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Cím beillesztése a vágólapról</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>Ide írja az aláírandó üzenetet</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>A jelenleg kiválasztott aláírás másolása a rendszer-vágólapra</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Titanium address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Mindent &töröl</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>Üzenet ellenőrzése</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Írja be az aláírás címét, az üzenetet (ügyelve arra, hogy az új-sor, szóköz, tab, stb. karaktereket is pontosan) és az aláírást az üzenet ellenőrzéséhez. Ügyeljen arra, ne gondoljon többet az aláírásról, mint amennyi az aláírt szövegben ténylegesen áll, hogy elkerülje a köztes-ember (man-in-the-middle) támadást.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Adj meg egy Titanium-címet (pl.: MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L )</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Titanium address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Titanium address (e.g. MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>Adj meg egy Titanium-címet (pl.: MNS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L )</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Titanium signature</source>
<translation>Adja meg a Titanium aláírást</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>A megadott cím nem érvényes.</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>Ellenőrizze a címet és próbálja meg újra.</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 type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>Dr. Kimoto Chan</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[teszthálózat]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Megnyitva %1-ig</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/megerősítetlen</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 megerősítés</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Állapot</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>Dátum</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Legenerálva</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Űrlap</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Címzett</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>címke</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Jóváírás</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>elutasítva</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Terhelés</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Tranzakciós díj</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Nettó összeg</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Üzenet</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Megjegyzés</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 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>A frissen generált érméket csak 120 blokkal később tudod elkölteni. Ez a blokk nyomban szétküldésre került a hálózatba, amint legeneráltad, hogy hozzáadhassák a blokklánchoz. Ha nem kerül be a láncba, úgy az állapota "elutasítva"-ra módosul, és nem költheted el az érméket. Ez akkor következhet be időnként, ha egy másik csomópont mindössze néhány másodperc különbséggel generált le egy blokkot a tiédhez képest.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Tranzakció</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Összeg</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, még nem sikerült elküldeni.</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>ismeretlen</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Tranzakció részletei</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Ez a mező a tranzakció részleteit mutatja</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Dátum</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Típus</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Cím</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Összeg</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>%1-ig megnyitva</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Offline (%1 megerősítés)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Megerősítetlen (%1 %2 megerősítésből)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Megerősítve (%1 megerősítés)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Ezt a blokkot egyetlen másik csomópont sem kapta meg, így valószínűleg nem lesz elfogadva!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Legenerálva, de még el nem fogadva.</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Erre a címre</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Erről az</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Erre a címre</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Magadnak kifizetve</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Kibányászva</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(nincs)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Tranzakció állapota. Húzd ide a kurzort, hogy lásd a megerősítések számát.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Tranzakció fogadásának dátuma és időpontja.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tranzakció típusa.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>A tranzakció címzettjének címe.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Az egyenleghez jóváírt vagy ráterhelt összeg.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Mind</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Mai</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Ezen a héten</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Ebben a hónapban</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Múlt hónapban</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Ebben az évben</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Tartomány ...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Erre a címre</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Erre a címre</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Magadnak</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Kibányászva</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Más</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Írd be a keresendő címet vagy címkét</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minimális összeg</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Cím másolása</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Címke másolása</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Összeg másolása</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Címke szerkesztése</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Tranzakciós részletek megjelenítése</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Tranzakció adatainak exportálása</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Vesszővel elválasztott fájl (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Megerősítve</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Dátum</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Típus</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Címke</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Cím</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Összeg</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>Azonosító</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Hiba lépett fel exportálás közben</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>%1 fájlba való kiírás sikertelen.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Tartomány:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>meddig</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Érmék küldése</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Jelenlegi nézet exportálása fájlba</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Biztonsági másolat készítése a Tárcáról</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Tárca fájl (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Biztonsági másolat készítése sikertelen</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Hiba lépett fel a Tárca másik helyre való mentése közben</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>titanium-core</name>
<message>
<location filename="../titaniumstrings.cpp" line="+94"/>
<source>Titanium version</source>
<translation>Titanium verzió</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Használat:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or titaniumd</source>
<translation>Parancs küldése a -serverhez vagy a titaniumdhez
</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Parancsok kilistázása
</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Segítség egy parancsról
</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Opciók
</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: titanium.conf)</source>
<translation>Konfigurációs fájl (alapértelmezett: titanium.conf)
</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: titaniumd.pid)</source>
<translation>pid-fájl (alapértelmezett: titaniumd.pid)
</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Adatkönyvtár
</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Az adatbázis gyorsítótár mérete megabájtban (alapértelmezés: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 7951 or testnet: 17951)</source>
<translation>Csatlakozásokhoz figyelendő <port> (alapértelmezett: 7951 or testnet: 17951)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Maximálisan <n> számú kapcsolat fenntartása a peerekkel (alapértelmezés: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Kapcsolódás egy csomóponthoz a peerek címeinek megszerzése miatt, majd szétkapcsolás</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Adja meg az Ön saját nyilvános címét</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Helytelenül viselkedő peerek leválasztási határértéke (alapértelmezés: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Helytelenül viselkedő peerek kizárási ideje másodpercben (alapértelmezés: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 7950 or testnet: 17950)</source>
<translation>JSON-RPC csatlakozásokhoz figyelendő <port> (alapértelmezett: 7950 or testnet: 17950)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Parancssoros és JSON-RPC parancsok elfogadása
</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Háttérben futtatás daemonként és parancsok elfogadása
</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Teszthálózat használata
</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=titaniumrpc
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 "Titanium Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<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="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Titanium is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<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>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Figyelem: a -paytxfee nagyon magas. Ennyi tranzakciós díjat fogsz fizetni, ha elküldöd a tranzakciót.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Titanium will not work properly.</source>
<translation>Figyelem: Ellenőrizd, hogy helyesen van-e beállítva a gépeden a dátum és az idő. A Titanium nem fog megfelelően működni, ha rosszul van beállítvaaz órád.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Csatlakozás csak a megadott csomóponthoz</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Érvénytelen -tor cím: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<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="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Csak blokklánccal egyező beépített ellenőrző pontok elfogadása (alapértelmezés: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<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="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Időbélyeges hibakeresési kimenet hozzáadása az elejéhez</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Titanium Wiki for SSL setup instructions)</source>
<translation>SSL-opciók: (lásd a Titanium Wiki SSL-beállítási instrukcióit)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>trace/debug információ küldése a konzolra a debog.log fájl helyett</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>trace/debug információ küldése a debuggerre</translation>
</message>
<message>
<location line="+5"/>
<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="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Csatlakozás időkerete milliszekundumban (alapértelmezett: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>UPnP-használat engedélyezése a figyelő port feltérképezésénél (default: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>UPnP-használat engedélyezése a figyelő port feltérképezésénél (default: 1 when listening)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Felhasználói név JSON-RPC csatlakozásokhoz
</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Jelszó JSON-RPC csatlakozásokhoz
</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>JSON-RPC csatlakozások engedélyezése meghatározott IP-címről
</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Parancsok küldése <ip> címen működő csomóponthoz (alapértelmezett: 127.0.0.1)
</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Parancs, amit akkor hajt végre, amikor a legjobb blokk megváltozik (%s a cmd-ban lecserélődik a blokk hash-re)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>A Tárca frissítése a legfrissebb formátumra</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Kulcskarika mérete <n> (alapértelmezett: 100)
</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Blokklánc újraszkennelése hiányzó tárca-tranzakciók után
</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>OpenSSL (https) használata JSON-RPC csatalkozásokhoz
</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Szervertanúsítvány-fájl (alapértelmezett: server.cert)
</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Szerver titkos kulcsa (alapértelmezett: server.pem)
</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Elfogadható rejtjelkulcsok (alapértelmezett: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH )
</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Ez a súgó-üzenet
</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>A %s nem elérhető ezen a gépen (bind returned error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Csatlakozás SOCKS proxyn keresztül</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>DNS-kikeresés engedélyezése az addnode-nál és a connect-nél</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Címek betöltése...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Hiba a wallet.dat betöltése közben: meghibásodott tárca</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Titanium</source>
<translation>Hiba a wallet.dat betöltése közben: ehhez a tárcához újabb verziójú Titanium-kliens szükséges</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Titanium to complete</source>
<translation>A Tárca újraírása szükséges: Indítsa újra a teljesen a Titanium-t</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Hiba az wallet.dat betöltése közben</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Érvénytelen -proxy cím: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Ismeretlen hálózat lett megadva -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Ismeretlen -socks proxy kérése: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Étvénytelen -paytxfee=<összeg> összeg: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Étvénytelen összeg</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Nincs elég titaniumod.</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Blokkindex betöltése...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Elérendő csomópont megadása and attempt to keep the connection open</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Titanium is probably already running.</source>
<translation>A %s nem elérhető ezen a gépen. A Titanium valószínűleg fut már.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>kB-onként felajánlandó díj az általad küldött tranzakciókhoz</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Tárca betöltése...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Nem sikerült a Tárca visszaállítása a korábbi verzióra</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Nem sikerült az alapértelmezett címet írni.</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Újraszkennelés...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Betöltés befejezve.</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Használd a %s opciót</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Hiba</translation>
</message>
<message>
<location line="-31"/>
<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>Be kell állítani rpcpassword=<password> a konfigurációs fájlban
%s
Ha a fájl nem létezik, hozd létre 'csak a felhasználó által olvasható' fájl engedéllyel</translation>
</message>
</context>
</TS><|fim▁end|> | <source>Debug log file</source> |
<|file_name|>flowlabel.py<|end_file_name|><|fim▁begin|># Copyright 2014 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");<|fim▁hole|># You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" flowlabels are abbreviations that can be used to identify a flow. Flows do
not have a single unique attribute, which makes them difficult to identify.
flows solve that problem.
flowlabels have 2 parts:
origin node index
destination node index
Example:
flowlabel 1_2 means the flow from the node at index 1 to the node at index 2
"""
import re
def parse_flowlabel(flowlabel):
""" Parses a flowlabel into a tuple """
result = re.findall("(^\d+)(_)(\d+$)", flowlabel)
if len(result) == 0:
raise Exception("Invalid flowlabel %s"%flowlabel)
return (int(result[0][0]), int(result[0][2]))
def gen_flowlabel(origin_index, destination_index):
""" generate a flowlabel """
return "%d_%d"%(origin_index, destination_index)<|fim▁end|> | # you may not use this file except in compliance with the License. |
<|file_name|>machine_configuration.rs<|end_file_name|><|fim▁begin|>// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0<Paste>
use super::super::VmmAction;
use crate::parsed_request::{method_to_error, Error, ParsedRequest};
use crate::request::{Body, Method};
use logger::{IncMetric, METRICS};
use vmm::vmm_config::machine_config::{VmConfig, VmUpdateConfig};
pub(crate) fn parse_get_machine_config() -> Result<ParsedRequest, Error> {
METRICS.get_api_requests.machine_cfg_count.inc();
Ok(ParsedRequest::new_sync(VmmAction::GetVmMachineConfig))
}
pub(crate) fn parse_put_machine_config(body: &Body) -> Result<ParsedRequest, Error> {
METRICS.put_api_requests.machine_cfg_count.inc();
let vm_config = serde_json::from_slice::<VmConfig>(body.raw()).map_err(|e| {
METRICS.put_api_requests.machine_cfg_fails.inc();
Error::SerdeJson(e)
})?;
let vm_config = VmUpdateConfig::from(vm_config);
Ok(ParsedRequest::new_sync(VmmAction::UpdateVmConfiguration(
vm_config,
)))
}
pub(crate) fn parse_patch_machine_config(body: &Body) -> Result<ParsedRequest, Error> {
METRICS.patch_api_requests.machine_cfg_count.inc();
let vm_config = serde_json::from_slice::<VmUpdateConfig>(body.raw()).map_err(|e| {
METRICS.patch_api_requests.machine_cfg_fails.inc();
Error::SerdeJson(e)
})?;
if vm_config.is_empty() {
return method_to_error(Method::Patch);
}
Ok(ParsedRequest::new_sync(VmmAction::UpdateVmConfiguration(
vm_config,
)))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parsed_request::tests::vmm_action_from_request;
use vmm::vmm_config::machine_config::CpuFeaturesTemplate;
#[test]
fn test_parse_get_machine_config_request() {
assert!(parse_get_machine_config().is_ok());
assert!(METRICS.get_api_requests.machine_cfg_count.count() > 0);
}
#[test]
fn test_parse_put_machine_config_request() {
// 1. Test case for invalid payload.
assert!(parse_put_machine_config(&Body::new("invalid_payload")).is_err());
assert!(METRICS.put_api_requests.machine_cfg_fails.count() > 0);
// 2. Test case for mandatory fields.
let body = r#"{
"mem_size_mib": 1024
}"#;
assert!(parse_put_machine_config(&Body::new(body)).is_err());
let body = r#"{
"vcpu_count": 8
}"#;
assert!(parse_put_machine_config(&Body::new(body)).is_err());
// 3. Test case for success scenarios for both architectures.
let body = r#"{
"vcpu_count": 8,
"mem_size_mib": 1024
}"#;
let expected_config = VmUpdateConfig {
vcpu_count: Some(8),
mem_size_mib: Some(1024),
smt: Some(false),
cpu_template: Some(CpuFeaturesTemplate::None),
track_dirty_pages: Some(false),
};
match vmm_action_from_request(parse_put_machine_config(&Body::new(body)).unwrap()) {
VmmAction::UpdateVmConfiguration(config) => assert_eq!(config, expected_config),
_ => panic!("Test failed."),
}
let body = r#"{
"vcpu_count": 8,
"mem_size_mib": 1024,
"smt": false,
"track_dirty_pages": true
}"#;
let expected_config = VmUpdateConfig {
vcpu_count: Some(8),
mem_size_mib: Some(1024),
smt: Some(false),
cpu_template: Some(CpuFeaturesTemplate::None),
track_dirty_pages: Some(true),
};
match vmm_action_from_request(parse_put_machine_config(&Body::new(body)).unwrap()) {
VmmAction::UpdateVmConfiguration(config) => assert_eq!(config, expected_config),
_ => panic!("Test failed."),
}
// 4. Test that applying a CPU template is successful on x86_64 while on aarch64, it is not.
let body = r#"{
"vcpu_count": 8,
"mem_size_mib": 1024,
"smt": false,
"cpu_template": "T2",
"track_dirty_pages": true
}"#;
#[cfg(target_arch = "x86_64")]
{
use vmm::vmm_config::machine_config::CpuFeaturesTemplate;
let expected_config = VmUpdateConfig {
vcpu_count: Some(8),
mem_size_mib: Some(1024),
smt: Some(false),
cpu_template: Some(CpuFeaturesTemplate::T2),
track_dirty_pages: Some(true),
};
match vmm_action_from_request(parse_put_machine_config(&Body::new(body)).unwrap()) {
VmmAction::UpdateVmConfiguration(config) => assert_eq!(config, expected_config),
_ => panic!("Test failed."),
}
}
#[cfg(target_arch = "aarch64")]
{
assert!(parse_put_machine_config(&Body::new(body)).is_err());
}
// 5. Test that setting `smt: true` is successful on x86_64 while on aarch64, it is not.
let body = r#"{
"vcpu_count": 8,
"mem_size_mib": 1024,
"smt": true,
"track_dirty_pages": true
}"#;
#[cfg(target_arch = "x86_64")]
{
let expected_config = VmUpdateConfig {
vcpu_count: Some(8),
mem_size_mib: Some(1024),
smt: Some(true),
cpu_template: Some(CpuFeaturesTemplate::None),
track_dirty_pages: Some(true),
};
match vmm_action_from_request(parse_put_machine_config(&Body::new(body)).unwrap()) {
VmmAction::UpdateVmConfiguration(config) => assert_eq!(config, expected_config),
_ => panic!("Test failed."),
}
}
#[cfg(target_arch = "aarch64")]
{
assert!(parse_put_machine_config(&Body::new(body)).is_err());
}
}
#[test]
fn test_parse_patch_machine_config_request() {
// 1. Test cases for invalid payload.
assert!(parse_patch_machine_config(&Body::new("invalid_payload")).is_err());
// 2. Check currently supported fields that can be patched.
let body = r#"{
"track_dirty_pages": true
}"#;
assert!(parse_patch_machine_config(&Body::new(body)).is_ok());
// On aarch64, CPU template is also not patch compatible.
let body = r#"{
"cpu_template": "T2"
}"#;
#[cfg(target_arch = "aarch64")]<|fim▁hole|> let body = r#"{
"vcpu_count": 8,
"mem_size_mib": 1024
}"#;
assert!(parse_patch_machine_config(&Body::new(body)).is_ok());
// On aarch64, we allow `smt` to be configured to `false` but not `true`.
let body = r#"{
"vcpu_count": 8,
"mem_size_mib": 1024,
"smt": false
}"#;
assert!(parse_patch_machine_config(&Body::new(body)).is_ok());
// 3. Check to see if an empty body returns an error.
let body = r#"{}"#;
assert!(parse_patch_machine_config(&Body::new(body)).is_err());
}
}<|fim▁end|> | assert!(parse_patch_machine_config(&Body::new(body)).is_err());
#[cfg(target_arch = "x86_64")]
assert!(parse_patch_machine_config(&Body::new(body)).is_ok());
|
<|file_name|>content_type.rs<|end_file_name|><|fim▁begin|>use mime::Mime;
header! {
/// `Content-Type` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-3.1.1.5)
///
/// The `Content-Type` header field indicates the media type of the
/// associated representation: either the representation enclosed in the
/// message payload or the selected representation, as determined by the
/// message semantics. The indicated media type defines both the data
/// format and how that data is intended to be processed by a recipient,<|fim▁hole|> ///
/// Although the `mime` crate allows the mime options to be any slice, this crate
/// forces the use of Vec. This is to make sure the same header can't have more than 1 type. If
/// this is an issue, it's possible to implement `Header` on a custom struct.
///
/// # ABNF
/// ```plain
/// Content-Type = media-type
/// ```
///
/// # Example values
/// * `text/html; charset=ISO-8859-4`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, ContentType};
///
/// let mut headers = Headers::new();
///
/// headers.set(
/// ContentType::json()
/// );
/// ```
/// ```
/// use hyper::header::{Headers, ContentType};
/// use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
///
/// let mut headers = Headers::new();
///
/// headers.set(
/// ContentType(Mime(TopLevel::Text, SubLevel::Html,
/// vec![(Attr::Charset, Value::Utf8)]))
/// );
/// ```
(ContentType, "Content-Type") => [Mime]
test_content_type {
test_header!(
test1,
// FIXME: Should be b"text/html; charset=ISO-8859-4" but mime crate lowercases
// the whole value so parsing and formatting the value gives a different result
vec![b"text/html; charset=iso-8859-4"],
Some(HeaderField(Mime(
TopLevel::Text,
SubLevel::Html,
vec![(Attr::Charset, Value::Ext("iso-8859-4".to_owned()))]))));
}
}
impl ContentType {
/// A constructor to easily create a `Content-Type: application/json` header.
#[inline]
pub fn json() -> ContentType {
ContentType(mime!(Application/Json))
}
/// A constructor to easily create a `Content-Type: text/plain; charset=utf-8` header.
#[inline]
pub fn plaintext() -> ContentType {
ContentType(mime!(Text/Plain; Charset=Utf8))
}
/// A constructor to easily create a `Content-Type: text/html; charset=utf-8` header.
#[inline]
pub fn html() -> ContentType {
ContentType(mime!(Text/Html; Charset=Utf8))
}
/// A constructor to easily create a `Content-Type: application/www-form-url-encoded` header.
#[inline]
pub fn form_url_encoded() -> ContentType {
ContentType(mime!(Application/WwwFormUrlEncoded))
}
/// A constructor to easily create a `Content-Type: image/jpeg` header.
#[inline]
pub fn jpeg() -> ContentType {
ContentType(mime!(Image/Jpeg))
}
/// A constructor to easily create a `Content-Type: image/png` header.
#[inline]
pub fn png() -> ContentType {
ContentType(mime!(Image/Png))
}
}
impl Eq for ContentType {}
bench_header!(bench, ContentType, { vec![b"application/json; charset=utf-8".to_vec()] });<|fim▁end|> | /// within the scope of the received message semantics, after any content
/// codings indicated by Content-Encoding are decoded. |
<|file_name|>about.js<|end_file_name|><|fim▁begin|>'use strict';
/**<|fim▁hole|> * @ngdoc function
* @name liteAppManagesystemApp.controller:AboutCtrl
* @description
* # AboutCtrl
* Controller of the liteAppManagesystemApp
*/
angular.module('liteAppManagesystemApp')
.controller('AboutCtrl', function ($scope) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
});<|fim▁end|> | |
<|file_name|>regions-pattern-typing-issue-19997.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// revisions: ast mir
//[mir]compile-flags: -Z borrowck=mir
fn main() {
let a0 = 0;
let f = 1;
let mut a1 = &a0;<|fim▁hole|> (&ref b0,) => {
a1 = &f; //[ast]~ ERROR cannot assign
//[mir]~^ ERROR cannot assign to `a1` because it is borrowed
drop(b0);
}
}
}<|fim▁end|> | match (&a1,) { |
<|file_name|>billing-info.js<|end_file_name|><|fim▁begin|>Template.billingInfo.helpers({
expMonth: function() {
return [
'01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'
]<|fim▁hole|> var yearsArray = [];
for (i = 0; i < 10; i++) {
yearsArray.push(parseInt(curYear)+i);
}
return yearsArray;
}
});<|fim▁end|> | },
expYear: function() {
var curYear = moment().format('YYYY'); |
<|file_name|>coluslife.js<|end_file_name|><|fim▁begin|>'use strict';
/**
* Created by zhaoxueyong on 2017/1/14.
*/
angular.module('browserApp').
controller('ColuslifeCtrl', function ($scope, $http) {
$scope.countryName = "China";<|fim▁hole|> level: 7,
building: false,
point: false
});
var marker = new AMap.Marker({
position: new AMap.LngLat(120.58, 31.335),
title: 'SuZhouLeYuan'
});
marker.setMap(mapObj);
};
$('#btnLocation').on("click", function(){
var locations = null;
if (null === locations){
$http({
method: 'GET',
url: 'http://127.0.0.1:8000/coluslife/locations',
timeout: 5
}).then(
function successCallback(response){
console.log(response.data);
locations = response.data;
for (var i = 0; i < locations.length; i++){
var loc = locations[i];
placeMarker(loc);
}
},
function errorCallback(error){
console.error(error);
});
}
});
var placeMarker = function(location){
var marker = new AMap.Marker({
position: new AMap.LngLat(location.fields.gislng, location.fields.gislat),
title: location.fields.name
});
marker.setMap(mapObj);
}
});<|fim▁end|> | var mapObj = null;
$scope.init_map = function(){
console.log("init map now");
mapObj = new AMap.Map("mapbody", { |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>extern crate rand;
use std::io;
use std::io::Write;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Zahlenraten!");
println!("============");
let secret = rand::thread_rng().gen_range(1, 101);
//println!("Die Geheimzahl lautet: {}", secret);
loop {
print!("Geheimzahl eingeben (< 100): ");
io::stdout().flush().ok().expect("Konnte stdout nicht flushen.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.ok()
.expect("Konnte die Zeile nicht einlesen.");
let guess: u8 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
<|fim▁hole|> println!("{} ist zu klein, versuch's nochmal!\n", guess);
},
Ordering::Greater => {
println!("{} ist zu gross, versuch's nochmal!\n", guess);
},
Ordering::Equal => {
println!("-------------------");
println!("\\o/ Gewonnen! \\o/");
println!("-------------------");
break;
},
}
}
}<|fim▁end|> | match guess.cmp(&secret) {
Ordering::Less => { |
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#Copyright (C) 2011 Seán Hayes
#Python imports
import logging
import pdb
#Django imports
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models, IntegrityError
from django.db.models.signals import post_save
from django.utils import safestring
#App imports
from exceptions import TeamAlreadyExistsError, TeamNoLongerExistsError, TeamFullError, NotOnATeamError, TeamAlreadyHasALeaderError, NotOnSameTeamError, NotALeaderError
from managers import *
from swarm_war.core.models import FacebookRequest
from swarm_war.core.managers import FacebookRequestManager
logger = logging.getLogger(__name__)
# Create your models here.
MAX_TEAM_SIZE = 10
class Team(models.Model):
name = models.CharField(unique=True, max_length=100)
def get_leader(self):
leader = None
try:
#TODO: use filter to better tolerate bugs (e.g. more than one leader) that may creep up
leader = self.members.get(leader=True).user
except TeamProfile.DoesNotExist:
pass
except Exception as e:
logger.error(e)
return leader
def html(self):
s = u'<a href="%s">%s</a>' % (reverse('teams_view', args=[self.id]), self.name)
return safestring.mark_safe(s)
def __unicode__(self):
return self.name
class TeamProfile(models.Model):
user = models.OneToOneField(User)
team = models.ForeignKey(Team, null=True, blank=True, related_name="members")
leader = models.BooleanField(default=False)
#TODO: need a leave_team() method that cleans up teams with no members left
def become_leader(self):
if self.team is None:
raise NotOnATeamError(self.user)
elif self.team.get_leader() is not None:
raise TeamAlreadyHasALeaderError()
else:
self.leader = True
self.save()
def create_team(self, name):
try:
team = Team(name=name)
team.save()
except IntegrityError as e:
raise TeamAlreadyExistsError()
self.team = team
self.leader = True
self.save()
return team
def join_team(self, team):
count = team.members.count()
if count < MAX_TEAM_SIZE:
self.team = team
self.leader = False
self.save()
else:
raise TeamFullError()
def kick_out(self, user):
if self.team is None:
raise NotOnATeamError(self.user)
if not self.leader:
raise NotALeaderError()
user_tp = TeamProfile.objects.get(user=user)
if user_tp.team is None:
raise NotOnATeamError(user)
if user_tp.team.id is not self.team.id:
raise NotOnSameTeamError()
user_tp.leave_team()
def leave_team(self):
team = self.team
self.team = None
self.leader = False
self.save()
count = team.members.count()
if count == 0:
team.delete()
def __unicode__(self):
return u'%s: %s' % (self.__class__.__name__, self.user)
def create_profile(user):
"""
Called using a post_save trigger on User, so when a new User is added a Profile is created as well.
"""
#create a profile
profile = TeamProfile(user=user)
profile.save()
def user_save_handler(sender, instance, created, **kwargs):
if created:
create_profile(instance)
post_save.connect(user_save_handler, sender=User)<|fim▁hole|>
class TeamFacebookRequest(FacebookRequest):
#has to be nullable so that this doesn't get deleted when a related team gets deleted
team = models.ForeignKey(Team, null=True)
objects = FacebookRequestManager()
def html(self):
s = u'%s has invited you to join a Team: %s.' % (self.user.username, self.team.html)
return safestring.mark_safe(s)
def confirm(self, friend):
try:
if self.team is None:
raise TeamNoLongerExistsError()
if self.user.id not in [u.id for u in self.team.members.all()]:
raise Exception('Can\'t join %s because %s isn\'t a member anymore.' % (self.team.name, self.user.username))
friend.teamprofile.join_team(self.team)
finally:
super(TeamFacebookRequest, self).confirm(friend)<|fim▁end|> | |
<|file_name|>fixedsizelist.d.ts<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | import { BaseVector } from './base';
import { DataType, FixedSizeList } from '../type';
export declare class FixedSizeListVector<T extends DataType = any> extends BaseVector<FixedSizeList<T>> {
} |
<|file_name|>okc_scraper_no_q.py<|end_file_name|><|fim▁begin|>"""okc_scraper includes all the functions needed to scrape profiles from
OKCupid"""
import requests
import cPickle as pickle
import time
from BeautifulSoup import BeautifulSoup
def authorize(username, password):
"""Log into OKCupid to scrape profiles"""
user_info = {"username": username, "password": password}
okc = requests.session()
okc.post("https://www.okcupid.com/login", data=user_info)
return okc
def getProfiles(okc):
"""Searches for profiles and returns a list of profiles (10)"""
# match_info = {"filter1": "0,63", "filter2": "2,100,18",
# "filter3": "5,2678400", "filter4": "1,1",
# "locid": "1", "custom_search": "0",
# "matchOrderBy": "SPECIAL_BLEND",
# "sa": "1", "sort_type": "0", "update_prefs": "1"}
soup = BeautifulSoup(okc.post("https://www.okcupid.com/match?filter1=0,63&filter2=2,100,18&filter3=5,2678400&filter4=1,1&locid=0&timekey=1&matchOrderBy=SPECIAL_BLEND&custom_search=0&fromWhoOnline=0&mygender=mwww.okcupid.com/match?filter1=0,63&filter2=2,100,18&filter3=5,2678400&filter4=1,1&locid=0&timekey=1&matchOrderBy=SPECIAL_BLEND&custom_search=0&fromWhoOnline=0&mygender=m").text)<|fim▁hole|>
def getProfile(okc, profile_link):
"""Takes a link to a profile and returns a BeautifulSoup object"""
page = BeautifulSoup(okc.get(profile_link).text)
return (page, page.find("form", {"id": "flag_form"})
.findAll("input")[0]["value"])
def getInfo(profile, profile_id):
"""Take a BeautifulSoup object corresponding to a profile's home page
and the profile's id and return a list of the profile's user info
(username, age, gender...)"""
try:
main = profile.find("div", {"id": "basic_info"}).findAll("span")
return {"id_table": {"user_id": profile_id,
"user_name": main[0].text,
"user_age": main[1].text,
"user_gender": main[2].text,
"user_orient": main[3].text,
"user_status": main[4].text,
"user_location": main[5].text}, }
except:
print profile
return {"id_table": {"user_id": profile_id,
"data": "NA"}}
def getEssays(profile, profile_id):
"""Takes a BeautifulSoup object corresponding to a profiles home
page and returns a list of the profile's essays"""
etd = {"user_id": profile_id, }
essay_index = ["self_summary", "my_life", "good_at", "first_thing",
"favorite", "six_things", "lot_time", "typical_Friday",
"most_private"]
main = profile.find("div", {"id": "main_column"})
for i in range(0, 9):
try:
etd[essay_index[i]] = (main.find("div", {"id": "essay_text_"
+ str(i)})
.getText(' '))
except:
etd[essay_index[i]] = ""
return {"essay_table": etd, }
def getLookingFor(profile, profile_id):
"""Takes a BeautifulSoup object corresponding to a profiles home
page and returns a list of the profile's looking for items"""
try:
main = (profile.find("div", {"id": "main_column"})
.find("div", {"id": "what_i_want"}).findAll("li"))
if len(main) == 4:
return {"looking_for_table": {"user_id": profile_id,
"other_user": main[0].text,
"other_age": main[1].text,
"other_location": main[2].text,
"other_type": main[3].text}, }
if len(main) == 5:
return {"looking_for_table": {"user_id": profile_id,
"other_user": main[0].text,
"other_age": main[1].text,
"other_location": main[2].text,
"other_status": main[3].text,
"other_type": main[4].text}, }
except:
print profile
return {"looking_for_table": {"user_id": profile_id,
"data": "NA"}}
def getDetails(profile, profile_id):
"""Takes a BeautifulSoup object corresponding to profiles home
page and returns a list of profile's details"""
try:
main = profile.find("div", {"id": "profile_details"}).findAll("dd")
return {"details_table": {"user_id": profile_id,
"last_online": main[0].text,
"ethnicity": main[1].text,
"height": main[2].text,
"body_type": main[3].text,
"diet": main[4].text,
"smokes": main[5].text,
"drinks": main[6].text,
"religion": main[7].text,
"sign": main[8].text,
"education": main[9].text,
"job": main[10].text,
"income": main[11].text,
"offspring": main[12].text,
"pets": main[13].text,
"speaks": main[14].text}, }
except:
print profile
return {"details_table": {"user_id": profile_id,
"data": "NA"}}
def getQuestions(okc, profile_link, profile_id):
"""Take a link to a profile and return a list the questions a user
has answered"""
# Currently this doesn't return anything. All functions need to be
# changed up to work with mysql 07/19/2013 22:50
question_list = []
question_categories = ["Ethics", "Sex", "Religion", "Lifestyle",
"Dating", "Other"]
for category in question_categories:
q = BeautifulSoup(okc.get(profile_link + "/questions?"
+ category).text)
try:
max_page = int(q.find("div", {"class": "pages clearfix"})
.findAll("li")[1].find("a").text)
except IndexError:
max_page = 1
except AttributeError:
return []
for page in range(1, max_page + 1):
q_page = BeautifulSoup(okc.get(profile_link + "/questions?"
+ category + "="
+ str(page)).text)
questions = [q for q in q_page.find("div", {"id": "questions"})
.findAll("div",
{"class":
"question public talk clearfix"})]
for question in questions:
question_id = question["id"]
qtext = question.find("p", {"class": "qtext"}).text
atext = question.find("p",
{"class":
"answer target clearfix"}).text
question_list.append({"question_table":
{"user_id": profile_id,
"question_id": question_id,
"question_text": qtext,
"user_answer": atext,
"question_category": category},
})
return question_list
def pickleDict(dict_, dir):
"""Takes in a directory and a dictionary to be pickled and pickles
the dict in the directory"""
dict_id = dict_.keys()[0]
tab_i = pickle.load(open(dir + dict_id + ".p", "rb"))
tab_i.append(dict_)
pickle.dump(tab_i, open(dir + dict_id + ".p", "wb"))
def main(okc_instance):
"""The main event, takes an okc_instance (logged in) and writes a
profile to the docs"""
profiles, soup = getProfiles(okc_instance)
locations = [l.text.split(";")[1] for l in
soup.findAll("div", {"class": "userinfo"})]
if len([l for l in locations if l == "Chicago, IL"]) > 2:
print "Possible Reset"
for profile in profiles:
prof = getProfile(okc_instance, profile)
pickleDict(getInfo(prof[0], prof[1]), "data/")
pickleDict(getEssays(prof[0], prof[1]), "data/")
pickleDict(getLookingFor(prof[0], prof[1]), "data/")
pickleDict(getDetails(prof[0], prof[1]), "data/")
time.sleep(2)
return prof[1]<|fim▁end|> | users = soup.findAll("div", {"class": "user_info"})
return (["https://www.okcupid.com" +
user.find("a")["href"].replace("?cf=regular", "")
for user in users], soup) |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from setuptools import setup, find_packages
setup(name='gelato.models',
version='0.1.2',
description='Gelato models',
namespace_packages=['gelato'],
long_description='',
author='',
author_email='',
license='',
url='',
include_package_data=True,
packages=find_packages(exclude=['tests']),<|fim▁hole|><|fim▁end|> | install_requires=['django', 'tower']) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import abc
try:
import collections.abc as collectionsabc
except ImportError:
import collections as collectionsabc
import decimal
import io
import json
import locale
import os
import os.path
import subprocess
import threading
import time
def parse_version_string():
path = os.path.abspath(__file__)
while os.path.islink(path):
path = os.path.join(os.path.dirname(path), os.readlink(path))
path = os.path.dirname(path) # go up one level, from repo/lazyjson.py to repo, where README.md is located
while os.path.islink(path):
path = os.path.join(os.path.dirname(path), os.readlink(path))
try:
version = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], cwd=path).decode('utf-8').strip('\n')
if version == 'master':
try:
with open(os.path.join(path, 'README.md')) as readme:
for line in readme.read().splitlines():
if line.startswith('This is `lazyjson` version '):
return line.split(' ')[4]
except:
pass
return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'], cwd=path).decode('utf-8').strip('\n')
except:
pass
__version__ = str(parse_version_string())
try:
import builtins
import pathlib
except ImportError:
pass
else:
def open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None):
if isinstance(file, pathlib.Path):
return file.open(mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline)
else:
return builtins.open(file, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, closefd=closefd, opener=opener)
class DecimalEncoder(json.JSONEncoder): #FROM http://stackoverflow.com/a/3885198/667338
def default(self, o):
if isinstance(o, decimal.Decimal):
return float(o) # do not use str as that would enclose the value in quotes
return super().default(o)
class Node(collectionsabc.MutableMapping, collectionsabc.MutableSequence):
def __init__(self, root, key_path=None):
if not isinstance(root, BaseFile):
root = File(root)
self.root = root
self.key_path = [] if key_path is None else key_path[:]
def __contains__(self, item):
if isinstance(item, Node):
item = item.value()
return item in self.value()
def __deepcopy__(self, memodict={}):
return self.value()
def __delitem__(self, key):
self.root.delete_value_at_key_path(self.key_path + [key])
def __eq__(self, other):
return self.root == other.root and self.key_path == other.key_path
def __format__(self, format_spec):
return format(self.value(), format_spec)
def __getitem__(self, key):
return Node(self.root, self.key_path + [key])
def __hash__(self):
return hash((self.root, self.key_path))
def __iter__(self):
v = self.value()
if isinstance(v, dict):
for item in v:
yield self[item]
else:
for i in range(len(v)):
yield self[i]
def __len__(self):
return len(self.value())
def __str__(self):
return str(self.value())
def __repr__(self):
return 'lazyjson.Node(' + repr(self.root) + ', ' + repr(self.key_path) + ')'
def __setitem__(self, key, value):
if isinstance(value, Node):
value = value.value()
self.root.set_value_at_key_path(self.key_path + [key], value)
def get(self, key, default=None):
try:
return self[key].value()
except:
if isinstance(default, Node):
return default.value()
else:
return default
def insert(self, key, value):
self.root.insert_value_at_key_path(self.key_path + [key], value)
@property
def key(self):
if len(self.key_path) == 0:
return None
else:
return self.key_path[-1]
@property
def parent(self):
if len(self.key_path) == 0:
return None
elif len(self.key_path) == 1:
return self.root
else:
return Node(self.root, self.key_path[:-1])
def set(self, new_value):
if isinstance(new_value, Node):
new_value = new_value.value()
self.root.set_value_at_key_path(self.key_path, new_value)
def value(self):
return self.root.value_at_key_path(self.key_path)
class BaseFile(Node, metaclass=abc.ABCMeta):
"""ABC for lazyjson files (root values)."""
def __init__(self):
super().__init__(self)
@abc.abstractmethod
def __eq__(self, other):
raise NotImplementedError()
@abc.abstractmethod
def __hash__(self):
raise NotImplementedError()
def delete_value_at_key_path(self, key_path):
json_value = self.value()
item = json_value
if len(key_path) == 0:
json_value = None
else:
for key in key_path[:-1]:
item = item[key]
del item[key_path[-1]]
self.set(json_value)
def insert_value_at_key_path(self, key_path, value):
json_value = self.value()
item = json_value
if len(key_path) == 0:
json_value = value
else:
for key in key_path[:-1]:
item = item[key]
item.insert(key_path[-1], value)
self.set(json_value)
@abc.abstractmethod
def set(self, new_value):
pass
def set_value_at_key_path(self, key_path, new_value):
json_value = self.value()
item = json_value
if len(key_path) == 0:
json_value = new_value
else:
for key in key_path[:-1]:
item = item[key]
item[key_path[-1]] = new_value
self.set(json_value)
@abc.abstractmethod
def value(self, new_value):
pass
def value_at_key_path(self, key_path):
ret = self.value()
for key in key_path:
ret = ret[key]
return ret
class File(BaseFile):
"""A file based on a file-like object, a pathlib.Path, or anything that can be opened."""
def __init__(self, file_info, file_is_open=None, tries=10, init=..., **kwargs):
super().__init__()
self.open_args = dict(kwargs)
self.file_is_open = isinstance(file_info, io.IOBase) if file_is_open is None else bool(file_is_open)
self.tries = tries
self.file_info = file_info
self.lock = threading.Lock()
if init != ... and not self.file_is_open and not pathlib.Path(self.file_info).exists():
with open(self.file_info, 'w', **self.open_args) as json_file:
json.dump(init, json_file, sort_keys=True, indent=4, separators=(',', ': '), cls=DecimalEncoder)
print(file=json_file) # json.dump doesn't end the file in a newline, so add it manually
def __eq__(self, other):
return self.file_info == other.file_info
def __hash__(self):
return hash(self.file_info)
def __repr__(self):
return 'lazyjson.File(' + repr(self.file_info) + ('' if self.file_is_open and isinstance(self.file_info, io.IOBase) or (not self.file_is_open) and not isinstance(self.file_info, io.IOBase) else ', file_is_open=' + repr(self.file_is_open)) + ('' if self.tries == 10 else ', tries=' + repr(self.tries)) + (', **' + repr(self.open_args) if self.open_args else '') + ')'
def set(self, new_value):
if isinstance(new_value, Node):
new_value = new_value.value()
json.dumps(new_value, cls=DecimalEncoder) # try writing the value to a string first to prevent corrupting the file if the value is not JSON serializable
with self.lock:
if self.file_is_open:
json.dump(new_value, self.file_info, sort_keys=True, indent=4, separators=(',', ': '), cls=DecimalEncoder)
print(file=self.file_info) # json.dump doesn't end the file in a newline, so add it manually
else:
with open(self.file_info, 'w', **self.open_args) as json_file:
json.dump(new_value, json_file, sort_keys=True, indent=4, separators=(',', ': '), cls=DecimalEncoder)
print(file=json_file) # json.dump doesn't end the file in a newline, so add it manually
def value(self):
if self.file_is_open:
return json.load(self.file_info, parse_float=decimal.Decimal)
else:
tried = 0
while True:
try:
with open(self.file_info, **self.open_args) as json_file:
return json.load(json_file, parse_float=decimal.Decimal)
except json.decoder.JSONDecodeError:
tried += 1
if tried >= self.tries:
raise
else:
time.sleep(1)
class CachedFile(BaseFile):
"""A file that wraps an inner file. The contents of the inner file are cached in a user-provided cache, which must be a mutable mapping.
Cache invalidation must be handled externally, for example by storing the cache inside flask.g when working with the Flask framework.
"""
def __init__(self, cache, inner):
super().__init__()
self.cache = cache
self.inner = inner
def __eq__(self, other):
return self.inner == other.inner
def __hash__(self):
return hash(self.inner)
def __repr__(self):
return 'lazyjson.CachedFile(' + repr(self.cache) + ', ' + repr(self.inner) + ')'
def set(self, new_value):
if self.inner in self.cache:
del self.cache[self.inner]
self.inner.set(new_value)
def value(self):
if self.inner not in self.cache:
self.cache[self.inner] = self.inner.value()
return self.cache[self.inner]
class HTTPFile(BaseFile):
def __init__(self, url, post_url=None, **kwargs):
super().__init__()
self.url = url
self.post_url = url if post_url is None else post_url
self.request_params = kwargs
def __eq__(self, other):
return self.url == other.url and self.post_url == other.post_url
def __hash__(self):
return hash((self.url, self.post_url))
def __repr__(self):
return 'lazyjson.HTTPFile(' + repr(self.url) + ('' if self.post_url == self.url else ', post_url=' + repr(self.post_url)) + ''.join(', {}={}'.format(k, repr(v)) for k, v in self.request_params.items()) + ')'
def set(self, new_value):
import requests
if isinstance(new_value, Node):
new_value = new_value.value()
request_params = self.request_params.copy()
request_params['json'] = new_value
requests.post(self.post_url, **request_params)
def value(self):
import requests
return requests.get(self.url, **self.request_params).json()
class MultiFile(BaseFile):
def __init__(self, *args):
super().__init__()
self.files = [arg if isinstance(arg, BaseFile) else File(arg) for arg in args]
def __eq__(self, other):
return self.files == other.files
def __hash__(self):
return hash(self.files)
def __repr__(self):
return 'lazyjson.MultiFile(' + ', '.join(repr(f) for f in self.files) + ')'
@staticmethod
def json_recursive_merge(json_values):
try:
first = next(json_values)
except StopIteration:
return None
if isinstance(first, dict):
objects_prefix = [first]
for value in json_values:
if isinstance(value, dict):
objects_prefix.append(value)
else:
break
return {k: MultiFile.json_recursive_merge(value[k] for value in objects_prefix if isinstance(value, dict) and k in value) for k in set.union(*(set(d.keys()) for d in objects_prefix))}
else:
return first
def set(self, new_value):
self.files[0].set(new_value)
def value(self):
return self.json_recursive_merge(f.value() for f in self.files)
class PythonFile(BaseFile):
"""A file based on a Python object. Can be used with MultiFile to provide fallback values."""
def __init__(self, value=None):
super().__init__()
self._value = value
def __eq__(self, other):<|fim▁hole|> return self._value == other._value
def __hash__(self):
return hash(self._value)
def __repr__(self):
return 'lazyjson.PythonFile(' + repr(self._value) + ')'
def set(self, new_value):
if isinstance(new_value, Node):
new_value = new_value.value()
json.dumps(new_value, cls=DecimalEncoder) # try writing the value to a string first to make sure it is JSON serializable
self._value = new_value
def value(self):
return self._value
class SFTPFile(BaseFile):
def __init__(self, host, port, path, **kwargs):
import paramiko
import paramiko.util
super().__init__()
self.hostname = host
self.port = port
self.remote_path = path
self.connection_args = kwargs.copy()
if 'pkey' not in self.connection_args:
self.connection_args['pkey'] = paramiko.RSAKey.from_private_key_file(os.path.expanduser('~/.ssh/id_rsa'))
if 'hostkey' not in self.connection_args:
host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
self.connection_args['hostkey'] = host_keys[self.hostname][host_keys[self.hostname].keys()[0]]
def __eq__(self, other):
return self.hostname == other.hostname and self.port == other.port and self.remote_path == other.remote_path
def __hash__(self):
return hash((self.hostname, self.port, self.remote_path))
def __repr__(self):
return 'lazyjson.SFTPFile(' + repr(self.hostname) + ', ' + repr(self.port) + ', ' + repr(self.remote_path) + ''.join(', {}={}'.format(k, repr(v)) for k, v in self.connection_args.items()) + ')'
def set(self, new_value):
import paramiko
if isinstance(new_value, Node):
new_value = new_value.value()
with paramiko.Transport((self.hostname, self.port)) as transport:
transport.connect(**self.connection_args)
with transport.open_sftp_client() as sftp_client:
with sftp_client.file(self.remote_path, 'w') as sftp_file:
json_string = json.dumps(new_value, sort_keys=True, indent=4, separators=(',', ': '), cls=DecimalEncoder)
sftp_file.write(json_string.encode('utf-8') + b'\n')
def value(self):
import paramiko
with paramiko.Transport((self.hostname, self.port)) as transport:
transport.connect(**self.connection_args)
with transport.open_sftp_client() as sftp_client:
with sftp_client.file(self.remote_path) as sftp_file:
return json.loads(sftp_file.read().decode('utf-8'), parse_float=decimal.Decimal)<|fim▁end|> | |
<|file_name|>decimal.js.d.ts<|end_file_name|><|fim▁begin|>// Type definitions for decimal.js
// Project: http://mikemcl.github.io/decimal.js
// Definitions by: Joseph Rossi <http://github.com/musicist288>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare var Decimal: decimal.IDecimalStatic;
// Support AMD require
declare module 'decimal.js' {
export = Decimal;
}
declare module decimal {
enum RoundingMode {
/**
* Rounds away from zero
*/
ROUND_UP = 0,
/**
* Rounds towards zero
*/
ROUND_DOWN = 1,
/**
* Rounds towards Infinity
*/
ROUND_CEIL = 2,
/**
* Rounds towards -Infinity
*/
ROUND_FLOOR = 3,
/**
* Rounds towards nearest neighbour.
* If equidistant, rounds away from zero
*/
ROUND_HALF_UP = 4,
/**
* Rounds towards nearest neighbour.
* If equidistant, rounds towards zero
*/
ROUND_HALF_DOWN = 5,
/**
* Rounds towards nearest neighbour.
* If equidistant, rounds towards even neighbour
*/
ROUND_HALF_EVEN = 6,
/**
* Rounds towards nearest neighbour.
* If equidistant, rounds towards Infinity
*/
ROUND_HALF_CEIL = 7,
/**
* Rounds towards nearest neighbour.
* If equidistant, rounds towards -Infinity
*/
ROUND_HALF_FLOOR = 8,
/**
* Not a rounding mode, see modulo
*/
EUCLID = 9,
}
interface IFormatConfig {
decimalSeparator?: string;
groupSeparator?: string;
groupSize?: number;
secondaryGroupSize?: number;
fractionGroupSeparator?: string;
fractionGroupSize?: number;
}
interface IDecimalConfig {
/**
* number: integer, 1 to 1e+9 inclusive
* Default value: 20
*
* The maximum number of significant digits of the result of a calculation or base conversion.
*
* All methods which return a Decimal will round the return value to precision significant digits except absoluteValue, ceil, floor, negated, round, toDecimalPlaces, toNearest and truncated.
*
* A Decimal constructor will also not round to precision unless a base is specified.
*/
precision?: number;
/**
* number: integer, 0 to 8 inclusive
* Default value: 4 (ROUND_HALF_UP)
*
* The default rounding mode used when rounding the result of a calculation or base conversion to precision significant digits, and when rounding the return value of the round, toDecimalPlaces, toExponential, toFixed, toFormat, toNearest, toPrecision and toSignificantDigits methods.
*
* The rounding modes are available as enumerated properties of the constructor.
*/
rounding?: RoundingMode;
/**
* number: integer, -9e15 to 0 inclusive
* Default value: -7
*
* The negative exponent value at and below which toString returns exponential notation.
* @type {[type]}
*/
toExpNeg?: number;
/**
* number: integer, 0 to 9e15 inclusive
* Default value: 20
*
* The positive exponent value at and above which toString returns exponential notation.
*/
toExpPos?: number;
/**
* number: integer, -9e15 to 0 inclusive
* Default value: -9e15
*
* The negative exponent limit, i.e. the exponent value below which underflow to zero occurs.
*
* If the Decimal to be returned by a calculation would have an exponent lower than minE then its value becomes zero.
*
* JavaScript numbers underflow to zero for exponents below -324.
*/
minE?: number;
/**
* number: integer, 0 to 9e15 inclusive
* Default value: 9e15
*
* The positive exponent limit, i.e. the exponent value above which overflow to Infinity occurs.
*
* If the Decimal to be returned by a calculation would have an exponent higher than maxE then its value becomes Infinity.
*
* JavaScript numbers overflow to Infinity for exponents above 308.
*/
maxE?: number;
/**
* boolean/number: true, false, 1 or 0
* Default value: true
*
* The value that determines whether Decimal Errors are thrown. If errors is false, this library will not throw errors.
*/
errors?: boolean | number;
/**
* boolean/number: true, false, 1 or 0
* Default value: false
*
* The value that determines whether cryptographically-secure pseudo-random number generation is used.
*
* If crypto is truthy then the random method will generate random digits using crypto.getRandomValues in browsers that support it, or crypto.randomBytes if using a version of Node.js that supports it.
*
* If neither function is supported by the host environment or if crypto is falsey then the source of randomness will be Math.random. If the crypto property is set directly (i.e. without using config) to true, then at the time the random method is called, if errors is true, an error will be thrown if the crypto methods are unavailable.
*/
crypto?: boolean | number;
/**
* number: integer, 0 to 9 inclusive
* Default value: 1 (ROUND_DOWN)
*
* The modulo mode used when calculating the modulus: a mod n.
*
* The quotient, q = a / n, is calculated according to the rounding mode that corresponds to the chosen modulo mode.
*
* The remainder, r, is calculated as: r = a - n * q.
*
* The modes that are most commonly used for the modulus/remainder operation are ROUND_UP, ROUND_DOWN, ROUND_FLOOR, ROUND_HALF_EVEN, and EUCLID. Although the other rounding modes can be used, they may not give useful results.
*/
modulo?: RoundingMode;
/**
* The format object configures the format of the string returned by the toFormat method.
*
* The example below shows the properties of the format object that are recognised, and their default values.
*
* Unlike setting other properties using config, the values of the properties of the format object will not be checked for validity. The existing format object will simply be replaced by the object that is passed in. Only the toFormat method ever references a Decimal constructor's format object property.
*
* See toFormat for examples of usage, and of setting format properties individually and directly without using config.
*/
format?: IFormatConfig;
}
interface IDecimalStatic extends IDecimalConfig {
(value: number | string | Decimal, base?: number): Decimal;
new(value: number | string | Decimal, base?: number): Decimal;
/**
* Configures the 'global' settings for this particular Decimal constructor.
*
* Returns this Decimal constructor.
*/
config(object: IDecimalConfig): IDecimalStatic;
/**
* Returns a new independent Decimal constructor with configuration settings as described by object
*/
constructor(object: IDecimalConfig): IDecimalStatic;
/**
* Returns a new Decimal whose value is the base e (Euler's number, the base of the natural logarithm) exponential of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.
*/
exp(n: number | string | Decimal): Decimal;
/**
* Returns a new Decimal whose value is the natural logarithm of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.
*
* The natual logarithm is the inverse of the exponential function.
*/
ln(n: number | string | Decimal): Decimal;
/**
* Returns a new Decimal whose value is the base n logarithm of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.
*
* If n is null or undefined, then the base 10 logarithm of the value of this Decimal will be returned.
*/
log(n: number | string | Decimal, base?: number): Decimal;
/**
* Returns a new Decimal whose value is the maximum of arg1, arg2,... .
*/
max(...args: any[]): Decimal;
/**
* Returns a new Decimal whose value is the minimum of arg1, arg2,... .
*/
min(...args: any[]): Decimal;
/**
* Reverts the Decimal variable to the value it had before this library was loaded and returns a reference to the original Decimal constructor so it can be assigned to a variable with a different name.
*/
noConflict(): IDecimalStatic;
/**
* Returns a new Decimal whose value is the value of this Decimal raised to the power n, rounded to precision significant digits using rounding mode rounding.
*
* The performance of this method degrades exponentially with increasing digits. For non-integer exponents in particular, the performance of this method may not be adequate.
*/
pow(base: number | string | Decimal, exponent: number | string | Decimal): Decimal;
/**
* Returns a new Decimal with a pseudo-random value equal to or greater than 0 and less than 1. The return value will have dp decimal places (or less if trailing zeros are produced). If dp is omitted then the number of decimal places will default to the current precision setting.
*
* Depending on the value of a Decimal constructor's crypto property and the support for the crypto object in the host environment, the random digits of the return value are generated by either Math.random (fastest), crypto.getRandomValues (Web Cryptography API in recent browsers) or crypto.randomBytes (Node.js).
*
* If crypto is true, i.e. one of the crypto methods is to be used, the value of a returned Decimal should be cryptographically-secure and statistically indistinguishable from a random value.
*/
random(dp?: number): Decimal;
/**
* The return value will be correctly rounded, i.e. rounded as if the result was first calculated to an infinite number of correct digits before rounding.
*
* This method is much faster than using the toPower method with an exponent of 0.5.
*/
sqrt(arg: number | string | Decimal): Decimal;
/**
* A Decimal instance with value one.
*/
ONE: number;
/**
* Rounds away from zero
*/
ROUND_UP: number;
/**
* Rounds towards zero
*/
ROUND_DOWN: number;
/**
* Rounds towards Infinity
*/
ROUND_CEIL: number;
/**
* Rounds towards -Infinity
*/
ROUND_FLOOR: number;
/**
* Rounds towards nearest neighbour.
* If equidistant, rounds away from zero
*/
ROUND_HALF_UP: number;
/**
* Rounds towards nearest neighbour.
* If equidistant, rounds towards zero
*/
ROUND_HALF_DOWN: number;
/**
* Rounds towards nearest neighbour.
* If equidistant, rounds towards even neighbour
*/
ROUND_HALF_EVEN: number;
/**
* Rounds towards nearest neighbour.
* If equidistant, rounds towards Infinity
*/
ROUND_HALF_CEIL: number;
/**
* Rounds towards nearest neighbour.
* If equidistant, rounds towards -Infinity
*/
ROUND_HALF_FLOOR: number;
/**
* Not a rounding mode, see modulo
*/
EUCLID: number;
}
interface Decimal {
/**
* Returns a new Decimal whose value is the absolute value, i.e. the magnitude, of the value of this Decimal.
*
* The return value is not rounded.
*/
absoluteValue(): Decimal;
/**
* Returns a new Decimal whose value is the absolute value, i.e. the magnitude, of the value of this Decimal.
*
* The return value is not rounded.
*/
abs(): Decimal;
/**
* Returns a new Decimal whose value is the value of this Decimal rounded to a whole number in the direction of positive Infinity.
*
* The return value is not rounded to precision.
*/
ceil(): Decimal;
/**
* @return 1, -1, 0, or null
* 1 If the value of this Decimal is greater than the
* value of n
* -1 If the value of this Decimal is less than the value
* of n
* 0 If this Decimal and n have the same value
* null If the value of either this Decimal or n is NaN
*/
comparedTo(n: number | string | Decimal, base?: number): number;
/**
* Returns 1, -1, 0, or null
* 1 If the value of this Decimal is greater than the value
* of n
* -1 If the value of this Decimal is less than the value
* of n
* 0 If this Decimal and n have the same value
* null If the value of either this Decimal or n is NaN
*/
cmp(n: number | string | Decimal, base?: number): number;
/**
* Returns the number of decimal places, i.e. the number of digits after the decimal point, of the value of this Decimal.
*/
decimalPlaces(): number;
/**
* Returns the number of decimal places, i.e. the number of digits after the decimal point, of the value of this Decimal.
*/
dp(): number;
/**
* Returns a new Decimal whose value is the value of this Decimal divided by n, rounded to precision significant digits using rounding mode rounding.
*/
dividedBy(n: number | string | Decimal, base?: number): Decimal;
/**
* Returns a new Decimal whose value is the value of this Decimal divided by n, rounded to precision significant digits using rounding mode rounding.
*/
div(n: number | string | Decimal, base?: number): Decimal;
/**
* Return a new Decimal whose value is the integer part of dividing this Decimal by n, rounded to precision significant digits using rounding mode rounding.
*/
dividedToIntegerBy(n: number | string| Decimal, base?: number): Decimal;
/**
* Return a new Decimal whose value is the integer part of dividing this Decimal by n, rounded to precision significant digits using rounding mode rounding.
*/
divToInt(n: number | string| Decimal, base?: number): Decimal;
/**
* Returns true if the value of this Decimal equals the value of n, otherwise returns false.
*
* As with JavaScript, NaN does not equal NaN.
*
* Note: This method uses the cmp method internally.
*/
equals(n: number | string | Decimal, base?: number): boolean;
/**
* Returns true if the value of this Decimal equals the value of n, otherwise returns false.
*
* As with JavaScript, NaN does not equal NaN.
*
* Note: This method uses the cmp method internally.
*/
eq(n: number | string | Decimal, base?: number): boolean;
/**
* Returns a new Decimal whose value is the base e (Euler's number, the base of the natural logarithm) exponential of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.
*/
exponential(): Decimal;
/**
* Returns a new Decimal whose value is the base e (Euler's number, the base of the natural logarithm) exponential of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.
*/
exp(): Decimal;
/**
* The return value is not rounded to precision.
*/
floor(): Decimal;
/**
* Note: This method uses cmp method internally.
*/
greaterThan(n: number | string | Decimal, base?: number): boolean;
/**
* Note: This method uses cmp method internally.
*/
gt(n: number | string | Decimal, base?: number): boolean;
/**
* Note: This method uses cmp method internally.
*/
greaterThanOrEqualTo(n: number | string | Decimal, base?: number): boolean;
/**
* Note: This method uses cmp method internally.
*/
gte(n: number | string | Decimal, base?: number): boolean;
/**
* The only possible non-finite values of a Decimal are NaN, Infinity and -Infinity.
*/
isFinite(): boolean;
isInteger(): boolean;
isInt(): boolean;
isNaN(): boolean;
isNegative(): boolean;
isNeg(): boolean;
isZero(): boolean;
/**
* Note: This method uses cmp method internally.
*/
lessThan(n: number | string | Decimal, base?: number): boolean;
/**
* Note: This method uses cmp method internally.
*/
lt(n: number | string | Decimal, base?: number): boolean;
/**
* Note: This method uses cmp method internally.
*/
lessThanOrEqualTo(n: number | string | Decimal, base?: number): boolean;
/**
* Note: This method uses cmp method internally.
*/
lte(n: number | string | Decimal, base?: number): boolean;
/**
* Returns a new Decimal whose value is the base n logarithm of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.
*
* If n is null or undefined, then the base 10 logarithm of the value of this Decimal will be returned.
*/
logarithm(n?: number | string | Decimal, base?: number): Decimal;
/**
* Returns a new Decimal whose value is the base n logarithm of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.
*
* If n is null or undefined, then the base 10 logarithm of the value of this Decimal will be returned.
*/
log(n?: number | string | Decimal, base?: number): Decimal;
/**
* Returns a new Decimal whose value is the value of this Decimal minus n, rounded to precision significant digits using rounding mode rounding.
*/
minus(n: number | string | Decimal, base?: number): Decimal;
/**
* Returns a new Decimal whose value is the value of this Decimal modulo n, rounded to precision significant digits using rounding mode rounding.
*
* The value returned, and in particular its sign, is dependent on the value of the modulo property of this Decimal's constructor. If it is 1 (default value), the result will have the same sign as this Decimal, and it will match that of Javascript's % operator (within the limits of double precision) and BigDecimal's remainder method.
*/
modulo(n: number | string | Decimal, base?: number): Decimal;
/**
* Returns a new Decimal whose value is the value of this Decimal modulo n, rounded to precision significant digits using rounding mode rounding.
*
* The value returned, and in particular its sign, is dependent on the value of the modulo property of this Decimal's constructor. If it is 1 (default value), the result will have the same sign as this Decimal, and it will match that of Javascript's % operator (within the limits of double precision) and BigDecimal's remainder method.
*/
mod(n: number | string | Decimal, base?: number): Decimal;
/**
* Returns a new Decimal whose value is the natural logarithm of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.
*
* The natual logarithm is the inverse of the exponential function.
*/
naturalLogarithm(): Decimal;
/**
* Returns a new Decimal whose value is the natural logarithm of the value of this Decimal, rounded to precision significant digits using rounding mode rounding.
*
* The natual logarithm is the inverse of the exponential function.
*/
ln(): Decimal;
/**
* The return value is not rounded.
*/
negated(): Decimal;
/**
* The return value is not rounded.
*/
neg(): Decimal;
/**
* Returns a new Decimal whose value is the value of this Decimal plus n, rounded to precision significant digits using rounding mode rounding.
*/
plus(n: number | string | Decimal, base?: number): Decimal;
/**
* If include_zeros is true or 1 then any trailing zeros of the integer part of a number are counted as significant digits, otherwise they are not.
*/
precision(include_leading_zeros?: boolean | number): number;
/**
* If include_zeros is true or 1 then any trailing zeros of the integer part of a number are counted as significant digits, otherwise they are not.
*/
sd(include_leading_zeros?: boolean | number): number;
round(): Decimal;
/**
* The return value will be correctly rounded, i.e. rounded as if the result was first calculated to an infinite number of correct digits before rounding.
*
* This method is much faster than using the toPower method with an exponent of 0.5.
*/
squareRoot(): Decimal;
/**
* The return value will be correctly rounded, i.e. rounded as if the result was first calculated to an infinite number of correct digits before rounding.
*
* This method is much faster than using the toPower method with an exponent of 0.5.
*/
sqrt(): Decimal;
/**
* Returns a new Decimal whose value is the value of this Decimal times n, rounded to precision significant digits using rounding mode rounding.
*/
times(n: number | string | Decimal, base?: number): Decimal;
/**
* Returns a new Decimal whose value is the value of this Decimal rounded to dp decimal places using rounding mode rm.
*
* If dp is omitted or is null or undefined, the return value will have the same value as this Decimal.
*
* If rm is omitted or is null or undefined, rounding mode rounding is used.
*/
toDecimalPlaces(dp?: number, rm?: RoundingMode): Decimal;
/**
* Returns a new Decimal whose value is the value of this Decimal rounded to dp decimal places using rounding mode rm.
*
* If dp is omitted or is null or undefined, the return value will have the same value as this Decimal.
*
* If rm is omitted or is null or undefined, rounding mode rounding is used.
*/
toDP(dp?: number, rm?: RoundingMode): Decimal;
/**
* Returns a string representing the value of this Decimal in exponential notation rounded using rounding mode rm to dp decimal places, i.e with one digit before the decimal point and dp digits after it.
*
* If the value of this Decimal in exponential notation has fewer than dp fraction digits, the return value will be appended with zeros accordingly.
*
* If dp is omitted, or is null or undefined, the number of digits after the decimal point defaults to the minimum number of digits necessary to represent the value exactly.
*
* If rm is omitted or is null or undefined, rounding mode rounding is used.
*/
toExponential(dp?: number, rm?: RoundingMode): string;
/**
* Returns a string representing the value of this Decimal in normal (fixed-point) notation rounded to dp decimal places using rounding mode rm.
*
* If the value of this Decimal in normal notation has fewer than dp fraction digits , the return value will be appended with zeros accordingly.
*
* Unlike Number.prototype.toFixed, which returns exponential notation if a number is greater or equal to 1021, this method will always return normal notation.
*
* If dp is omitted or is null or undefined, then the return value will be unrounded and in normal notation. This is unlike Number.prototype.toFixed, which returns the value to zero decimal places, but is useful when because of the current toExpNeg or toExpNeg values, toString returns exponential notation
*
* if rm is omitted or is null or undefined, rounding mode rounding is used.
*/
toFixed(dp?: number, rm?: RoundingMode): string;
/**
* Returns a string representing the value of this Decimal in fixed-point notation rounded to dp decimal places using rounding mode rm (as toFixed), and formatted according to the properties of this Decimal's constructor's format object property.
*
* See the examples below for the properties of the format object, their types and their usage.
*
* If dp is omitted or is null or undefined, then the return value is not rounded to a fixed number of decimal places.
*
* if rm is omitted or is null or undefined, rounding mode rounding is used.
*/
toFormat(dp?: number, rm?: RoundingMode): string;
/**
* Returns a string array representing the value of this Decimal as a simple fraction with an integer numerator and an integer denominator. The denominator will be a positive non-zero value less than or equal to max_denominator.
*
* If a maximum denominator is not specified, or is null or undefined, the denominator will be the lowest value necessary to represent the number exactly.
*/
toFraction(max_denominator?: number | string | Decimal): string[];
toJSON(): string;
/**
* Returns a new Decimal whose value is the nearest multiple of n to the value of this Decimal.
*
* If the value of this Decimal is equidistant from two multiples of n, the rounding mode rm, or rounding if rm is omitted or is null or undefined, determines the direction of the nearest.
*
* In this context, rounding mode ROUND_HALF_UP is interpreted the same as rounding mode ROUND_UP, and so on. I.e. the rounding is either up, own, to ceil, to floor or to even.
*
* The return value will always have the same sign as this Decimal, unless either this Decimal or n is NaN, in which case the return value will be also be NaN.
*
* The return value is not rounded to precision.
*/
toNearest(n: number | string | Decimal, rm?: RoundingMode): Decimal;
/**
* Returns the value of this Decimal converted to a number primitive.
*
* Type coercion with, for example, JavaScript's unary plus operator will also work, except that a Decimal with the value minus zero will convert to positive zero.
*/
toNumber(): number;
/**
* Returns a new Decimal whose value is the value of this Decimal raised to the power n, rounded to precision significant digits using rounding mode rounding.
*<|fim▁hole|>
/**
* Returns a new Decimal whose value is the value of this Decimal raised to the power n, rounded to precision significant digits using rounding mode rounding.
*
* The performance of this method degrades exponentially with increasing digits. For non-integer exponents in particular, the performance of this method may not be adequate.
*/
pow(n: number | string | Decimal, base?: number): Decimal;
/**
* Returns a string representing the value of this Decimal rounded to sd significant digits using rounding mode rm.
*
* If sd is less than the number of digits necessary to represent the integer part of the value in normal (fixed-point) notation, then exponential notation is used.
*
* If sd is omitted or is null or undefined, then the return value is the same as toString.
*
* if rm is omitted or is null or undefined, rounding mode rounding is used.
*/
toPrecision(sd?: number, rm?: RoundingMode): string;
/**
* Returns a new Decimal whose value is the value of this Decimal rounded to sd significant digits using rounding mode rm.
*
* If sd is omitted or is null or undefined, the return value will be rounded to precision significant digits.
*
* if rm is omitted or is null or undefined, rounding mode rounding will be used.
*/
toSignificantDigits(sd?: number, rm?: RoundingMode): Decimal;
/**
* Returns a new Decimal whose value is the value of this Decimal rounded to sd significant digits using rounding mode rm.
*
* If sd is omitted or is null or undefined, the return value will be rounded to precision significant digits.
*
* if rm is omitted or is null or undefined, rounding mode rounding will be used.
*/
toSD(sd?: number, rm?: RoundingMode): Decimal;
/**
* base: number: integer, 2 to 64 inclusive
*
* Returns a string representing the value of this Decimal in the specified base, or base 10 if base is omitted or is null or undefined.
*
* For bases above 10, values from 10 to 35 are represented by a-z (as with Number.prototype.toString), 36 to 61 by A-Z, and 62 and 63 by $ and _ respectively.
*
* If a base is specified the value is rounded to precision significant digits using rounding mode rounding.
*
* If a base is not specified and this Decimal has a positive exponent that is equal to or greater than toExpPos, or a negative exponent equal to or less than toExpNeg, then exponential notation is returned.
*
* If base is null or undefined it is ignored.
*/
toString(base?: number): string;
/**
* Returns a new Decimal whose value is the value of this Decimal truncated to a whole number.
*
* The return value is not rounded to precision.
*/
truncated(): Decimal;
/**
* Returns a new Decimal whose value is the value of this Decimal truncated to a whole number.
*
* The return value is not rounded to precision.
*/
trunc(): Decimal;
/**
* As toString, but does not accept a base argument.
*/
valueOf(): string;
/**
* coefficient
*
* Array of integers, each 0 - 1e7
*/
c: number[];
/**
* exponent
*
* Integer, -9e15 to 9e15 inclusive
*/
e: number;
/**
* sign
*
* -1 or 1
*/
s: number;
}
}<|fim▁end|> | * The performance of this method degrades exponentially with increasing digits. For non-integer exponents in particular, the performance of this method may not be adequate.
*/
toPower(n: number | string | Decimal, base?: number): Decimal; |
<|file_name|>tri10.rs<|end_file_name|><|fim▁begin|>use russell_lab::{Matrix, Vector};
/// Defines a triangle with 10 nodes (cubic edges; interior node)
///
/// # Local IDs of nodes
///
/// ```text
/// s
/// |
/// 2, (0,1)
/// | ',
/// | ',
/// 5 7,
/// | ',
/// | ',
/// 8 9 4,
/// | ',
/// | (0,0) ', (1,0)
/// 0-----3-----6-----1 ---- r
/// ```
///
/// # Local IDs of edges
///
/// ```text
/// |\
/// | \
/// | \ 1
/// 2| \
/// | \
/// |_____\
/// 0<|fim▁hole|>pub struct Tri10 {}
impl Tri10 {
pub const NDIM: usize = 2;
pub const NNODE: usize = 10;
pub const NEDGE: usize = 3;
pub const NFACE: usize = 0;
pub const EDGE_NNODE: usize = 4;
pub const FACE_NNODE: usize = 0;
pub const FACE_NEDGE: usize = 0;
#[rustfmt::skip]
pub const EDGE_NODE_IDS: [[usize; Tri10::EDGE_NNODE]; Tri10::NEDGE] = [
[0, 1, 3, 6],
[1, 2, 4, 7],
[2, 0, 5, 8],
];
#[rustfmt::skip]
pub const NODE_REFERENCE_COORDS: [[f64; Tri10::NDIM]; Tri10::NNODE] = [
[0.0 , 0.0 ], // 0
[1.0 , 0.0 ], // 1
[0.0 , 1.0 ], // 2
[1.0 / 3.0 , 0.0 ], // 3
[2.0 / 3.0 , 1.0 / 3.0], // 4
[0.0 , 2.0 / 3.0], // 5
[2.0 / 3.0 , 0.0 ], // 6
[1.0 / 3.0 , 2.0 / 3.0], // 7
[0.0 , 1.0 / 3.0], // 8
[1.0 / 3.0 , 1.0 / 3.0], // 9
];
/// Computes the interpolation functions
pub fn calc_interp(interp: &mut Vector, ksi: &[f64]) {
let (r, s) = (ksi[0], ksi[1]);
let z = 1.0 - r - s;
let t1 = s * (3.0 * s - 1.0);
let t2 = z * (3.0 * z - 1.0);
let t3 = r * (3.0 * r - 1.0);
interp[0] = 0.5 * t2 * (3.0 * z - 2.0);
interp[1] = 0.5 * t3 * (3.0 * r - 2.0);
interp[2] = 0.5 * t1 * (3.0 * s - 2.0);
interp[3] = 4.5 * r * t2;
interp[4] = 4.5 * s * t3;
interp[5] = 4.5 * z * t1;
interp[6] = 4.5 * z * t3;
interp[7] = 4.5 * r * t1;
interp[8] = 4.5 * s * t2;
interp[9] = 27.0 * s * z * r;
}
/// Computes the derivatives of interpolation functions
pub fn calc_deriv(deriv: &mut Matrix, ksi: &[f64]) {
let (r, s) = (ksi[0], ksi[1]);
let z = 1.0 - r - s;
let q0 = 4.5 * (6.0 * z - 1.0);
let q1 = 4.5 * s * (3.0 * s - 1.0);
let q2 = 4.5 * z * (3.0 * z - 1.0);
let q3 = 4.5 * r * (3.0 * r - 1.0);
let q4 = 4.5 * (6.0 * s - 1.0);
let q5 = 4.5 * (6.0 * r - 1.0);
let q6 = q0 * s;
let q7 = q0 * r;
let q8 = -0.5 * (27.0 * z * z - 18.0 * z + 2.0);
let q9 = 0.5 * (27.0 * s * s - 18.0 * s + 2.0);
let q10 = 0.5 * (27.0 * r * r - 18.0 * r + 2.0);
deriv[0][0] = q8;
deriv[1][0] = q10;
deriv[2][0] = 0.0;
deriv[3][0] = q2 - q7;
deriv[4][0] = s * q5;
deriv[5][0] = -q1;
deriv[6][0] = z * q5 - q3;
deriv[7][0] = q1;
deriv[8][0] = -q6;
deriv[9][0] = 27.0 * s * (z - r);
deriv[0][1] = q8;
deriv[1][1] = 0.0;
deriv[2][1] = q9;
deriv[3][1] = -q7;
deriv[4][1] = q3;
deriv[5][1] = z * q4 - q1;
deriv[6][1] = -q3;
deriv[7][1] = r * q4;
deriv[8][1] = q2 - q6;
deriv[9][1] = 27.0 * r * (z - s);
}
}<|fim▁end|> | /// ``` |
<|file_name|>Main.java<|end_file_name|><|fim▁begin|>public class Main {
public static void main(String[] args) {
ProdutoContext manga = new ProdutoContext();
System.out.println("Quantia: " + manga.getQuantia());
manga.fazerCompra(5);
manga.reestocar(5);
manga.fazerCompra(5);
manga.reestocar(15);
System.out.println("Quantia: " + manga.getQuantia());
manga.fazerCompra(5);
System.out.println("Quantia: " + manga.getQuantia());<|fim▁hole|><|fim▁end|> | }
} |
<|file_name|>Gruntfile.js<|end_file_name|><|fim▁begin|>/*global module */
module.exports = function(grunt) {
'use strict';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
//define the string to go between each file in the concat'd output
separator: ';'
},
dist: {
//files to concatenate
src: ['src/**/*.js'],
//destination js file
dest: 'build/js/<%= pkg.name %>.js'
}
},
uglify: {
options: {
// the banner to stamp at top of output
banner: '/* <%= pkg.name %> <%= grunt.template.today("dd-mm-yy") %> /* \n'
},
dist: {
files: {
'build/js/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
}
}
},
jshint: {
//files to lint
files: ['Gruntfile.js', 'src/**/*.js'],
options: {
globals: {
jQuery: true,
console: true,
module: true
}
}
},
compass: {
dist: {
options: {
sassDir: 'src/sass',
cssDir: 'build/css'
}
}
},
watch: {
css: {
files: 'src/sass/*.scss',
tasks: ['compass']
},
js: {
files: ['src/js/*.js'],
tasks: ['jshint', 'uglify', 'concat']
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-compass');
<|fim▁hole|><|fim▁end|> | grunt.registerTask('default', ['jshint', 'concat', 'uglify', 'compass']);
}; //exports |
<|file_name|>send.py<|end_file_name|><|fim▁begin|># Copyright (C) 2009, 2010 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
from __future__ import absolute_import
import os
import time
from bzrlib import (
controldir,
errors,
osutils,
registry,
trace,
)
from bzrlib.i18n import gettext
from bzrlib.branch import (
Branch,
)
from bzrlib.revision import (
NULL_REVISION,
)
format_registry = registry.Registry()
def send(target_branch, revision, public_branch, remember,
format, no_bundle, no_patch, output, from_, mail_to, message, body,
to_file, strict=None):
possible_transports = []
tree, branch = controldir.ControlDir.open_containing_tree_or_branch(
from_, possible_transports=possible_transports)[:2]
# we may need to write data into branch's repository to calculate
# the data to send.
branch.lock_write()
try:
if output is None:
config_stack = branch.get_config_stack()
if mail_to is None:
mail_to = config_stack.get('submit_to')
mail_client = config_stack.get('mail_client')(config_stack)
if (not getattr(mail_client, 'supports_body', False)<|fim▁hole|> if remember and target_branch is None:
raise errors.BzrCommandError(gettext(
'--remember requires a branch to be specified.'))
stored_target_branch = branch.get_submit_branch()
remembered_target_branch = None
if target_branch is None:
target_branch = stored_target_branch
remembered_target_branch = "submit"
else:
# Remembers if asked explicitly or no previous location is set
if remember or (
remember is None and stored_target_branch is None):
branch.set_submit_branch(target_branch)
if target_branch is None:
target_branch = branch.get_parent()
remembered_target_branch = "parent"
if target_branch is None:
raise errors.BzrCommandError(gettext('No submit branch known or'
' specified'))
if remembered_target_branch is not None:
trace.note(gettext('Using saved {0} location "{1}" to determine '
'what changes to submit.').format(
remembered_target_branch,
target_branch))
submit_branch = Branch.open(target_branch,
possible_transports=possible_transports)
possible_transports.append(submit_branch.bzrdir.root_transport)
if mail_to is None or format is None:
if mail_to is None:
mail_to = submit_branch.get_config_stack().get(
'child_submit_to')
if format is None:
formatname = submit_branch.get_child_submit_format()
try:
format = format_registry.get(formatname)
except KeyError:
raise errors.BzrCommandError(
gettext("No such send format '%s'.") % formatname)
stored_public_branch = branch.get_public_branch()
if public_branch is None:
public_branch = stored_public_branch
# Remembers if asked explicitly or no previous location is set
elif (remember
or (remember is None and stored_public_branch is None)):
branch.set_public_branch(public_branch)
if no_bundle and public_branch is None:
raise errors.BzrCommandError(gettext('No public branch specified or'
' known'))
base_revision_id = None
revision_id = None
if revision is not None:
if len(revision) > 2:
raise errors.BzrCommandError(gettext('bzr send takes '
'at most two one revision identifiers'))
revision_id = revision[-1].as_revision_id(branch)
if len(revision) == 2:
base_revision_id = revision[0].as_revision_id(branch)
if revision_id is None:
if tree is not None:
tree.check_changed_or_out_of_date(
strict, 'send_strict',
more_error='Use --no-strict to force the send.',
more_warning='Uncommitted changes will not be sent.')
revision_id = branch.last_revision()
if revision_id == NULL_REVISION:
raise errors.BzrCommandError(gettext('No revisions to submit.'))
if format is None:
format = format_registry.get()
directive = format(branch, revision_id, target_branch,
public_branch, no_patch, no_bundle, message, base_revision_id,
submit_branch)
if output is None:
directive.compose_merge_request(mail_client, mail_to, body,
branch, tree)
else:
if directive.multiple_output_files:
if output == '-':
raise errors.BzrCommandError(gettext('- not supported for '
'merge directives that use more than one output file.'))
if not os.path.exists(output):
os.mkdir(output, 0755)
for (filename, lines) in directive.to_files():
path = os.path.join(output, filename)
outfile = open(path, 'wb')
try:
outfile.writelines(lines)
finally:
outfile.close()
else:
if output == '-':
outfile = to_file
else:
outfile = open(output, 'wb')
try:
outfile.writelines(directive.to_lines())
finally:
if outfile is not to_file:
outfile.close()
finally:
branch.unlock()
def _send_4(branch, revision_id, target_branch, public_branch,
no_patch, no_bundle, message,
base_revision_id, local_target_branch=None):
from bzrlib import merge_directive
return merge_directive.MergeDirective2.from_objects(
branch.repository, revision_id, time.time(),
osutils.local_time_offset(), target_branch,
public_branch=public_branch,
include_patch=not no_patch,
include_bundle=not no_bundle, message=message,
base_revision_id=base_revision_id,
local_target_branch=local_target_branch)
def _send_0_9(branch, revision_id, submit_branch, public_branch,
no_patch, no_bundle, message,
base_revision_id, local_target_branch=None):
if not no_bundle:
if not no_patch:
patch_type = 'bundle'
else:
raise errors.BzrCommandError(gettext('Format 0.9 does not'
' permit bundle with no patch'))
else:
if not no_patch:
patch_type = 'diff'
else:
patch_type = None
from bzrlib import merge_directive
return merge_directive.MergeDirective.from_objects(
branch.repository, revision_id, time.time(),
osutils.local_time_offset(), submit_branch,
public_branch=public_branch, patch_type=patch_type,
message=message, local_target_branch=local_target_branch)
format_registry.register('4',
_send_4, 'Bundle format 4, Merge Directive 2 (default)')
format_registry.register('0.9',
_send_0_9, 'Bundle format 0.9, Merge Directive 1')
format_registry.default_key = '4'<|fim▁end|> | and body is not None):
raise errors.BzrCommandError(gettext(
'Mail client "%s" does not support specifying body') %
mail_client.__class__.__name__) |
<|file_name|>joystick.cpp<|end_file_name|><|fim▁begin|>/*
* E-UAE - The portable Amiga Emulator
*
* BeOS joystick driver
*
* (c) Richard Drummond 2005
*/
extern "C" {
#include "sysconfig.h"
#include "sysdeps.h"
#include "options.h"
#include "memory_uae.h"
#include "custom.h"
#include "inputdevice.h"
}
#include <device/Joystick.h>
#include <support/String.h>
//#define DEBUG
#ifdef DEBUG
#define DEBUG_LOG write_log
#else
#define DEBUG_LOG(...) { }
#endif
extern "C" {
static int init_joysticks (void);
static void close_joysticks (void);
static int acquire_joy (unsigned int nr, int flags);
static void unacquire_joy (unsigned int nr);
static void read_joysticks (void);
static unsigned int get_joystick_count (void);
static const char *get_joystick_name (unsigned int nr);
static unsigned int get_joystick_widget_num (unsigned int nr);
static int get_joystick_widget_type (unsigned int nr, unsigned int num, char *name);
static int get_joystick_widget_first (unsigned int nr, int type);
};
<|fim▁hole|> * We choose to believe both and thus that there's at most one joystick attached
* to each port. Since USB ain't supported, I don't have any hardware which
* disproves that belief...
*/
class UAEJoystick :public BJoystick
{
public:
UAEJoystick (unsigned int nr, const char *port_name);
private:
unsigned int nr; /* Device number that UAE assigns to a joystick */
BString port_name; /* Name used to open the joystick port */
BString name; /* Full name used to describe this joystick to the user */
public:
const char *getName () { return name.String(); }
int acquire ();
void unacquire ();
void read ();
};
UAEJoystick :: UAEJoystick (unsigned int nr, const char *port_name)
{
/* Create joystick name using both port and joystick name */
BString stick_name;
this->Open(port_name);
this->GetControllerName (&stick_name);
this->Close ();
this->name = port_name;
this->name += ":";
this->name += stick_name;
this->port_name = port_name;
this->nr = nr;
}
int UAEJoystick :: acquire ()
{
return this->Open (this->port_name.String());
}
void UAEJoystick :: unacquire ()
{
this->Close ();
}
void UAEJoystick :: read ()
{
DEBUG_LOG ("read: polling joy:%d\n", this->nr);
if (this->Update () != B_ERROR) {
/* Read axis values */
{
unsigned int nr_axes = this->CountAxes ();
int16 values[nr_axes];
unsigned int axis;
this->GetAxisValues (values);
for (axis = 0; axis < nr_axes; axis++)
setjoystickstate (this->nr, axis, values[axis], 32767);
}
/* Read button values */
{
unsigned int nr_buttons = this->CountButtons ();
int32 values;
unsigned int button;
values = this->ButtonValues ();
for (button = 0; button < nr_buttons; button++) {
setjoybuttonstate (this->nr, button, values & 1);
values >>= 1;
}
}
}
}
/*
* Inputdevice API
*/
#define MAX_JOYSTICKS MAX_INPUT_DEVICES
static unsigned int nr_joysticks;
static UAEJoystick *joysticks [MAX_JOYSTICKS];
static int init_joysticks (void)
{
BJoystick joy;
unsigned int nr_ports;
unsigned int i;
nr_joysticks = 0;
nr_ports = joy.CountDevices ();
if (nr_ports > MAX_JOYSTICKS)
nr_ports = MAX_JOYSTICKS;
/*
* Enumerate joysticks
*/
for (i = 0; i < nr_ports; i++) {
char port_name[B_OS_NAME_LENGTH];
joy.GetDeviceName (i, port_name);
if (joy.Open (port_name)) {
BString stick_name;
joy.Close ();
joysticks[nr_joysticks] = new UAEJoystick (nr_joysticks, port_name);
write_log ("BJoystick: device %d = %s\n", nr_joysticks,
joysticks[nr_joysticks]->getName ());
nr_joysticks++;
} else
DEBUG_LOG ("Failed to open port='%s'\n", port_name);
}
write_log ("BJoystick: Found %d joystick(s)\n", nr_joysticks);
return 1;
}
static void close_joysticks (void)
{
unsigned int i;
for (i = 0; i < nr_joysticks; i++)
delete joysticks[i];
nr_joysticks = 0;
}
static int acquire_joy (unsigned int nr, int flags)
{
int result = 0;
DEBUG_LOG ("acquire_joy (%d)...\n", nr);
if (nr < nr_joysticks)
result = joysticks[nr]->acquire ();
DEBUG_LOG ("%s\n", result ? "okay" : "failed");
return result;
}
static void unacquire_joy (unsigned int nr)
{
DEBUG_LOG ("unacquire_joy (%d)\n", nr);
if (nr < nr_joysticks)
joysticks[nr]->unacquire ();
}
static void read_joysticks (void)
{
unsigned int i;
for (i = 0; i < get_joystick_count (); i++) {
/* In compatibility mode, don't read joystick unless it's selected in the prefs */
if (currprefs.input_selected_setting == 0) {
if (jsem_isjoy (0, &currprefs) != (int)i && jsem_isjoy (1, &currprefs) != (int)i)
continue;
}
joysticks[i]->read ();
}
}
static unsigned int get_joystick_num (void)
{
return nr_joysticks;
}
static const char *get_joystick_friendlyname (unsigned int nr)
{
return joysticks[nr]->getName ();
}
static const char *get_joystick_uniquename (unsigned int nr)
{
return joysticks[nr]->getName ();
}
static unsigned int get_joystick_widget_num (unsigned int nr)
{
return joysticks[nr]->CountAxes () + joysticks[nr]->CountButtons ();
}
static int get_joystick_widget_type (unsigned int nr, unsigned int widget_num, char *name, uae_u32 *what)
{
unsigned int nr_axes = joysticks[nr]->CountAxes ();
unsigned int nr_buttons = joysticks[nr]->CountButtons ();
if (widget_num >= nr_axes && widget_num < nr_axes + nr_buttons) {
if (name)
sprintf (name, "Button %d", widget_num + 1 - nr_axes);
return IDEV_WIDGET_BUTTON;
} else if (widget_num < nr_axes) {
if (name)
sprintf (name, "Axis %d", widget_num + 1);
return IDEV_WIDGET_AXIS;
}
return IDEV_WIDGET_NONE;
}
static int get_joystick_widget_first (unsigned int nr, int type)
{
switch (type) {
case IDEV_WIDGET_BUTTON:
return joysticks[nr]->CountAxes ();
case IDEV_WIDGET_AXIS:
return 0;
}
return -1;
}
static int get_joystick_flags (int num)
{
return 0;
}
struct inputdevice_functions inputdevicefunc_joystick = {
init_joysticks,
close_joysticks,
acquire_joy,
unacquire_joy,
read_joysticks,
get_joystick_num,
get_joystick_friendlyname,
get_joystick_uniquename,
get_joystick_widget_num,
get_joystick_widget_type,
get_joystick_widget_first,
get_joystick_flags
};
/*
* Set default inputdevice config for joysticks
*/
int input_get_default_joystick (struct uae_input_device *uid, int num, int port, int cd32)
{
unsigned int i, port;
for (i = 0; i < nr_joysticks; i++) {
port = i & 1;
uid[i].eventid[ID_AXIS_OFFSET + 0][0] = port ? INPUTEVENT_JOY2_HORIZ : INPUTEVENT_JOY1_HORIZ;
uid[i].eventid[ID_AXIS_OFFSET + 1][0] = port ? INPUTEVENT_JOY2_VERT : INPUTEVENT_JOY1_VERT;
uid[i].eventid[ID_BUTTON_OFFSET + 0][0] = port ? INPUTEVENT_JOY2_FIRE_BUTTON : INPUTEVENT_JOY1_FIRE_BUTTON;
uid[i].eventid[ID_BUTTON_OFFSET + 1][0] = port ? INPUTEVENT_JOY2_2ND_BUTTON : INPUTEVENT_JOY1_2ND_BUTTON;
uid[i].eventid[ID_BUTTON_OFFSET + 2][0] = port ? INPUTEVENT_JOY2_3RD_BUTTON : INPUTEVENT_JOY1_3RD_BUTTON;
}
uid[0].enabled = 1;
if (i == 0)
return 1;
return 0;
}<|fim▁end|> | /*
* The BJoystick class can't make up its mind whether it represents a joystick
* port or the device attached to a port.
* |
<|file_name|>ConfigExtension.java<|end_file_name|><|fim▁begin|>/* gvSIG. Sistema de Información Geográfica de la Generalitat Valenciana
*
* Copyright (C) 2004 IVER T.I. and Generalitat Valenciana.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,USA.
*
* For more information, contact:
*
* Generalitat Valenciana
* Conselleria d'Infraestructures i Transport
* Av. Blasco Ibáñez, 50
* 46010 VALENCIA
* SPAIN
*
* +34 963862235
* [email protected]
* www.gvsig.gva.es
*
* or
*
* IVER T.I. S.A
* Salamanca 50
* 46005 Valencia
* Spain
*
* +34 963163400
* [email protected]
*/
package com.iver.core;
/**
*/
import com.iver.andami.PluginServices;
import com.iver.andami.plugins.Extension;
import com.iver.core.configExtensions.ConfigPlugins;
/**
* Extensión para abrir el diálogo de configuración de ANDAMI.
*
* @author Vicente Caballero Navarro
* @deprecated
*
*/
public class ConfigExtension extends Extension {
/* (non-Javadoc)
* @see com.iver.andami.plugins.Extension#execute(java.lang.String)
*/
public void execute(String actionCommand) {
ConfigPlugins cp=new ConfigPlugins();
PluginServices.getMDIManager().addWindow(cp);
}
<|fim▁hole|> /**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isVisible() {
return true;
}
/**
* @see com.iver.mdiApp.plugins.IExtension#isEnabled()
*/
public boolean isEnabled() {
return true;
}
/**
* @see com.iver.andami.plugins.IExtension#initialize()
*/
public void initialize() {
}
}<|fim▁end|> | |
<|file_name|>range.py<|end_file_name|><|fim▁begin|># Copyright 2013, Michael H. Goldwasser
#
# Developed for use with the book:
#
# Data Structures and Algorithms in Python
# Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser
# John Wiley & Sons, 2013
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,<|fim▁hole|># GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class Range:
"""A class that mimic's the built-in range class."""
def __init__(self, start, stop=None, step=1):
"""Initialize a Range instance.
Semantics is similar to built-in range class.
"""
if step == 0:
raise ValueError('step cannot be 0')
if stop is None: # special case of range(n)
start, stop = 0, start # should be treated as if range(0,n)
# calculate the effective length once
self._length = max(0, (stop - start + step - 1) // step)
# need knowledge of start and step (but not stop) to support __getitem__
self._start = start
self._step = step
def __len__(self):
"""Return number of entries in the range."""
return self._length
def __getitem__(self, k):
"""Return entry at index k (using standard interpretation if negative)."""
if k < 0:
k += len(self) # attempt to convert negative index
if not 0 <= k < self._length:
raise IndexError('index out of range')
return self._start + k * self._step<|fim▁end|> | # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
<|file_name|>Ti_Data.cpp<|end_file_name|><|fim▁begin|>/*<|fim▁hole|> *
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
#include "Ti_Data.h"
Ti::TiData::TiData(const char* name) :
Ti::TiProxy(name)
{
}
Ti::TiData::~TiData()
{
}<|fim▁end|> | * Ti_Data.cpp |
<|file_name|>test_flask_ext.py<|end_file_name|><|fim▁begin|>"""
"""
import logging
import time
import hiro
import mock
from flask import Flask, request
from werkzeug.exceptions import BadRequest
from flask_limiter.extension import C, Limiter
from flask_limiter.util import get_remote_address
def test_reset(extension_factory):
app, limiter = extension_factory({C.DEFAULT_LIMITS: "1 per day"})
@app.route("/")
def null():
return "Hello Reset"
with app.test_client() as cli:
cli.get("/")
assert "1 per 1 day" in cli.get("/").data.decode()
limiter.reset()
assert "Hello Reset" == cli.get("/").data.decode()
assert "1 per 1 day" in cli.get("/").data.decode()
def test_reset_unsupported(extension_factory, memcached_connection):
app, limiter = extension_factory(
{C.DEFAULT_LIMITS: "1 per day", C.STORAGE_URI: "memcached://localhost:31211"}
)
@app.route("/")
def null():
return "Hello Reset"
with app.test_client() as cli:
cli.get("/")
assert "1 per 1 day" in cli.get("/").data.decode()
# no op with memcached but no error raised
limiter.reset()
assert "1 per 1 day" in cli.get("/").data.decode()
def test_combined_rate_limits(extension_factory):
app, limiter = extension_factory({C.DEFAULT_LIMITS: "1 per hour; 10 per day"})
@app.route("/t1")
@limiter.limit("100 per hour;10/minute")
def t1():
return "t1"
@app.route("/t2")
def t2():
return "t2"
with hiro.Timeline().freeze():
with app.test_client() as cli:
assert 200 == cli.get("/t1").status_code
assert 200 == cli.get("/t2").status_code
assert 429 == cli.get("/t2").status_code
def test_defaults_per_method(extension_factory):
app, limiter = extension_factory(
{C.DEFAULT_LIMITS: "1 per hour", C.DEFAULT_LIMITS_PER_METHOD: True}
)
@app.route("/t1", methods=["GET", "POST"])
def t1():
return "t1"
with hiro.Timeline().freeze():
with app.test_client() as cli:
assert 200 == cli.get("/t1").status_code
assert 429 == cli.get("/t1").status_code
assert 200 == cli.post("/t1").status_code
assert 429 == cli.post("/t1").status_code
def test_default_limit_with_exemption(extension_factory):
def is_backdoor():
return request.headers.get("backdoor") == "true"
app, limiter = extension_factory(
{C.DEFAULT_LIMITS: "1 per hour", C.DEFAULT_LIMITS_EXEMPT_WHEN: is_backdoor}
)
@app.route("/t1")
def t1():
return "test"
with hiro.Timeline() as timeline:
with app.test_client() as cli:
assert cli.get("/t1", headers={"backdoor": "true"}).status_code == 200
assert cli.get("/t1", headers={"backdoor": "true"}).status_code == 200
assert cli.get("/t1").status_code == 200
assert cli.get("/t1").status_code == 429
timeline.forward(3600)
assert cli.get("/t1").status_code == 200
def test_default_limit_with_conditional_deduction(extension_factory):
def failed_request(response):
return response.status_code != 200
app, limiter = extension_factory(
{C.DEFAULT_LIMITS: "1 per hour", C.DEFAULT_LIMITS_DEDUCT_WHEN: failed_request}
)
@app.route("/t1/<path:path>")
def t1(path):
if path != "1":
raise BadRequest()
return path
with hiro.Timeline() as timeline:
with app.test_client() as cli:
assert cli.get("/t1/1").status_code == 200
assert cli.get("/t1/1").status_code == 200
assert cli.get("/t1/2").status_code == 400
assert cli.get("/t1/1").status_code == 429
assert cli.get("/t1/2").status_code == 429
timeline.forward(3600)
assert cli.get("/t1/1").status_code == 200
assert cli.get("/t1/2").status_code == 400
def test_key_func(extension_factory):
app, limiter = extension_factory()
@app.route("/t1")
@limiter.limit("100 per minute", lambda: "test")
def t1():
return "test"
with hiro.Timeline().freeze():
with app.test_client() as cli:
for i in range(0, 100):
assert (
200
== cli.get(
"/t1", headers={"X_FORWARDED_FOR": "127.0.0.2"}
).status_code
)
assert 429 == cli.get("/t1").status_code
def test_logging(caplog):
app = Flask(__name__)
limiter = Limiter(app, key_func=get_remote_address)
@app.route("/t1")
@limiter.limit("1/minute")
def t1():
return "test"
with app.test_client() as cli:
assert 200 == cli.get("/t1").status_code
assert 429 == cli.get("/t1").status_code
assert len(caplog.records) == 1
assert caplog.records[0].levelname == "WARNING"
def test_reuse_logging():
app = Flask(__name__)
app_handler = mock.Mock()
app_handler.level = logging.INFO
app.logger.addHandler(app_handler)
limiter = Limiter(app, key_func=get_remote_address)
for handler in app.logger.handlers:
limiter.logger.addHandler(handler)
@app.route("/t1")
@limiter.limit("1/minute")
def t1():
return "42"
with app.test_client() as cli:
cli.get("/t1")
cli.get("/t1")
assert app_handler.handle.call_count == 1
def test_disabled_flag(extension_factory):
app, limiter = extension_factory(
config={C.ENABLED: False}, default_limits=["1/minute"]
)
@app.route("/t1")
def t1():
return "test"
@app.route("/t2")
@limiter.limit("10 per minute")
def t2():
return "test"
with app.test_client() as cli:
assert cli.get("/t1").status_code == 200
assert cli.get("/t1").status_code == 200
for i in range(0, 10):
assert cli.get("/t2").status_code == 200
assert cli.get("/t2").status_code == 200
def test_multiple_apps():
app1 = Flask(__name__)
app2 = Flask(__name__)
limiter = Limiter(default_limits=["1/second"], key_func=get_remote_address)
limiter.init_app(app1)
limiter.init_app(app2)
@app1.route("/ping")
def ping():
return "PONG"
@app1.route("/slowping")
@limiter.limit("1/minute")
def slow_ping():
return "PONG"
@app2.route("/ping")
@limiter.limit("2/second")
def ping_2():
return "PONG"
@app2.route("/slowping")
@limiter.limit("2/minute")
def slow_ping_2():
return "PONG"
with hiro.Timeline().freeze() as timeline:
with app1.test_client() as cli:
assert cli.get("/ping").status_code == 200
assert cli.get("/ping").status_code == 429
timeline.forward(1)
assert cli.get("/ping").status_code == 200
assert cli.get("/slowping").status_code == 200
timeline.forward(59)
assert cli.get("/slowping").status_code == 429
timeline.forward(1)
assert cli.get("/slowping").status_code == 200
with app2.test_client() as cli:
assert cli.get("/ping").status_code == 200
assert cli.get("/ping").status_code == 200
assert cli.get("/ping").status_code == 429
timeline.forward(1)
assert cli.get("/ping").status_code == 200
assert cli.get("/slowping").status_code == 200
timeline.forward(59)
assert cli.get("/slowping").status_code == 200
assert cli.get("/slowping").status_code == 429
timeline.forward(1)
assert cli.get("/slowping").status_code == 200
def test_headers_no_breach():
app = Flask(__name__)
limiter = Limiter(
app,
default_limits=["10/minute"],
headers_enabled=True,
key_func=get_remote_address,
)
@app.route("/t1")
def t1():
return "test"
@app.route("/t2")
@limiter.limit("2/second; 5 per minute; 10/hour")
def t2():
return "test"
with hiro.Timeline().freeze():
with app.test_client() as cli:
resp = cli.get("/t1")
assert resp.headers.get("X-RateLimit-Limit") == "10"
assert resp.headers.get("X-RateLimit-Remaining") == "9"
assert resp.headers.get("X-RateLimit-Reset") == str(int(time.time() + 61))
assert resp.headers.get("Retry-After") == str(60)
resp = cli.get("/t2")
assert resp.headers.get("X-RateLimit-Limit") == "2"
assert resp.headers.get("X-RateLimit-Remaining") == "1"
assert resp.headers.get("X-RateLimit-Reset") == str(int(time.time() + 2))
assert resp.headers.get("Retry-After") == str(1)
assert limiter.current_limit.remaining == 1
assert limiter.current_limit.reset_at == int(time.time() + 2)
assert not limiter.current_limit.breached
def test_headers_breach():
app = Flask(__name__)
limiter = Limiter(
app,
default_limits=["10/minute"],
headers_enabled=True,
key_func=get_remote_address,
)
@app.route("/t1")
@limiter.limit("2/second; 10 per minute; 20/hour")
def t():
return "test"
with hiro.Timeline().freeze() as timeline:
with app.test_client() as cli:
for i in range(10):
resp = cli.get("/t1")
timeline.forward(1)
assert len(limiter.current_limits) == 3
assert all(not limit.breached for limit in limiter.current_limits)
resp = cli.get("/t1")
timeline.forward(1)
assert resp.headers.get("X-RateLimit-Limit") == "10"
assert resp.headers.get("X-RateLimit-Remaining") == "0"
assert resp.headers.get("X-RateLimit-Reset") == str(int(time.time() + 50))
assert resp.headers.get("Retry-After") == str(int(50))
assert limiter.current_limit.remaining == 0
assert limiter.current_limit.reset_at == int(time.time() + 50)
assert limiter.current_limit.breached
def test_retry_after():
app = Flask(__name__)
_ = Limiter(
app,
default_limits=["1/minute"],
headers_enabled=True,
key_func=get_remote_address,
)
@app.route("/t1")
def t():
return "test"
with hiro.Timeline().freeze() as timeline:
with app.test_client() as cli:
resp = cli.get("/t1")
retry_after = int(resp.headers.get("Retry-After"))
assert retry_after > 0
timeline.forward(retry_after)
resp = cli.get("/t1")
assert resp.status_code == 200
def test_retry_after_exists_seconds():
app = Flask(__name__)
_ = Limiter(
app,
default_limits=["1/minute"],
headers_enabled=True,
key_func=get_remote_address,
)
@app.route("/t1")
def t():
return "", 200, {"Retry-After": "1000000"}
with app.test_client() as cli:
resp = cli.get("/t1")
retry_after = int(resp.headers.get("Retry-After"))
assert retry_after > 1000
def test_retry_after_exists_rfc1123():
app = Flask(__name__)
_ = Limiter(
app,
default_limits=["1/minute"],
headers_enabled=True,
key_func=get_remote_address,
)
@app.route("/t1")
def t():
return "", 200, {"Retry-After": "Sun, 06 Nov 2032 01:01:01 GMT"}
with app.test_client() as cli:
resp = cli.get("/t1")
retry_after = int(resp.headers.get("Retry-After"))
assert retry_after > 1000
def test_custom_headers_from_config():
app = Flask(__name__)
app.config.setdefault(C.HEADER_LIMIT, "X-Limit")
app.config.setdefault(C.HEADER_REMAINING, "X-Remaining")
app.config.setdefault(C.HEADER_RESET, "X-Reset")
limiter = Limiter(
app,
default_limits=["10/minute"],
headers_enabled=True,
key_func=get_remote_address,
)
@app.route("/t1")
@limiter.limit("2/second; 10 per minute; 20/hour")
def t():
return "test"
with hiro.Timeline().freeze() as timeline:
with app.test_client() as cli:
for i in range(11):
resp = cli.get("/t1")
timeline.forward(1)
assert resp.headers.get("X-Limit") == "10"
assert resp.headers.get("X-Remaining") == "0"
assert resp.headers.get("X-Reset") == str(int(time.time() + 50))
def test_application_shared_limit(extension_factory):
app, limiter = extension_factory(application_limits=["2/minute"])
@app.route("/t1")
def t1():
return "route1"
@app.route("/t2")
def t2():
return "route2"
with hiro.Timeline().freeze():
with app.test_client() as cli:
assert 200 == cli.get("/t1").status_code
assert 200 == cli.get("/t2").status_code
assert 429 == cli.get("/t1").status_code
def test_callable_default_limit(extension_factory):
app, limiter = extension_factory(default_limits=[lambda: "1/minute"])
@app.route("/t1")
def t1():
return "t1"
@app.route("/t2")
def t2():
return "t2"
with hiro.Timeline().freeze():
with app.test_client() as cli:
assert cli.get("/t1").status_code == 200
assert cli.get("/t2").status_code == 200
assert cli.get("/t1").status_code == 429
assert cli.get("/t2").status_code == 429
def test_callable_application_limit(extension_factory):<|fim▁hole|>
app, limiter = extension_factory(application_limits=[lambda: "1/minute"])
@app.route("/t1")
def t1():
return "t1"
@app.route("/t2")
def t2():
return "t2"
with hiro.Timeline().freeze():
with app.test_client() as cli:
assert cli.get("/t1").status_code == 200
assert cli.get("/t2").status_code == 429
def test_no_auto_check(extension_factory):
app, limiter = extension_factory(auto_check=False)
@app.route("/", methods=["GET", "POST"])
@limiter.limit("1/second", per_method=True)
def root():
return "root"
with hiro.Timeline().freeze():
with app.test_client() as cli:
assert 200 == cli.get("/").status_code
assert 200 == cli.get("/").status_code
# attach before_request to perform check
@app.before_request
def _():
limiter.check()
with hiro.Timeline().freeze():
with app.test_client() as cli:
assert 200 == cli.get("/").status_code
assert 429 == cli.get("/").status_code
def test_fail_on_first_breach(extension_factory):
app, limiter = extension_factory(fail_on_first_breach=True)
@app.route("/", methods=["GET", "POST"])
@limiter.limit("1/second", per_method=True)
@limiter.limit("2/minute", per_method=True)
def root():
return "root"
with hiro.Timeline().freeze() as timeline:
with app.test_client() as cli:
assert 200 == cli.get("/").status_code
assert 429 == cli.get("/").status_code
assert [True] == [k.breached for k in limiter.current_limits]
timeline.forward(1)
assert 200 == cli.get("/").status_code
assert [False, False] == [k.breached for k in limiter.current_limits]
timeline.forward(1)
assert 429 == cli.get("/").status_code
assert [False, True] == [k.breached for k in limiter.current_limits]
def test_no_fail_on_first_breach(extension_factory):
app, limiter = extension_factory(fail_on_first_breach=False)
@app.route("/", methods=["GET", "POST"])
@limiter.limit("1/second", per_method=True)
@limiter.limit("2/minute", per_method=True)
def root():
return "root"
with hiro.Timeline().freeze() as timeline:
with app.test_client() as cli:
assert 200 == cli.get("/").status_code
assert 429 == cli.get("/").status_code
assert [True, False] == [k.breached for k in limiter.current_limits]
timeline.forward(1)
assert 429 == cli.get("/").status_code
assert [False, True] == [k.breached for k in limiter.current_limits]
def test_custom_key_prefix(redis_connection, extension_factory):
app1, limiter1 = extension_factory(
key_prefix="moo", storage_uri="redis://localhost:46379"
)
app2, limiter2 = extension_factory(
{C.KEY_PREFIX: "cow"}, storage_uri="redis://localhost:46379"
)
app3, limiter3 = extension_factory(storage_uri="redis://localhost:46379")
@app1.route("/test")
@limiter1.limit("1/day")
def app1_test():
return "app1 test"
@app2.route("/test")
@limiter2.limit("1/day")
def app2_test():
return "app1 test"
@app3.route("/test")
@limiter3.limit("1/day")
def app3_test():
return "app1 test"
with app1.test_client() as cli:
resp = cli.get("/test")
assert 200 == resp.status_code
resp = cli.get("/test")
assert 429 == resp.status_code
with app2.test_client() as cli:
resp = cli.get("/test")
assert 200 == resp.status_code
resp = cli.get("/test")
assert 429 == resp.status_code
with app3.test_client() as cli:
resp = cli.get("/test")
assert 200 == resp.status_code
resp = cli.get("/test")
assert 429 == resp.status_code
def test_second_instance_bypassed_by_shared_g():
app = Flask(__name__)
limiter1 = Limiter(app, key_func=get_remote_address)
limiter2 = Limiter(app, key_func=get_remote_address)
@app.route("/test1")
@limiter2.limit("1/second")
def app_test1():
return "app test1"
@app.route("/test2")
@limiter1.limit("10/minute")
@limiter2.limit("1/second")
def app_test2():
return "app test2"
with hiro.Timeline().freeze() as timeline:
with app.test_client() as cli:
assert cli.get("/test1").status_code == 200
assert cli.get("/test2").status_code == 200
assert cli.get("/test1").status_code == 429
assert cli.get("/test2").status_code == 200
for i in range(8):
assert cli.get("/test1").status_code == 429
assert cli.get("/test2").status_code == 200
assert cli.get("/test2").status_code == 429
timeline.forward(1)
assert cli.get("/test1").status_code == 200
assert cli.get("/test2").status_code == 429
timeline.forward(59)
assert cli.get("/test1").status_code == 200
assert cli.get("/test2").status_code == 200
def test_independent_instances_by_key_prefix():
app = Flask(__name__)
limiter1 = Limiter(app, key_prefix="lmt1", key_func=get_remote_address)
limiter2 = Limiter(app, key_prefix="lmt2", key_func=get_remote_address)
@app.route("/test1")
@limiter2.limit("1/second")
def app_test1():
return "app test1"
@app.route("/test2")
@limiter1.limit("10/minute")
@limiter2.limit("1/second")
def app_test2():
return "app test2"
with hiro.Timeline().freeze() as timeline:
with app.test_client() as cli:
assert cli.get("/test1").status_code == 200
assert cli.get("/test2").status_code == 200
resp = cli.get("/test1")
assert resp.status_code == 429
assert "1 per 1 second" in resp.data.decode()
resp = cli.get("/test2")
assert resp.status_code == 429
assert "1 per 1 second" in resp.data.decode()
for i in range(8):
assert cli.get("/test1").status_code == 429
assert cli.get("/test2").status_code == 429
assert cli.get("/test2").status_code == 429
timeline.forward(1)
assert cli.get("/test1").status_code == 200
assert cli.get("/test2").status_code == 429
timeline.forward(59)
assert cli.get("/test1").status_code == 200
assert cli.get("/test2").status_code == 200<|fim▁end|> | |
<|file_name|>book.model.ts<|end_file_name|><|fim▁begin|>export class Book {
id: number;
name: string;
isbn: string;
description: string;
category: string;
writer: string;
price: number;
picture_path: string;
status: string;
created: string;<|fim▁hole|><|fim▁end|> | modified: any;
constructor() {
}
} |
<|file_name|>htmlmodelement.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLModElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLModElementDerived;
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use servo_util::str::DOMString;
#[dom_struct]
pub struct HTMLModElement {
htmlelement: HTMLElement
}
impl HTMLModElementDerived for EventTarget {
fn is_htmlmodelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLModElement)))
}
}
impl HTMLModElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLModElement {<|fim▁hole|>
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLModElement> {
let element = HTMLModElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLModElementBinding::Wrap)
}
}<|fim▁end|> | HTMLModElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLModElement, localName, prefix, document)
}
} |
<|file_name|>GroovyScript.java<|end_file_name|><|fim▁begin|>package org.devocative.demeter.service.template;<|fim▁hole|>import groovy.lang.Script;
import org.devocative.demeter.iservice.template.BaseStringTemplate;
import java.util.Map;
public class GroovyScript extends BaseStringTemplate<Script> {
private Script script;
public GroovyScript(Script script) {
this.script = script;
}
@Override
public Object process(Map<String, Object> params) {
Binding binding = new Binding();
for (Map.Entry<String, Object> entry : params.entrySet()) {
binding.setVariable(entry.getKey(), entry.getValue());
}
script.setBinding(binding);
return script.run();
}
@Override
public Script unwrap() {
return script;
}
}<|fim▁end|> |
import groovy.lang.Binding; |
<|file_name|>commwidgets.py<|end_file_name|><|fim▁begin|>#
# Moisture control - Serial communication widgets
#
# Copyright (c) 2013 Michael Buesch <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
from pymoistcontrol.util import *
import os
class SerialOpenDialog(QDialog):
"""Serial port connection dialog."""
def __init__(self, parent):
"""Class constructor."""
QDialog.__init__(self, parent)
self.setLayout(QGridLayout(self))
self.setWindowTitle("Select serial port")
self.portCombo = QComboBox(self)
if os.name.lower() == "posix":
# Unix operating system
# Add all serial devices from /dev to
# the combo box.
devNodes = QDir("/dev").entryInfoList(QDir.System,
QDir.Name)
select = None<|fim▁hole|> continue
path = node.filePath()
self.portCombo.addItem(path, path)
if select is None and\
name.startswith("ttyUSB"):
# Select the first ttyUSB by default.
select = self.portCombo.count() - 1
if select is not None:
self.portCombo.setCurrentIndex(select)
elif os.name.lower() in ("nt", "ce"):
# Windows operating system
# Add 8 COM ports to the combo box.
for i in range(8):
port = "COM%d" % (i + 1)
self.portCombo.addItem(port, port)
else:
raise Error("Operating system not supported")
self.layout().addWidget(self.portCombo, 0, 0, 1, 2)
self.okButton = QPushButton("&Ok", self)
self.layout().addWidget(self.okButton, 1, 0)
self.cancelButton = QPushButton("&Cancel", self)
self.layout().addWidget(self.cancelButton, 1, 1)
self.okButton.released.connect(self.accept)
self.cancelButton.released.connect(self.reject)
def getSelectedPort(self):
"""Get the selected port name."""
index = self.portCombo.currentIndex()
if index < 0:
return None
return self.portCombo.itemData(index)<|fim▁end|> | for node in devNodes:
name = node.fileName()
if not name.startswith("ttyS") and\
not name.startswith("ttyUSB"): |
<|file_name|>borderLayout.ts<|end_file_name|><|fim▁begin|>import {Utils as _} from '../utils';
export class BorderLayout {
private eNorthWrapper: any;
private eSouthWrapper: any;
private eEastWrapper: any;
private eWestWrapper: any;
private eCenterWrapper: any;
private eOverlayWrapper: any;
private eCenterRow: any;
private eNorthChildLayout: any;
private eSouthChildLayout: any;
private eEastChildLayout: any;
private eWestChildLayout: any;
private eCenterChildLayout: any;
private isLayoutPanel: any;
private fullHeight: any;
private layoutActive: any;
private eGui: any;
private id: any;
private childPanels: any;
private centerHeightLastTime: any;
private centerWidthLastTime: any;
private centerLeftMarginLastTime: any;
private sizeChangeListeners = <any>[];
private overlays: any;
constructor(params: any) {
this.isLayoutPanel = true;
this.fullHeight = !params.north && !params.south;
var template: any;
if (!params.dontFill) {
if (this.fullHeight) {
template =
'<div style="height: 100%; overflow: auto; position: relative;">' +
'<div id="west" style="height: 100%; float: left;"></div>' +
'<div id="east" style="height: 100%; float: right;"></div>' +
'<div id="center" style="height: 100%;"></div>' +
'<div id="overlay" style="pointer-events: none; position: absolute; height: 100%; width: 100%; top: 0px; left: 0px;"></div>' +
'</div>';
} else {
template =
'<div style="height: 100%; position: relative;">' +
'<div id="north"></div>' +
'<div id="centerRow" style="height: 100%; overflow: hidden;">' +
'<div id="west" style="height: 100%; float: left;"></div>' +
'<div id="east" style="height: 100%; float: right;"></div>' +
'<div id="center" style="height: 100%;"></div>' +
'</div>' +
'<div id="south"></div>' +
'<div id="overlay" style="pointer-events: none; position: absolute; height: 100%; width: 100%; top: 0px; left: 0px;"></div>' +
'</div>';
}
this.layoutActive = true;
} else {
template =
'<div style="position: relative;">' +
'<div id="north"></div>' +
'<div id="centerRow">' +
'<div id="west"></div>' +
'<div id="east"></div>' +
'<div id="center"></div>' +
'</div>' +
'<div id="south"></div>' +
'<div id="overlay" style="pointer-events: none; position: absolute; height: 100%; width: 100%; top: 0px; left: 0px;"></div>' +
'</div>';
this.layoutActive = false;
}
this.eGui = _.loadTemplate(template);
this.id = 'borderLayout';
if (params.name) {
this.id += '_' + params.name;
}
this.eGui.setAttribute('id', this.id);
this.childPanels = [];
if (params) {
this.setupPanels(params);
}
this.overlays = params.overlays;
this.setupOverlays();
}
public addSizeChangeListener(listener: Function): void {
this.sizeChangeListeners.push(listener);
}
public fireSizeChanged(): void {
this.sizeChangeListeners.forEach( function(listener: Function) {
listener();
});
}
private setupPanels(params: any) {
this.eNorthWrapper = this.eGui.querySelector('#north');
this.eSouthWrapper = this.eGui.querySelector('#south');
this.eEastWrapper = this.eGui.querySelector('#east');
this.eWestWrapper = this.eGui.querySelector('#west');
this.eCenterWrapper = this.eGui.querySelector('#center');
this.eOverlayWrapper = this.eGui.querySelector('#overlay');
this.eCenterRow = this.eGui.querySelector('#centerRow');
this.eNorthChildLayout = this.setupPanel(params.north, this.eNorthWrapper);
this.eSouthChildLayout = this.setupPanel(params.south, this.eSouthWrapper);
this.eEastChildLayout = this.setupPanel(params.east, this.eEastWrapper);
this.eWestChildLayout = this.setupPanel(params.west, this.eWestWrapper);
this.eCenterChildLayout = this.setupPanel(params.center, this.eCenterWrapper);
}
private setupPanel(content: any, ePanel: any) {
if (!ePanel) {
return;
}
if (content) {<|fim▁hole|> this.childPanels.push(content);
ePanel.appendChild(content.getGui());
return content;
} else {
ePanel.appendChild(content);
return null;
}
} else {
ePanel.parentNode.removeChild(ePanel);
return null;
}
}
public getGui() {
return this.eGui;
}
// returns true if any item changed size, otherwise returns false
public doLayout() {
if (!_.isVisible(this.eGui)) {
return false;
}
var atLeastOneChanged = false;
var childLayouts = [this.eNorthChildLayout, this.eSouthChildLayout, this.eEastChildLayout, this.eWestChildLayout];
var that = this;
_.forEach(childLayouts, function (childLayout: any) {
var childChangedSize = that.layoutChild(childLayout);
if (childChangedSize) {
atLeastOneChanged = true;
}
});
if (this.layoutActive) {
var ourHeightChanged = this.layoutHeight();
var ourWidthChanged = this.layoutWidth();
if (ourHeightChanged || ourWidthChanged) {
atLeastOneChanged = true;
}
}
var centerChanged = this.layoutChild(this.eCenterChildLayout);
if (centerChanged) {
atLeastOneChanged = true;
}
if (atLeastOneChanged) {
this.fireSizeChanged();
}
return atLeastOneChanged;
}
private layoutChild(childPanel: any) {
if (childPanel) {
return childPanel.doLayout();
} else {
return false;
}
}
private layoutHeight() {
if (this.fullHeight) {
return this.layoutHeightFullHeight();
} else {
return this.layoutHeightNormal();
}
}
// full height never changes the height, because the center is always 100%,
// however we do check for change, to inform the listeners
private layoutHeightFullHeight(): boolean {
var centerHeight = _.offsetHeight(this.eGui);
if (centerHeight < 0) {
centerHeight = 0;
}
if (this.centerHeightLastTime !== centerHeight) {
this.centerHeightLastTime = centerHeight;
return true;
} else {
return false;
}
}
private layoutHeightNormal(): boolean {
var totalHeight = _.offsetHeight(this.eGui);
var northHeight = _.offsetHeight(this.eNorthWrapper);
var southHeight = _.offsetHeight(this.eSouthWrapper);
var centerHeight = totalHeight - northHeight - southHeight;
if (centerHeight < 0) {
centerHeight = 0;
}
if (this.centerHeightLastTime !== centerHeight) {
this.eCenterRow.style.height = centerHeight + 'px';
this.centerHeightLastTime = centerHeight;
return true; // return true because there was a change
} else {
return false;
}
}
public getCentreHeight(): number {
return this.centerHeightLastTime;
}
private layoutWidth(): boolean {
var totalWidth = _.offsetWidth(this.eGui);
var eastWidth = _.offsetWidth(this.eEastWrapper);
var westWidth = _.offsetWidth(this.eWestWrapper);
var centerWidth = totalWidth - eastWidth - westWidth;
if (centerWidth < 0) {
centerWidth = 0;
}
var atLeastOneChanged = false;
if (this.centerLeftMarginLastTime !== westWidth) {
this.centerLeftMarginLastTime = westWidth;
this.eCenterWrapper.style.marginLeft = westWidth + 'px';
atLeastOneChanged = true;
}
if (this.centerWidthLastTime !== centerWidth) {
this.centerWidthLastTime = centerWidth;
this.eCenterWrapper.style.width = centerWidth + 'px';
atLeastOneChanged = true;
}
return atLeastOneChanged;
}
public setEastVisible(visible: any) {
if (this.eEastWrapper) {
this.eEastWrapper.style.display = visible ? '' : 'none';
}
this.doLayout();
}
private setupOverlays(): void {
// if no overlays, just remove the panel
if (!this.overlays) {
this.eOverlayWrapper.parentNode.removeChild(this.eOverlayWrapper);
return;
}
this.hideOverlay();
//
//this.setOverlayVisible(false);
}
public hideOverlay() {
_.removeAllChildren(this.eOverlayWrapper);
this.eOverlayWrapper.style.display = 'none';
}
public showOverlay(key: string) {
var overlay = this.overlays ? this.overlays[key] : null;
if (overlay) {
_.removeAllChildren(this.eOverlayWrapper);
this.eOverlayWrapper.style.display = '';
this.eOverlayWrapper.appendChild(overlay);
} else {
console.log('ag-Grid: unknown overlay');
this.hideOverlay();
}
}
}<|fim▁end|> | if (content.isLayoutPanel) { |
<|file_name|>Lepton.py<|end_file_name|><|fim▁begin|>import numpy as np
import ctypes
import struct
import time
# relative imports in Python3 must be explicit
from .ioctl_numbers import _IOR, _IOW
from fcntl import ioctl
SPI_IOC_MAGIC = ord("k")
SPI_IOC_RD_MODE = _IOR(SPI_IOC_MAGIC, 1, "=B")
SPI_IOC_WR_MODE = _IOW(SPI_IOC_MAGIC, 1, "=B")
SPI_IOC_RD_LSB_FIRST = _IOR(SPI_IOC_MAGIC, 2, "=B")
SPI_IOC_WR_LSB_FIRST = _IOW(SPI_IOC_MAGIC, 2, "=B")
SPI_IOC_RD_BITS_PER_WORD = _IOR(SPI_IOC_MAGIC, 3, "=B")
SPI_IOC_WR_BITS_PER_WORD = _IOW(SPI_IOC_MAGIC, 3, "=B")
SPI_IOC_RD_MAX_SPEED_HZ = _IOR(SPI_IOC_MAGIC, 4, "=I")
SPI_IOC_WR_MAX_SPEED_HZ = _IOW(SPI_IOC_MAGIC, 4, "=I")
SPI_CPHA = 0x01 # /* clock phase */
SPI_CPOL = 0x02 # /* clock polarity */
SPI_MODE_0 = (0|0) # /* (original MicroWire) */
SPI_MODE_1 = (0|SPI_CPHA)
SPI_MODE_2 = (SPI_CPOL|0)
SPI_MODE_3 = (SPI_CPOL|SPI_CPHA)
class Lepton(object):
"""Communication class for FLIR Lepton module on SPI
Args:
spi_dev (str): Location of SPI device node. Default '/dev/spidev0.0'.
"""
ROWS = 60
COLS = 80
VOSPI_FRAME_SIZE = COLS + 2
VOSPI_FRAME_SIZE_BYTES = VOSPI_FRAME_SIZE * 2
MODE = SPI_MODE_3
BITS = 8
SPEED = 18000000
SPIDEV_MESSAGE_LIMIT = 24
def __init__(self, spi_dev = "/dev/spidev0.0"):
self.__spi_dev = spi_dev
self.__txbuf = np.zeros(Lepton.VOSPI_FRAME_SIZE, dtype=np.uint16)
# struct spi_ioc_transfer {
# __u64 tx_buf;
# __u64 rx_buf;
# __u32 len;
# __u32 speed_hz;
# __u16 delay_usecs;
# __u8 bits_per_word;
# __u8 cs_change;
# __u32 pad;
# };
self.__xmit_struct = struct.Struct("=QQIIHBBI")
self.__msg_size = self.__xmit_struct.size
self.__xmit_buf = np.zeros((self.__msg_size * Lepton.ROWS), dtype=np.uint8)
self.__msg = _IOW(SPI_IOC_MAGIC, 0, self.__xmit_struct.format)
self.__capture_buf = np.zeros((Lepton.ROWS, Lepton.VOSPI_FRAME_SIZE, 1), dtype=np.uint16)
for i in range(Lepton.ROWS):
self.__xmit_struct.pack_into(self.__xmit_buf, i * self.__msg_size,
self.__txbuf.ctypes.data, # __u64 tx_buf;
self.__capture_buf.ctypes.data + Lepton.VOSPI_FRAME_SIZE_BYTES * i, # __u64 rx_buf;
Lepton.VOSPI_FRAME_SIZE_BYTES, # __u32 len;
Lepton.SPEED, # __u32 speed_hz;
0, # __u16 delay_usecs;
Lepton.BITS, # __u8 bits_per_word;
1, # __u8 cs_change;
0) # __u32 pad;
def __enter__(self):
# "In Python 3 the only way to open /dev/tty under Linux appears to be 1) in binary mode and 2) with buffering disabled."
self.__handle = open(self.__spi_dev, "wb+", buffering=0)
ioctl(self.__handle, SPI_IOC_RD_MODE, struct.pack("=B", Lepton.MODE))
ioctl(self.__handle, SPI_IOC_WR_MODE, struct.pack("=B", Lepton.MODE))
ioctl(self.__handle, SPI_IOC_RD_BITS_PER_WORD, struct.pack("=B", Lepton.BITS))
ioctl(self.__handle, SPI_IOC_WR_BITS_PER_WORD, struct.pack("=B", Lepton.BITS))
ioctl(self.__handle, SPI_IOC_RD_MAX_SPEED_HZ, struct.pack("=I", Lepton.SPEED))
ioctl(self.__handle, SPI_IOC_WR_MAX_SPEED_HZ, struct.pack("=I", Lepton.SPEED))
return self
def __exit__(self, type, value, tb):
self.__handle.close()<|fim▁hole|> messages = Lepton.ROWS
iow = _IOW(SPI_IOC_MAGIC, 0, xs_size)
ioctl(handle, iow, xs_buf, True)
while (capture_buf[0] & 0x000f) == 0x000f: # byteswapped 0x0f00
ioctl(handle, iow, xs_buf, True)
messages -= 1
# NB: the default spidev bufsiz is 4096 bytes so that's where the 24 message limit comes from: 4096 / Lepton.VOSPI_FRAME_SIZE_BYTES = 24.97...
# This 24 message limit works OK, but if you really need to optimize the read speed here, this hack is for you:
# The limit can be changed when spidev is loaded, but since it is compiled statically into newer raspbian kernels, that means
# modifying the kernel boot args to pass this option. This works too:
# $ sudo chmod 666 /sys/module/spidev/parameters/bufsiz
# $ echo 65536 > /sys/module/spidev/parameters/bufsiz
# Then Lepton.SPIDEV_MESSAGE_LIMIT of 24 can be raised to 59
while messages > 0:
if messages > Lepton.SPIDEV_MESSAGE_LIMIT:
count = Lepton.SPIDEV_MESSAGE_LIMIT
else:
count = messages
iow = _IOW(SPI_IOC_MAGIC, 0, xs_size * count)
ret = ioctl(handle, iow, xs_buf[xs_size * (60 - messages):], True)
if ret < 1:
raise IOError("can't send {0} spi messages ({1})".format(60, ret))
messages -= count
def capture(self, data_buffer = None, log_time = False, debug_print = False, retry_reset = True):
"""Capture a frame of data.
Captures 80x60 uint16 array of non-normalized (raw 12-bit) data. Returns that frame and a frame_id (which
is currently just the sum of all pixels). The Lepton will return multiple, identical frames at a rate of up
to ~27 Hz, with unique frames at only ~9 Hz, so the frame_id can help you from doing additional work
processing duplicate frames.
Args:
data_buffer (numpy.ndarray): Optional. If specified, should be ``(60,80,1)`` with `dtype`=``numpy.uint16``.
Returns:
tuple consisting of (data_buffer, frame_id)
"""
start = time.time()
if data_buffer is None:
data_buffer = np.ndarray((Lepton.ROWS, Lepton.COLS, 1), dtype=np.uint16)
elif data_buffer.ndim < 2 or data_buffer.shape[0] < Lepton.ROWS or data_buffer.shape[1] < Lepton.COLS or data_buffer.itemsize < 2:
raise Exception("Provided input array not large enough")
while True:
Lepton.capture_segment(self.__handle, self.__xmit_buf, self.__msg_size, self.__capture_buf[0])
if retry_reset and (self.__capture_buf[20, 0] & 0xFF0F) != 0x1400: # make sure that this is a well-formed frame, should find line 20 here
# Leave chip select deasserted for at least 185 ms to reset
if debug_print:
print("Garbage frame number reset waiting...")
time.sleep(0.185)
else:
break
self.__capture_buf.byteswap(True)
data_buffer[:,:] = self.__capture_buf[:,2:]
end = time.time()
if debug_print:
print("---")
for i in range(Lepton.ROWS):
fid = self.__capture_buf[i, 0, 0]
crc = self.__capture_buf[i, 1, 0]
fnum = fid & 0xFFF
print("0x{0:04x} 0x{1:04x} : Row {2:2} : crc={1}".format(fid, crc, fnum))
print("---")
if log_time:
print("frame processed int {0}s, {1}hz".format(end-start, 1.0/(end-start)))
# TODO: turn on telemetry to get real frame id, sum on this array is fast enough though (< 500us)
return data_buffer, data_buffer.sum()<|fim▁end|> |
@staticmethod
def capture_segment(handle, xs_buf, xs_size, capture_buf): |
<|file_name|>VecbosModule_initializeTalkTo.cc<|end_file_name|><|fim▁begin|>//--------------------------------------------------------------------------
// Description:
// Belongs to class VecbosModule
//
// Wed Jul 11 16:09:46 CDT 2001, G.Velev fix a bug with W or Z selection and
// add vegas read/write flag
//--------------------------------------------------------------------------
#include "generatorMods/VecbosModule.hh"
void VecbosModule::_initializeTalkTo() {
// Init the menus
_structureFunctionMenu.initialize("StructureFunction",this);
_structureFunctionMenu.initTitle("Pdf Menu: internal/exatarnal (group and set)");
_importantMenu.initialize("Important",this);<|fim▁hole|> _importantMenu.initTitle(" Importance sampling for jet Pt");
_isubMenu.initialize("Subprocesses",this);
_isubMenu.initTitle(" 2, 4 or 6 quark subprocess");
_processMenu.initialize("Process",this);
_processMenu.initTitle("Select the process");
_primaryCutsMenu.initialize("PrimaryCuts",this);
_primaryCutsMenu.initTitle("Select Primary Cuts");
_vegasParamMenu.initialize("VegasParam",this);
_vegasParamMenu.initTitle("Vegas Menu, only for an advanced user");
// Descriptions of the Parameters
_debug.addDescription("\t\t\tDebug flag\n\
\t\t\t Increase Vegas print flag from 0 to 1 [0]\n\
\t\t\t Syntax: debug set <t/f>");
_beam_type.addDescription("\t\t\tBeam type\n\
\t\t\t Specify beam type: pp (0) or ppbar (1) [0]\n\
\t\t\t Syntax: beam set <beam>");
_which_boson.addDescription("\t\t\tBoson type\n\
\t\t\t Select W (1) or Z (2) Bosons [1] \n\
\t\t\tSyntax: wORz set <number>");
_decay_boson.addDescription("\t\t\tDecay the boson\n\
\t\t\t Decay the W or Z boson: (t/f) [t] \n\
\t\t\t Syntax: decayWorZ set <t/f>");
_charge_of_W.addDescription("\t\t\tW charge\n\
\t\t\t Generate W with charge -1,+1 or 0 for both [0] \n\
\t\t\t Warning: Choosing to sum over charges\n\
\t\t\t in W events will produce\n\
\t\t\t leptons of both signs, but no\n\
\t\t\t charge specific analysis\n\
\t\t\t should be done on this event\n\
\t\t\t sample! (See documentation).\n\
\t\t\t Syntax: chargeOfW set <charge>");
_howto_decay_Z.addDescription("\t\t\tZDecays\n\
\t\t\t Z decays via ll (1) or nunu (X) [1] \n\
\t\t\t Syntax: zDecayMode set <decaymode>");
_njets.addDescription("\t\t\tNoOfJets\n\
\t\t\t Specify number of jets (min 0-max 4) [3] \n\
\t\t\t Syntax: njets set <njets>");
_structure_function.addDescription("\t\t\t StructureFunction\n\
\t\t\t Specify the structure function (1-6) [6], \n\
\t\t\t 1 - CTEQ1_M, \n\
\t\t\t 2 - CTEQ1MS, \n\
\t\t\t 3 - KMRSS0 , \n\
\t\t\t 4 - KMRSD0 , \n\
\t\t\t 5 - KMRSDM , \n\
\t\t\t 6 use the PDF library \n\
\t\t\t Syntax: strFunct set <number>");
_pdf_group.addDescription("\t\t\tPDFGroup\n\
\t\t\t If use PDF lib specify PDF group [3] \n\
\t\t\t Syntax: pdfGroup set <number>");
_pdf_set.addDescription("\t\t\tPDFSet\n\
\t\t\t If use PDF lib specify PDF set [30] \n\
\t\t\t Syntax: pdfSet set <number>");
_run_number.addDescription("\t\t\tRunNumber\n\
\t\t\t Set the run number [1]. Please use\n\
\t\t\t GenInputManager to set the run number correctly.\n\
\t\t\t Syntax: runNumber set <number>");
_cm_energy.addDescription("\t\t\tEnergyCM\n\
\t\t\t Set the CM energy in GeV/c^2 [1960] \n\
\t\t\t Syntax: enrgyCM set <number>");
_qcd_scale.addDescription("\t\t\tQCDScale\n\
\t\t\t Set QCD scale(1-6) [1] \n\
\t\t\t For [1] Q = PT-average \n\
\t\t\t For [2] Q = Total invariant mass \n\
\t\t\t For [3] Q = Average inv-mass of two jets \n\
\t\t\t For [4] Q = Mass of vector boson \n\
\t\t\t For [5] Q = Pt-max in event \n\
\t\t\t For [6] Q = PT-average / 2 \n\
\t\t\t For [7] Q = PT-average / 4 (min 2.5 GeV) \n\
\t\t\t For [8] Q = PT-average * 2 \n\
\t\t\t For [9] Q = Rt(M(b)**2 + Pt(b)**2) \n\
\t\t\t For [10] Q = Rt(0.5*(M(b)**2 + Pt(b)**2)) \n\
\t\t\t For [11] Q = Rt(4*(M(b)**2 + Pt(b)**2)) \n\
\t\t\t Syntax: qcdScale set <number>");
_helicity.addDescription("\t\t\tHelicity\n\
\t\t\t Perform MC over helicities (in Q^2)? [0] \n\
\t\t\t Syntax: helicity set <number>");
_force_bbbar.addDescription("\t\t\tbbBarMode\n\
\t\t\t Force to generate bbbar final state (0-1) [0] \n\
\t\t\t Syntax: bbBar set <number>");
_important.addDescription("\t\t\tImportance\n\
\t\t\t Use importance sampling for jet Pt (0-1) [1] \n\
\t\t\t Syntax: important set <number>");
_sampling_mode.addDescription("\t\t\tSamplingMode\n\
\t\t\t Choose importance sampling mode, if importance is selected \n\
\t\t\t 1: Pt^(-alpha), alpha should be set to ~ 2.0 \n\
\t\t\t 2: e^(-alpha*Pt)/Pt, alpha should be set to ~ 0.02 \n\
\t\t\t Syntax: samplingMode set <number>");
_lepton_type.addDescription("\t\t\tLeptonType\n\
\t\t\t Specify the lepton type (1-electron,2-muon,3-tau) [1] \n\
\t\t\t Syntax: leptonType set <number>");
_matrix_ele.addDescription("\t\t\tMatrixElement\n\
\t\t\t Matrix elements: Exact (1), M^2=1 (2), 'M^2=1/Shat^Njets (3)? [1] \n\
\t\t\t Syntax: matrixElement set <number>");
_alpha_jet_generation.addDescription("\t\t\tAlphaJets\n\
\t\t\t Set the alpha for the jet generation [0.019] \n\
\t\t\t Syntax: AlphaPt set <value>");
_subprocesses.addDescription("\t\t\tSubProcesses\n\
\t\t\t Set subprocesses (100,110,111) [100] \n\
\t\t\t Include 2-quark subprocess - 100 \n\
\t\t\t Include 4-quark subprocess - 110 \n\
\t\t\t Include 6-quark subprocess - 111 \n\
\t\t\t Syntax: subprocesses set <number>");
_make_jets.addDescription("\t\t\tMakeJets\n\
\t\t\t Force boson to decay to quarks? \n\
\t\t\t true will force decay products to be light quarks. \n\
\t\t\t This is done by changing particle types in the output. \n\
\t\t\t No correction is made to the weights. \n\
\t\t\t Make Jets (t/f) [f] \n\
\t\t\t Syntax: makeJets set <t/f>");
_jet_min_pt.addDescription("\t\t\tJetMinPt\n\
\t\t\t Set the minimum jet Pt in GeV [8.0] \n\
\t\t\t Syntax: jetMinPt set <value>");
_jet_sum_pt.addDescription("\t\t\tJetSumPt\n\
\t\t\t Set sum of jet Pt in GeV [0.0] \n\
\t\t\t Syntax: jetMinPt set <value>");
_jet_eta_max.addDescription("\t\t\tJetEtaMax\n\
\t\t\t Set the maximal value of abs(eta) [2.5] \n\
\t\t\t Syntax:jetEtaMax set <value> ");
_jet_eta_separation.addDescription("\t\t\tJetEtaSeparation\n\
\t\t\t Set the separation between the jets eta [0.4] \n\
\t\t\t Syntax: jetEtaSep set <value>");
_boson_min_pt.addDescription("\t\t\tBosonMinPt\n\
\t\t\t Boson minimum Pt [0.0] \n\
\t\t\t Syntax: bosonMinPt set <value>");
_no_of_leptons.addDescription("\t\t\tNumberOfLeptons\n\
\t\t\t Number of leptonss required to pass cuts [1] \n\
\t\t\t Syntax: noOfLeptons set <nleptons>");
_lep_max_eta.addDescription("\t\t\tLeptonMaxEta\n\
\t\t\t Lepton maximum abs(eta) [2.5] \n\
\t\t\t Syntax: lepMaxEta set <value>");
_lep_min_pt.addDescription("\t\t\tLeptonMinPt\n\
\t\t\t Lepton minimum Pt(GeV) [12.0] \n\
\t\t\t Syntax: lepMinPt set <value>");
_mis_pt_min.addDescription("\t\t\tMissingPtMin\n\
\t\t\t Missing Pt cut [0.0] \n\
\t\t\t Syntax: misPtMin set <value>");
_min_weght.addDescription("\t\t\tMinimalWeigth\n\
\t\t\t Minimum event weight to pass [0.0] \n\
\t\t\t Syntax: minWeigth set <value>");
_vegas_rw_flag.addDescription("\t\t\tReadWriteFlag\n\
\t\t\t Flag to read(1)/write(2) vegas grid [1] (0-no action)\n\
\t\t\t Syntax: rwGrid set <value>");
_vegas_inp_grid_file.addDescription("\t\t\tGridFileInputName\n\
\t\t\t Input VEGAS grid from a file. \n\
\t\t\t Use enviroment CDFVEGIN to specify the input file.");
// \t\t\t Syntax: gridInputName set <string>");
_vegas_out_grid_file.addDescription("\t\t\tGridFileOutputName\n\
\t\t\t Output VEGAS grid from a file. \n\
\t\t\t Use enviroment CDFVEGOUT to specify the output file.");
// \t\t\t Syntax: gridOutputName set <string>");
_vegas_print.addDescription("\t\t\tVegasPrint\n\
\t\t\t VEGAS output flag: (0=none ,1) [0] \n\
\t\t\t Syntax: vegasPrint set <flag> ");
_vegas_n_inter.addDescription("\t\t\tVegasNInterations\n\
\t\t\t Number of init. grid iterations [5] \n\
\t\t\t Syntax: vegasNInter set <value>");
_vegas_n_calls1.addDescription("\t\t\tVegasNCalls1\n\
\t\t\t Number of init. grid calls [max(1000,nevent/5)] \n\
\t\t\t Syntax: vegasNCalls1 set <value>");
_vegas_n_calls2.addDescription("\t\t\tTVegasNCalls2\n\
\t\t\t Number of generation grid calls [NEVENT/2] \n\
\t\t\t Syntax: vegasNCalls2 set <value>");
// Connect all menus and parameters
// First menus
commands( )->append( &_structureFunctionMenu);
_structureFunctionMenu.commands( )->append(&_structure_function);
_structureFunctionMenu.commands( )->append(&_pdf_group);
_structureFunctionMenu.commands( )->append(&_pdf_set);
commands( )->append( &_importantMenu);
_importantMenu.commands( )->append(&_important);
_importantMenu.commands( )->append(&_sampling_mode);
commands( )->append( &_isubMenu);
_isubMenu.commands( )->append(&_subprocesses);
commands( )->append( &_processMenu);
_processMenu.commands( )->append( &_boson_min_pt);
_processMenu.commands( )->append( &_charge_of_W);
_processMenu.commands( )->append( &_howto_decay_Z);
commands( )->append( &_primaryCutsMenu);
_primaryCutsMenu.commands( )->append(&_lep_max_eta);
_primaryCutsMenu.commands( )->append(&_lep_min_pt);
_primaryCutsMenu.commands( )->append (&_jet_min_pt);
_primaryCutsMenu.commands( )->append (&_jet_eta_max);
_primaryCutsMenu.commands( )->append (&_jet_eta_separation);
_primaryCutsMenu.commands( )->append (&_mis_pt_min);
_primaryCutsMenu.commands( )->append (&_min_weght);
commands( )->append( &_vegasParamMenu);
_vegasParamMenu.commands( )->append (&_vegas_print);
_vegasParamMenu.commands( )->append (&_vegas_n_inter);
_vegasParamMenu.commands( )->append (&_vegas_n_calls1);
_vegasParamMenu.commands( )->append (&_vegas_n_calls2);
_vegasParamMenu.commands( )->append (&_vegas_inp_grid_file);
_vegasParamMenu.commands( )->append (&_vegas_out_grid_file);
_vegasParamMenu.commands( )->append (&_vegas_rw_flag);
// Parameters
commands( )->append(&_debug);
commands( )->append(&_which_boson);
commands( )->append(&_decay_boson);
commands( )->append(&_make_jets);
commands( )->append(&_beam_type);
commands( )->append(&_njets);
commands( )->append(&_run_number);
commands( )->append(&_cm_energy);
commands( )->append(&_qcd_scale);
commands( )->append(&_helicity);
commands( )->append(&_force_bbbar);
commands( )->append(&_lepton_type);
commands( )->append(&_matrix_ele);
commands( )->append(&_no_of_leptons);
commands( )->append(&_alpha_jet_generation);
commands( )->append(&_cm_energy);
}<|fim▁end|> | |
<|file_name|>main.js<|end_file_name|><|fim▁begin|>requirejs.config({
"paths": {
"jquery": "https://code.jquery.com/jquery-1.11.3.min",
"moment": "../../moment",
"daterangepicker": "../../daterangepicker"
}
});
requirejs(['jquery', 'moment', 'daterangepicker'] , function ($, moment) {
$(document).ready(function() {
$('#config-text').keyup(function() {
eval($(this).val());
});
$('.configurator input, .configurator select').change(function() {
updateConfig();
});
$('.demo i').click(function() {
$(this).parent().find('input').click();
});
$('#startDate').daterangepicker({
singleDatePicker: true,
startDate: moment().subtract(6, 'days')
});
$('#endDate').daterangepicker({
singleDatePicker: true,
startDate: moment()
});
updateConfig();
function updateConfig() {
var options = {};
if ($('#singleDatePicker').is(':checked'))
options.singleDatePicker = true;
if ($('#showDropdowns').is(':checked'))
options.showDropdowns = true;
if ($('#showWeekNumbers').is(':checked'))
options.showWeekNumbers = true;
if ($('#showISOWeekNumbers').is(':checked'))
options.showISOWeekNumbers = true;
if ($('#timePicker').is(':checked'))
options.timePicker = true;
if ($('#timePicker24Hour').is(':checked'))
options.timePicker24Hour = true;
if ($('#timePickerIncrement').val().length && $('#timePickerIncrement').val() != 1)
options.timePickerIncrement = parseInt($('#timePickerIncrement').val(), 10);
if ($('#timePickerSeconds').is(':checked'))
options.timePickerSeconds = true;
if ($('#autoApply').is(':checked'))
options.autoApply = true;
if ($('#dateLimit').is(':checked'))
options.dateLimit = { days: 7 };
if ($('#ranges').is(':checked')) {
options.ranges = {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'Last 7 Days': [moment().subtract(6, 'days'), moment()],
'Last 30 Days': [moment().subtract(29, 'days'), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
};
}
if ($('#locale').is(':checked')) {
options.locale = {
format: 'MM/DD/YYYY HH:mm',
separator: ' - ',
applyLabel: 'Apply',
cancelLabel: 'Cancel',
fromLabel: 'From',
toLabel: 'To',
customRangeLabel: 'Custom',
daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr','Sa'],
monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
firstDay: 1
};
}
if (!$('#linkedCalendars').is(':checked'))
options.linkedCalendars = false;
if (!$('#autoUpdateInput').is(':checked'))
options.autoUpdateInput = false;
if ($('#alwaysShowCalendars').is(':checked'))
options.alwaysShowCalendars = true;
if ($('#parentEl').val().length)
options.parentEl = $('#parentEl').val();
if ($('#startDate').val().length)
options.startDate = $('#startDate').val();
if ($('#endDate').val().length)
options.endDate = $('#endDate').val();
if ($('#minDate').val().length)
options.minDate = $('#minDate').val();
if ($('#maxDate').val().length)
options.maxDate = $('#maxDate').val();
if ($('#opens').val().length && $('#opens').val() != 'right')
options.opens = $('#opens').val();
if ($('#drops').val().length && $('#drops').val() != 'down')
options.drops = $('#drops').val();
if ($('#buttonClasses').val().length && $('#buttonClasses').val() != 'btn btn-sm')
options.buttonClasses = $('#buttonClasses').val();
if ($('#applyClass').val().length && $('#applyClass').val() != 'btn-success')
options.applyClass = $('#applyClass').val();
if ($('#cancelClass').val().length && $('#cancelClass').val() != 'btn-default')
options.cancelClass = $('#cancelClass').val();
$('#config-text').val("$('#demo').daterangepicker(" + JSON.stringify(options, null, ' ') + ", function(start, end, label) {\n console.log(\"New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')\");\n});");
$('#config-demo').daterangepicker(options, function(start, end, label) { console.log('New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')'); });
}
});
<|fim▁hole|><|fim▁end|> | }); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.