prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>pkg.installspace.context.pc.py<|end_file_name|><|fim▁begin|># generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "commanding_velocity"<|fim▁hole|><|fim▁end|> | PROJECT_SPACE_DIR = "/home/computing/catkin_ws/install"
PROJECT_VERSION = "0.0.0" |
<|file_name|>test_format.py<|end_file_name|><|fim▁begin|>from __future__ import division, absolute_import, print_function
r''' Test the .npy file format.
Set up:
>>> import sys
>>> from io import BytesIO
>>> from numpy.lib import format
>>>
>>> scalars = [
... np.uint8,
... np.int8,
... np.uint16,
... np.int16,
... np.uint32,
... np.int32,
... np.uint64,
... np.int64,
... np.float32,
... np.float64,<|fim▁hole|> >>>
>>> basic_arrays = []
>>>
>>> for scalar in scalars:
... for endian in '<>':
... dtype = np.dtype(scalar).newbyteorder(endian)
... basic = np.arange(15).astype(dtype)
... basic_arrays.extend([
... np.array([], dtype=dtype),
... np.array(10, dtype=dtype),
... basic,
... basic.reshape((3,5)),
... basic.reshape((3,5)).T,
... basic.reshape((3,5))[::-1,::2],
... ])
...
>>>
>>> Pdescr = [
... ('x', 'i4', (2,)),
... ('y', 'f8', (2, 2)),
... ('z', 'u1')]
>>>
>>>
>>> PbufferT = [
... ([3,2], [[6.,4.],[6.,4.]], 8),
... ([4,3], [[7.,5.],[7.,5.]], 9),
... ]
>>>
>>>
>>> Ndescr = [
... ('x', 'i4', (2,)),
... ('Info', [
... ('value', 'c16'),
... ('y2', 'f8'),
... ('Info2', [
... ('name', 'S2'),
... ('value', 'c16', (2,)),
... ('y3', 'f8', (2,)),
... ('z3', 'u4', (2,))]),
... ('name', 'S2'),
... ('z2', 'b1')]),
... ('color', 'S2'),
... ('info', [
... ('Name', 'U8'),
... ('Value', 'c16')]),
... ('y', 'f8', (2, 2)),
... ('z', 'u1')]
>>>
>>>
>>> NbufferT = [
... ([3,2], (6j, 6., ('nn', [6j,4j], [6.,4.], [1,2]), 'NN', True), 'cc', ('NN', 6j), [[6.,4.],[6.,4.]], 8),
... ([4,3], (7j, 7., ('oo', [7j,5j], [7.,5.], [2,1]), 'OO', False), 'dd', ('OO', 7j), [[7.,5.],[7.,5.]], 9),
... ]
>>>
>>>
>>> record_arrays = [
... np.array(PbufferT, dtype=np.dtype(Pdescr).newbyteorder('<')),
... np.array(NbufferT, dtype=np.dtype(Ndescr).newbyteorder('<')),
... np.array(PbufferT, dtype=np.dtype(Pdescr).newbyteorder('>')),
... np.array(NbufferT, dtype=np.dtype(Ndescr).newbyteorder('>')),
... ]
Test the magic string writing.
>>> format.magic(1, 0)
'\x93NUMPY\x01\x00'
>>> format.magic(0, 0)
'\x93NUMPY\x00\x00'
>>> format.magic(255, 255)
'\x93NUMPY\xff\xff'
>>> format.magic(2, 5)
'\x93NUMPY\x02\x05'
Test the magic string reading.
>>> format.read_magic(BytesIO(format.magic(1, 0)))
(1, 0)
>>> format.read_magic(BytesIO(format.magic(0, 0)))
(0, 0)
>>> format.read_magic(BytesIO(format.magic(255, 255)))
(255, 255)
>>> format.read_magic(BytesIO(format.magic(2, 5)))
(2, 5)
Test the header writing.
>>> for arr in basic_arrays + record_arrays:
... f = BytesIO()
... format.write_array_header_1_0(f, arr) # XXX: arr is not a dict, items gets called on it
... print repr(f.getvalue())
...
"F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '|u1', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '|u1', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '|u1', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '|u1', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '|u1', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '|i1', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '|i1', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '|i1', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '|i1', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '|i1', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '<u2', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '<u2', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '<u2', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '<u2', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '<u2', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '<u2', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '>u2', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '>u2', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '>u2', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '>u2', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '>u2', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '>u2', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '<i2', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '<i2', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '<i2', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '<i2', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '<i2', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '<i2', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '>i2', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '>i2', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '>i2', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '>i2', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '>i2', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '>i2', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '<u4', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '<u4', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '<u4', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '<u4', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '<u4', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '<u4', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '>u4', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '>u4', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '>u4', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '>u4', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '>u4', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '>u4', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '<i4', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '<i4', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '<i4', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '<i4', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '<i4', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '<i4', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '>i4', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '>i4', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '>i4', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '>i4', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '>i4', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '>i4', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '<u8', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '<u8', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '<u8', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '<u8', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '<u8', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '<u8', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '>u8', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '>u8', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '>u8', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '>u8', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '>u8', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '>u8', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '<i8', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '<i8', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '<i8', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '<i8', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '<i8', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '<i8', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '>i8', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '>i8', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '>i8', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '>i8', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '>i8', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '>i8', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '<f4', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '<f4', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '<f4', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '<f4', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '<f4', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '<f4', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '>f4', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '>f4', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '>f4', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '>f4', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '>f4', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '>f4', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '<f8', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '<f8', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '<f8', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '<f8', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '<f8', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '<f8', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '>f8', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '>f8', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '>f8', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '>f8', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '>f8', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '>f8', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '<c8', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '<c8', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '<c8', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '<c8', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '<c8', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '<c8', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '>c8', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '>c8', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '>c8', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '>c8', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '>c8', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '>c8', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '<c16', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '<c16', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '<c16', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '<c16', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '<c16', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '<c16', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': '>c16', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': '>c16', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': '>c16', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': '>c16', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': '>c16', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': '>c16', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': 'O', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': 'O', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': 'O', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': 'O', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': 'O', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': 'O', 'fortran_order': False, 'shape': (3, 3)} \n"
"F\x00{'descr': 'O', 'fortran_order': False, 'shape': (0,)} \n"
"F\x00{'descr': 'O', 'fortran_order': False, 'shape': ()} \n"
"F\x00{'descr': 'O', 'fortran_order': False, 'shape': (15,)} \n"
"F\x00{'descr': 'O', 'fortran_order': False, 'shape': (3, 5)} \n"
"F\x00{'descr': 'O', 'fortran_order': True, 'shape': (5, 3)} \n"
"F\x00{'descr': 'O', 'fortran_order': False, 'shape': (3, 3)} \n"
"v\x00{'descr': [('x', '<i4', (2,)), ('y', '<f8', (2, 2)), ('z', '|u1')],\n 'fortran_order': False,\n 'shape': (2,)} \n"
"\x16\x02{'descr': [('x', '<i4', (2,)),\n ('Info',\n [('value', '<c16'),\n ('y2', '<f8'),\n ('Info2',\n [('name', '|S2'),\n ('value', '<c16', (2,)),\n ('y3', '<f8', (2,)),\n ('z3', '<u4', (2,))]),\n ('name', '|S2'),\n ('z2', '|b1')]),\n ('color', '|S2'),\n ('info', [('Name', '<U8'), ('Value', '<c16')]),\n ('y', '<f8', (2, 2)),\n ('z', '|u1')],\n 'fortran_order': False,\n 'shape': (2,)} \n"
"v\x00{'descr': [('x', '>i4', (2,)), ('y', '>f8', (2, 2)), ('z', '|u1')],\n 'fortran_order': False,\n 'shape': (2,)} \n"
"\x16\x02{'descr': [('x', '>i4', (2,)),\n ('Info',\n [('value', '>c16'),\n ('y2', '>f8'),\n ('Info2',\n [('name', '|S2'),\n ('value', '>c16', (2,)),\n ('y3', '>f8', (2,)),\n ('z3', '>u4', (2,))]),\n ('name', '|S2'),\n ('z2', '|b1')]),\n ('color', '|S2'),\n ('info', [('Name', '>U8'), ('Value', '>c16')]),\n ('y', '>f8', (2, 2)),\n ('z', '|u1')],\n 'fortran_order': False,\n 'shape': (2,)} \n"
'''
import sys
import os
import shutil
import tempfile
import warnings
from io import BytesIO
import numpy as np
from numpy.compat import asbytes, asbytes_nested, sixu
from numpy.testing import (
run_module_suite, assert_, assert_array_equal, assert_raises, raises,
dec
)
from numpy.lib import format
tempdir = None
# Module-level setup.
def setup_module():
global tempdir
tempdir = tempfile.mkdtemp()
def teardown_module():
global tempdir
if tempdir is not None and os.path.isdir(tempdir):
shutil.rmtree(tempdir)
tempdir = None
# Generate some basic arrays to test with.
scalars = [
np.uint8,
np.int8,
np.uint16,
np.int16,
np.uint32,
np.int32,
np.uint64,
np.int64,
np.float32,
np.float64,
np.complex64,
np.complex128,
object,
]
basic_arrays = []
for scalar in scalars:
for endian in '<>':
dtype = np.dtype(scalar).newbyteorder(endian)
basic = np.arange(1500).astype(dtype)
basic_arrays.extend([
# Empty
np.array([], dtype=dtype),
# Rank-0
np.array(10, dtype=dtype),
# 1-D
basic,
# 2-D C-contiguous
basic.reshape((30, 50)),
# 2-D F-contiguous
basic.reshape((30, 50)).T,
# 2-D non-contiguous
basic.reshape((30, 50))[::-1, ::2],
])
# More complicated record arrays.
# This is the structure of the table used for plain objects:
#
# +-+-+-+
# |x|y|z|
# +-+-+-+
# Structure of a plain array description:
Pdescr = [
('x', 'i4', (2,)),
('y', 'f8', (2, 2)),
('z', 'u1')]
# A plain list of tuples with values for testing:
PbufferT = [
# x y z
([3, 2], [[6., 4.], [6., 4.]], 8),
([4, 3], [[7., 5.], [7., 5.]], 9),
]
# This is the structure of the table used for nested objects (DON'T PANIC!):
#
# +-+---------------------------------+-----+----------+-+-+
# |x|Info |color|info |y|z|
# | +-----+--+----------------+----+--+ +----+-----+ | |
# | |value|y2|Info2 |name|z2| |Name|Value| | |
# | | | +----+-----+--+--+ | | | | | | |
# | | | |name|value|y3|z3| | | | | | | |
# +-+-----+--+----+-----+--+--+----+--+-----+----+-----+-+-+
#
# The corresponding nested array description:
Ndescr = [
('x', 'i4', (2,)),
('Info', [
('value', 'c16'),
('y2', 'f8'),
('Info2', [
('name', 'S2'),
('value', 'c16', (2,)),
('y3', 'f8', (2,)),
('z3', 'u4', (2,))]),
('name', 'S2'),
('z2', 'b1')]),
('color', 'S2'),
('info', [
('Name', 'U8'),
('Value', 'c16')]),
('y', 'f8', (2, 2)),
('z', 'u1')]
NbufferT = [
# x Info color info y z
# value y2 Info2 name z2 Name Value
# name value y3 z3
([3, 2], (6j, 6., ('nn', [6j, 4j], [6., 4.], [1, 2]), 'NN', True),
'cc', ('NN', 6j), [[6., 4.], [6., 4.]], 8),
([4, 3], (7j, 7., ('oo', [7j, 5j], [7., 5.], [2, 1]), 'OO', False),
'dd', ('OO', 7j), [[7., 5.], [7., 5.]], 9),
]
record_arrays = [
np.array(PbufferT, dtype=np.dtype(Pdescr).newbyteorder('<')),
np.array(NbufferT, dtype=np.dtype(Ndescr).newbyteorder('<')),
np.array(PbufferT, dtype=np.dtype(Pdescr).newbyteorder('>')),
np.array(NbufferT, dtype=np.dtype(Ndescr).newbyteorder('>')),
]
#BytesIO that reads a random number of bytes at a time
class BytesIOSRandomSize(BytesIO):
def read(self, size=None):
import random
size = random.randint(1, size)
return super(BytesIOSRandomSize, self).read(size)
def roundtrip(arr):
f = BytesIO()
format.write_array(f, arr)
f2 = BytesIO(f.getvalue())
arr2 = format.read_array(f2)
return arr2
def roundtrip_randsize(arr):
f = BytesIO()
format.write_array(f, arr)
f2 = BytesIOSRandomSize(f.getvalue())
arr2 = format.read_array(f2)
return arr2
def roundtrip_truncated(arr):
f = BytesIO()
format.write_array(f, arr)
#BytesIO is one byte short
f2 = BytesIO(f.getvalue()[0:-1])
arr2 = format.read_array(f2)
return arr2
def assert_equal_(o1, o2):
assert_(o1 == o2)
def test_roundtrip():
for arr in basic_arrays + record_arrays:
arr2 = roundtrip(arr)
yield assert_array_equal, arr, arr2
def test_roundtrip_randsize():
for arr in basic_arrays + record_arrays:
if arr.dtype != object:
arr2 = roundtrip_randsize(arr)
yield assert_array_equal, arr, arr2
def test_roundtrip_truncated():
for arr in basic_arrays:
if arr.dtype != object:
yield assert_raises, ValueError, roundtrip_truncated, arr
def test_long_str():
# check items larger than internal buffer size, gh-4027
long_str_arr = np.ones(1, dtype=np.dtype((str, format.BUFFER_SIZE + 1)))
long_str_arr2 = roundtrip(long_str_arr)
assert_array_equal(long_str_arr, long_str_arr2)
@dec.slow
def test_memmap_roundtrip():
# Fixme: test crashes nose on windows.
if not (sys.platform == 'win32' or sys.platform == 'cygwin'):
for arr in basic_arrays + record_arrays:
if arr.dtype.hasobject:
# Skip these since they can't be mmap'ed.
continue
# Write it out normally and through mmap.
nfn = os.path.join(tempdir, 'normal.npy')
mfn = os.path.join(tempdir, 'memmap.npy')
fp = open(nfn, 'wb')
try:
format.write_array(fp, arr)
finally:
fp.close()
fortran_order = (
arr.flags.f_contiguous and not arr.flags.c_contiguous)
ma = format.open_memmap(mfn, mode='w+', dtype=arr.dtype,
shape=arr.shape, fortran_order=fortran_order)
ma[...] = arr
del ma
# Check that both of these files' contents are the same.
fp = open(nfn, 'rb')
normal_bytes = fp.read()
fp.close()
fp = open(mfn, 'rb')
memmap_bytes = fp.read()
fp.close()
yield assert_equal_, normal_bytes, memmap_bytes
# Check that reading the file using memmap works.
ma = format.open_memmap(nfn, mode='r')
del ma
def test_compressed_roundtrip():
arr = np.random.rand(200, 200)
npz_file = os.path.join(tempdir, 'compressed.npz')
np.savez_compressed(npz_file, arr=arr)
arr1 = np.load(npz_file)['arr']
assert_array_equal(arr, arr1)
def test_python2_python3_interoperability():
if sys.version_info[0] >= 3:
fname = 'win64python2.npy'
else:
fname = 'python3.npy'
path = os.path.join(os.path.dirname(__file__), 'data', fname)
data = np.load(path)
assert_array_equal(data, np.ones(2))
def test_pickle_python2_python3():
# Test that loading object arrays saved on Python 2 works both on
# Python 2 and Python 3 and vice versa
data_dir = os.path.join(os.path.dirname(__file__), 'data')
if sys.version_info[0] >= 3:
xrange = range
else:
import __builtin__
xrange = __builtin__.xrange
expected = np.array([None, xrange, sixu('\u512a\u826f'),
asbytes('\xe4\xb8\x8d\xe8\x89\xaf')],
dtype=object)
for fname in ['py2-objarr.npy', 'py2-objarr.npz',
'py3-objarr.npy', 'py3-objarr.npz']:
path = os.path.join(data_dir, fname)
if (fname.endswith('.npz') and sys.version_info[0] == 2 and
sys.version_info[1] < 7):
# Reading object arrays directly from zipfile appears to fail
# on Py2.6, see cfae0143b4
continue
for encoding in ['bytes', 'latin1']:
if (sys.version_info[0] >= 3 and sys.version_info[1] < 4 and
encoding == 'bytes'):
# The bytes encoding is available starting from Python 3.4
continue
data_f = np.load(path, encoding=encoding)
if fname.endswith('.npz'):
data = data_f['x']
data_f.close()
else:
data = data_f
if sys.version_info[0] >= 3:
if encoding == 'latin1' and fname.startswith('py2'):
assert_(isinstance(data[3], str))
assert_array_equal(data[:-1], expected[:-1])
# mojibake occurs
assert_array_equal(data[-1].encode(encoding), expected[-1])
else:
assert_(isinstance(data[3], bytes))
assert_array_equal(data, expected)
else:
assert_array_equal(data, expected)
if sys.version_info[0] >= 3:
if fname.startswith('py2'):
if fname.endswith('.npz'):
data = np.load(path)
assert_raises(UnicodeError, data.__getitem__, 'x')
data.close()
data = np.load(path, fix_imports=False, encoding='latin1')
assert_raises(ImportError, data.__getitem__, 'x')
data.close()
else:
assert_raises(UnicodeError, np.load, path)
assert_raises(ImportError, np.load, path,
encoding='latin1', fix_imports=False)
def test_version_2_0():
f = BytesIO()
# requires more than 2 byte for header
dt = [(("%d" % i) * 100, float) for i in range(500)]
d = np.ones(1000, dtype=dt)
format.write_array(f, d, version=(2, 0))
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', UserWarning)
format.write_array(f, d)
assert_(w[0].category is UserWarning)
f.seek(0)
n = format.read_array(f)
assert_array_equal(d, n)
# 1.0 requested but data cannot be saved this way
assert_raises(ValueError, format.write_array, f, d, (1, 0))
def test_version_2_0_memmap():
# requires more than 2 byte for header
dt = [(("%d" % i) * 100, float) for i in range(500)]
d = np.ones(1000, dtype=dt)
tf = tempfile.mktemp('', 'mmap', dir=tempdir)
# 1.0 requested but data cannot be saved this way
assert_raises(ValueError, format.open_memmap, tf, mode='w+', dtype=d.dtype,
shape=d.shape, version=(1, 0))
ma = format.open_memmap(tf, mode='w+', dtype=d.dtype,
shape=d.shape, version=(2, 0))
ma[...] = d
del ma
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', '', UserWarning)
ma = format.open_memmap(tf, mode='w+', dtype=d.dtype,
shape=d.shape, version=None)
assert_(w[0].category is UserWarning)
ma[...] = d
del ma
ma = format.open_memmap(tf, mode='r')
assert_array_equal(ma, d)
def test_write_version():
f = BytesIO()
arr = np.arange(1)
# These should pass.
format.write_array(f, arr, version=(1, 0))
format.write_array(f, arr)
format.write_array(f, arr, version=None)
format.write_array(f, arr)
format.write_array(f, arr, version=(2, 0))
format.write_array(f, arr)
# These should all fail.
bad_versions = [
(1, 1),
(0, 0),
(0, 1),
(2, 2),
(255, 255),
]
for version in bad_versions:
try:
format.write_array(f, arr, version=version)
except ValueError:
pass
else:
raise AssertionError("we should have raised a ValueError for the bad version %r" % (version,))
bad_version_magic = asbytes_nested([
'\x93NUMPY\x01\x01',
'\x93NUMPY\x00\x00',
'\x93NUMPY\x00\x01',
'\x93NUMPY\x02\x00',
'\x93NUMPY\x02\x02',
'\x93NUMPY\xff\xff',
])
malformed_magic = asbytes_nested([
'\x92NUMPY\x01\x00',
'\x00NUMPY\x01\x00',
'\x93numpy\x01\x00',
'\x93MATLB\x01\x00',
'\x93NUMPY\x01',
'\x93NUMPY',
'',
])
def test_read_magic_bad_magic():
for magic in malformed_magic:
f = BytesIO(magic)
yield raises(ValueError)(format.read_magic), f
def test_read_version_1_0_bad_magic():
for magic in bad_version_magic + malformed_magic:
f = BytesIO(magic)
yield raises(ValueError)(format.read_array), f
def test_bad_magic_args():
assert_raises(ValueError, format.magic, -1, 1)
assert_raises(ValueError, format.magic, 256, 1)
assert_raises(ValueError, format.magic, 1, -1)
assert_raises(ValueError, format.magic, 1, 256)
def test_large_header():
s = BytesIO()
d = {'a': 1, 'b': 2}
format.write_array_header_1_0(s, d)
s = BytesIO()
d = {'a': 1, 'b': 2, 'c': 'x'*256*256}
assert_raises(ValueError, format.write_array_header_1_0, s, d)
def test_bad_header():
# header of length less than 2 should fail
s = BytesIO()
assert_raises(ValueError, format.read_array_header_1_0, s)
s = BytesIO(asbytes('1'))
assert_raises(ValueError, format.read_array_header_1_0, s)
# header shorter than indicated size should fail
s = BytesIO(asbytes('\x01\x00'))
assert_raises(ValueError, format.read_array_header_1_0, s)
# headers without the exact keys required should fail
d = {"shape": (1, 2),
"descr": "x"}
s = BytesIO()
format.write_array_header_1_0(s, d)
assert_raises(ValueError, format.read_array_header_1_0, s)
d = {"shape": (1, 2),
"fortran_order": False,
"descr": "x",
"extrakey": -1}
s = BytesIO()
format.write_array_header_1_0(s, d)
assert_raises(ValueError, format.read_array_header_1_0, s)
def test_large_file_support():
from nose import SkipTest
if (sys.platform == 'win32' or sys.platform == 'cygwin'):
raise SkipTest("Unknown if Windows has sparse filesystems")
# try creating a large sparse file
tf_name = os.path.join(tempdir, 'sparse_file')
try:
# seek past end would work too, but linux truncate somewhat
# increases the chances that we have a sparse filesystem and can
# avoid actually writing 5GB
import subprocess as sp
sp.check_call(["truncate", "-s", "5368709120", tf_name])
except:
raise SkipTest("Could not create 5GB large file")
# write a small array to the end
with open(tf_name, "wb") as f:
f.seek(5368709120)
d = np.arange(5)
np.save(f, d)
# read it back
with open(tf_name, "rb") as f:
f.seek(5368709120)
r = np.load(f)
assert_array_equal(r, d)
if __name__ == "__main__":
run_module_suite()<|fim▁end|> | ... np.complex64,
... np.complex128,
... object,
... ] |
<|file_name|>bitcoin_sv.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="sv" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Fastcoin</source>
<translation>Om Fastcoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Fastcoin</b> version</source>
<translation><b>Fastcoin</b>-version</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>
Detta är experimentell mjukvara.
Distribuerad under mjukvarulicensen MIT/X11, se den medföljande filen COPYING eller http://www.opensource.org/licenses/mit-license.php.
Denna produkten innehåller mjukvara utvecklad av OpenSSL Project för användning i OpenSSL Toolkit (http://www.openssl.org/) och kryptografisk mjukvara utvecklad av Eric Young ([email protected]) samt UPnP-mjukvara skriven av Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Copyright</translation>
</message>
<message>
<location line="+0"/>
<source>The Fastcoin developers</source>
<translation>Fastcoin-utvecklarna</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adressbok</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Dubbel-klicka för att ändra adressen eller etiketten</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Skapa ny adress</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopiera den markerade adressen till systemets Urklipp</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Ny adress</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Fastcoin 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>Detta är dina Fastcoin-adresser för att ta emot betalningar. Du kan ge varje avsändare en egen adress så att du kan hålla reda på vem som betalar dig.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Kopiera adress</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Visa &QR-kod</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Fastcoin address</source>
<translation>Signera ett meddelande för att bevisa att du äger denna adress</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Signera &Meddelande</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Ta bort den valda adressen från listan</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportera informationen i den nuvarande fliken till en fil</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Exportera</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Fastcoin address</source>
<translation>Verifiera meddelandet för att vara säker på att den var signerad med den specificerade Fastcoin-adressen</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verifiera Meddelande</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Radera</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Fastcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Detta är dina Fastcoin adresser för att skicka betalningar. Kolla alltid summan och den mottagande adressen innan du skickar Fastcoins.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Kopiera &etikett</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Editera</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Skicka &Fastcoins</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Exportera Adressbok</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommaseparerad fil (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Fel vid export</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kunde inte skriva till filen %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Etikett</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adress</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(Ingen etikett)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Lösenords Dialog</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Ange lösenord</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nytt lösenord</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Upprepa nytt lösenord</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>Ange plånbokens nya lösenord. <br/> Använd ett lösenord på <b>10 eller fler slumpmässiga tecken,</b> eller <b>åtta eller fler ord.</b></translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Kryptera plånbok</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Denna operation behöver din plånboks lösenord för att låsa upp plånboken.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Lås upp plånbok</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Denna operation behöver din plånboks lösenord för att dekryptera plånboken.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Dekryptera plånbok</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Ändra lösenord</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Ange plånbokens gamla och nya lösenord.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Bekräfta kryptering av plånbok</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!</source>
<translation>VARNING: Om du krypterar din plånbok och glömmer ditt lösenord, kommer du att <b>FÖRLORA ALLA DINA TILLGÅNGAR</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Är du säker på att du vill kryptera din plånbok?</translation>
</message>
<message><|fim▁hole|> <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>VIKTIGT: Alla tidigare säkerhetskopior du har gjort av plånbokens fil ska ersättas med den nya genererade, krypterade plånboks filen. Av säkerhetsskäl kommer tidigare säkerhetskopior av den okrypterade plånboks filen blir oanvändbara när du börjar använda en ny, krypterad plånbok.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Varning: Caps Lock är påslaget!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Plånboken är krypterad</translation>
</message>
<message>
<location line="-56"/>
<source>Fastcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your fastcoins from being stolen by malware infecting your computer.</source>
<translation>Programmet kommer nu att stänga ner för att färdigställa krypteringen. Tänk på att en krypterad plånbok inte skyddar mot stöld om din dator är infekterad med en keylogger.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Kryptering av plånbok misslyckades</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Kryptering av plånbok misslyckades på grund av ett internt fel. Din plånbok blev inte krypterad.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>De angivna lösenorden överensstämmer inte.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Upplåsning av plånbok misslyckades</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Lösenordet för dekryptering av plånbok var felaktig.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Dekryptering av plånbok misslyckades</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Plånbokens lösenord har ändrats.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Signera &meddelande...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Synkroniserar med nätverk...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Översikt</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Visa översiktsvy av plånbok</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transaktioner</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Bläddra i transaktionshistorik</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Redigera listan med lagrade adresser och etiketter</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Visa listan med adresser för att ta emot betalningar</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Avsluta</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Avsluta programmet</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Fastcoin</source>
<translation>Visa information om Fastcoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Om &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Visa information om Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Alternativ...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Kryptera plånbok...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Säkerhetskopiera plånbok...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Byt Lösenord...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Importerar block från disk...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Återindexerar block på disken...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Fastcoin address</source>
<translation>Skicka mynt till en Fastcoin-adress</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Fastcoin</source>
<translation>Ändra konfigurationsalternativ för Fastcoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Säkerhetskopiera plånboken till en annan plats</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Byt lösenord för kryptering av plånbok</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>&Debug fönster</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Öppna debug- och diagnostikkonsolen</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Verifiera meddelande...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Fastcoin</source>
<translation>Fastcoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Plånbok</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Skicka</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Ta emot</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Adresser</translation>
</message>
<message>
<location line="+22"/>
<source>&About Fastcoin</source>
<translation>&Om Fastcoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Visa / Göm</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Visa eller göm huvudfönstret</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Kryptera de privata nycklar som tillhör din plånbok</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Fastcoin addresses to prove you own them</source>
<translation>Signera meddelanden med din Fastcoinadress för att bevisa att du äger dem</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Fastcoin addresses</source>
<translation>Verifiera meddelanden för att vara säker på att de var signerade med den specificerade Fastcoin-adressen</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Arkiv</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Inställningar</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Hjälp</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Verktygsfält för Tabbar</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Fastcoin client</source>
<translation>Fastcoin-klient</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Fastcoin network</source>
<translation><numerusform>%n aktiv anslutning till Fastcoin-nätverket</numerusform><numerusform>%n aktiva anslutningar till Fastcoin-nätverket</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>Ingen block-källa tillgänglig...</translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>Bearbetat %1 av %2 (uppskattade) block av transaktionshistorik.</translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Bearbetat %1 block i transaktionshistoriken.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n timme</numerusform><numerusform>%n timmar</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n dag</numerusform><numerusform>%n dagar</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n vecka</numerusform><numerusform>%n veckor</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 efter</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Senast mottagna block genererades %1 sen.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Transaktioner efter denna kommer inte ännu vara synliga.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Fel</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Varning</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Information</translation>
</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>Transaktionen överskrider storleksgränsen. Du kan dock fortfarande skicka den mot en kostnad av %1, som går till noderna som behandlar din transaktion och bidrar till nätverket. Vill du betala denna avgift?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Uppdaterad</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Hämtar senaste...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Bekräfta överföringsavgift</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Transaktion skickad</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Inkommande transaktion</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Datum: %1
Belopp: %2
Typ: %3
Adress: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>URI hantering</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Fastcoin address or malformed URI parameters.</source>
<translation>URI går inte att tolkas! Detta kan orsakas av en ogiltig Fastcoin-adress eller felaktiga URI parametrar.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Denna plånbok är <b>krypterad</b> och för närvarande <b>olåst</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Denna plånbok är <b>krypterad</b> och för närvarande <b>låst</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Fastcoin can no longer continue safely and will quit.</source>
<translation>Ett allvarligt fel har uppstått. Fastcoin kan inte längre köras säkert och kommer att avslutas.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Nätverkslarm</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Redigera Adress</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etikett</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Den etikett som är associerad med detta adressboksinlägg</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adress</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>Adressen som är associerad med detta adressboksinlägg. Detta kan enbart ändras för sändande adresser.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Ny mottagaradress</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Ny avsändaradress</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Redigera mottagaradress</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Redigera avsändaradress</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Den angivna adressen "%1" finns redan i adressboken.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Fastcoin address.</source>
<translation>Den angivna adressen "%1" är inte en giltig Fastcoin-adress.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Plånboken kunde inte låsas upp.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Misslyckades med generering av ny nyckel.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Fastcoin-Qt</source>
<translation>Fastcoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>version</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Användning:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>kommandoradsalternativ</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>UI alternativ</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Ändra språk, till exempel "de_DE" (förvalt: systemets språk)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Starta som minimerad</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Visa startbilden vid uppstart (förvalt: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Alternativ</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Allmänt</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>Valfri transaktionsavgift per kB som ser till att dina transaktioner behandlas snabbt. De flesta transaktioner är 1 kB.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Betala överförings&avgift</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Fastcoin after logging in to the system.</source>
<translation>Starta Fastcoin automatiskt efter inloggning.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Fastcoin on system login</source>
<translation>&Starta Fastcoin vid systemstart</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Återställ alla klient inställningar till förvalen.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>&Återställ Alternativ</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Nätverk</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Fastcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Öppna automatiskt Fastcoin-klientens port på routern. Detta fungerar endast om din router har UPnP aktiverat.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Tilldela port med hjälp av &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Fastcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Anslut till Fastcoin-nätverket genom en SOCKS-proxy (t.ex. när du ansluter genom Tor).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Anslut genom SOCKS-proxy:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Proxy-&IP: </translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Proxyns IP-adress (t.ex. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port: </translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Proxyns port (t.ex. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Version:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS version av proxyn (t.ex. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Fönster</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Visa endast en systemfältsikon vid minimering.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimera till systemfältet istället för aktivitetsfältet</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>Minimera applikationen istället för att stänga ner den när fönstret stängs. Detta innebär att programmet fotrsätter att köras tills du väljer Avsluta i menyn.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimera vid stängning</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Visa</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Användargränssnittets &språk: </translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Fastcoin.</source>
<translation>Användargränssnittets språk kan ställas in här. Denna inställning träder i kraft efter en omstart av Fastcoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Måttenhet att visa belopp i: </translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Välj en måttenhet att visa när du skickar mynt.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Fastcoin addresses in the transaction list or not.</source>
<translation>Anger om Fastcoin-adresser skall visas i transaktionslistan.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Visa adresser i transaktionslistan</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Avbryt</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Verkställ</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>standard</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Bekräfta att alternativen ska återställs</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Vissa inställningar kan behöva en omstart av klienten för att börja gälla.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Vill du fortsätta?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Varning</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Fastcoin.</source>
<translation>Denna inställning träder i kraft efter en omstart av Fastcoin.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Den medföljande proxy adressen är ogiltig.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Formulär</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Fastcoin network after a connection is established, but this process has not completed yet.</source>
<translation>Den visade informationen kan vara inaktuell. Plånboken synkroniseras automatiskt med Fastcoin-nätverket efter att anslutningen är upprättad, men denna process har inte slutförts ännu.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Obekräftade:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Plånbok</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Omogen:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Den genererade balansen som ännu inte har mognat</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Nyligen genomförda transaktioner</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Ditt nuvarande saldo</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>Totalt antal transaktioner som ännu inte bekräftats, och som ännu inte räknas med i aktuellt saldo</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>osynkroniserad</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start fastcoin: click-to-pay handler</source>
<translation>Kan inte starta fastcoin: klicka-och-betala handhavare</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR-kod dialogruta</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Begär Betalning</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Belopp:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Etikett:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Meddelande:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Spara som...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Fel vid skapande av QR-kod från URI.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Det angivna beloppet är ogiltigt, vänligen kontrollera.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>URI:n är för lång, försöka minska texten för etikett / meddelande.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Spara QR-kod</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG-bilder (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Klientnamn</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>ej tillgänglig</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Klient-version</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Information</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Använder OpenSSL version</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Uppstartstid</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Nätverk</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Antalet anslutningar</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>På testnet</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blockkedja</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Aktuellt antal block</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Beräknade totala block</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Sista blocktid</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Öppna</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Kommandoradsalternativ</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Fastcoin-Qt help message to get a list with possible Fastcoin command-line options.</source>
<translation>Visa Fastcoin-Qt hjälpmeddelande för att få en lista med möjliga Fastcoin kommandoradsalternativ.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Visa</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsol</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Kompileringsdatum</translation>
</message>
<message>
<location line="-104"/>
<source>Fastcoin - Debug window</source>
<translation>Fastcoin - Debug fönster</translation>
</message>
<message>
<location line="+25"/>
<source>Fastcoin Core</source>
<translation>Fastcoin Kärna</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Debugloggfil</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Fastcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Öppna Fastcoin debug-loggfilen som finns i datakatalogen. Detta kan ta några sekunder för stora loggfiler.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Rensa konsollen</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Fastcoin RPC console.</source>
<translation>Välkommen till Fastcoin RPC-konsollen.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Använd upp- och ner-pilarna för att navigera i historiken, och <b>Ctrl-L</b> för att rensa skärmen.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Skriv <b>help</b> för en översikt av alla kommandon.</translation>
</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>Skicka pengar</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Skicka till flera mottagare samtidigt</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Lägg till &mottagare</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Ta bort alla transaktions-fält</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Rensa &alla</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Balans:</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>Bekräfta sändordern</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Skicka</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> till %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Bekräfta skickade mynt</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Är du säker på att du vill skicka %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation> och </translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Mottagarens adress är inte giltig, vänligen kontrollera igen.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Det betalade beloppet måste vara större än 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Värdet överstiger ditt saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Totalvärdet överstiger ditt saldo när transaktionsavgiften %1 är pålagd.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Dubblett av adress funnen, kan bara skicka till varje adress en gång per sändning.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Fel: Transaktionen gick inte att skapa!</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Fel: Transaktionen avslogs. Detta kan hända om några av mynten i plånboken redan spenderats, t.ex om du använt en kopia av wallet.dat och mynt spenderades i kopian men inte markerats som spenderas här.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Formulär</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>&Belopp:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>Betala &Till:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Adressen som betalningen skall skickas till (t.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</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>Ange ett namn för den här adressen och lägg till den i din adressbok</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Etikett:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Välj adress från adresslistan</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>Klistra in adress från Urklipp</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>Ta bort denna mottagare</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Fastcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Ange en Fastcoin-adress (t.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Signaturer - Signera / Verifiera ett Meddelande</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Signera Meddelande</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>Du kan signera meddelanden med dina adresser för att bevisa att du äger dem. Var försiktig med vad du signerar eftersom phising-attacker kan försöka få dig att skriva över din identitet till någon annan. Signera bara väldetaljerade påståenden du kan gå i god för.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Adressen att signera meddelandet med (t.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Välj en adress från adressboken</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>Klistra in adress från Urklipp</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>Skriv in meddelandet du vill signera här</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Signatur</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Kopiera signaturen till systemets Urklipp</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Fastcoin address</source>
<translation>Signera meddelandet för att bevisa att du äger denna adress</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Signera &Meddelande</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Rensa alla fält</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Rensa &alla</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Verifiera Meddelande</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>Skriv in din adress, meddelande (se till att du kopierar radbrytningar, mellanslag, tabbar, osv. exakt) och signatur nedan för att verifiera meddelandet. Var noga med att inte läsa in mer i signaturen än vad som finns i det signerade meddelandet, för att undvika att luras av en man-in-the-middle attack.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Adressen som meddelandet var signerat med (t.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Fastcoin address</source>
<translation>Verifiera meddelandet för att vara säker på att den var signerad med den angivna Fastcoin-adressen</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Verifiera &Meddelande</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Rensa alla fält</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Fastcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Ange en Fastcoin-adress (t.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Klicka "Signera Meddelande" för att få en signatur</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Fastcoin signature</source>
<translation>Ange Fastcoin-signatur</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Den angivna adressen är ogiltig.</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>Vad god kontrollera adressen och försök igen.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Den angivna adressen refererar inte till en nyckel.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Upplåsningen av plånboken avbröts.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Privata nyckel för den angivna adressen är inte tillgänglig.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Signeringen av meddelandet misslyckades.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Meddelandet är signerat.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Signaturen kunde inte avkodas.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Kontrollera signaturen och försök igen.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Signaturen matchade inte meddelandesammanfattningen.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Meddelandet verifikation misslyckades.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Meddelandet är verifierad.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Fastcoin developers</source>
<translation>Fastcoin-utvecklarna</translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Öppet till %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/nerkopplad</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/obekräftade</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 bekräftelser</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Status</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, sänd genom %n nod</numerusform><numerusform>, sänd genom %n noder</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Källa</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Genererad</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Från</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Till</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>egen adress</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>etikett</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Kredit</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>mognar om %n block</numerusform><numerusform>mognar om %n fler block</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>inte accepterad</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Belasta</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Transaktionsavgift</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Nettobelopp</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Meddelande</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Kommentar</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Transaktions-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>Genererade mynt måste vänta 120 block innan de kan användas. När du skapade detta block sändes det till nätverket för att läggas till i blockkedjan. Om blocket inte kommer in i kedjan kommer det att ändras till "accepteras inte" och kommer ej att gå att spendera. Detta kan ibland hända om en annan nod genererar ett block nästan samtidigt som dig.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Debug information</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transaktion</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>Inputs</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Mängd</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>sant</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>falsk</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, har inte lyckats skickas ännu</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Öppet för %n mer block</numerusform><numerusform>Öppet för %n mer block</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>okänd</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transaktionsdetaljer</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Den här panelen visar en detaljerad beskrivning av transaktionen</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Typ</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adress</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Mängd</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Öppet för %n mer block</numerusform><numerusform>Öppet för %n mer block</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Öppet till %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Offline (%1 bekräftelser)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Obekräftad (%1 av %2 bekräftelser)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Bekräftad (%1 bekräftelser)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>Genererade balansen kommer att finnas tillgänglig när den mognar om %n mer block</numerusform><numerusform>Genererade balansen kommer att finnas tillgänglig när den mognar om %n fler block</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>Det här blocket togs inte emot av några andra noder och kommer antagligen inte att bli godkänt.</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Genererad men inte accepterad</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Mottagen med</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Mottaget från</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Skickad till</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Betalning till dig själv</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Genererade</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(n/a)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Transaktionsstatus. Håll muspekaren över för att se antal bekräftelser.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Tidpunkt då transaktionen mottogs.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Transaktionstyp.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Transaktionens destinationsadress.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Belopp draget eller tillagt till balans.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Alla</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Idag</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Denna vecka</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Denna månad</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Föregående månad</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Det här året</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Period...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Mottagen med</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Skickad till</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Till dig själv</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Genererade</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Övriga</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Sök efter adress eller etikett </translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Minsta mängd</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopiera adress</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Kopiera etikett</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Kopiera belopp</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Kopiera transaktions ID</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Ändra etikett</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Visa transaktionsdetaljer</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Exportera Transaktionsdata</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Kommaseparerad fil (*. csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Bekräftad</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Typ</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etikett</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adress</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Mängd</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Fel vid export</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Kunde inte skriva till filen %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Intervall:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>till</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Skicka pengar</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Exportera</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportera informationen i den nuvarande fliken till en fil</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Säkerhetskopiera Plånbok</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Plånboks-data (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Säkerhetskopiering misslyckades</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Det inträffade ett fel när plånboken skulle sparas till den nya platsen.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Säkerhetskopiering lyckades</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Plånbokens data har sparats till den nya platsen.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Fastcoin version</source>
<translation>Fastcoin version</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Användning:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or fastcoind</source>
<translation>Skicka kommando till -server eller fastcoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Lista kommandon</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Få hjälp med ett kommando</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Inställningar:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: fastcoin.conf)</source>
<translation>Ange konfigurationsfil (förvalt: fastcoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: fastcoind.pid)</source>
<translation>Ange pid fil (förvalt: fastcoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Ange katalog för data</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Sätt databas cache storleken i megabyte (förvalt: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation>Lyssna efter anslutningar på <port> (förvalt: 9333 eller testnet: 19333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Ha som mest <n> anslutningar till andra klienter (förvalt: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Anslut till en nod för att hämta klientadresser, och koppla från</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Ange din egen publika adress</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Tröskelvärde för att koppla ifrån klienter som missköter sig (förvalt: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Antal sekunder att hindra klienter som missköter sig från att ansluta (förvalt: 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>Ett fel uppstod vid upprättandet av RPC port %u för att lyssna på IPv4: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation>Lyssna på JSON-RPC-anslutningar på <port> (förvalt: 9332 eller testnet: 19332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Tillåt kommandon från kommandotolken och JSON-RPC-kommandon</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Kör i bakgrunden som tjänst och acceptera kommandon</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Använd testnätverket</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Acceptera anslutningar utifrån (förvalt: 1 om ingen -proxy eller -connect)</translation>
</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=fastcoinrpc
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 "Fastcoin Alert" [email protected]
</source>
<translation>%s, du behöver sätta ett rpclösensord i konfigurationsfilen:
%s
Det är rekommenderat att använda följande slumpade lösenord:
rpcuser=fastcoinrpc
rpcpassword=%s
(du behöver inte komma ihåg lösenordet)
Användarnamnet och lösenordet FÅR INTE bara detsamma.
Om filen inte existerar, skapa den med enbart ägarläsbara filrättigheter.
Det är också rekommenderat att sätta alertnotify så du meddelas om problem;
till exempel: alertnotify=echo %%s | mail -s "Fastcoin Alert" [email protected]
</translation>
</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>Ett fel uppstod vid upprättandet av RPC port %u för att lyssna på IPv6, faller tillbaka till IPV4: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Bind till given adress och lyssna alltid på den. Använd [värd]:port notation för IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Fastcoin is probably already running.</source>
<translation>Kan inte låsa data-mappen %s. Fastcoin körs förmodligen redan.</translation>
</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>Fel: Transaktionen avslogs! Detta kan hända om några av mynten i plånboken redan spenderats, t.ex om du använt en kopia av wallet.dat och mynt spenderades i kopian men inte markerats som spenderas här.</translation>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation>Fel: Denna transaktion kräver en transaktionsavgift på minst %s på grund av dess storlek, komplexitet, eller användning av senast mottagna fastcoins!</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Exekvera kommando när ett relevant meddelande är mottagen (%s i cmd är utbytt med ett meddelande)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Exekvera kommando när en plånbokstransaktion ändras (%s i cmd är ersatt av TxID)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Sätt den maximala storleken av hög-prioriterade/låg-avgifts transaktioner i byte (förvalt: 27000)</translation>
</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>Detta är ett förhands testbygge - använd på egen risk - använd inte för mining eller handels applikationer</translation>
</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>Varning: -paytxfee är satt väldigt hög! Detta är avgiften du kommer betala för varje transaktion.</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>Varning: Visade transaktioner kanske inte är korrekt! Du kan behöva uppgradera, eller andra noder kan behöva uppgradera.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Fastcoin will not work properly.</source>
<translation>Varning: Vänligen kolla så att din dators datum och tid är korrekt! Om din klocka går fel kommer Fastcoin inte fungera korrekt.</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>Varning: fel vid läsning av wallet.dat! Alla nycklar lästes korrekt, men transaktionsdatan eller adressbokens poster kanske saknas eller är felaktiga.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Varning: wallet.dat korrupt, datan har räddats! Den ursprungliga wallet.dat har sparas som wallet.{timestamp}.bak i %s; om ditt saldo eller transaktioner är felaktiga ska du återställa från en säkerhetskopia.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Försök att rädda de privata nycklarna från en korrupt wallet.dat</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Block skapande inställningar:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Koppla enbart upp till den/de specificerade noden/noder</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Korrupt blockdatabas har upptäckts</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Hitta egen IP-adress (förvalt: 1 under lyssning och utan -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Vill du bygga om blockdatabasen nu?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Fel vid initiering av blockdatabasen</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Fel vid initiering av plånbokens databasmiljö %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Fel vid inläsning av blockdatabasen</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Fel vid öppning av blockdatabasen</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Fel: Hårddiskutrymme är lågt!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Fel: Plånboken är låst, det går ej att skapa en transaktion!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Fel: systemfel:</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Misslyckades att lyssna på någon port. Använd -listen=0 om du vill detta.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Misslyckades att läsa blockinformation</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Misslyckades att läsa blocket</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Misslyckades att synkronisera blockindex</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Misslyckades att skriva blockindex</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Misslyckades att skriva blockinformation</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Misslyckades att skriva blocket</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>Misslyckades att skriva filinformation</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Misslyckades att skriva till myntdatabas</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Misslyckades att skriva transaktionsindex</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Misslyckades att skriva ångradata</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Sök efter klienter med DNS sökningen (förvalt: 1 om inte -connect)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Generera mynt (förvalt: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Hur många block att kontrollera vid uppstart (standardvärde: 288, 0 = alla)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>Hur grundlig blockverifikationen är (0-4, förvalt: 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>Inte tillräckligt med filbeskrivningar tillgängliga.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Återskapa blockkedjans index från nuvarande blk000??.dat filer</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Ange antalet trådar för att hantera RPC anrop (standard: 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Verifierar block...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Verifierar plånboken...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Importerar block från extern blk000??.dat fil</translation>
</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>Ange antalet skriptkontrolltrådar (upp till 16, 0 = auto, <0 = lämna så många kärnor lediga, förval: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Information</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Ogiltig -tor adress: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Ogiltigt belopp för -minrelaytxfee=<belopp>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Ogiltigt belopp för -mintxfee=<belopp>: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Upprätthåll ett fullständigt transaktionsindex (förval: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Maximal buffert för mottagning per anslutning, <n>*1000 byte (förvalt: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Maximal buffert för sändning per anslutning, <n>*1000 byte (förvalt: 5000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Acceptera bara blockkedjans matchande inbyggda kontrollpunkter (förvalt: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Anslut enbart till noder i nätverket <net> (IPv4, IPv6 eller Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Skriv ut extra felsökningsinformation. Gäller alla andra -debug* alternativ</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Skriv ut extra felsökningsinformation om nätverk</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Skriv ut tid i felsökningsinformationen</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Fastcoin Wiki for SSL setup instructions)</source>
<translation>SSL-inställningar: (se Fastcoin-wikin för SSL-setup instruktioner)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Välj socks-proxy version att använda (4-5, förvalt: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Skicka trace-/debuginformation till terminalen istället för till debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Skicka trace-/debuginformation till debugger</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Sätt maximal blockstorlek i byte (förvalt: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Sätt minsta blockstorlek i byte (förvalt: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Krymp debug.log filen vid klient start (förvalt: 1 vid ingen -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Signering av transaktion misslyckades</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Ange timeout för uppkoppling i millisekunder (förvalt: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Systemfel:</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Transaktions belopp för fastn</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Transaktionens belopp måste vara positiva</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Transaktionen är för stor</translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Använd UPnP för att mappa den lyssnande porten (förvalt: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Använd UPnP för att mappa den lyssnande porten (förvalt: 1 under lyssning)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Använd en proxy för att nå tor (förvalt: samma som -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Användarnamn för JSON-RPC-anslutningar</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Varning</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Varning: denna version är föråldrad, uppgradering krävs!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>Du måste återskapa databaserna med -reindex för att ändra -txindex</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat korrupt, räddning misslyckades</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Lösenord för JSON-RPC-anslutningar</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Tillåt JSON-RPC-anslutningar från specifika IP-adresser</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Skicka kommandon till klient på <ip> (förvalt: 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>Exekvera kommando när det bästa blocket ändras (%s i cmd är utbytt av blockhash)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Uppgradera plånboken till senaste formatet</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Sätt storleken på nyckelpoolen till <n> (förvalt: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Sök i blockkedjan efter saknade plånboks transaktioner</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Använd OpenSSL (https) för JSON-RPC-anslutningar</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Serverns certifikatfil (förvalt: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Serverns privata nyckel (förvalt: server.pem)</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Accepterade krypteringsalgoritmer (förvalt: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Det här hjälp medelandet</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Det går inte att binda till %s på den här datorn (bind returnerade felmeddelande %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Anslut genom socks-proxy</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Tillåt DNS-sökningar för -addnode, -seednode och -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Laddar adresser...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Fel vid inläsningen av wallet.dat: Plånboken är skadad</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Fastcoin</source>
<translation>Fel vid inläsningen av wallet.dat: Plånboken kräver en senare version av Fastcoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Fastcoin to complete</source>
<translation>Plånboken behöver skrivas om: Starta om Fastcoin för att färdigställa</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Fel vid inläsning av plånboksfilen wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Ogiltig -proxy adress: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Okänt nätverk som anges i -onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Okänd -socks proxy version begärd: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Kan inte matcha -bind adress: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Kan inte matcha -externalip adress: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Ogiltigt belopp för -paytxfee=<belopp>:'%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Ogiltig mängd</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Otillräckligt med fastcoins</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Laddar blockindex...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Lägg till en nod att koppla upp mot och försök att hålla anslutningen öppen</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Fastcoin is probably already running.</source>
<translation>Det går inte att binda till %s på den här datorn. Fastcoin är förmodligen redan igång.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Avgift per KB att lägga till på transaktioner du skickar</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Laddar plånbok...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Kan inte nedgradera plånboken</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Kan inte skriva standardadress</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Söker igen...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Klar med laddning</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Att använda %s alternativet</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Fel</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>Du behöver välja ett rpclösensord i konfigurationsfilen:
%s
Om filen inte existerar, skapa den med filrättigheten endast läsbar för ägaren.</translation>
</message>
</context>
</TS><|fim▁end|> | |
<|file_name|>config.js<|end_file_name|><|fim▁begin|>// Use this file to change prototype configuration.
// Note: prototype config can be overridden using environment variables (eg on heroku)
module.exports = {
// Service name used in header. Eg: 'Renew your passport'
serviceName: "Publish data",
// Default port that prototype runs on
port: '3000',
// Enable or disable password protection on production
useAuth: 'true',
// Force HTTP to redirect to HTTPs on production<|fim▁hole|>
};<|fim▁end|> | useHttps: 'true',
// Cookie warning - update link to service's cookie page.
cookieText: 'GOV.UK uses cookies to make the site simpler. <a href="#" title="Find out more about cookies">Find out more about cookies</a>' |
<|file_name|>plugins-utils.ts<|end_file_name|><|fim▁begin|>import { MediaManagerPluginEntry, MediaPluginEnvType } from 'mmir-lib';
import { PluginExportConfigInfo , RuntimeConfiguration, SettingsBuildEntry , SpeechConfigField , AppConfig , PluginExportInfo , DirectoriesInfo , ResourceConfig , PluginOptions , PluginConfig , TTSPluginSpeechConfig , PluginExportBuildConfig , PluginExportConfigInfoMultiple , PluginExportBuildConfigCreator } from '../index.d';
import path from 'path';
import _ from 'lodash';
import appConfigUtils from '../utils/module-config-init';
import settingsUtils from './settings-utils';
import fileUtils from '../utils/filepath-utils';
import { customMerge , mergeLists } from '../utils/merge-utils';
import logUtils from '../utils/log-utils';
import { WebpackAppConfig } from '../index-webpack.d';
const log = logUtils.log;
const warn = logUtils.warn;
const asrCoreId = 'mmir-plugin-encoder-core.js';
const ttsCoreId = 'audiotts.js';
const applyToAllSpeechConfigs = '__apply-to-all-configs__';
const ALL_SPEECH_CONFIGS_TYPE = settingsUtils.getAllSpeechConfigsType();
/**
* mapping from file-name to load-module-ID in MediaManager/plugin-loading mechanism
* (to be used in configuration.json)
*/
const moduleIdMap = {
'webaudioinput.js': 'mmir-plugin-encoder-core.js',
'mmir-plugin-tts-core-xhr.js': 'audiotts.js'
};
/**
* for webAudioInput module's specific service/implementations:
* mapping from file-name to load-module-ID in MediaManager/plugin-loading mechanism
* (to be used in configuration.json)
*/
const implFileIdMap = {
'webasrgoogleimpl.js': 'mmir-plugin-asr-google-xhr.js',
'webasrnuanceimpl.js': 'mmir-plugin-asr-nuance-xhr.js'
};
const deprecatedImplFileIdMap = {
'webasratntimpl.js': 'webasrAtntImpl.js',
'webasrgooglev1impl.js': 'webasrGooglev1Impl.js'
};
function isAsrPlugin(pluginId: string): boolean {
return /^mmir-plugin-asr-/.test(pluginId);
}
function resolveAndAddAliasPaths(alias: {[aliasId: string]: string}, paths: {[moduleId: string]: string}): {[moduleId: string]: string} {
for(var p in paths){
paths[p] = path.resolve(paths[p]);
alias[p] = paths[p];
}
return paths;
}
function normalizeModName(modName: string): string {
return modName.replace(/\.js$/i, '');
}
function getPluginEntryFrom(confEntry: MediaManagerPluginEntry, pluginConfigList: Array<MediaManagerPluginEntry | string>): MediaManagerPluginEntry | string {
var simpleModName = normalizeModName(confEntry.mod);
var simpleConfigName = normalizeModName(confEntry.config);
var ctx = confEntry.ctx || false;
return pluginConfigList.find(function(entry){
if(typeof entry === 'string'){
return normalizeModName(entry) === simpleModName;
}
return (
normalizeModName(entry.mod) === simpleModName &&
normalizeModName(entry.config) === simpleConfigName &&
(!ctx || entry.ctx === ctx)
);
});
}
function normalizeImplName(implName: string): string {
if(!/\.js$/i.test(implName)){
implName += '.js';
}
return implName.toLowerCase();
}
function normalizeMediaManagerPluginConfig(configList: Array<MediaManagerPluginEntry | string>): void {
var id: string, normalized: string;
configList.forEach(function(entry, index, list){
if(typeof entry === 'string'){
id = implFileIdMap[normalizeImplName(entry)];
if(id){
list[index] = id;
}
} else {
if(typeof entry.mod === 'string'){
id = moduleIdMap[normalizeImplName(entry.mod)];
if(id){
entry.mod = id;
}
}
if(typeof entry.config === 'string'){
normalized = normalizeImplName(entry.config);
id = moduleIdMap[normalized];
if(id){
entry.config = id;
} else if(deprecatedImplFileIdMap[normalized]){
warn('WARN plugin-utils: found deprecated media-plugin '+deprecatedImplFileIdMap[normalized]+' in configuration; this plugin will probably not work ', entry);
}
}
}
});
}
function getConfigDefaultValue(configName: string, pluginInfo: PluginExportConfigInfo): any {
return pluginInfo.defaultValues && pluginInfo.defaultValues[configName];
}
function getSpeechConfigDefaultValue(configName: string, pluginInfo: PluginExportConfigInfo){
return pluginInfo.defaultSpeechValues && pluginInfo.defaultSpeechValues[configName];
}
function getConfigEnv(pluginConfig: PluginConfig | TTSPluginSpeechConfig, pluginInfo: PluginExportConfigInfo, runtimeConfig: RuntimeConfiguration): Array<MediaPluginEnvType | string> {
let env = pluginConfig && (pluginConfig as PluginConfig).env;
if(!env && getConfigDefaultValue('env', pluginInfo)){
env = getConfigDefaultValue('env', pluginInfo);
if(!Array.isArray(env)){
env = [env];
}
}
if(!env && runtimeConfig.mediaManager && runtimeConfig.mediaManager.plugins){
env = Object.keys(runtimeConfig.mediaManager.plugins);
}
if(!env){
//FIXME TODO get default env-definitions from MediaManager!
env = ['browser', 'cordova'];
}
if(typeof env === 'string'){
env = [env];
}
// log('########### using env', env);
return env;
}
/**
* create plugin-entry in mediaManager.plugin configuration
*
* @param {PluginConfig | TTSPluginSpeechConfig} pluginConfig the (user supplied) plugin-configuration
* @param {MMIRPluginInfo} pluginConfigInfo the plugin-info
* @param {string} pluginId the plugin-ID
* @return {MediaManagerPluginEntry} the plugin-entry for mediaManager.plugin
*/
function createConfigEntry(pluginConfig: PluginConfig | TTSPluginSpeechConfig, pluginConfigInfo: PluginExportConfigInfo, pluginId: string): MediaManagerPluginEntry {
var isAsr = isAsrPlugin(pluginId);
var mod = getConfigDefaultValue('mod', pluginConfigInfo);
var type = getConfigDefaultValue('type', pluginConfigInfo);
// log('#### config entry for '+pluginConfigInfo.pluginName+' default mod? ', JSON.stringify(mod));//DEBUG
if(!mod){
// log('#### config entry for '+pluginConfigInfo.pluginName+' default mod? ', mod);//DEBUG
if(type){
mod = type === 'asr'? asrCoreId : ttsCoreId;
if(mod === ttsCoreId && type !== 'tts'){
warn('ERROR plugin-utils: plugin did not specify module-name and a plugin-type other than "asr" and "tts" (type '+type+'), cannot automatically derive module-name for config-entry of ', pluginId);
}
} else {
mod = isAsr? asrCoreId : ttsCoreId;
}
} else {
mod = moduleIdMap[normalizeImplName(mod)] || mod;
}
var config = normalizeImplName(pluginId);//TODO should only create plugin-ID-config, if necessary (i.e. for "sub-module implementations", not for "main module plugins" like android-speech plugin)
var ctx = (pluginConfig && (pluginConfig as PluginConfig).ctx) || void(0);
//{ "mod": "mmir-plugin-encoder-core.js", "config": "mmir-plugin-asr-nuance-xhr.js", "type": "asr"}
return {mod: mod, config: config, type: type, ctx: ctx};
}
/**
* apply config-values from pluginConfig to runtimeConfig into entry pluginConfigInfo.pluginName
*
* @param {MMIRPluginConfig} pluginConfig the plugin-configuration
* @param {Configuration} runtimeConfig the main configuration (JSON-like) object
* @param {Settings} settings the application settings (dicitionaries, speech-configs etc)
* @param {MMIRPluginInfo} pluginConfigInfo the plugin-info
*/
function applyPluginSpeechConfig(pluginConfig: PluginConfig | TTSPluginSpeechConfig, settings: SettingsBuildEntry[], pluginConfigInfo: PluginExportConfigInfo): void {
var speechConfs = pluginConfigInfo.speechConfig;
if(speechConfs){
var applyList: {name: SpeechConfigField, value: any}[] = [], defaultVal: any;
speechConfs.forEach(function(sc){
if(pluginConfig[sc]){
applyList.push({name: sc, value: pluginConfig[sc]});
} else {
defaultVal = getSpeechConfigDefaultValue(sc, pluginConfigInfo);
if(typeof defaultVal !== 'undefined' && defaultVal !== null){
applyList.push({name: sc, value: defaultVal});
}
}
});
if(applyList.length > 0){
var speechConfigs = new Map<string, SettingsBuildEntry>();
settingsUtils.getSettingsFor(settings, 'speech').forEach(function(sc){
speechConfigs.set(sc.id, sc);
});
const allSpeech = settings.find(function(s){ return s.type === ALL_SPEECH_CONFIGS_TYPE; });
if(allSpeech){
speechConfigs.set(ALL_SPEECH_CONFIGS_TYPE, allSpeech);
}
let val: any, name: SpeechConfigField;
applyList.forEach(function(config){
val = config.value;
name = config.name;
if(typeof val !== 'string'){
Object.keys(val).forEach(function(lang){
doApplySpeechConfigValue(name, val[lang], lang, pluginConfigInfo.pluginName, speechConfigs, settings);
});
} else {
doApplySpeechConfigValue(name, val, applyToAllSpeechConfigs, pluginConfigInfo.pluginName, speechConfigs, settings);
}
});
}
}
}
function doApplySpeechConfigValue(name: SpeechConfigField, val: any, lang: string, pluginName: string, speechConfigs: Map<string, SettingsBuildEntry>, settings: SettingsBuildEntry[]): void {
var sc = speechConfigs.get(lang);
if(!sc){
sc = settingsUtils.createSettingsEntryFor(lang === applyToAllSpeechConfigs? ALL_SPEECH_CONFIGS_TYPE : 'speech', {plugins: {}}, lang);
speechConfigs.set(lang, sc);
settings.push(sc);
} else {
if(!sc.value){
//NOTE will crash, if file is a list ... for now, no support for file-list speech-configs!
sc.value = settingsUtils.loadSettingsFrom(sc.file);
}
}
sc.value.plugins = sc.value.plugins || {};
var configEntry = sc.value.plugins[pluginName];
if(!configEntry){
configEntry = {};
sc.value.plugins[pluginName] = configEntry;
}
configEntry[name] = val;
}
/**
* apply config-values from pluginConfig to runtimeConfig into entry pluginConfigInfo.pluginName
*
* @param {MMIRPluginConfig} pluginConfig the plugin-configuration
* @param {Configuration} runtimeConfig the main configuration (JSON-like) object
* @param {MMIRPluginInfo} pluginConfigInfo the plugin-info
*/
function applyPluginConfig(pluginConfig: PluginConfig | TTSPluginSpeechConfig, runtimeConfig: RuntimeConfiguration, pluginConfigInfo: PluginExportConfigInfo): void {
var config = runtimeConfig[pluginConfigInfo.pluginName] || {};
var speechConfs = pluginConfigInfo.speechConfig? new Set(pluginConfigInfo.speechConfig) : null;
for(var c in pluginConfig){
if(c === 'env' || c === 'ctx' || c === 'mod' || (speechConfs && speechConfs.has(c as any))){
continue;
}
config[c] = pluginConfig[c];
}
runtimeConfig[pluginConfigInfo.pluginName] = config;
}
function addConfig(pluginConfig: PluginConfig | TTSPluginSpeechConfig, runtimeConfig: RuntimeConfiguration, settings: SettingsBuildEntry[], pluginConfigInfo: PluginExportConfigInfo, pluginId: string): void {
if(pluginConfig){
applyPluginConfig(pluginConfig, runtimeConfig, pluginConfigInfo);
applyPluginSpeechConfig(pluginConfig, settings, pluginConfigInfo);
}
var pluginType = getConfigDefaultValue('type', pluginConfigInfo);
if(pluginType !== 'custom'){
//-> media plugin, e.g. "asr" or "tts" or "audio"
// (for "custom" plugins: do not create mediaManager entry, inlcude the exported module (already done in addPluginInfos()))
var confEntry = createConfigEntry(pluginConfig, pluginConfigInfo, pluginId);
var env = getConfigEnv(pluginConfig, pluginConfigInfo, runtimeConfig);
// log('#### will add '+pluginConfigInfo.pluginName+' to envs ', env, ' with entry ', confEntry);//DEBUG
if(!runtimeConfig.mediaManager){
runtimeConfig.mediaManager = {};
}
if(!runtimeConfig.mediaManager.plugins){
runtimeConfig.mediaManager.plugins = {};
}
var pConfig = runtimeConfig.mediaManager.plugins;
var pList: Array<MediaManagerPluginEntry | string>, cEntry: MediaManagerPluginEntry | string;
env.forEach(function(e){
pList = pConfig[e];
if(pList){
normalizeMediaManagerPluginConfig(pList);
cEntry = getPluginEntryFrom(confEntry, pList);
if(cEntry){
_.mergeWith(cEntry, confEntry, mergeLists);
} else {
pConfig[e].push(confEntry);
}
} else {
//FIXME this whould also require to add defaults like audio-output
pConfig[e] = [confEntry]
}
});
//TODO add/apply configuration for core-dependency mmir-plugin-encoder-core ~> silence-detection, if specified
}
}
/**
*
* @param target target for merging the build configs (INOUT parameter)
* @param list array of build configs
* @param listOffset offset index from where to start merging from the list (i.e. use 0 to merge from the start of the list)
* @return the merged build-config
*/
function mergeBuildConfigs(target: PluginConfig | TTSPluginSpeechConfig, list: (PluginExportBuildConfig | PluginExportBuildConfigCreator)[], listOffset: number, pluginConfig: PluginConfig | TTSPluginSpeechConfig, runtimeConfig: RuntimeConfiguration, pluginBuildConfig: PluginExportBuildConfig[] | undefined): PluginConfig | TTSPluginSpeechConfig {
for(var i=listOffset, size = list.length; i < size; ++i){
// if entry is a build-config creator function -> replace with created build-config
if(typeof list[i] === 'function'){
list[i] = (list[i] as PluginExportBuildConfigCreator)(pluginConfig, runtimeConfig, pluginBuildConfig);
// if result is a list, do merge into its first entry and replace list[i] with the merged result
if(Array.isArray(list[i])){
list[i] = mergeBuildConfigs(list[i][0], list[i] as (PluginExportBuildConfig | PluginExportBuildConfigCreator)[], 1, pluginConfig, runtimeConfig, pluginBuildConfig);
}
}
customMerge(target, list[i]);
}
return target;
}
function addBuildConfig(pluginConfig: PluginConfig | TTSPluginSpeechConfig, pluginBuildConfig: PluginExportBuildConfig[] | undefined, runtimeConfig: RuntimeConfiguration, appConfig: AppConfig, buildConfigs: (PluginExportBuildConfig | PluginExportBuildConfigCreator)[], pluginId: string){
if(Array.isArray(buildConfigs) && buildConfigs.length > 0){
//NOTE if no pluginConfigInfo.buildConfig is specified, then the plugin does not support build-config settings, so pluginBuildConfig will also be ignored!
// console.log('plugin-utils.addBuildConfig['+pluginId+']: applying plugin\'s build configuration ', pluginConfigInfo.buildConfigs);
// console.log('plugin-utils.addBuildConfig['+pluginId+']: runtimeConfig', runtimeConfig);
var bconfigList = buildConfigs;
var bconfig = bconfigList[0];
if(typeof bconfig === 'function'){
// if entry is a build-config creator function -> do create build-config now
bconfig = bconfig(pluginConfig, runtimeConfig, pluginBuildConfig) || {};//<- if undefined result, bootstrap with empty build-config
if(Array.isArray(bconfig)){
bconfig = mergeBuildConfigs({}, bconfig as (PluginExportBuildConfig | PluginExportBuildConfigCreator)[], 0, pluginConfig, runtimeConfig, pluginBuildConfig);
}
}
bconfig = mergeBuildConfigs(bconfig, bconfigList, 1, pluginConfig, runtimeConfig, pluginBuildConfig);
var usedPluginBuildConfigKeys = new Set<string>();
Object.keys(bconfig).forEach(function(key){
var val = bconfig[key];
if(typeof val === 'undefined'){
<|fim▁hole|> }
if(typeof appConfig[key] === 'undefined'){
if(pluginBuildConfig && typeof pluginBuildConfig[key] !== 'undefined'){
customMerge(val, pluginBuildConfig[key]);
usedPluginBuildConfigKeys.add(key);
}
appConfig[key] = val;
} else if(appConfig[key] && typeof appConfig[key] === 'object' && val && typeof val === 'object'){
//if both build-configs are valid objects:
if(pluginBuildConfig && typeof pluginBuildConfig[key] !== 'undefined'){
//user-supplied plugin-specific build-config overrides general user-supplied build-config:
customMerge(appConfig[key], pluginBuildConfig[key]);
usedPluginBuildConfigKeys.add(key);
}
//... then merge appConfig's value into the plugin's build config
// (i.e. user-supplied build-configuration overrides plugin-build-configuration when merging)
customMerge(val, appConfig[key]);
appConfig[key] = val;
} else if(pluginBuildConfig && typeof pluginBuildConfig[key] !== 'undefined'){
customMerge(appConfig[key], pluginBuildConfig[key]);
usedPluginBuildConfigKeys.add(key);
}
//else: use value of appConfig[key] (i.e. user-supplied build-configuration overrides plugin-build-configuration)
});
//lastly: add config-settings from pluginBuildConfig that were not applied yet:
if(pluginBuildConfig){
Object.keys(pluginBuildConfig).forEach(function(key){
if(usedPluginBuildConfigKeys.has(key)){
return;
}
var val = pluginBuildConfig[key];
if(typeof val === 'undefined'){
return;
}
if(typeof appConfig[key] === 'undefined'){
appConfig[key] = val;
} else if(appConfig[key] && typeof appConfig[key] === 'object' && val && typeof val === 'object'){
//if both build-configs are valid objects: plugin-specific user-supplied config is merged, but overrides general user-supplied build-config:
customMerge(appConfig[key], val);
} else {
//otherwise: plugin-specific user-supplied config overrides general user-supplied build-config:
appConfig[key] = pluginBuildConfig[key];
}
});
}
} else if(pluginBuildConfig){
warn('WARN plugin-utils: encountered user-specified build-configuration for plugin '+pluginId+', but plugin does not not support build-configuration, ignoring user build config ', pluginBuildConfig);
}
//TODO transfere requirejs config unto runtimeConfig?
// if(!runtimeConfig.config){
// runtimeConfig.config = {};
// }
// var pConfig = runtimeConfig.config;
// var pList, cEntry;
// env.forEach(function(e){
// pList = pConfig[e];
// // if(pList){
// // normalizeMediaManagerPluginConfig(pList);
// // cEntry = getPluginEntryFrom(confEntry, pList);
// // if(cEntry){
// // customMerge(cEntry, confEntry);
// // } else {
// // pConfig[e].push(confEntry);
// // }
// // } else {
// // //FIXME this whould also require to add defaults like audio-output
// // pConfig[e] = [confEntry]
// // }
// });
}
function isPluginExportConfigInfoMultiple(pluginInfo: PluginExportConfigInfoMultiple | PluginExportConfigInfo): pluginInfo is PluginExportConfigInfoMultiple {
return Array.isArray(pluginInfo.pluginName);
}
/**
* check if `plugin` is already contained in `pluginList`
*
* NOTE: uses deep comparision, i.e. entries with same id (plugin.id) are considered
* deferent, if their (other) properties differ (even if the IDs match).
*
* @param plugin the plugin
* @param pluginList the list of plugins to check
* @param deepComparison if `true`, makes deep comparision, instead of comparing the IDs
* @return `false` if `plugin` is NOT contained in `pluginList`, otherwise the duplicate entry from `pluginList`
*/
function constainsPlugin(plugin: PluginOptions, pluginList: PluginOptions[] | null | undefined, deepComparison: boolean): false | PluginOptions {
if(!pluginList){
return false;
}
for(var j=pluginList.length-1; j >= 0; --j){
if(deepComparison? _.isEqual(plugin, pluginList[j]) : plugin.id === pluginList[j].id){
return pluginList[j];
}
}
return false;
}
function processDuplicates(pluginList: PluginOptions[], removeFromList?: boolean): Map<string, PluginOptions[]> {
const map = new Map<string, PluginOptions[]>();
for(let i=pluginList.length-1; i >= 0; --i){
const plugin = pluginList[i];
let duplicates: PluginOptions[] = map.get(plugin.id);
if(!duplicates){
duplicates = [plugin];
map.set(plugin.id, duplicates);
} else {
let hasDuplicate = constainsPlugin(plugin, duplicates, false);
if(!hasDuplicate){
duplicates.push(plugin);
} else if(removeFromList) {
pluginList.splice(i, 1);
}
}
}
return map;
}
function normalizePluginEntry(plugin: PluginOptions | string): PluginOptions {
const id = typeof plugin === 'string'? plugin : plugin.id;
return typeof plugin !== 'string'? plugin : {id: id};
}
export = {
addPluginInfos: function(pluginSettings: PluginOptions, appConfig: WebpackAppConfig, _directories: DirectoriesInfo, resourcesConfig: ResourceConfig, runtimeConfig: RuntimeConfiguration, settings: SettingsBuildEntry[]){
const workersList = resourcesConfig.workers;
const binFilesList = resourcesConfig.fileResources;
const binFilesPaths = resourcesConfig.resourcesPaths;
// const _textFilesList = resourcesConfig.textResources;
const pluginId = pluginSettings.id;
const pluginConfig = pluginSettings.config;
const pluginBuildConfig = pluginSettings.build;
const mode = pluginSettings.mode;
const pluginInfo: PluginExportInfo = require(pluginId + '/module-ids.gen.js');
const paths = pluginInfo.getAll('paths', mode, true) as {[moduleId: string]: string};
resolveAndAddAliasPaths(appConfig.paths, paths)
const workers = pluginInfo.getAll('workers', mode) as string[];
workers.forEach(function(w){
workersList.push(paths[w]);
});
const includeModules = pluginInfo.getAll('modules', mode) as string[];
includeModules.forEach(function(mod){
appConfigUtils.addIncludeModule(appConfig, mod, paths[mod]);
});
const includeFiles = pluginInfo.getAll('files', mode) as string[];
includeFiles.forEach(function(mod){
const modPath = paths[mod];
binFilesList.push(modPath);
//NOTE the module-ID for exported files is <plugin ID>/<file name without extension>
// -> specify the include-path for the files (i.e. relative path to which the file is copied) as
// <plugin ID>/<file name>
binFilesPaths[fileUtils.normalizePath(modPath)] = path.normalize(path.join(path.dirname(mod), path.basename(modPath)));
// log(' ############### adding exported (raw) file for plugin '+pluginId+' ['+mod+'] -> ', modPath);//DEBUG
appConfigUtils.addIncludeModule(appConfig, mod, modPath);
});
const pluginConfigInfo = require(pluginId + '/module-config.gen.js') as PluginExportConfigInfo;
if(pluginConfigInfo.pluginName){
if(isPluginExportConfigInfoMultiple(pluginConfigInfo)){
pluginConfigInfo.pluginName.forEach(function(pluginName){
addConfig(pluginConfig, runtimeConfig, settings, pluginConfigInfo.plugins[pluginName], pluginId);
const buildConfigs = pluginInfo.getBuildConfig(pluginName);
// backwards compatiblity when generated by mmir-plugin-exports < 2.3.0 (would not include build-configs of dependencies):
if(!buildConfigs || buildConfigs.length === 0){
if(pluginConfigInfo.plugins[pluginName].buildConfigs) customMerge(buildConfigs, pluginConfigInfo.plugins[pluginName].buildConfigs);
if(pluginConfigInfo.buildConfigs) customMerge(buildConfigs, pluginConfigInfo.buildConfigs);
}
addBuildConfig(pluginConfig, pluginBuildConfig, runtimeConfig, appConfig, buildConfigs, pluginId);
});
} else {
const buildConfigs = pluginInfo.getBuildConfig();
// backwards compatiblity when generated by mmir-plugin-exports < 2.3.0 (would not include build-configs of dependencies):
if((!buildConfigs || buildConfigs.length === 0) && pluginConfigInfo.buildConfigs){
customMerge(buildConfigs, pluginConfigInfo.buildConfigs);
}
addConfig(pluginConfig, runtimeConfig, settings, pluginConfigInfo, pluginId);
addBuildConfig(pluginConfig, pluginBuildConfig, runtimeConfig, appConfig, buildConfigs, pluginId);
}
} else {
warn('ERROR plugin-utils: invalid module-config.js for plugin '+pluginId+': missing field pluginName ', pluginConfigInfo);
}
log('plugin-utils: addPluginInfos() -> paths ', paths, ', workers ', workers, ', include modules ', includeModules, runtimeConfig);//DEBUG
},
processDuplicates: processDuplicates,
constainsPlugin: constainsPlugin,
normalizePluginEntry: normalizePluginEntry
};<|fim▁end|> | return;
|
<|file_name|>BibTeXTechReport.java<|end_file_name|><|fim▁begin|>package ecologylab.serialization.deserializers.parsers.bibtex.entrytypes;
import ecologylab.serialization.annotations.bibtex_tag;
import ecologylab.serialization.annotations.bibtex_type;
import ecologylab.serialization.annotations.simpl_inherit;
import ecologylab.serialization.annotations.simpl_scalar;
import ecologylab.serialization.annotations.simpl_tag;
@simpl_inherit
@simpl_tag("bibtex_techreport")
@bibtex_type("techreport")
public class BibTeXTechReport extends AbstractBibTeXEntry
{
// required fields
@simpl_scalar
@bibtex_tag("institution")
private String institution;
@simpl_scalar
@bibtex_tag("type")
private String type;
@simpl_scalar
@bibtex_tag("number")
private long number;
@simpl_scalar
@bibtex_tag("address")
private String address;
public String getInstitution()
{
<|fim▁hole|>
public void setInstitution(String institution)
{
this.institution = institution;
}
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
public long getNumber()
{
return number;
}
public void setNumber(long number)
{
this.number = number;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
}<|fim▁end|> | return institution;
}
|
<|file_name|>definitions.cpp<|end_file_name|><|fim▁begin|>/*
SPDX-FileCopyrightText: 2007 Jean-Baptiste Mardelle <[email protected]>
SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
*/
#include "definitions.h"
#include <klocalizedstring.h>
#include <QColor>
#include <utility>
#ifdef CRASH_AUTO_TEST
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#pragma GCC diagnostic ignored "-Wfloat-equal"
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wpedantic"
#include <rttr/registration>
#pragma GCC diagnostic pop
RTTR_REGISTRATION
{
using namespace rttr;
// clang-format off
registration::enumeration<GroupType>("GroupType")(
value("Normal", GroupType::Normal),
value("Selection", GroupType::Selection),
value("AVSplit", GroupType::AVSplit),
value("Leaf", GroupType::Leaf)
);
registration::enumeration<PlaylistState::ClipState>("PlaylistState")(
value("VideoOnly", PlaylistState::VideoOnly),
value("AudioOnly", PlaylistState::AudioOnly),
value("Disabled", PlaylistState::Disabled)
);
// clang-format on
}
#endif
QDebug operator<<(QDebug qd, const ItemInfo &info)
{
qd << "ItemInfo " << &info;
qd << "\tTrack" << info.track;
qd << "\tStart pos: " << info.startPos.toString();
qd << "\tEnd pos: " << info.endPos.toString();
qd << "\tCrop start: " << info.cropStart.toString();
qd << "\tCrop duration: " << info.cropDuration.toString();
return qd.maybeSpace();
}
CommentedTime::CommentedTime()
: m_time(GenTime(0))
{
}
CommentedTime::CommentedTime(const GenTime &time, QString comment, int markerType)
: m_time(time)
, m_comment(std::move(comment))
, m_type(markerType)
{
}
CommentedTime::CommentedTime(const QString &hash, const GenTime &time)
: m_time(time)
, m_comment(hash.section(QLatin1Char(':'), 1))
, m_type(hash.section(QLatin1Char(':'), 0, 0).toInt())
{
}
QString CommentedTime::comment() const
{
return (m_comment.isEmpty() ? i18n("Marker") : m_comment);
}
GenTime CommentedTime::time() const
{
return m_time;
}
void CommentedTime::setComment(const QString &comm)
{
m_comment = comm;
}
void CommentedTime::setTime(const GenTime &t)
{
m_time = t;
}
void CommentedTime::setMarkerType(int newtype)
{
m_type = newtype;
}
QString CommentedTime::hash() const
{
return QString::number(m_type) + QLatin1Char(':') + (m_comment.isEmpty() ? i18n("Marker") : m_comment);
}
int CommentedTime::markerType() const
{
return m_type;
}
<|fim▁hole|>bool CommentedTime::operator>(const CommentedTime &op) const
{
return m_time > op.time();
}
bool CommentedTime::operator<(const CommentedTime &op) const
{
return m_time < op.time();
}
bool CommentedTime::operator>=(const CommentedTime &op) const
{
return m_time >= op.time();
}
bool CommentedTime::operator<=(const CommentedTime &op) const
{
return m_time <= op.time();
}
bool CommentedTime::operator==(const CommentedTime &op) const
{
return m_time == op.time();
}
bool CommentedTime::operator!=(const CommentedTime &op) const
{
return m_time != op.time();
}
const QString groupTypeToStr(GroupType t)
{
switch (t) {
case GroupType::Normal:
return QStringLiteral("Normal");
case GroupType::Selection:
return QStringLiteral("Selection");
case GroupType::AVSplit:
return QStringLiteral("AVSplit");
case GroupType::Leaf:
return QStringLiteral("Leaf");
}
Q_ASSERT(false);
return QString();
}
GroupType groupTypeFromStr(const QString &s)
{
std::vector<GroupType> types{GroupType::Selection, GroupType::Normal, GroupType::AVSplit, GroupType::Leaf};
for (const auto &t : types) {
if (s == groupTypeToStr(t)) {
return t;
}
}
Q_ASSERT(false);
return GroupType::Normal;
}
std::pair<bool, bool> stateToBool(PlaylistState::ClipState state)
{
return {state == PlaylistState::VideoOnly, state == PlaylistState::AudioOnly};
}
PlaylistState::ClipState stateFromBool(std::pair<bool, bool> av)
{
Q_ASSERT(!av.first || !av.second);
if (av.first) {
return PlaylistState::VideoOnly;
} else if (av.second) {
return PlaylistState::AudioOnly;
} else {
return PlaylistState::Disabled;
}
}
SubtitledTime::SubtitledTime()
: m_starttime(0)
, m_endtime(0)
{
}
SubtitledTime::SubtitledTime(const GenTime &start, QString sub, const GenTime &end)
: m_starttime(start)
, m_subtitle(std::move(sub))
, m_endtime(end)
{
}
QString SubtitledTime::subtitle() const
{
return m_subtitle;
}
GenTime SubtitledTime::start() const
{
return m_starttime;
}
GenTime SubtitledTime::end() const
{
return m_endtime;
}
void SubtitledTime::setSubtitle(const QString& sub)
{
m_subtitle = sub;
}
void SubtitledTime::setEndTime(const GenTime& end)
{
m_endtime = end;
}
bool SubtitledTime::operator>(const SubtitledTime& op) const
{
return(m_starttime > op.m_starttime && m_endtime > op.m_endtime && m_starttime > op.m_endtime);
}
bool SubtitledTime::operator<(const SubtitledTime& op) const
{
return(m_starttime < op.m_starttime && m_endtime < op.m_endtime && m_endtime < op.m_starttime);
}
bool SubtitledTime::operator==(const SubtitledTime& op) const
{
return(m_starttime == op.m_starttime && m_endtime == op.m_endtime);
}
bool SubtitledTime::operator!=(const SubtitledTime& op) const
{
return(m_starttime != op.m_starttime && m_endtime != op.m_endtime);
}<|fim▁end|> | |
<|file_name|>base.py<|end_file_name|><|fim▁begin|># emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""The freesurfer module provides basic functions for interfacing with
freesurfer tools.
Currently these tools are supported:
* Dicom2Nifti: using mri_convert
* Resample: using mri_convert
Examples
--------
See the docstrings for the individual classes for 'working' examples.
"""
__docformat__ = 'restructuredtext'
from builtins import object
import os
from ..base import (CommandLine, Directory,
CommandLineInputSpec, isdefined,
traits, TraitedSpec, File)
from ...utils.filemanip import fname_presuffix
class Info(object):
""" Freesurfer subject directory and version information.
Examples
--------
>>> from nipype.interfaces.freesurfer import Info
>>> Info.version() # doctest: +SKIP
>>> Info.subjectsdir() # doctest: +SKIP
"""
@staticmethod
def version():
"""Check for freesurfer version on system
Find which freesurfer is being used....and get version from
/path/to/freesurfer/build-stamp.txt
Returns
-------
version : string
version number as string
or None if freesurfer version not found
"""
fs_home = os.getenv('FREESURFER_HOME')
if fs_home is None:
return None
versionfile = os.path.join(fs_home, 'build-stamp.txt')
if not os.path.exists(versionfile):
return None
fid = open(versionfile, 'rt')
version = fid.readline()
fid.close()
return version
@classmethod
def subjectsdir(cls):
"""Check the global SUBJECTS_DIR
Parameters
----------
subjects_dir : string
The system defined subjects directory
Returns
-------
subject_dir : string
Represents the current environment setting of SUBJECTS_DIR
"""
if cls.version():
return os.environ['SUBJECTS_DIR']
return None
class FSTraitedSpec(CommandLineInputSpec):
subjects_dir = Directory(exists=True, desc='subjects directory')
class FSCommand(CommandLine):
"""General support for FreeSurfer commands.
Every FS command accepts 'subjects_dir' input.
"""
input_spec = FSTraitedSpec
_subjects_dir = None
def __init__(self, **inputs):
super(FSCommand, self).__init__(**inputs)
self.inputs.on_trait_change(self._subjects_dir_update, 'subjects_dir')
if not self._subjects_dir:
self._subjects_dir = Info.subjectsdir()
if not isdefined(self.inputs.subjects_dir) and self._subjects_dir:
self.inputs.subjects_dir = self._subjects_dir
self._subjects_dir_update()
def _subjects_dir_update(self):
if self.inputs.subjects_dir:
self.inputs.environ.update({'SUBJECTS_DIR':<|fim▁hole|> self.inputs.subjects_dir})
@classmethod
def set_default_subjects_dir(cls, subjects_dir):
cls._subjects_dir = subjects_dir
@property
def version(self):
return Info.version()
def run(self, **inputs):
if 'subjects_dir' in inputs:
self.inputs.subjects_dir = inputs['subjects_dir']
self._subjects_dir_update()
return super(FSCommand, self).run(**inputs)
def _gen_fname(self, basename, fname=None, cwd=None, suffix='_fs',
use_ext=True):
'''Define a generic mapping for a single outfile
The filename is potentially autogenerated by suffixing inputs.infile
Parameters
----------
basename : string (required)
filename to base the new filename on
fname : string
if not None, just use this fname
cwd : string
prefix paths with cwd, otherwise os.getcwd()
suffix : string
default suffix
'''
if basename == '':
msg = 'Unable to generate filename for command %s. ' % self.cmd
msg += 'basename is not set!'
raise ValueError(msg)
if cwd is None:
cwd = os.getcwd()
fname = fname_presuffix(basename, suffix=suffix,
use_ext=use_ext, newpath=cwd)
return fname
@property
def version(self):
ver = Info.version()
if ver:
if 'dev' in ver:
return ver.rstrip().split('-')[-1] + '.dev'
else:
return ver.rstrip().split('-v')[-1]
class FSScriptCommand(FSCommand):
""" Support for Freesurfer script commands with log inputs.terminal_output """
_terminal_output = 'file'
_always_run = False
def __init__(self, **inputs):
super(FSScriptCommand, self).__init__(**inputs)
self.set_default_terminal_output(self._terminal_output)
def _list_outputs(self):
outputs = self._outputs().get()
outputs['log_file'] = os.path.abspath('stdout.nipype')
return outputs
class FSScriptOutputSpec(TraitedSpec):
log_file = File('stdout.nipype', usedefault=True,
exists=True, desc="The output log")
class FSTraitedSpecOpenMP(FSTraitedSpec):
num_threads = traits.Int(desc='allows for specifying more threads')
class FSCommandOpenMP(FSCommand):
"""Support for FS commands that utilize OpenMP
Sets the environment variable 'OMP_NUM_THREADS' to the number
of threads specified by the input num_threads.
"""
input_spec = FSTraitedSpecOpenMP
_num_threads = None
def __init__(self, **inputs):
super(FSCommandOpenMP, self).__init__(**inputs)
self.inputs.on_trait_change(self._num_threads_update, 'num_threads')
if not self._num_threads:
self._num_threads = os.environ.get('OMP_NUM_THREADS', None)
if not isdefined(self.inputs.num_threads) and self._num_threads:
self.inputs.num_threads = int(self._num_threads)
self._num_threads_update()
def _num_threads_update(self):
if self.inputs.num_threads:
self.inputs.environ.update(
{'OMP_NUM_THREADS': str(self.inputs.num_threads)})
def run(self, **inputs):
if 'num_threads' in inputs:
self.inputs.num_threads = inputs['num_threads']
self._num_threads_update()
return super(FSCommandOpenMP, self).run(**inputs)<|fim▁end|> | |
<|file_name|>a00278.js<|end_file_name|><|fim▁begin|>var a00278 =
[<|fim▁hole|><|fim▁end|> | [ "c_blob_comparator", "a00278.html#adf90dfe481e3980859ab92739b51caa6", null ]
]; |
<|file_name|>GrTraitField.java<|end_file_name|><|fim▁begin|>// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.psi.impl.synthetic;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition;
import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil;
import org.jetbrains.plugins.groovy.transformations.TransformationContext;
public class GrTraitField extends GrLightField implements PsiMirrorElement {
private static final Logger LOG = Logger.getInstance(GrTraitField.class);
private final PsiField myField;
public GrTraitField(@NotNull GrField field, GrTypeDefinition clazz, PsiSubstitutor substitutor, @Nullable TransformationContext context) {
super(clazz, getNewNameForField(field), substitutor.substitute(field.getType()), field);
GrLightModifierList modifierList = getModifierList();
for (String modifier : PsiModifier.MODIFIERS) {
boolean hasModifierProperty;
GrModifierList fieldModifierList = field.getModifierList();
if (context == null || fieldModifierList == null) {
hasModifierProperty = field.hasModifierProperty(modifier);
} else {
hasModifierProperty = context.hasModifierProperty(fieldModifierList, modifier);<|fim▁hole|> if (hasModifierProperty) {
modifierList.addModifier(modifier);
}
}
modifierList.copyAnnotations(field.getModifierList());
myField = field;
}
@NotNull
private static String getNewNameForField(@NotNull PsiField field) {
PsiClass containingClass = field.getContainingClass();
LOG.assertTrue(containingClass != null);
return GrTraitUtil.getTraitFieldPrefix(containingClass) + field.getName();
}
@NotNull
@Override
public PsiField getPrototype() {
return myField;
}
}<|fim▁end|> | } |
<|file_name|>optionsdialog.cpp<|end_file_name|><|fim▁begin|>// Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "optionsdialog.h"
#include "ui_optionsdialog.h"<|fim▁hole|>#include "optionsmodel.h"
#include <QDir>
#include <QIntValidator>
#include <QLocale>
#include <QMessageBox>
OptionsDialog::OptionsDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OptionsDialog),
model(0),
mapper(0),
fRestartWarningDisplayed_Proxy(false),
fRestartWarningDisplayed_Lang(false),
fProxyIpValid(true)
{
ui->setupUi(this);
/* Network elements init */
#ifndef USE_UPNP
ui->mapPortUpnp->setEnabled(false);
#endif
ui->proxyIp->setEnabled(false);
ui->proxyPort->setEnabled(false);
ui->proxyPort->setValidator(new QIntValidator(1, 65535, this));
ui->socksVersion->setEnabled(false);
ui->socksVersion->addItem("5", 5);
ui->socksVersion->addItem("4", 4);
ui->socksVersion->setCurrentIndex(0);
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool)));
connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy()));
ui->proxyIp->installEventFilter(this);
/* Window elements init */
#ifdef Q_OS_MAC
/* remove Window tab on Mac */
ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow));
#endif
/* Display elements init */
QDir translations(":translations");
ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant(""));
foreach(const QString &langStr, translations.entryList())
{
QLocale locale(langStr);
/** check if the locale name consists of 2 parts (language_country) */
if(langStr.contains("_"))
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
else
{
#if QT_VERSION >= 0x040800
/** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */
ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr));
#else
/** display language strings as "language (locale name)", e.g. "German (de)" */
ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr));
#endif
}
}
ui->unit->setModel(new BitcoinUnits(this));
/* Widget-to-option mapper */
mapper = new MonitoredDataMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* enable apply button when data modified */
connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton()));
/* disable apply button when new data loaded */
connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton()));
/* setup/change UI elements when proxy IP is invalid/valid */
connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool)));
}
OptionsDialog::~OptionsDialog()
{
delete ui;
}
void OptionsDialog::setModel(OptionsModel *model)
{
this->model = model;
if(model)
{
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
mapper->setModel(model);
setMapper();
mapper->toFirst();
}
/* update the display unit, to not use the default ("BTC") */
updateDisplayUnit();
/* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */
connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang()));
/* disable apply button after settings are loaded as there is nothing to save */
disableApplyButton();
}
void OptionsDialog::setMapper()
{
/* Main */
mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup);
/* Wallet */
mapper->addMapping(ui->transactionFee, OptionsModel::Fee);
mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange);
/* Network */
mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP);
mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse);
mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP);
mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort);
mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion);
/* Window */
#ifndef Q_OS_MAC
mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray);
mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose);
#endif
/* Display */
mapper->addMapping(ui->lang, OptionsModel::Language);
mapper->addMapping(ui->unit, OptionsModel::DisplayUnit);
mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses);
mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures);
}
void OptionsDialog::enableApplyButton()
{
ui->applyButton->setEnabled(true);
}
void OptionsDialog::disableApplyButton()
{
ui->applyButton->setEnabled(false);
}
void OptionsDialog::enableSaveButtons()
{
/* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */
if(fProxyIpValid)
setSaveButtonState(true);
}
void OptionsDialog::disableSaveButtons()
{
setSaveButtonState(false);
}
void OptionsDialog::setSaveButtonState(bool fState)
{
ui->applyButton->setEnabled(fState);
ui->okButton->setEnabled(fState);
}
void OptionsDialog::on_resetButton_clicked()
{
if(model)
{
// confirmation dialog
QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"),
tr("Some settings may require a client restart to take effect.") + "<br><br>" + tr("Do you want to proceed?"),
QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel);
if(btnRetVal == QMessageBox::Cancel)
return;
disableApplyButton();
/* disable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = true;
/* reset all options and save the default values (QSettings) */
model->Reset();
mapper->toFirst();
mapper->submit();
/* re-enable restart warning messages display */
fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = false;
}
}
void OptionsDialog::on_okButton_clicked()
{
mapper->submit();
accept();
}
void OptionsDialog::on_cancelButton_clicked()
{
reject();
}
void OptionsDialog::on_applyButton_clicked()
{
mapper->submit();
disableApplyButton();
}
void OptionsDialog::showRestartWarning_Proxy()
{
if(!fRestartWarningDisplayed_Proxy)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Potcoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Proxy = true;
}
}
void OptionsDialog::showRestartWarning_Lang()
{
if(!fRestartWarningDisplayed_Lang)
{
QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Potcoin."), QMessageBox::Ok);
fRestartWarningDisplayed_Lang = true;
}
}
void OptionsDialog::updateDisplayUnit()
{
if(model)
{
/* Update transactionFee with the current unit */
ui->transactionFee->setDisplayUnit(model->getDisplayUnit());
}
}
void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState)
{
// this is used in a check before re-enabling the save buttons
fProxyIpValid = fState;
if(fProxyIpValid)
{
enableSaveButtons();
ui->statusLabel->clear();
}
else
{
disableSaveButtons();
object->setValid(fProxyIpValid);
ui->statusLabel->setStyleSheet("QLabel { color: red; }");
ui->statusLabel->setText(tr("The supplied proxy address is invalid."));
}
}
bool OptionsDialog::eventFilter(QObject *object, QEvent *event)
{
if(event->type() == QEvent::FocusOut)
{
if(object == ui->proxyIp)
{
CService addr;
/* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */
emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr));
}
}
return QDialog::eventFilter(object, event);
}<|fim▁end|> |
#include "bitcoinunits.h"
#include "monitoreddatamapper.h"
#include "netbase.h" |
<|file_name|>MainActivity.java<|end_file_name|><|fim▁begin|>package com.pajato.android.gamechat;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.identitytoolkit.GitkitClient;
import com.google.identitytoolkit.GitkitUser;
import com.google.identitytoolkit.IdToken;
import com.pajato.android.gamechat.chat.ChatManager;
import com.pajato.android.gamechat.chat.ChatManagerImpl;
import com.pajato.android.gamechat.game.GameManager;
import com.pajato.android.gamechat.game.GameManagerImpl;
import com.pajato.android.gamechat.account.AccountManager;
import com.pajato.android.gamechat.account.AccountManagerImpl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
/**
* The main activity ... <tbd>
*/
public class MainActivity extends AppCompatActivity implements GitkitClient.SignInCallbacks {
// Public class constants
// Private class constants
/** The logcat tag constant. */
private static final String TAG = MainActivity.class.getSimpleName();
/** The preferences file name. */
private static final String PREFS = "GameChatPrefs";
// Private instance variables
/** The account manager handles all things related to accounts: signing in, switching accounts, setup, aliases, etc. */
private AccountManager mAccountManager;
/** The chat manager handles all things chat: accessing rooms, history, settings, etc. */
private ChatManager mChatManager;
/** The game manager handles all game related activities: mode, players, game selection, etc. */
private GameManager mGameManager;
/** The top level container. */
private DrawerLayout mDrawerLayout;
// Public instance methods
/**
* Override to implement a successful login by ensuring that the account is registered and up to date..
*/
@Override public void onSignIn(IdToken idToken, GitkitUser user) {
// Create a session for the given user by saving the token in the account.
Log.d(TAG, String.format("Processing a successful signin: idToken/user {%s/%s}.", idToken, user));
Toast.makeText(this, "You are successfully signed in to GameChat", Toast.LENGTH_LONG).show();
mAccountManager.handleSigninSuccess(user.getUserProfile(), idToken, getSharedPreferences(PREFS, 0));
}
/** Override to implement a failed signin by posting a message to the User. */
@Override public void onSignInFailed() {
// Post a message and head back to the main screen.
Log.d(TAG, "Processing a failed signin attempt.");
Toast.makeText(this, "Sign in failed", Toast.LENGTH_LONG).show();
mAccountManager.handleSigninFailed();
}
// Protected instance methods
/**
* Handle the signin activity result value by passing it back to the account manager.
*
* @param requestCode ...
* @param resultCode ...
* @param intent ...
*/
@Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
// Pass the event off to the account manager for processing.
Log.d(TAG, String.format("Processing a signin result: requestCode/resultCode/intent {%d/%d/%s}.", requestCode, resultCode, intent));
if (!mAccountManager.handleSigninResult(requestCode, resultCode, intent)) {
Log.d(TAG, "Signin result was not processed by the GIT.");
super.onActivityResult(requestCode, resultCode, intent);
}
}
/**
* Set up the app per the characteristics of the running device.
*
* @see android.app.Activity#onCreate(Bundle)
*/
@Override protected void onCreate(Bundle savedInstanceState) {
// Initialize the app state as necessary.
super.onCreate(savedInstanceState);
mAccountManager = new AccountManagerImpl(savedInstanceState, getSharedPreferences(PREFS, 0));
mGameManager = new GameManagerImpl(savedInstanceState);
mChatManager = new ChatManagerImpl(savedInstanceState);
// Start the app. Setup the top level views: toolbar, action bar and drawer layout.
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu);
actionBar.setDisplayHomeAsUpEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Setup the navigation view and the main app pager.
//
// Todo: extend this to work with specific device classes based on size to provide optimal layouts.
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationHandler());
GameChatPagerAdapter adapter = new GameChatPagerAdapter(getSupportFragmentManager());
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
// Determine if an account needs to be set up.
if (!mAccountManager.hasAccount()) {
// There is no account yet. Give the User a chance to sign in even though it is not strictly necessary, for
// example when playing games with the computer.
mAccountManager.signin(this);
}
}
/**
* Override to implement by passing a given intent to the account manager to see if it is consuming the intent.
*
* @param intent The given Intent object.
*/
@Override protected void onNewIntent(final Intent intent) {
// Give the account manager a chance to consume the intent.
if (!mAccountManager.handleIntent(intent)) {
Log.d(TAG, "Signin intent was not processed by the GIT.");
super.onNewIntent(intent);
}
}
// Private instance methods
// Private classes
/**
* Provide a class to handle the view pager setup.
*/
private class GameChatPagerAdapter extends FragmentStatePagerAdapter {
/**
* A list of panels ordered left to right.
*/
private List<Panel> panelList = new ArrayList<>();
/**
* Build an adapter to handle the panels.
*
* @param fm The fragment manager.
*/
public GameChatPagerAdapter(final FragmentManager fm) {
super(fm);
panelList.add(Panel.ROOMS);
panelList.add(Panel.CHAT);
panelList.add(Panel.MEMBERS);
panelList.add(Panel.GAME);
}
@Override
public Fragment getItem(int position) {
return panelList.get(position).getFragment();
}
@Override
public int getCount() {
return panelList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return MainActivity.this.getString(panelList.get(position).getTitleId());
}
}
/**
* Provide a handler for navigation panel selections.
*/
private class NavigationHandler implements NavigationView.OnNavigationItemSelectedListener {
@Override
public boolean onNavigationItemSelected(final MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
Toast.makeText(MainActivity.this, menuItem.getTitle(), Toast.LENGTH_LONG).show();<|fim▁hole|>}<|fim▁end|> | return true;
}
}
|
<|file_name|>test_list.py<|end_file_name|><|fim▁begin|>tests=[
("python","UnitTestBuildComposite.py",{}),
("python","UnitTestScreenComposite.py",{}),
("python","UnitTestAnalyzeComposite.py",{}),
]
for dir in ['Cluster','Composite','Data','DecTree','Descriptors','FeatureSelect','InfoTheory','KNN','ModelPackage','NaiveBayes','Neural','SLT']:<|fim▁hole|> tests.append(('python','test_list.py',{'dir':dir}))
longTests=[
]
if __name__=='__main__':
import sys
from rdkit import TestRunner
failed,tests = TestRunner.RunScript('test_list.py',0,1)
sys.exit(len(failed))<|fim▁end|> | |
<|file_name|>setup-no-deprecations.js<|end_file_name|><|fim▁begin|>import QUnit from 'qunit';
import { registerDeprecationHandler } from '@ember/debug';
let isRegistered = false;
let deprecations = new Set();
let expectedDeprecations = new Set();
// Ignore deprecations that are not caused by our own code, and which we cannot fix easily.
const ignoredDeprecations = [
// @todo remove when we can land https://github.com/emberjs/ember-render-modifiers/pull/33 here
/Versions of modifier manager capabilities prior to 3\.22 have been deprecated/,
/Usage of the Ember Global is deprecated./,
/import .* directly from/,
/Use of `assign` has been deprecated/,
];
export default function setupNoDeprecations({ beforeEach, afterEach }) {
beforeEach(function () {
deprecations.clear();
expectedDeprecations.clear();
if (!isRegistered) {
registerDeprecationHandler((message, options, next) => {
if (!ignoredDeprecations.some((regex) => message.match(regex))) {
deprecations.add(message);
}
next(message, options);
});
isRegistered = true;
}
});<|fim▁hole|> if (deprecations.size > expectedDeprecations.size) {
assert.ok(
false,
`Expected ${expectedDeprecations.size} deprecations, found: ${[...deprecations]
.map((msg) => `"${msg}"`)
.join(', ')}`
);
}
});
QUnit.assert.deprecations = function (count) {
if (count === undefined) {
this.ok(deprecations.size, 'Expected deprecations during test.');
} else {
this.equal(deprecations.size, count, `Expected ${count} deprecation(s) during test.`);
}
deprecations.forEach((d) => expectedDeprecations.add(d));
};
QUnit.assert.deprecationsInclude = function (expected) {
let found = [...deprecations].find((deprecation) => deprecation.includes(expected));
this.pushResult({
result: !!found,
actual: deprecations,
message: `expected to find \`${expected}\` deprecation. Found ${[...deprecations]
.map((d) => `"${d}"`)
.join(', ')}`,
});
if (found) {
expectedDeprecations.add(found);
}
};
}<|fim▁end|> |
afterEach(function (assert) {
// guard in if instead of using assert.equal(), to not make assert.expect() fail |
<|file_name|>MissingDeprecatedAnnotationInspection.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2003-2019 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.siyeh.ig.javadoc;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.pom.Navigatable;
import com.intellij.psi.*;
import com.intellij.psi.javadoc.PsiDocComment;
import com.intellij.psi.javadoc.PsiDocTag;
import com.intellij.psi.javadoc.PsiDocTagValue;
import com.intellij.psi.javadoc.PsiDocToken;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import com.siyeh.ig.InspectionGadgetsFix;
import com.siyeh.ig.psiutils.MethodUtils;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
final class MissingDeprecatedAnnotationInspection extends BaseInspection {
@SuppressWarnings("PublicField") public boolean warnOnMissingJavadoc = false;
@Override
@NotNull
protected String buildErrorString(Object... infos) {
final boolean annotationWarning = ((Boolean)infos[0]).booleanValue();
return annotationWarning
? InspectionGadgetsBundle.message("missing.deprecated.annotation.problem.descriptor")
: InspectionGadgetsBundle.message("missing.deprecated.tag.problem.descriptor");
}
@NotNull
@Override
public JComponent createOptionsPanel() {
return new SingleCheckboxOptionsPanel(InspectionGadgetsBundle.message("missing.deprecated.tag.option"),
this, "warnOnMissingJavadoc");
}
@Override
public boolean runForWholeFile() {
return true;
}
@Override
protected InspectionGadgetsFix buildFix(Object... infos) {
final boolean annotationWarning = ((Boolean)infos[0]).booleanValue();
return annotationWarning ? new MissingDeprecatedAnnotationFix() : new MissingDeprecatedTagFix();
}
private static class MissingDeprecatedAnnotationFix extends InspectionGadgetsFix {
@Override
@NotNull
public String getFamilyName() {
return InspectionGadgetsBundle.message("missing.deprecated.annotation.add.quickfix");
}
@Override
public void doFix(Project project, ProblemDescriptor descriptor) {
final PsiElement identifier = descriptor.getPsiElement();
final PsiModifierListOwner parent = (PsiModifierListOwner)identifier.getParent();
if (parent == null) {
return;
}
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
final PsiAnnotation annotation = factory.createAnnotationFromText("@java.lang.Deprecated", parent);
final PsiModifierList modifierList = parent.getModifierList();
if (modifierList == null) {
return;
}
modifierList.addAfter(annotation, null);
}
}
private static class MissingDeprecatedTagFix extends InspectionGadgetsFix {
private static final String DEPRECATED_TAG_NAME = "deprecated";
@Nls(capitalization = Nls.Capitalization.Sentence)
@NotNull
@Override
public String getFamilyName() {
return InspectionGadgetsBundle.message("missing.add.deprecated.javadoc.tag.quickfix");
}
@Override
protected void doFix(Project project, ProblemDescriptor descriptor) {
PsiElement parent = descriptor.getPsiElement().getParent();
if (!(parent instanceof PsiJavaDocumentedElement)) {
return;
}
PsiJavaDocumentedElement documentedElement = (PsiJavaDocumentedElement)parent;
PsiDocComment docComment = documentedElement.getDocComment();
if (docComment != null) {
PsiDocTag existingTag = docComment.findTagByName(DEPRECATED_TAG_NAME);
if (existingTag != null) {
moveCaretAfter(existingTag);
return;
}
PsiDocTag deprecatedTag = JavaPsiFacade.getElementFactory(project).createDocTagFromText("@" + DEPRECATED_TAG_NAME + " TODO: explain");
PsiElement addedTag = docComment.add(deprecatedTag);
moveCaretAfter(addedTag);
}
else {
PsiDocComment newDocComment = JavaPsiFacade.getElementFactory(project).createDocCommentFromText(
StringUtil.join("/**\n", " * ", "@" + DEPRECATED_TAG_NAME + " TODO: explain", "\n */")
);
PsiElement addedComment = documentedElement.addBefore(newDocComment, documentedElement.getFirstChild());
if (addedComment instanceof PsiDocComment) {
PsiDocTag addedTag = ((PsiDocComment)addedComment).findTagByName(DEPRECATED_TAG_NAME);
if (addedTag != null) {
moveCaretAfter(addedTag);
}
}
}
}
private static void moveCaretAfter(PsiElement newCaretPosition) {
PsiElement sibling = newCaretPosition.getNextSibling();
if (sibling instanceof Navigatable) {
((Navigatable)sibling).navigate(true);
}
}
}
@Override
public boolean shouldInspect(PsiFile file) {
return PsiUtil.isLanguageLevel5OrHigher(file);
}
@Override
public BaseInspectionVisitor buildVisitor() {
return new MissingDeprecatedAnnotationVisitor();
}
private class MissingDeprecatedAnnotationVisitor extends BaseInspectionVisitor {
@Override
public void visitModule(@NotNull PsiJavaModule module) {
super.visitModule(module);
if (hasDeprecatedAnnotation(module)) {
if (warnOnMissingJavadoc && !hasDeprecatedComment(module, true)) {
registerModuleError(module, Boolean.FALSE);
}
}
else if (hasDeprecatedComment(module, false)) {
registerModuleError(module, Boolean.TRUE);
}
}
@Override
public void visitClass(@NotNull PsiClass aClass) {
super.visitClass(aClass);
if (hasDeprecatedAnnotation(aClass)) {
if (warnOnMissingJavadoc && !hasDeprecatedComment(aClass, true)) {
registerClassError(aClass, Boolean.FALSE);
}
}
else if (hasDeprecatedComment(aClass, false)) {
registerClassError(aClass, Boolean.TRUE);
}
}
@Override
public void visitMethod(@NotNull PsiMethod method) {
if (method.getNameIdentifier() == null) {<|fim▁hole|> }
if (hasDeprecatedAnnotation(method)) {
if (warnOnMissingJavadoc) {
PsiMethod m = method;
while (m != null) {
if (hasDeprecatedComment(m, true)) {
return;
}
m = MethodUtils.getSuper(m);
}
registerMethodError(method, Boolean.FALSE);
}
}
else if (hasDeprecatedComment(method, false)) {
registerMethodError(method, Boolean.TRUE);
}
}
@Override
public void visitField(@NotNull PsiField field) {
if (hasDeprecatedAnnotation(field)) {
if (warnOnMissingJavadoc && !hasDeprecatedComment(field, true)) {
registerFieldError(field, Boolean.FALSE);
}
}
else if (hasDeprecatedComment(field, false)) {
registerFieldError(field, Boolean.TRUE);
}
}
private boolean hasDeprecatedAnnotation(PsiModifierListOwner element) {
final PsiModifierList modifierList = element.getModifierList();
return modifierList != null && modifierList.hasAnnotation(CommonClassNames.JAVA_LANG_DEPRECATED);
}
private boolean hasDeprecatedComment(PsiJavaDocumentedElement documentedElement, boolean checkContent) {
final PsiDocComment comment = documentedElement.getDocComment();
if (comment == null) {
return false;
}
final PsiDocTag deprecatedTag = comment.findTagByName("deprecated");
if (deprecatedTag == null) {
return false;
}
if (!checkContent) {
return true;
}
for (PsiElement element : deprecatedTag.getDataElements()) {
if (element instanceof PsiDocTagValue ||
element instanceof PsiDocToken && ((PsiDocToken)element).getTokenType() == JavaDocTokenType.DOC_COMMENT_DATA) {
return true;
}
}
return false;
}
}
}<|fim▁end|> | return; |
<|file_name|>cookie.py<|end_file_name|><|fim▁begin|><|fim▁hole|>cookie = ''<|fim▁end|> | # Log into the site with your browser, obtain the "Cookie" header,
# and put it here |
<|file_name|>row_data.py<|end_file_name|><|fim▁begin|># Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Container for Google Cloud Bigtable Cells and Streaming Row Contents."""
import copy
import six
from gcloud._helpers import _datetime_from_microseconds
from gcloud._helpers import _to_bytes
class Cell(object):
"""Representation of a Google Cloud Bigtable Cell.
:type value: bytes
:param value: The value stored in the cell.
:type timestamp: :class:`datetime.datetime`
:param timestamp: The timestamp when the cell was stored.
:type labels: list
:param labels: (Optional) List of strings. Labels applied to the cell.
"""
def __init__(self, value, timestamp, labels=()):
self.value = value
self.timestamp = timestamp
self.labels = list(labels)
@classmethod
def from_pb(cls, cell_pb):
"""Create a new cell from a Cell protobuf.
:type cell_pb: :class:`._generated.data_pb2.Cell`
:param cell_pb: The protobuf to convert.
:rtype: :class:`Cell`
:returns: The cell corresponding to the protobuf.
"""
timestamp = _datetime_from_microseconds(cell_pb.timestamp_micros)
if cell_pb.labels:
return cls(cell_pb.value, timestamp, labels=cell_pb.labels)
else:
return cls(cell_pb.value, timestamp)
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return (other.value == self.value and
other.timestamp == self.timestamp and
other.labels == self.labels)
def __ne__(self, other):
return not self.__eq__(other)
class PartialCellData(object):
"""Representation of partial cell in a Google Cloud Bigtable Table.
These are expected to be updated directly from a
:class:`._generated.bigtable_service_messages_pb2.ReadRowsResponse`
:type row_key: bytes
:param row_key: The key for the row holding the (partial) cell.
:type family_name: str
:param family_name: The family name of the (partial) cell.
:type qualifier: bytes
:param qualifier: The column qualifier of the (partial) cell.
:type timestamp_micros: int
:param timestamp_micros: The timestamp (in microsecods) of the
(partial) cell.
:type labels: list of str
:param labels: labels assigned to the (partial) cell
:type value: bytes
:param value: The (accumulated) value of the (partial) cell.
"""
def __init__(self, row_key, family_name, qualifier, timestamp_micros,
labels=(), value=b''):
self.row_key = row_key
self.family_name = family_name
self.qualifier = qualifier
self.timestamp_micros = timestamp_micros
self.labels = labels
self.value = value
def append_value(self, value):
"""Append bytes from a new chunk to value.
:type value: bytes
:param value: bytes to append
"""
self.value += value
class PartialRowData(object):
"""Representation of partial row in a Google Cloud Bigtable Table.
These are expected to be updated directly from a
:class:`._generated.bigtable_service_messages_pb2.ReadRowsResponse`
:type row_key: bytes
:param row_key: The key for the row holding the (partial) data.
"""
def __init__(self, row_key):
self._row_key = row_key
self._cells = {}
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return (other._row_key == self._row_key and
other._cells == self._cells)
def __ne__(self, other):
return not self.__eq__(other)
def to_dict(self):
"""Convert the cells to a dictionary.
This is intended to be used with HappyBase, so the column family and
column qualiers are combined (with ``:``).
:rtype: dict
:returns: Dictionary containing all the data in the cells of this row.
"""
result = {}
for column_family_id, columns in six.iteritems(self._cells):
for column_qual, cells in six.iteritems(columns):
key = (_to_bytes(column_family_id) + b':' +
_to_bytes(column_qual))
result[key] = cells
return result
@property
def cells(self):
"""Property returning all the cells accumulated on this partial row.
:rtype: dict
:returns: Dictionary of the :class:`Cell` objects accumulated. This
dictionary has two-levels of keys (first for column families
and second for column names/qualifiers within a family). For
a given column, a list of :class:`Cell` objects is stored.<|fim▁hole|> return copy.deepcopy(self._cells)
@property
def row_key(self):
"""Getter for the current (partial) row's key.
:rtype: bytes
:returns: The current (partial) row's key.
"""
return self._row_key
class InvalidReadRowsResponse(RuntimeError):
"""Exception raised to to invalid response data from back-end."""
class InvalidChunk(RuntimeError):
"""Exception raised to to invalid chunk data from back-end."""
class PartialRowsData(object):
"""Convenience wrapper for consuming a ``ReadRows`` streaming response.
:type response_iterator:
:class:`grpc.framework.alpha._reexport._CancellableIterator`
:param response_iterator: A streaming iterator returned from a
``ReadRows`` request.
"""
START = "Start" # No responses yet processed.
NEW_ROW = "New row" # No cells yet complete for row
ROW_IN_PROGRESS = "Row in progress" # Some cells complete for row
CELL_IN_PROGRESS = "Cell in progress" # Incomplete cell for row
def __init__(self, response_iterator):
self._response_iterator = response_iterator
# Fully-processed rows, keyed by `row_key`
self._rows = {}
# Counter for responses pulled from iterator
self._counter = 0
# Maybe cached from previous response
self._last_scanned_row_key = None
# In-progress row, unset until first response, after commit/reset
self._row = None
# Last complete row, unset until first commit
self._previous_row = None
# In-progress cell, unset until first response, after completion
self._cell = None
# Last complete cell, unset until first completion, after new row
self._previous_cell = None
def __eq__(self, other):
if not isinstance(other, self.__class__):
return False
return other._response_iterator == self._response_iterator
def __ne__(self, other):
return not self.__eq__(other)
@property
def state(self):
"""State machine state.
:rtype: str
:returns: name of state corresponding to currrent row / chunk
processing.
"""
if self._last_scanned_row_key is None:
return self.START
if self._row is None:
assert self._cell is None
assert self._previous_cell is None
return self.NEW_ROW
if self._cell is not None:
return self.CELL_IN_PROGRESS
if self._previous_cell is not None:
return self.ROW_IN_PROGRESS
return self.NEW_ROW # row added, no chunk yet processed
@property
def rows(self):
"""Property returning all rows accumulated from the stream.
:rtype: dict
:returns: row_key -> :class:`PartialRowData`.
"""
# NOTE: To avoid duplicating large objects, this is just the
# mutable private data.
return self._rows
def cancel(self):
"""Cancels the iterator, closing the stream."""
self._response_iterator.cancel()
def consume_next(self):
"""Consume the next ``ReadRowsResponse`` from the stream.
Parse the response and its chunks into a new/existing row in
:attr:`_rows`
"""
response = six.next(self._response_iterator)
self._counter += 1
if self._last_scanned_row_key is None: # first response
if response.last_scanned_row_key:
raise InvalidReadRowsResponse()
self._last_scanned_row_key = response.last_scanned_row_key
row = self._row
cell = self._cell
for chunk in response.chunks:
self._validate_chunk(chunk)
if chunk.reset_row:
row = self._row = None
cell = self._cell = self._previous_cell = None
continue
if row is None:
row = self._row = PartialRowData(chunk.row_key)
if cell is None:
cell = self._cell = PartialCellData(
chunk.row_key,
chunk.family_name.value,
chunk.qualifier.value,
chunk.timestamp_micros,
chunk.labels,
chunk.value)
self._copy_from_previous(cell)
else:
cell.append_value(chunk.value)
if chunk.commit_row:
self._save_current_row()
row = cell = None
continue
if chunk.value_size == 0:
self._save_current_cell()
cell = None
def consume_all(self, max_loops=None):
"""Consume the streamed responses until there are no more.
This simply calls :meth:`consume_next` until there are no
more to consume.
:type max_loops: int
:param max_loops: (Optional) Maximum number of times to try to consume
an additional ``ReadRowsResponse``. You can use this
to avoid long wait times.
"""
curr_loop = 0
if max_loops is None:
max_loops = float('inf')
while curr_loop < max_loops:
curr_loop += 1
try:
self.consume_next()
except StopIteration:
break
@staticmethod
def _validate_chunk_status(chunk):
"""Helper for :meth:`_validate_chunk_row_in_progress`, etc."""
# No reseet with other keys
if chunk.reset_row:
_raise_if(chunk.row_key)
_raise_if(chunk.HasField('family_name'))
_raise_if(chunk.HasField('qualifier'))
_raise_if(chunk.timestamp_micros)
_raise_if(chunk.labels)
_raise_if(chunk.value_size)
_raise_if(chunk.value)
# No commit with value size
_raise_if(chunk.commit_row and chunk.value_size > 0)
# No negative value_size (inferred as a general constraint).
_raise_if(chunk.value_size < 0)
def _validate_chunk_new_row(self, chunk):
"""Helper for :meth:`_validate_chunk`."""
assert self.state == self.NEW_ROW
_raise_if(chunk.reset_row)
_raise_if(not chunk.row_key)
_raise_if(not chunk.family_name)
_raise_if(not chunk.qualifier)
# This constraint is not enforced in the Go example.
_raise_if(chunk.value_size > 0 and chunk.commit_row is not False)
# This constraint is from the Go example, not the spec.
_raise_if(self._previous_row is not None and
chunk.row_key <= self._previous_row.row_key)
def _same_as_previous(self, chunk):
"""Helper for :meth:`_validate_chunk_row_in_progress`"""
previous = self._previous_cell
return (chunk.row_key == previous.row_key and
chunk.family_name == previous.family_name and
chunk.qualifier == previous.qualifier and
chunk.labels == previous.labels)
def _validate_chunk_row_in_progress(self, chunk):
"""Helper for :meth:`_validate_chunk`"""
assert self.state == self.ROW_IN_PROGRESS
self._validate_chunk_status(chunk)
if not chunk.HasField('commit_row') and not chunk.reset_row:
_raise_if(not chunk.timestamp_micros or not chunk.value)
_raise_if(chunk.row_key and
chunk.row_key != self._row.row_key)
_raise_if(chunk.HasField('family_name') and
not chunk.HasField('qualifier'))
previous = self._previous_cell
_raise_if(self._same_as_previous(chunk) and
chunk.timestamp_micros <= previous.timestamp_micros)
def _validate_chunk_cell_in_progress(self, chunk):
"""Helper for :meth:`_validate_chunk`"""
assert self.state == self.CELL_IN_PROGRESS
self._validate_chunk_status(chunk)
self._copy_from_current(chunk)
def _validate_chunk(self, chunk):
"""Helper for :meth:`consume_next`."""
if self.state == self.NEW_ROW:
self._validate_chunk_new_row(chunk)
if self.state == self.ROW_IN_PROGRESS:
self._validate_chunk_row_in_progress(chunk)
if self.state == self.CELL_IN_PROGRESS:
self._validate_chunk_cell_in_progress(chunk)
def _save_current_cell(self):
"""Helper for :meth:`consume_next`."""
row, cell = self._row, self._cell
family = row._cells.setdefault(cell.family_name, {})
qualified = family.setdefault(cell.qualifier, [])
complete = Cell.from_pb(self._cell)
qualified.append(complete)
self._cell, self._previous_cell = None, cell
def _copy_from_current(self, chunk):
"""Helper for :meth:`consume_next`."""
current = self._cell
if current is not None:
if not chunk.row_key:
chunk.row_key = current.row_key
if not chunk.HasField('family_name'):
chunk.family_name.value = current.family_name
if not chunk.HasField('qualifier'):
chunk.qualifier.value = current.qualifier
if not chunk.timestamp_micros:
chunk.timestamp_micros = current.timestamp_micros
if not chunk.labels:
chunk.labels.extend(current.labels)
def _copy_from_previous(self, cell):
"""Helper for :meth:`consume_next`."""
previous = self._previous_cell
if previous is not None:
if not cell.row_key:
cell.row_key = previous.row_key
if not cell.family_name:
cell.family_name = previous.family_name
if not cell.qualifier:
cell.qualifier = previous.qualifier
def _save_current_row(self):
"""Helper for :meth:`consume_next`."""
if self._cell:
self._save_current_cell()
self._rows[self._row.row_key] = self._row
self._row, self._previous_row = None, self._row
self._previous_cell = None
def _raise_if(predicate, *args):
"""Helper for validation methods."""
if predicate:
raise InvalidChunk(*args)<|fim▁end|> | """ |
<|file_name|>bitcoin_tr.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="tr" version="2.1">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Mojocoin</source>
<translation>Mojocoin Hakkında</translation>
</message>
<message>
<location line="+39"/>
<source><b>Mojocoin</b> version</source>
<translation><b>Mojocoin</b> versiyonu</translation>
</message>
<message>
<location line="+41"/>
<source>Copyright © 2009-2014 The Bitcoin developers
Copyright © 2012-2014 The MojoCoin developers
Copyright © 2014 The Mojocoin developers</source>
<translation>Telif Hakkı © 2009-2014 Bitcoin geliştiricileri
Telif Hakkı © 2012-2014 MojoCoin geliştiricileri
Telif Hakkı © 2014 Mojocoin geliştiricileri</translation>
</message>
<message>
<location line="+15"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or <a href="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a>.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (<a href="https://www.openssl.org/">https://www.openssl.org/</a>) and cryptographic software written by Eric Young (<a href="mailto:[email protected]">[email protected]</a>) and UPnP software written by Thomas Bernard.</source>
<translation>
Bu, deneysel bir yazılımdır.
MIT/X11 yazılım lisansı kapsamında yayınlanmıştır, beraberindeki COPYING dosyasına veya <a href="http://www.opensource.org/licenses/mit-license.php">http://www.opensource.org/licenses/mit-license.php</a> sayfasına bakınız.
Bu ürün, OpenSSL projesi tarafından OpenSSL araç takımıThis product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (<a href="https://www.openssl.org/">https://www.openssl.org/</a>) için geliştirilmiş yazılımı, Eric Young (<a href="mailto:[email protected]">[email protected]</a>) tarafından hazırlanmış şifreleme yazılımı ve Thomas Bernard tarafından yazılmış UPnP yazılımı içerir.</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adres Defteri</translation>
</message>
<message>
<location line="+22"/>
<source>Double-click to edit address or label</source>
<translation>Adresi ya da etiketi düzenlemek için çift tıklayınız</translation>
</message>
<message>
<location line="+24"/>
<source>Create a new address</source>
<translation>Yeni bir adres oluştur</translation>
</message>
<message>
<location line="+10"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Seçili adresi sistem panosuna kopyala</translation>
</message>
<message>
<location line="-7"/>
<source>&New Address</source>
<translation>&Yeni Adres</translation>
</message>
<message>
<location line="-43"/>
<source>These are your Mojocoin 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>Bunlar, ödeme almak için Mojocoin adreslerinizdir. Her bir göndericiye farklı birini verebilir, böylece size kimin ödeme yaptığını takip edebilirsiniz.</translation>
</message>
<message>
<location line="+53"/>
<source>&Copy Address</source>
<translation>Adresi &Kopyala</translation>
</message>
<message>
<location line="+7"/>
<source>Show &QR Code</source>
<translation>&QR Kodunu Göster</translation>
</message>
<message>
<location line="+7"/>
<source>Sign a message to prove you own a Mojocoin address</source>
<translation>Bir Mojocoin adresine sahip olduğunu ispatlamak için bir mesaj imzala</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Mesaj İmzala</translation>
</message>
<message>
<location line="+17"/>
<source>Delete the currently selected address from the list</source>
<translation>Seçili adresi listeden sil</translation>
</message>
<message>
<location line="-10"/>
<source>Verify a message to ensure it was signed with a specified Mojocoin address</source>
<translation>Mesajın, belirli bir Mojocoin adresiyle imzalandığından emin olmak için onu doğrula</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>Mesajı &Doğrula</translation>
</message>
<message>
<location line="+10"/>
<source>&Delete</source>
<translation>&Sil</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+66"/>
<source>Copy &Label</source>
<translation>&Etiketi Kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Düzenle</translation>
</message>
<message>
<location line="+248"/>
<source>Export Address Book Data</source>
<translation>Adres Defteri Verisini Dışarı Aktar</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Virgülle ayrılmış değerler dosyası (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Dışarı aktarım hatası</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>%1 dosyasına yazılamadı.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+145"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(boş etiket)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Parola Diyaloğu</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Parolayı giriniz</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Yeni parola</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Yeni parolayı tekrarlayınız</translation>
</message>
<message>
<location line="+33"/>
<source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source>
<translation>OS hesabı tehlike girdiğinde önemsiz para gönderme özelliğini devre dışı bırakmayı sağlar. Gerçek anlamda bir güvenlik sağlamaz.</translation>
</message>
<message>
<location line="+3"/>
<source>For staking only</source>
<translation>Sadece pay almak için</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+38"/>
<source>Encrypt wallet</source>
<translation>Cüzdanı şifrele</translation>
</message>
<message>
<location line="+7"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Bu işlem cüzdan kilidini açmak için cüzdan parolanızı gerektirir.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Cüzdan kilidini aç</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Bu işlem, cüzdan şifresini açmak için cüzdan parolasını gerektirir.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Cüzdan şifresini aç</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Parolayı değiştir</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Cüzdan için eski ve yeni parolaları giriniz.</translation>
</message>
<message>
<location line="+45"/>
<source>Confirm wallet encryption</source>
<translation>Cüzdan şifrelenmesini teyit eder</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>Uyarı: Eğer cüzdanınızı şifreleyip parolanızı kaybederseniz, <b> TÜM COINLERİNİZİ KAYBEDECEKSİNİZ</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Cüzdanınızı şifrelemek istediğinizden emin misiniz?</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>ÖNEMLİ: Önceden yapmış olduğunuz cüzdan dosyası yedeklemelerinin yeni oluşturulan, şifrelenmiş cüzdan dosyası ile değiştirilmeleri gerekmektedir. Güvenlik nedenleriyle yeni, şifrelenmiş cüzdanı kullanmaya başladığınızda, şifrelenmemiş cüzdan dosyasının önceki yedekleri işe yaramaz hale gelecektir.</translation>
</message>
<message>
<location line="+103"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Uyarı: Caps Lock tuşu faal durumda!</translation>
</message>
<message>
<location line="-133"/>
<location line="+60"/>
<source>Wallet encrypted</source>
<translation>Cüzdan şifrelendi</translation>
</message>
<message>
<location line="-140"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Cüzdanınız için yeni parolayı giriniz.<br/>Lütfen <b>on veya daha fazla rastgele karakter</b> ya da <b>sekiz veya daha fazla kelime</b> içeren bir parola seçiniz.</translation>
</message>
<message>
<location line="+82"/>
<source>Mojocoin 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>Mojocoin, şifreleme işlemini tamamlamak için şimdi kapatılacak. Cüzdanınızı şifrelemenin; coinlerinizin, bilgisayarınızı etkileyen zararlı yazılımlar tarafından çalınmasını bütünüyle engelleyemeyebileceğini unutmayınız.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+44"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Cüzdan şifrelemesi başarısız oldu</translation>
</message>
<message>
<location line="-56"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Dahili bir hata sebebiyle cüzdan şifrelemesi başarısız oldu. Cüzdanınız şifrelenmedi.</translation>
</message>
<message>
<location line="+7"/>
<location line="+50"/>
<source>The supplied passphrases do not match.</source>
<translation>Girilen parolalar birbirleriyle eşleşmiyor.</translation>
</message>
<message>
<location line="-38"/>
<source>Wallet unlock failed</source>
<translation>Cüzdan kilidinin açılması başarısız oldu</translation>
</message>
<message>
<location line="+1"/>
<location line="+12"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Cüzdan şifresinin açılması için girilen parola yanlıştı.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Cüzdan şifresinin açılması başarısız oldu</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Cüzdan parolası başarılı bir şekilde değiştirildi.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+297"/>
<source>Sign &message...</source>
<translation>&Mesaj imzala...</translation>
</message>
<message>
<location line="-64"/>
<source>Show general overview of wallet</source>
<translation>Cüzdana genel bakışı göster</translation>
</message>
<message>
<location line="+17"/>
<source>&Transactions</source>
<translation>&İşlemler</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>İşlem geçmişine göz at</translation>
</message>
<message>
<location line="+5"/>
<source>&Address Book</source>
<translation>&Adres Defteri</translation>
</message>
<message>
<location line="+1"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Kayıtlı adresler ve etiketler listesini düzenle</translation>
</message>
<message>
<location line="-18"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Ödeme almak için kullanılan adres listesini göster</translation>
</message>
<message>
<location line="+34"/>
<source>E&xit</source>
<translation>&Çık</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Uygulamadan çık</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about Mojocoin</source>
<translation>Mojocoin hakkındaki bilgiyi göster</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>&Qt hakkında</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Qt hakkındaki bilgiyi göster</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Seçenekler...</translation>
</message>
<message>
<location line="+4"/>
<source>&Encrypt Wallet...</source>
<translation>Cüzdanı &Şifrele...</translation>
</message>
<message>
<location line="+2"/>
<source>&Backup Wallet...</source>
<translation>Cüzdanı &Yedekle...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>Parolayı &Değiştir...</translation>
</message>
<message>
<location line="+9"/>
<source>&Export...</source>
<translation>&Dışarı aktar...</translation>
</message>
<message>
<location line="-55"/>
<source>Send coins to a Mojocoin address</source>
<translation>Bir Mojocoin adresine coin gönder</translation>
</message>
<message>
<location line="+39"/>
<source>Modify configuration options for Mojocoin</source>
<translation>Mojocoin yapılandırma seçeneklerini değiştir</translation>
</message>
<message>
<location line="+17"/>
<source>Export the data in the current tab to a file</source>
<translation>Mevcut sekmedeki veriyi bir dosyaya aktar</translation>
</message>
<message>
<location line="-13"/>
<source>Encrypt or decrypt wallet</source>
<translation>Cüzdanı şifrele veya cüzdanın şifresini aç</translation>
</message>
<message>
<location line="+2"/>
<source>Backup wallet to another location</source>
<translation>Cüzdanı başka bir konuma yedekle</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Cüzdan şifrelemesi için kullanılan parolayı değiştir</translation>
</message>
<message>
<location line="+10"/>
<source>&Debug window</source>
<translation>&Hata ayıklama penceresi</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Hata ayıklama ve teşhis penceresini aç</translation>
</message>
<message>
<location line="-5"/>
<source>&Verify message...</source>
<translation>Mesajı &doğrula...</translation>
</message>
<message>
<location line="-214"/>
<location line="+555"/>
<source>Mojocoin</source>
<translation>Mojocoin</translation>
</message>
<message>
<location line="-555"/>
<source>Wallet</source>
<translation>Cüzdan</translation>
</message>
<message>
<location line="+193"/>
<source>&About Mojocoin</source>
<translation>Mojocoin &Hakkında</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Göster / Gizle</translation>
</message>
<message>
<location line="+8"/>
<source>Unlock wallet</source>
<translation>Cüzdanın kilidini aç</translation>
</message>
<message>
<location line="+1"/>
<source>&Lock Wallet</source>
<translation>Cüzdanı &Kilitle</translation>
</message>
<message>
<location line="+1"/>
<source>Lock wallet</source>
<translation>Cüzdanı kilitle</translation>
</message>
<message>
<location line="+32"/>
<source>&File</source>
<translation>&Dosya</translation>
</message>
<message>
<location line="+8"/>
<source>&Settings</source>
<translation>&Ayarlar</translation>
</message>
<message>
<location line="+8"/>
<source>&Help</source>
<translation>&Yardım</translation>
</message>
<message>
<location line="+17"/>
<source>Tabs toolbar</source>
<translation>Sekme araç çubuğu</translation>
</message>
<message>
<location line="+46"/>
<location line="+9"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+0"/>
<location line="+58"/>
<source>Mojocoin client</source>
<translation>Mojocoin istemcisi</translation>
</message>
<message numerus="yes">
<location line="+70"/>
<source>%n active connection(s) to Mojocoin network</source>
<translation><numerusform>Mojocoin ağına %n etkin bağlantı</numerusform><numerusform>Mojocoin ağına %n etkin bağlantı</numerusform></translation>
</message>
<message>
<location line="+488"/>
<source>Staking.<br>Your weight is %1<br>Network weight is %2<br>Expected time to earn reward is %3</source>
<translation>Pay alınıyor.<br>Sizin ağırlığınız %1<br>Ağın ağırlığı %2<br>Ödül almak için tahmini süre %3</translation>
</message>
<message>
<location line="+6"/>
<source>Not staking because wallet is locked</source>
<translation>Pay alınmıyor çünkü cüzdan kilitlidir</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is offline</source>
<translation>Pay alınmıyor çünkü cüzdan çevrimdışıdır</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because wallet is syncing</source>
<translation>Pay alınmıyor çünkü cüzdan senkronize ediliyor</translation>
</message>
<message>
<location line="+2"/>
<source>Not staking because you don't have mature coins</source>
<translation>Pay alınmıyor çünkü olgunlaşmış coininiz yoktur</translation>
</message>
<message>
<location line="-812"/>
<source>&Dashboard</source>
<translation>&Pano</translation>
</message>
<message>
<location line="+6"/>
<source>&Receive</source>
<translation>&Al</translation>
</message>
<message>
<location line="+6"/>
<source>&Send</source>
<translation>&Gönder</translation>
</message>
<message>
<location line="+49"/>
<source>&Unlock Wallet...</source>
<translation>Cüzdanı &Kilitle...</translation>
</message>
<message>
<location line="+277"/>
<source>Up to date</source>
<translation>Güncel</translation>
</message>
<message>
<location line="+43"/>
<source>Catching up...</source>
<translation>Aralık kapatılıyor...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>İşlem ücretini onayla</translation>
</message>
<message>
<location line="+27"/>
<source>Sent transaction</source>
<translation>İşlem gerçekleştirildi</translation>
</message>
<message>
<location line="+1"/>
<source>Incoming transaction</source>
<translation>Gelen işlem</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Tarih: %1
Miktar: %2
Tür: %3
Adres: %4
</translation>
</message>
<message>
<location line="+100"/>
<location line="+15"/>
<source>URI handling</source>
<translation>URI işleme</translation>
</message>
<message>
<location line="-15"/>
<location line="+15"/>
<source>URI can not be parsed! This can be caused by an invalid Mojocoin address or malformed URI parameters.</source>
<translation>URI ayrıştırılamadı! Bu, geçersiz bir Mojocoin adresi veya hatalı URI parametreleri nedeniyle olabilir.</translation>
</message>
<message>
<location line="+9"/>
<source>Wallet is <b>not encrypted</b></source>
<translation>Cüzdan <b>şifreli değil</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Cüzdan <b>şifrelenmiştir</b> ve şu anda <b>kilidi açıktır</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Cüzdan <b>şifrelenmiştir</b> ve şu anda <b>kilitlidir</b></translation>
</message>
<message>
<location line="+24"/>
<source>Backup Wallet</source>
<translation>Cüzdanı Yedekle</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Cüzdan Verisi (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Yedekleme Başarısız Oldu</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Cüzdan verisi, yeni bir konuma kaydedilmeye çalışılırken bir hata oluştu.</translation>
</message>
<message numerus="yes">
<location line="+91"/>
<source>%n second(s)</source>
<translation><numerusform>%n saniye</numerusform><numerusform>%n saniye</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n minute(s)</source>
<translation><numerusform>%n dakika</numerusform><numerusform>%n dakika</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+433"/>
<source>%n hour(s)</source>
<translation><numerusform>%n saat</numerusform><numerusform>%n saat</numerusform></translation>
</message>
<message>
<location line="-456"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Muamele tarihçesindeki %1 blok işlendi.</translation>
</message>
<message numerus="yes">
<location line="+27"/>
<location line="+433"/>
<source>%n day(s)</source>
<translation><numerusform>%n gün</numerusform><numerusform>%n gün</numerusform></translation>
</message>
<message numerus="yes">
<location line="-429"/>
<location line="+6"/>
<source>%n week(s)</source>
<translation><numerusform>%n hafta</numerusform><numerusform>%n hafta</numerusform></translation>
</message>
<message>
<location line="+0"/>
<source>%1 and %2</source>
<translation>%1 ve %2</translation>
</message>
<message numerus="yes">
<location line="+0"/>
<source>%n year(s)</source>
<translation><numerusform>%n yıl</numerusform><numerusform>%n yıl</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>%1 behind</source>
<translation>%1 geride</translation>
</message>
<message>
<location line="+15"/>
<source>Last received block was generated %1 ago.</source>
<translation>Son alınan blok %1 önce üretildi.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Bundan sonraki işlemler daha görünür olmayacaktır.</translation>
</message>
<message>
<location line="+23"/>
<source>Error</source>
<translation>Hata</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Uyarı</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Bilgi</translation>
</message>
<message>
<location line="+69"/>
<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>Bu işlem, büyüklük sınırının üzerindedir. İşleminizi gerçekleştirecek devrelere gidecek ve ağı desteklemeye yardımcı olacak %1 ücretle coin gönderebilirsiniz. Ücreti ödemek istiyor musunuz?</translation>
</message>
<message>
<location line="+324"/>
<source>Not staking</source>
<translation>Pay alınmıyor</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+104"/>
<source>A fatal error occurred. Mojocoin can no longer continue safely and will quit.</source>
<translation>Önemli bir hata oluştu. Mojocoin artık güvenli bir şekilde devam edemez ve şimdi kapatılacak.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+110"/>
<source>Network Alert</source>
<translation>Ağ Uyarısı</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<location filename="../forms/coincontroldialog.ui" line="+14"/>
<source>Coin Control</source>
<translation>Coin Kontrolü</translation>
</message>
<message>
<location line="+31"/>
<source>Quantity:</source>
<translation>Adet:</translation>
</message>
<message>
<location line="+32"/>
<source>Bytes:</source>
<translation>Bayt:</translation>
</message>
<message>
<location line="+48"/>
<source>Amount:</source>
<translation>Miktar:</translation>
</message>
<message>
<location line="+32"/>
<source>Priority:</source>
<translation>Öncelik:</translation>
</message>
<message>
<location line="+48"/>
<source>Fee:</source>
<translation>Ücret:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Düşük Çıktı:</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="+537"/>
<source>no</source>
<translation>hayır</translation>
</message>
<message>
<location filename="../forms/coincontroldialog.ui" line="+51"/>
<source>After Fee:</source>
<translation>Ücretten sonra:</translation>
</message>
<message>
<location line="+35"/>
<source>Change:</source>
<translation>Para üstü:</translation>
</message>
<message>
<location line="+69"/>
<source>(un)select all</source>
<translation>tümünü seç(me)</translation>
</message>
<message>
<location line="+13"/>
<source>Tree mode</source>
<translation>Ağaç kipi</translation>
</message>
<message>
<location line="+16"/>
<source>List mode</source>
<translation>Liste kipi</translation>
</message>
<message>
<location line="+45"/>
<source>Amount</source>
<translation>Miktar</translation>
</message>
<message>
<location line="+5"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location line="+5"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+5"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location line="+5"/>
<source>Confirmations</source>
<translation>Onaylar</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed</source>
<translation>Onaylandı</translation>
</message>
<message>
<location line="+5"/>
<source>Priority</source>
<translation>Öncelik</translation>
</message>
<message>
<location filename="../coincontroldialog.cpp" line="-500"/>
<source>Copy address</source>
<translation>Adresi kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Etiketi kopyala</translation>
</message>
<message>
<location line="+1"/>
<location line="+26"/>
<source>Copy amount</source>
<translation>Miktarı kopyala</translation>
</message>
<message>
<location line="-25"/>
<source>Copy transaction ID</source>
<translation>İşlem Numarasını Kopyala</translation>
</message>
<message>
<location line="+24"/>
<source>Copy quantity</source>
<translation>Adedi kopyala</translation>
</message>
<message>
<location line="+2"/>
<source>Copy fee</source>
<translation>Ücreti kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Ücretten sonrakini kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Baytları kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Önceliği kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Düşük çıktıyı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Para üstünü kopyala</translation>
</message>
<message>
<location line="+317"/>
<source>highest</source>
<translation>en yüksek</translation>
</message>
<message>
<location line="+1"/>
<source>high</source>
<translation>yüksek</translation>
</message>
<message>
<location line="+1"/>
<source>medium-high</source>
<translation>orta-yüksek</translation>
</message>
<message>
<location line="+1"/>
<source>medium</source>
<translation>orta</translation>
</message>
<message>
<location line="+4"/>
<source>low-medium</source>
<translation>düşük-orta</translation>
</message>
<message>
<location line="+1"/>
<source>low</source>
<translation>düşük</translation>
</message>
<message>
<location line="+1"/>
<source>lowest</source>
<translation>en düşük</translation>
</message>
<message>
<location line="+140"/>
<source>DUST</source>
<translation>BOZUKLUK</translation>
</message>
<message>
<location line="+0"/>
<source>yes</source>
<translation>evet</translation>
</message>
<message>
<location line="+10"/>
<source>This label turns red, if the transaction size is bigger than 10000 bytes.
This means a fee of at least %1 per kb is required.
Can vary +/- 1 Byte per input.</source>
<translation>İşlem büyüklüğü 10000 bayttan büyükse, bu etiket kırmızıya dönüşür.
Bu, kb başına en az %1 ücret gerektiği anlamına gelir.
Girdi başına +/- 1 Byte değişkenlik gösterebilir.</translation>
</message>
<message>
<location line="+1"/>
<source>Transactions with higher priority get more likely into a block.
<|fim▁hole|>
This means a fee of at least %1 per kb is required.</source>
<translation>Yüksek öncelikli işlemler, daha yüksek ihtimalle bir bloğa düşer.
Öncelik "orta" seviyeden düşükse, bu etiket kırmızıya döner.
Bu, kb başına en az %1 ücret gerektiği anlamına gelir.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if any recipient receives an amount smaller than %1.
This means a fee of at least %2 is required.
Amounts below 0.546 times the minimum relay fee are shown as DUST.</source>
<translation>Eğer herhangi bir alıcı, %1'den daha küçük bir miktar alırsa, bu etiket kırmızıya dönüşür.
Bu, en az %2 bir ücretin gerektiği anlamına gelir.
Minimum aktarım ücretinin 0.546 katından düşük miktarlar, BOZUKLUK olarak gösterilir.</translation>
</message>
<message>
<location line="+1"/>
<source>This label turns red, if the change is smaller than %1.
This means a fee of at least %2 is required.</source>
<translation>Eğer para üstü %1'den küçükse, bu etiket kırmızıya dönüşür.
Bu, en az %2 bir ücretin gerektiği anlamına gelir.</translation>
</message>
<message>
<location line="+36"/>
<location line="+66"/>
<source>(no label)</source>
<translation>(boş etiket)</translation>
</message>
<message>
<location line="-9"/>
<source>change from %1 (%2)</source>
<translation>%1 unsurundan para üstü (%2)</translation>
</message>
<message>
<location line="+1"/>
<source>(change)</source>
<translation>(para üstü)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Adresi düzenle</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etiket</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>Bu adres defteri kaydıyla ilişkili etiket</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adres</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>Bu adres defteri kaydıyla ilişkili etiket. Bu, sadece gönderi adresleri için değiştirilebilir.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Yeni alım adresi</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Yeni gönderi adresi</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Alım adresini düzenle</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Gönderi adresini düzenle</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>Girilen "%1" adresi hâlihazırda adres defterinde mevcuttur.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Mojocoin address.</source>
<translation>Girilen %1 adresi, geçerli bir Mojocoin adresi değildir.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Cüzdan kilidi açılamadı.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Yeni anahtar oluşturulması başarısız oldu.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+426"/>
<location line="+12"/>
<source>Mojocoin-Qt</source>
<translation>Mojocoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versiyon</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Kullanım:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>komut satırı seçenekleri</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>GA seçenekleri</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Dili ayarla, örneğin "de_DE" (varsayılan: sistem yerel ayarları)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Simge durumunda başlat</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Başlangıçta açılış ekranını göster (varsayılan: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Seçenekler</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Esas ayarlar</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source>
<translation>İşlemlerinizin hızlıca gerçekleştirilmesini sağlayan kB başına opsiyonel işlem ücreti. Birçok işlem 1 kB'tır. Tavsiye edilen ücret 0.01'dir.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>İşlem ücreti &öde</translation>
</message>
<message>
<location line="+31"/>
<source>Reserved amount does not participate in staking and is therefore spendable at any time.</source>
<translation>Ayrılan miktar, pay almaya katılamıyor ve bu yüzden herhangi bir anda harcanabilir.</translation>
</message>
<message>
<location line="+15"/>
<source>Reserve</source>
<translation>Ayrılan</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Mojocoin after logging in to the system.</source>
<translation>Sisteme giriş yaptıktan sonra Mojocoin'i otomatik olarak başlat</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Mojocoin on system login</source>
<translation>Sisteme girişte Mojocoin'i &başlat</translation>
</message>
<message>
<location line="+21"/>
<source>&Network</source>
<translation>&Şebeke</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Mojocoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Yönelticide Mojocoin istemci portunu otomatik olarak aç. Bu, sadece yönelticiniz UPnP'i desteklediğinde ve etkin olduğunda çalışır.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Portları &UPnP kullanarak haritala</translation>
</message>
<message>
<location line="+19"/>
<source>Proxy &IP:</source>
<translation>Vekil &İP:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Vekil sunucunun IP adresi (örn. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Vekil sunucunun portu (mesela 9050)</translation>
</message>
<message>
<location line="-57"/>
<source>Connect to the Mojocoin network through a SOCKS5 proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS5 proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+90"/>
<source>&Window</source>
<translation>&Pencere</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Küçültüldükten sonra sadece çekmece ikonu göster.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>İşlem çubuğu yerine sistem çekmecesine &küçült</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>Pencere kapatıldığında uygulamadan çıkmak yerine uygulamayı küçültür. Bu seçenek etkinleştirildiğinde, uygulama sadece menüden çıkış seçildiğinde kapanacaktır.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>Kapatma sırasında k&üçült</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Görünüm</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Kullanıcı arayüzü &lisanı:</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Mojocoin.</source>
<translation>Kullanıcı arabirimi dili buradan ayarlanabilir. Ayar, Mojocoin yeniden başlatıldığında etkin olacaktır.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>Meblağları göstermek için &birim:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Bitcoin gönderildiğinde arayüzde gösterilecek varsayılan alt birimi seçiniz.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show coin control features or not.</source>
<translation>Para kontrol özelliklerinin gösterilip gösterilmeyeceğini ayarlar.</translation>
</message>
<message>
<location line="+3"/>
<source>Display coin &control features (experts only!)</source>
<translation>Coin &kontrol özelliklerini göster (sadece uzman kişiler!)</translation>
</message>
<message>
<location line="+7"/>
<source>Whether to select the coin outputs randomly or with minimal coin age.</source>
<translation>Coin çıktılarını rastgele veya asgari coin yıllandırmasına göre seçme.</translation>
</message>
<message>
<location line="+3"/>
<source>Minimize weight consumption (experimental)</source>
<translation>Ağırlık tüketimini minimuma indirme (deneysel)</translation>
</message>
<message>
<location line="+7"/>
<source>Use black visual theme (requires restart)</source>
<translation>Siyah görsel temayı kullan (baştan başlatmayı gerektirir)</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&Tamam</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&İptal</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Uygula</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+47"/>
<source>default</source>
<translation>varsayılan</translation>
</message>
<message>
<location line="+148"/>
<location line="+9"/>
<source>Warning</source>
<translation>Uyarı</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Mojocoin.</source>
<translation>Bu ayar, Mojocoin'i yeniden başlattıktan sonra etkin olacaktır.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Girilen vekil sunucu adresi geçersizdir.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+46"/>
<location line="+247"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Mojocoin network after a connection is established, but this process has not completed yet.</source>
<translation>Görüntülenen bilginin tarihi geçmiş olabilir. Cüzdanınız, bağlantı kurulduktan sonra otomatik olarak Mojocoin ağı ile senkronize olur ancak bu süreç, henüz tamamlanmamıştır.</translation>
</message>
<message>
<location line="-173"/>
<source>Stake:</source>
<translation>Pay:</translation>
</message>
<message>
<location line="+32"/>
<source>Unconfirmed:</source>
<translation>Doğrulanmamış:</translation>
</message>
<message>
<location line="-113"/>
<source>Wallet</source>
<translation>Cüzdan</translation>
</message>
<message>
<location line="+49"/>
<source>Spendable:</source>
<translation>Harcanabilir:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>Güncel harcanabilir bakiyeniz</translation>
</message>
<message>
<location line="+80"/>
<source>Immature:</source>
<translation>Olgunlaşmamış:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Oluşturulan bakiye henüz olgunlaşmamıştır</translation>
</message>
<message>
<location line="+23"/>
<source>Total:</source>
<translation>Toplam:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>Güncel toplam bakiyeniz</translation>
</message>
<message>
<location line="+50"/>
<source><b>Recent transactions</b></source>
<translation><b>Son işlemler</b></translation>
</message>
<message>
<location line="-118"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation>Henüz onaylanmamış ve mevcut bakiyede yer almayan işlemler toplamı</translation>
</message>
<message>
<location line="-32"/>
<source>Total of coins that was staked, and do not yet count toward the current balance</source>
<translation>Pay alınmış ve mevcut bakiyede yer almayan coin toplamı</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>eşleşme dışı</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start mojocoin: click-to-pay handler</source>
<translation>Mojocoin: tıkla-ve-öde işleyicisi başlatılamıyor</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR Kodu İletisi</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Ödeme Talep Et</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Miktar:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Etiket:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Mesaj:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Farklı Kaydet...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>URI'nin QR koduna kodlanmasında hata oluştu.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Girilen miktar geçersizdir, lütfen kontrol ediniz.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Sonuç URI'si çok uzundur, etiket / mesaj için olan metni kısaltmaya çalışın.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>QR Kodu'nu Kaydet</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG İmgeleri (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>İstemci ismi</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"/>
<source>N/A</source>
<translation>Mevcut değil</translation>
</message>
<message>
<location line="-194"/>
<source>Client version</source>
<translation>İstemci sürümü</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Malumat</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Kullanılan OpenSSL sürümü</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Başlama zamanı</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Şebeke</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Bağlantı sayısı</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Testnet üzerinde</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Blok zinciri</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Güncel blok sayısı</translation>
</message>
<message>
<location line="+197"/>
<source>&Network Traffic</source>
<translation>&Şebeke Trafiği</translation>
</message>
<message>
<location line="+52"/>
<source>&Clear</source>
<translation>&Temizle</translation>
</message>
<message>
<location line="+13"/>
<source>Totals</source>
<translation>Toplam</translation>
</message>
<message>
<location line="+64"/>
<source>In:</source>
<translation>Gelen:</translation>
</message>
<message>
<location line="+80"/>
<source>Out:</source>
<translation>Giden:</translation>
</message>
<message>
<location line="-383"/>
<source>Last block time</source>
<translation>Son blok zamanı</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Aç</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Komut satırı seçenekleri</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Mojocoin-Qt help message to get a list with possible Mojocoin command-line options.</source>
<translation>Muhtemel Mojocoin komut satırı seçeneklerinin bir listesini getirmek için Mojocoin-Qt yardım mesajını göster</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Göster</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Konsol</translation>
</message>
<message>
<location line="-237"/>
<source>Build date</source>
<translation>Derleme tarihi</translation>
</message>
<message>
<location line="-104"/>
<source>Mojocoin - Debug window</source>
<translation>Mojocoin - Hata ayıklama penceresi</translation>
</message>
<message>
<location line="+25"/>
<source>Mojocoin Core</source>
<translation>Mojocoin Core</translation>
</message>
<message>
<location line="+256"/>
<source>Debug log file</source>
<translation>Hata ayıklama kütük dosyası</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Mojocoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Mojocoin hata ayıklama günlük kütüğü dosyasını, mevcut veri klasöründen aç. Bu işlem, büyük günlük kütüğü dosyaları için birkaç saniye sürebilir.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Konsolu temizle</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="+325"/>
<source>Welcome to the Mojocoin RPC console.</source>
<translation>Mojocoin RPC konsoluna hoş geldiniz.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Tarihçede gezinmek için imleç tuşlarını kullanınız, <b>Ctrl-L</b> ile de ekranı temizleyebilirsiniz.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Mevcut komutların listesi için <b>help</b> yazınız.</translation>
</message>
<message>
<location line="+127"/>
<source>%1 B</source>
<translation>%1 B</translation>
</message>
<message>
<location line="+2"/>
<source>%1 KB</source>
<translation>%1 KB</translation>
</message>
<message>
<location line="+2"/>
<source>%1 MB</source>
<translation>%1 MB</translation>
</message>
<message>
<location line="+2"/>
<source>%1 GB</source>
<translation>%1 GB</translation>
</message>
<message>
<location line="+7"/>
<source>%1 m</source>
<translation>%1 dk</translation>
</message>
<message>
<location line="+5"/>
<source>%1 h</source>
<translation>%1 sa</translation>
</message>
<message>
<location line="+2"/>
<source>%1 h %2 m</source>
<translation>%1 sa %2 dk</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+182"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Bitcoin yolla</translation>
</message>
<message>
<location line="+76"/>
<source>Coin Control Features</source>
<translation>Para kontrolü özellikleri</translation>
</message>
<message>
<location line="+20"/>
<source>Inputs...</source>
<translation>Girdiler...</translation>
</message>
<message>
<location line="+7"/>
<source>automatically selected</source>
<translation>otomatik seçilmiş</translation>
</message>
<message>
<location line="+19"/>
<source>Insufficient funds!</source>
<translation>Yetersiz fon!</translation>
</message>
<message>
<location line="+77"/>
<source>Quantity:</source>
<translation>Miktar:</translation>
</message>
<message>
<location line="+22"/>
<location line="+35"/>
<source>0</source>
<translation>0</translation>
</message>
<message>
<location line="-19"/>
<source>Bytes:</source>
<translation>Bayt:</translation>
</message>
<message>
<location line="+51"/>
<source>Amount:</source>
<translation>Meblağ:</translation>
</message>
<message>
<location line="+35"/>
<source>Priority:</source>
<translation>Öncelik:</translation>
</message>
<message>
<location line="+19"/>
<source>medium</source>
<translation>orta</translation>
</message>
<message>
<location line="+32"/>
<source>Fee:</source>
<translation>Ücret:</translation>
</message>
<message>
<location line="+35"/>
<source>Low Output:</source>
<translation>Düşük çıktı:</translation>
</message>
<message>
<location line="+19"/>
<source>no</source>
<translation>hayır</translation>
</message>
<message>
<location line="+32"/>
<source>After Fee:</source>
<translation>Ücretten sonra:</translation>
</message>
<message>
<location line="+35"/>
<source>Change</source>
<translation>Değiştir</translation>
</message>
<message>
<location line="+50"/>
<source>custom change address</source>
<translation>özel adres değişikliği</translation>
</message>
<message>
<location line="+106"/>
<source>Send to multiple recipients at once</source>
<translation>Birçok alıcıya aynı anda gönder</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Alıcı ekle</translation>
</message>
<message>
<location line="+16"/>
<source>Remove all transaction fields</source>
<translation>Tüm işlem alanlarını kaldır</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Tümünü &temizle</translation>
</message>
<message>
<location line="+24"/>
<source>Balance:</source>
<translation>Bakiye:</translation>
</message>
<message>
<location line="+47"/>
<source>Confirm the send action</source>
<translation>Yollama etkinliğini teyit ediniz</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>G&önder</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-174"/>
<source>Enter a Mojocoin address (e.g. MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</source>
<translation>Bir Mojocoin adresi gir (örn: MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</translation>
</message>
<message>
<location line="+15"/>
<source>Copy quantity</source>
<translation>Miktarı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Meblağı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy fee</source>
<translation>Ücreti kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy after fee</source>
<translation>Ücretten sonrakini kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy bytes</source>
<translation>Baytları kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy priority</source>
<translation>Önceliği kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy low output</source>
<translation>Düşük çıktıyı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy change</source>
<translation>Para üstünü kopyala</translation>
</message>
<message>
<location line="+87"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> %2'ye (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Gönderiyi teyit ediniz</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>%1 göndermek istediğinizden emin misiniz?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>ve</translation>
</message>
<message>
<location line="+29"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Alıcı adresi geçerli değildir, lütfen denetleyiniz.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Ödeyeceğiniz tutarın sıfırdan yüksek olması gerekir.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Tutar bakiyenizden yüksektir.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Toplam, %1 işlem ücreti ilâve edildiğinde bakiyenizi geçmektedir.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Çift adres bulundu, belli bir gönderi sırasında her adrese sadece tek bir gönderide bulunulabilir.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Hata: İşlem yaratma başarısız oldu!</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Hata: İşlem reddedildi. Bu, örneğin wallet.dat dosyasının bir kopyasını kullandıysanız ve coinler, kopyada harcanmış ve burada harcanmış olarak işaretlenmemişse, cüzdanınızdaki coinlerin bir bölümünün harcanması nedeniyle olabilir. </translation>
</message>
<message>
<location line="+247"/>
<source>WARNING: Invalid Mojocoin address</source>
<translation>UYARI: Geçersiz Mojocoin adresi</translation>
</message>
<message>
<location line="+13"/>
<source>(no label)</source>
<translation>(boş etiket)</translation>
</message>
<message>
<location line="+4"/>
<source>WARNING: unknown change address</source>
<translation>UYARI: bilinmeyen adres değişikliği</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Form</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Mebla&ğ:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Şu adrese öde:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</source>
<translation>Ödemenin gönderileceği adres (örn: MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</translation>
</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>Adres defterinize eklemek için bu adrese ilişik bir etiket giriniz</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Etiket:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Adres defterinden adres seç</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>Panodan adres yapıştır</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>Bu alıcıyı kaldır</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Mojocoin address (e.g. MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</source>
<translation>Bir Mojocoin adresi girin (örn: MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>İmzalar - Mesaj İmzala / Kontrol et</translation>
</message>
<message>
<location line="+13"/>
<location line="+124"/>
<source>&Sign Message</source>
<translation>Mesaj &imzala</translation>
</message>
<message>
<location line="-118"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Bir adresin sizin olduğunu ispatlamak için adresinizle mesaj imzalayabilirsiniz. Oltalama saldırılarının kimliğinizi imzanızla elde etmeyi deneyebilecekleri için belirsiz hiçbir şey imzalamamaya dikkat ediniz. Sadece ayrıntılı açıklaması olan ve tümüne katıldığınız ifadeleri imzalayınız.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</source>
<translation>Mesajın imzalanacağı adres (örn: MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</translation>
</message>
<message>
<location line="+10"/>
<location line="+203"/>
<source>Choose an address from the address book</source>
<translation>Adres defterinden adres seç</translation>
</message>
<message>
<location line="-193"/>
<location line="+203"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-193"/>
<source>Paste address from clipboard</source>
<translation>Panodan adres yapıştır</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>İmzalamak istediğiniz mesajı burada giriniz</translation>
</message>
<message>
<location line="+24"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Güncel imzayı sistem panosuna kopyala</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Mojocoin address</source>
<translation>Bu Mojocoin adresine sahip olduğunuzu ispatlamak için mesajı imzala</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all sign message fields</source>
<translation>Tüm mesaj alanlarını sıfırla</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Tümünü &temizle</translation>
</message>
<message>
<location line="-87"/>
<location line="+70"/>
<source>&Verify Message</source>
<translation>Mesaj &kontrol et</translation>
</message>
<message>
<location line="-64"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>İmza için kullanılan adresi, mesajı (satır sonları, boşluklar, sekmeler vs. karakterleri tam olarak kopyaladığınızdan emin olunuz) ve imzayı aşağıda giriniz. Bir ortadaki adam saldırısı tarafından kandırılmaya mâni olmak için imzadan, imzalı mesajın içeriğini aşan bir anlam çıkarmamaya dikkat ediniz.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</source>
<translation>Mesajın imzalandığı adres (örn: MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Mojocoin address</source>
<translation>Mesajın, belirtilen Mojocoin adresiyle imzalandığından emin olmak için onu doğrula</translation>
</message>
<message>
<location line="+17"/>
<source>Reset all verify message fields</source>
<translation>Tüm mesaj kontrolü alanlarını sıfırla</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Mojocoin address (e.g. MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</source>
<translation>Bir Mojocoin adresi girin (örn: MAAMQ3NSzuRRzdz3Z5b9Y9nGzdCTyjArVk)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>İmzayı oluşturmak için "Mesaj İmzala" unsurunu tıklayın</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Mojocoin signature</source>
<translation>Mojocoin imzası gir</translation>
</message>
<message>
<location line="+85"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Girilen adres geçersizdir.</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>Adresi kontrol edip tekrar deneyiniz.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Girilen adres herhangi bir anahtara işaret etmemektedir.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Cüzdan kilidinin açılması iptal edildi.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Girilen adres için özel anahtar mevcut değildir.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Mesajın imzalanması başarısız oldu.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Mesaj imzalandı.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>İmzanın kodu çözülemedi.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>İmzayı kontrol edip tekrar deneyiniz.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>İmza mesajın hash değeri ile eşleşmedi.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Mesaj doğrulaması başarısız oldu.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Mesaj doğrulandı.</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<location filename="../trafficgraphwidget.cpp" line="+75"/>
<source>KB/s</source>
<translation>KB/s</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+25"/>
<source>Open until %1</source>
<translation>%1 değerine dek açık</translation>
</message>
<message>
<location line="+6"/>
<source>conflicted</source>
<translation>çakışma</translation>
</message>
<message>
<location line="+2"/>
<source>%1/offline</source>
<translation>%1/çevrim dışı</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/doğrulanmadı</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 teyit</translation>
</message>
<message>
<location line="+17"/>
<source>Status</source>
<translation>Durum</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, %n devre üzerinde yayınlama</numerusform><numerusform>, %n devre üzerinde yayınlama</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Kaynak</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Oluşturuldu</translation>
</message>
<message>
<location line="+5"/>
<location line="+13"/>
<source>From</source>
<translation>Gönderen</translation>
</message>
<message>
<location line="+1"/>
<location line="+19"/>
<location line="+58"/>
<source>To</source>
<translation>Alıcı</translation>
</message>
<message>
<location line="-74"/>
<location line="+2"/>
<source>own address</source>
<translation>kendi adresiniz</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>etiket</translation>
</message>
<message>
<location line="+34"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Gider</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>%n blok içerisinde olgunlaşıyor</numerusform><numerusform>%n blok içerisinde olgunlaşıyor</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>kabul edilmedi</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Gelir</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>İşlem ücreti</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Net meblağ</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mesaj</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Yorum</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>İşlem NO</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>Üretilen coinler, harcanmaya başlamadan önce 510 blokta olgunlaşmalıdır. Bu bloğu ürettiğinizde, blok zincirine eklenmek üzere ağda yayınlanır. Eğer blok, zincire girmede başarısız olursa, bloğun durumu "kabul edilmedi"ye dönüşür ve harcanamaz. Bu, başka bir devre sizden birkaç saniye önce bir blok ürettiyse gerçekleşebilir.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Hata ayıklama verileri</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>İşlem</translation>
</message>
<message>
<location line="+5"/>
<source>Inputs</source>
<translation>Girdiler</translation>
</message>
<message>
<location line="+21"/>
<source>Amount</source>
<translation>Meblağ</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>doğru</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>yanlış</translation>
</message>
<message>
<location line="-202"/>
<source>, has not been successfully broadcast yet</source>
<translation>, henüz başarılı bir şekilde yayınlanmadı</translation>
</message>
<message numerus="yes">
<location line="-36"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>%n blok için aç</numerusform><numerusform>%n blok için aç</numerusform></translation>
</message>
<message>
<location line="+67"/>
<source>unknown</source>
<translation>bilinmiyor</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>İşlem detayları</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Bu pano işlemlerin ayrıntılı açıklamasını gösterir</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+231"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tür</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Meblağ</translation>
</message>
<message>
<location line="+52"/>
<source>Open until %1</source>
<translation>%1 değerine dek açık</translation>
</message>
<message>
<location line="+12"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Doğrulandı (%1 teyit)</translation>
</message>
<message numerus="yes">
<location line="-15"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>%n blok için aç</numerusform><numerusform>%n blok için aç</numerusform></translation>
</message>
<message>
<location line="+6"/>
<source>Offline</source>
<translation>Çevrim dışı</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed</source>
<translation>Teyit edilmemiş</translation>
</message>
<message>
<location line="+3"/>
<source>Confirming (%1 of %2 recommended confirmations)</source>
<translation>Teyit ediliyor (tavsiye edilen %2 teyit üzerinden %1 doğrulama)</translation>
</message>
<message>
<location line="+6"/>
<source>Conflicted</source>
<translation>Çakışma</translation>
</message>
<message>
<location line="+3"/>
<source>Immature (%1 confirmations, will be available after %2)</source>
<translation>Olgunlaşmamış (%1 teyit, %2 teyit ardından kullanılabilir olacaktır)</translation>
</message>
<message>
<location line="+3"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Bu blok başka hiçbir düğüm tarafından alınmamıştır ve muhtemelen kabul edilmeyecektir!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Oluşturuldu ama kabul edilmedi</translation>
</message>
<message>
<location line="+42"/>
<source>Received with</source>
<translation>Şununla alındı</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Alındığı kişi</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Gönderildiği adres</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Kendinize ödeme</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Madenden çıkarılan</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(mevcut değil)</translation>
</message>
<message>
<location line="+194"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>İşlem durumu. Doğrulama sayısını görüntülemek için imleci bu alanda tutunuz.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>İşlemin alındığı tarih ve zaman.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>İşlemin türü.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>İşlemin alıcı adresi.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Bakiyeden alınan ya da bakiyeye eklenen meblağ.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+54"/>
<location line="+17"/>
<source>All</source>
<translation>Hepsi</translation>
</message>
<message>
<location line="-16"/>
<source>Today</source>
<translation>Bugün</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Bu hafta</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Bu ay</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Geçen ay</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Bu sene</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Aralık...</translation>
</message>
<message>
<location line="+12"/>
<source>Received with</source>
<translation>Şununla alınan</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Gönderildiği adres</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Kendinize</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Oluşturulan</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Diğer</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Aranacak adres ya da etiket giriniz</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Asgari meblağ</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Adresi kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Etiketi kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Meblağı kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>İşlem numarasını kopyala</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Etiketi düzenle</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>İşlem detaylarını göster</translation>
</message>
<message>
<location line="+138"/>
<source>Export Transaction Data</source>
<translation>İşlem Verisini Dışarı Aktar</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Virgülle ayrılmış değerler dosyası (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Doğrulandı</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Tarih</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tür</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etiket</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Meblağ</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>Tanımlayıcı</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Dışarı aktarmada hata</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>%1 dosyasına yazılamadı.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Aralık:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>ilâ</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+212"/>
<source>Sending...</source>
<translation>Gönderiyor...</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+171"/>
<source>Mojocoin version</source>
<translation>Mojocoin versiyonu</translation>
</message>
<message>
<location line="+1"/>
<source>Usage:</source>
<translation>Kullanım:</translation>
</message>
<message>
<location line="+1"/>
<source>Send command to -server or mojocoind</source>
<translation>-sunucu veya mojocoind'ye komut gönder</translation>
</message>
<message>
<location line="+1"/>
<source>List commands</source>
<translation>Komutları listele</translation>
</message>
<message>
<location line="+1"/>
<source>Get help for a command</source>
<translation>Bir komut için yardım al</translation>
</message>
<message>
<location line="-145"/>
<source>Options:</source>
<translation>Seçenekler:</translation>
</message>
<message>
<location line="+2"/>
<source>Specify configuration file (default: mojocoin.conf)</source>
<translation>Konfigürasyon dosyasını belirt (varsayılan: mojocoin.conf)</translation>
</message>
<message>
<location line="+1"/>
<source>Specify pid file (default: mojocoind.pid)</source>
<translation>pid dosyasını belirt (varsayılan: mojocoin.pid)</translation>
</message>
<message>
<location line="+2"/>
<source>Specify wallet file (within data directory)</source>
<translation>Cüzdan dosyası belirtiniz (veri klasörünün içinde)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Veri dizinini belirt</translation>
</message>
<message>
<location line="-25"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=mojocoinrpc
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 "Mojocoin Alert" [email protected]
</source>
<translation>%s, konfigürasyon dosyasında bir rpcpassword belirlemelisiniz:
%s
Aşağıdaki rastgele şifreyi kullanmanız tavsiye edilir:
rpcuser=mojocoinrpc
rpcpassword=%s
(bu şifreyi hatırlamanız gerekmemektedir)
Kullanıcı adı ve şifre aynı OLMAMALIDIR.
Dosya mevcut değilse, sadece sahibi tarafından okunabilir yetkiyle yaratın.
Ayrıca sorunlardan haberdar edilmek için alertnotify parametresini doldurmanız önerilir;
örneğin: alertnotify=echo %%s | mail -s "Mojocoin Alarmı" [email protected]
</translation>
</message>
<message>
<location line="+27"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Veritabanı önbellek boyutunu megabayt olarak belirt (varsayılan: 25)</translation>
</message>
<message>
<location line="+1"/>
<source>Set database disk log size in megabytes (default: 100)</source>
<translation>Veritabanı disk log boyutunu megabayt olarak ayarla (varsayılan: 100)</translation>
</message>
<message>
<location line="+5"/>
<source>Listen for connections on <port> (default: 9495 or testnet: 19495)</source>
<translation><port> üzerinde bağlantıları dinle (varsayılan: 9495 veya testnet: 19495)</translation>
</message>
<message>
<location line="+1"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Eşler ile en çok <n> adet bağlantı kur (varsayılan: 125)</translation>
</message>
<message>
<location line="+3"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Eş adresleri elde etmek için bir düğüme bağlan ve ardından bağlantıyı kes</translation>
</message>
<message>
<location line="+1"/>
<source>Specify your own public address</source>
<translation>Kendi genel adresinizi tanımlayın</translation>
</message>
<message>
<location line="+4"/>
<source>Bind to given address. Use [host]:port notation for IPv6</source>
<translation>Belirtilen adrese bağlı. IPv6 için [host]:port notasyonunu kullan</translation>
</message>
<message>
<location line="+1"/>
<source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source>
<translation>DNS araması ile eş adresleri sorgula, adres sayısı az ise (varsayılan: 1 -connect hariç)</translation>
</message>
<message>
<location line="+3"/>
<source>Always query for peer addresses via DNS lookup (default: 0)</source>
<translation>DNS araması ile eş adresleri her zaman sorgula (varsayılan: 0)</translation>
</message>
<message>
<location line="+4"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Aksaklık gösteren eşlerle bağlantıyı kesme sınırı (varsayılan: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Aksaklık gösteren eşlerle yeni bağlantıları engelleme süresi, saniye olarak (varsayılan: 86400)</translation>
</message>
<message>
<location line="-35"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>IPv4 üzerinde dinlemek için %u numaralı RPC portunun kurulumu sırasında hata meydana geldi: %s</translation>
</message>
<message>
<location line="+62"/>
<source>Listen for JSON-RPC connections on <port> (default: 9496 or testnet: 19496)</source>
<translation><port> üzerinde JSON-RPC bağlantılarını dinle (varsayılan: 9496 veya testnet: 19496)</translation>
</message>
<message>
<location line="-16"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Konut satırı ve JSON-RPC komutlarını kabul et</translation>
</message>
<message>
<location line="+1"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Arka planda daemon (servis) olarak çalış ve komutları kabul et</translation>
</message>
<message>
<location line="+1"/>
<source>Use the test network</source>
<translation>Deneme şebekesini kullan</translation>
</message>
<message>
<location line="-23"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Dışarıdan gelen bağlantıları kabul et (varsayılan: -proxy veya -connect yoksa 1)</translation>
</message>
<message>
<location line="-28"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>IPv6 üzerinde dinlemek için %u numaralı RPC portu kurulurken bir hata meydana geldi, IPv4'e dönülüyor: %s</translation>
</message>
<message>
<location line="+93"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Bayt olarak yüksek öncelikli/düşük ücretli işlemlerin maksimum boyutunu belirle (varsayılan: 27000)</translation>
</message>
<message>
<location line="+15"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Uyarı: -paytxfee çok yüksek bir değere ayarlanmış! Bu, bir işlem gönderdiğiniz takdirde ödeyeceğiniz ücrettir.</translation>
</message>
<message>
<location line="-103"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Mojocoin will not work properly.</source>
<translation>Uyarı: Lütfen bilgisayarınızın tarih ve saatinin doğru olduğunu kontrol ediniz! Saatiniz yanlış ise, Mojocoin düzgün çalışmayacaktır.</translation>
</message>
<message>
<location line="+130"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>Uyarı: wallet.dat dosyasının okunması sırasında bir hata meydana geldi! Tüm anahtarlar doğru bir şekilde okundu, ancak işlem verileri ya da adres defteri girdileri hatalı veya eksik olabilir.</translation>
</message>
<message>
<location line="-16"/>
<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>Uyarı: wallet.dat bozuk, veriler geri kazanıldı! Orijinal wallet.dat, wallet.{zamandamgası}.bak olarak %s klasörüne kaydedildi; bakiyeniz ya da işlemleriniz yanlışsa bir yedekten tekrar yüklemelisiniz.</translation>
</message>
<message>
<location line="-34"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Bozuk bir wallet.dat dosyasından özel anahtarları geri kazanmayı dene</translation>
</message>
<message>
<location line="+5"/>
<source>Block creation options:</source>
<translation>Blok oluşturma seçenekleri:</translation>
</message>
<message>
<location line="-67"/>
<source>Connect only to the specified node(s)</source>
<translation>Sadece belirtilen düğüme veya düğümlere bağlan</translation>
</message>
<message>
<location line="+4"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Kendi IP adresini keşfet (varsayılan: dinlenildiğinde ve -externalip yoksa 1)</translation>
</message>
<message>
<location line="+101"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Herhangi bir portun dinlenmesi başarısız oldu. Bunu istiyorsanız -listen=0 seçeneğini kullanınız.</translation>
</message>
<message>
<location line="-2"/>
<source>Invalid -tor address: '%s'</source>
<translation>Geçersiz -tor adresi: '%s'</translation>
</message>
<message>
<location line="+4"/>
<source>Invalid amount for -reservebalance=<amount></source>
<translation>-reservebalance=<amount> için geçersiz miktar</translation>
</message>
<message>
<location line="-89"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Bağlantı başına azami alım tamponu, <n>*1000 bayt (varsayılan: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Bağlantı başına azami yollama tamponu, <n>*1000 bayt (varsayılan: 1000)</translation>
</message>
<message>
<location line="-16"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Sadece <net> şebekesindeki düğümlere bağlan (IPv4, IPv6 ya da Tor)</translation>
</message>
<message>
<location line="+30"/>
<source>Prepend debug output with timestamp</source>
<translation>Tarih bilgisini, hata ayıklama çıktısının başına ekle</translation>
</message>
<message>
<location line="+40"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation> SSL seçenekleri: (SSL kurulum bilgisi için Bitcoin vikisine bakınız)</translation>
</message>
<message>
<location line="-38"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Trace/hata ayıklama verilerini debug.log dosyası yerine konsola gönder</translation>
</message>
<message>
<location line="+34"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Bayt olarak maksimum blok boyutunu belirle (varsayılan: 250000)</translation>
</message>
<message>
<location line="-1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Bayt olarak asgari blok boyutunu tanımla (varsayılan: 0)</translation>
</message>
<message>
<location line="-34"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>İstemci başlatıldığında debug.log dosyasını küçült (varsayılan: -debug bulunmadığında 1)</translation>
</message>
<message>
<location line="-41"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Bağlantı zaman aşım süresini milisaniye olarak belirt (varsayılan: 5000)</translation>
</message>
<message>
<location line="+28"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Dinlenecek portu haritalamak için UPnP kullan (varsayılan: 0)</translation>
</message>
<message>
<location line="-1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Dinlenecek portu haritalamak için UPnP kullan (varsayılan: dinlenildiğinde 1)</translation>
</message>
<message>
<location line="-25"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Tor gizli servisine erişim için vekil sunucu kullan (varsayılan: -proxy ile aynı)</translation>
</message>
<message>
<location line="+45"/>
<source>Username for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için kullanıcı ismi</translation>
</message>
<message>
<location line="+54"/>
<source>Verifying database integrity...</source>
<translation>Veritabanı bütünlüğü doğrulanıyor...</translation>
</message>
<message>
<location line="+42"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Hata: Cüzdan kilitli, işlem yaratılamıyor!</translation>
</message>
<message>
<location line="+2"/>
<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>Hata: Bu işlem; miktarı, karmaşıklığı veya son alınan miktarın kullanımı nedeniyle en az %s işlem ücreti gerektirir!</translation>
</message>
<message>
<location line="+3"/>
<source>Error: Transaction creation failed!</source>
<translation>Hata: İşlem yaratma başarısız oldu!</translation>
</message>
<message>
<location line="+2"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Hata: İşlem reddedildi. Bu; cüzdanınızdaki bazı coinler, önceden harcanmışsa, örneğin wallet.dat dosyasının bir kopyasını kullandıysanız ve bu kopyadaki coinler harcanmış ve burada harcanmış olarak işaretlenmediyse gerçekleşebilir.</translation>
</message>
<message>
<location line="+7"/>
<source>Warning</source>
<translation>Uyarı</translation>
</message>
<message>
<location line="+1"/>
<source>Information</source>
<translation>Bilgi</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Uyarı: Bu sürüm çok eskidir, güncellemeniz gerekir!</translation>
</message>
<message>
<location line="-52"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat bozuk, geri kazanım başarısız oldu</translation>
</message>
<message>
<location line="-59"/>
<source>Password for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için parola</translation>
</message>
<message>
<location line="-47"/>
<source>Connect through SOCKS5 proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source>
<translation>Diğer devrelerle saati senkronize et. Sisteminizdeki saat doğru ise devre dışı bırakın, örn: NTC ile senkronize etme (varsayılan: 1)</translation>
</message>
<message>
<location line="+12"/>
<source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source>
<translation>İşlem yaratırken, bundan daha küçük değere sahip girdileri yok say (varsayılan: 0.01)</translation>
</message>
<message>
<location line="+6"/>
<source>Output debugging information (default: 0, supplying <category> is optional)</source>
<translation>Hata ayıklama bilgisi çıktısı al (varsayılan: 0, <category> belirtmek isteğe bağlıdır)</translation>
</message>
<message>
<location line="+2"/>
<source>If <category> is not supplied, output all debugging information.</source>
<translation><category> belirtilmediyse, bütün ayıklama bilgisinin çıktısını al.</translation>
</message>
<message>
<location line="+1"/>
<source><category> can be:</source>
<translation><category> şunlar olabilir:</translation>
</message>
<message>
<location line="+4"/>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source>
<translation>Bağlanım deneme moduna gir, bu mod blokların anında çözülebilmesini sağlayan özel bir zincir kullanır. Bu seçenek bağlanım deneme araçları ve uygulama geliştirme için tasarlanmıştır.</translation>
</message>
<message>
<location line="+8"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Belirtilen İP adresinden JSON-RPC bağlantılarını kabul et</translation>
</message>
<message>
<location line="+1"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Şu <ip> adresinde (varsayılan: 127.0.0.1) çalışan düğüme komut yolla</translation>
</message>
<message>
<location line="+1"/>
<source>Wait for RPC server to start</source>
<translation>RPC sunucusunun başlamasını bekle</translation>
</message>
<message>
<location line="+1"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>RPC çağrı hizmeti verecek dizi sayısını ayarla (varsayılan: 4)</translation>
</message>
<message>
<location line="+1"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>En iyi blok değiştiğinde komutu çalıştır (komut için %s parametresi blok hash değeri ile değiştirilecektir)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Bir cüzdan işlemi değiştiğinde komutu çalıştır (komuttaki %s TxID ile değiştirilecektir)</translation>
</message>
<message>
<location line="+3"/>
<source>Require a confirmations for change (default: 0)</source>
<translation>Değişim için bir onay sayısı talep et (varsayılan: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>İlgili alarm alındığında komutu çalıştır (cmd'deki %s, mesaj ile değiştirilecektir)</translation>
</message>
<message>
<location line="+3"/>
<source>Upgrade wallet to latest format</source>
<translation>Cüzdanı en yeni biçime güncelle</translation>
</message>
<message>
<location line="+1"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Anahtar alan boyutunu <n> değerine ayarla (varsayılan: 100)</translation>
</message>
<message>
<location line="+1"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Blok zincirini eksik cüzdan işlemleri için tekrar tara</translation>
</message>
<message>
<location line="+3"/>
<source>How thorough the block verification is (0-6, default: 1)</source>
<translation>Blok kontrolünün ne kadar derin olacağı (0-6, varsayılan: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Imports blocks from external blk000?.dat file</source>
<translation>Harici blk000?.dat dosyasından blok içeri aktar</translation>
</message>
<message>
<location line="+1"/>
<source>Keep at most <n> MiB of unconnectable blocks in memory (default: %u)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>JSON-RPC bağlantıları için OpenSSL (https) kullan</translation>
</message>
<message>
<location line="+1"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Sunucu sertifika dosyası (varsayılan: server.cert)</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Sunucu özel anahtarı (varsayılan: server.pem)</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Initialization sanity check failed. Mojocoin is shutting down.</source>
<translation>Başlangıç uygunluk kontrolü başarısız oldu. Mojocoin kapatılıyor.</translation>
</message>
<message>
<location line="+20"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Error: Wallet unlocked for staking only, unable to create transaction.</source>
<translation>Hata: Cüzdanın kilidi sadece pay almak için açılmıştır, işlem yaratılamıyor.</translation>
</message>
<message>
<location line="+16"/>
<source>Error: Disk space is low!</source>
<translation>Uyarı: Disk alanı düşük!</translation>
</message>
<message>
<location line="+1"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>Bu bir ön test sürümüdür - kullanım riski size aittir - madencilik veya ticari uygulamalarda kullanmayın</translation>
</message>
<message>
<location line="-168"/>
<source>This help message</source>
<translation>Bu yardım mesajı</translation>
</message>
<message>
<location line="+104"/>
<source>Wallet %s resides outside data directory %s.</source>
<translation>Cüzdan %s, veri klasörü %s dışında yer alıyor.</translation>
</message>
<message>
<location line="+35"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Bu bilgisayarda %s unsuruna bağlanılamadı. (bind şu hatayı iletti: %d, %s)</translation>
</message>
<message>
<location line="-129"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>-addnode, -seednode ve -connect için DNS aramalarına izin ver</translation>
</message>
<message>
<location line="+125"/>
<source>Loading addresses...</source>
<translation>Adresler yükleniyor...</translation>
</message>
<message>
<location line="-10"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>wallet.dat dosyasının yüklenmesinde hata oluştu: bozuk cüzdan</translation>
</message>
<message>
<location line="+4"/>
<source>Error loading wallet.dat: Wallet requires newer version of Mojocoin</source>
<translation>wallet.dat yüklenirken hata: Cüzdan, daha yeni bir Mojocoin versiyonuna ihtiyaç duyuyor.</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet needed to be rewritten: restart Mojocoin to complete</source>
<translation>Cüzdanın yeniden yazılması gerekmektedir: Tamamlamak için Mojocoin'i yeniden başlatın</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat</source>
<translation>wallet.dat dosyasının yüklenmesinde hata oluştu</translation>
</message>
<message>
<location line="-15"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Geçersiz -proxy adresi: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>-onlynet için bilinmeyen bir şebeke belirtildi: '%s'</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>-bind adresi çözümlenemedi: '%s'</translation>
</message>
<message>
<location line="+2"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>-externalip adresi çözümlenemedi: '%s'</translation>
</message>
<message>
<location line="-22"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>-paytxfee=<meblağ> için geçersiz meblağ: '%s'</translation>
</message>
<message>
<location line="+58"/>
<source>Sending...</source>
<translation>Gönderiyor...</translation>
</message>
<message>
<location line="+5"/>
<source>Invalid amount</source>
<translation>Geçersiz meblağ</translation>
</message>
<message>
<location line="+1"/>
<source>Insufficient funds</source>
<translation>Yetersiz bakiye</translation>
</message>
<message>
<location line="-40"/>
<source>Loading block index...</source>
<translation>Blok indeksi yükleniyor...</translation>
</message>
<message>
<location line="-109"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Bağlanılacak düğüm ekle ve bağlantıyı zinde tutmaya çalış</translation>
</message>
<message>
<location line="+124"/>
<source>Unable to bind to %s on this computer. Mojocoin is probably already running.</source>
<translation>Bu bilgisayarda %s bağlanamadı. Mojocoin muhtemelen halen çalışmaktadır.</translation>
</message>
<message>
<location line="-101"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Gönderdiğiniz işleme eklenmek üzere KB başına ücret</translation>
</message>
<message>
<location line="+33"/>
<source>Minimize weight consumption (experimental) (default: 0)</source>
<translation>Ağırlık tüketimini minimuma indirme (deneysel) (varsayılan: 0)</translation>
</message>
<message>
<location line="+8"/>
<source>How many blocks to check at startup (default: 500, 0 = all)</source>
<translation>Başlangıçta kontrol edilecek blok sayısı (varsayılan: 500, 0 = tümü)</translation>
</message>
<message>
<location line="+14"/>
<source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source>
<translation>Kabul edilebilir şifre kodları (varsayılan: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source>
<translation>Uyarı: Artık kullanılmayan değişken -debugnet yoksayıldı. Bunun yerine -debug=net kullanın.</translation>
</message>
<message>
<location line="+8"/>
<source>Invalid amount for -mininput=<amount>: '%s'</source>
<translation>-mininput=<amount>: '%s' için geçersiz miktar</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Mojocoin is probably already running.</source>
<translation>Veri klasörü %s üzerinde kilit elde edilemedi. Mojocoin muhtemelen halen çalışmaktadır.</translation>
</message>
<message>
<location line="+4"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Cüzdan veritabanı ortamı %s başlatılmaya çalışılırken hata oluştu!</translation>
</message>
<message>
<location line="+15"/>
<source>Loading wallet...</source>
<translation>Cüzdan yükleniyor...</translation>
</message>
<message>
<location line="+8"/>
<source>Cannot downgrade wallet</source>
<translation>Cüzdan eski biçime geri alınamaz</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot write default address</source>
<translation>Varsayılan adres yazılamadı</translation>
</message>
<message>
<location line="+1"/>
<source>Rescanning...</source>
<translation>Yeniden tarama...</translation>
</message>
<message>
<location line="+2"/>
<source>Done loading</source>
<translation>Yükleme tamamlandı</translation>
</message>
<message>
<location line="-159"/>
<source>To use the %s option</source>
<translation>%s seçeneğini kullanmak için</translation>
</message>
<message>
<location line="+186"/>
<source>Error</source>
<translation>Hata</translation>
</message>
<message>
<location line="-18"/>
<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>rpcpassword=<parola> şu yapılandırma dosyasında belirtilmelidir:
%s
Dosya mevcut değilse, sadece sahibi için okumayla sınırlı izin ile oluşturunuz.</translation>
</message>
</context>
</TS><|fim▁end|> | This label turns red, if the priority is smaller than "medium". |
<|file_name|>ABTreeSceneNode.cpp<|end_file_name|><|fim▁begin|>/*-------------------------------------------------------------------------
This source file is a part of Whisperwind.(GameEngine + GamePlay + GameTools)
For the latest info, see http://lisuyong.com
Copyright (c) 2012 Suyong Li ([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<|fim▁hole|>all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE
-------------------------------------------------------------------------*/
#include "ABTreeSceneNode.h"
namespace Engine
{
//---------------------------------------------------------------------
void ABTreeSceneNode::updatedAABB()
{
/// TODO!
}
}<|fim▁end|> | 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 |
<|file_name|>tweetService.ts<|end_file_name|><|fim▁begin|>import {Injectable} from '@angular/core';
import {Http} from '@angular/http';
import {Events, Platform} from 'ionic-angular';
@Injectable()
export class TweetService {
tweets: any;
timer: any;
error: any;
errorCount: number;
constructor(public http: Http, public events: Events, public platform: Platform) {
this.timer = null;
this.errorCount = 0;
this.tweets = [];
this.loadTweets();
// Reload Trains when we come out of the background
this.platform.resume.subscribe(() => {
this.loadTweets();
});
}
loadTweets() {
if (this.timer !== null) {
clearTimeout(this.timer);
}
if (this.http) {
let url = "http://klingmandesign.com/marta/twitter/index.php?key=martaApp&count=40&date=" + (new Date()).getTime();
//url = "http://klingmandesign.com/marta/data.php";<|fim▁hole|> data => {
this.tweets = data;
this.errorCount = 0;
this.events.publish('tweets:updated');
},
err => {
this.error = err;
this.events.publish('tweets:error');
},
() => {
//console.log("Finally");
this.timer = setTimeout(() => {
this.loadTweets()
}, 60000); // 1 minute
});
} else {
this.errorCount++;
this.timer = setTimeout(() => {
this.loadTweets()
}, 200); // try again in a fifth a second
console.log('http went missing');
if (this.errorCount > 10) {
this.events.publish('tweets:error');
}
}
}
getError() {
return this.error;
}
getTweets() {
return this.tweets;
}
}<|fim▁end|> | this.http.get(url)
.map(res => res.json()).subscribe( |
<|file_name|>inflate.go<|end_file_name|><|fim▁begin|>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:generate go run gen.go -output fixedhuff.go
// Package flate implements the DEFLATE compressed data format, described in
// RFC 1951. The gzip and zlib packages implement access to DEFLATE-based file
// formats.
package flate
import (
"bufio"
"io"
"strconv"
)
const (
maxCodeLen = 16 // max length of Huffman code
maxHist = 32768 // max history required
// The next three numbers come from the RFC section 3.2.7, with the
// additional proviso in section 3.2.5 which implies that distance codes
// 30 and 31 should never occur in compressed data.
maxNumLit = 286
maxNumDist = 30
numCodes = 19 // number of codes in Huffman meta-code
)
// A CorruptInputError reports the presence of corrupt input at a given offset.
type CorruptInputError int64
func (e CorruptInputError) Error() string {
return "flate: corrupt input before offset " + strconv.FormatInt(int64(e), 10)
}
// An InternalError reports an error in the flate code itself.
type InternalError string
func (e InternalError) Error() string { return "flate: internal error: " + string(e) }
// A ReadError reports an error encountered while reading input.
type ReadError struct {
Offset int64 // byte offset where error occurred
Err error // error returned by underlying Read
}
func (e *ReadError) Error() string {
return "flate: read error at offset " + strconv.FormatInt(e.Offset, 10) + ": " + e.Err.Error()
}
// A WriteError reports an error encountered while writing output.
type WriteError struct {
Offset int64 // byte offset where error occurred
Err error // error returned by underlying Write
}
func (e *WriteError) Error() string {
return "flate: write error at offset " + strconv.FormatInt(e.Offset, 10) + ": " + e.Err.Error()
}
// Resetter resets a ReadCloser returned by NewReader or NewReaderDict to
// to switch to a new underlying Reader. This permits reusing a ReadCloser
// instead of allocating a new one.
type Resetter interface {
// Reset discards any buffered data and resets the Resetter as if it was
// newly initialized with the given reader.
Reset(r io.Reader, dict []byte) error
}
// Note that much of the implementation of huffmanDecoder is also copied
// into gen.go (in package main) for the purpose of precomputing the
// fixed huffman tables so they can be included statically.
// The data structure for decoding Huffman tables is based on that of
// zlib. There is a lookup table of a fixed bit width (huffmanChunkBits),
// For codes smaller than the table width, there are multiple entries
// (each combination of trailing bits has the same value). For codes
// larger than the table width, the table contains a link to an overflow
// table. The width of each entry in the link table is the maximum code
// size minus the chunk width.
// Note that you can do a lookup in the table even without all bits
// filled. Since the extra bits are zero, and the DEFLATE Huffman codes
// have the property that shorter codes come before longer ones, the
// bit length estimate in the result is a lower bound on the actual
// number of bits.
// chunk & 15 is number of bits
// chunk >> 4 is value, including table link
const (
huffmanChunkBits = 9
huffmanNumChunks = 1 << huffmanChunkBits
huffmanCountMask = 15
huffmanValueShift = 4
)
type huffmanDecoder struct {
min int // the minimum code length
chunks [huffmanNumChunks]uint32 // chunks as described above
links [][]uint32 // overflow links
linkMask uint32 // mask the width of the link table
}
// Initialize Huffman decoding tables from array of code lengths.
// Following this function, h is guaranteed to be initialized into a complete
// tree (i.e., neither over-subscribed nor under-subscribed). The exception is a
// degenerate case where the tree has only a single symbol with length 1. Empty
// trees are permitted.
func (h *huffmanDecoder) init(bits []int) bool {
// Sanity enables additional runtime tests during Huffman
// table construction. It's intended to be used during
// development to supplement the currently ad-hoc unit tests.
const sanity = false
if h.min != 0 {
*h = huffmanDecoder{}
}
// Count number of codes of each length,
// compute min and max length.
var count [maxCodeLen]int
var min, max int
for _, n := range bits {
if n == 0 {
continue
}
if min == 0 || n < min {
min = n
}
if n > max {
max = n
}
count[n]++
}
// Empty tree. The decompressor.huffSym function will fail later if the tree
// is used. Technically, an empty tree is only valid for the HDIST tree and
// not the HCLEN and HLIT tree. However, a stream with an empty HCLEN tree
// is guaranteed to fail since it will attempt to use the tree to decode the
// codes for the HLIT and HDIST trees. Similarly, an empty HLIT tree is
// guaranteed to fail later since the compressed data section must be
// composed of at least one symbol (the end-of-block marker).
if max == 0 {
return true
}
code := 0
var nextcode [maxCodeLen]int
for i := min; i <= max; i++ {
code <<= 1
nextcode[i] = code
code += count[i]
}
// Check that the coding is complete (i.e., that we've
// assigned all 2-to-the-max possible bit sequences).
// Exception: To be compatible with zlib, we also need to
// accept degenerate single-code codings. See also
// TestDegenerateHuffmanCoding.
if code != 1<<uint(max) && !(code == 1 && max == 1) {
return false
}
h.min = min
if max > huffmanChunkBits {
numLinks := 1 << (uint(max) - huffmanChunkBits)
h.linkMask = uint32(numLinks - 1)
// create link tables
link := nextcode[huffmanChunkBits+1] >> 1
h.links = make([][]uint32, huffmanNumChunks-link)
for j := uint(link); j < huffmanNumChunks; j++ {
reverse := int(reverseByte[j>>8]) | int(reverseByte[j&0xff])<<8
reverse >>= uint(16 - huffmanChunkBits)
off := j - uint(link)
if sanity && h.chunks[reverse] != 0 {
panic("impossible: overwriting existing chunk")
}
h.chunks[reverse] = uint32(off<<huffmanValueShift | (huffmanChunkBits + 1))
h.links[off] = make([]uint32, numLinks)
}
}
for i, n := range bits {
if n == 0 {
continue
}
code := nextcode[n]
nextcode[n]++
chunk := uint32(i<<huffmanValueShift | n)
reverse := int(reverseByte[code>>8]) | int(reverseByte[code&0xff])<<8
reverse >>= uint(16 - n)
if n <= huffmanChunkBits {
for off := reverse; off < len(h.chunks); off += 1 << uint(n) {
// We should never need to overwrite
// an existing chunk. Also, 0 is
// never a valid chunk, because the
// lower 4 "count" bits should be
// between 1 and 15.
if sanity && h.chunks[off] != 0 {
panic("impossible: overwriting existing chunk")
}
h.chunks[off] = chunk
}
} else {
j := reverse & (huffmanNumChunks - 1)
if sanity && h.chunks[j]&huffmanCountMask != huffmanChunkBits+1 {
// Longer codes should have been
// associated with a link table above.
panic("impossible: not an indirect chunk")
}
value := h.chunks[j] >> huffmanValueShift
linktab := h.links[value]
reverse >>= huffmanChunkBits
for off := reverse; off < len(linktab); off += 1 << uint(n-huffmanChunkBits) {
if sanity && linktab[off] != 0 {
panic("impossible: overwriting existing chunk")
}
linktab[off] = chunk
}
}
}
if sanity {
// Above we've sanity checked that we never overwrote
// an existing entry. Here we additionally check that
// we filled the tables completely.
for i, chunk := range h.chunks {
if chunk == 0 {
// As an exception, in the degenerate
// single-code case, we allow odd
// chunks to be missing.
if code == 1 && i%2 == 1 {
continue
}
panic("impossible: missing chunk")
}
}
for _, linktab := range h.links {
for _, chunk := range linktab {
if chunk == 0 {
panic("impossible: missing chunk")
}
}
}
}
return true
}
// The actual read interface needed by NewReader.
// If the passed in io.Reader does not also have ReadByte,
// the NewReader will introduce its own buffering.
type Reader interface {
io.Reader
io.ByteReader
}
// Decompress state.
type decompressor struct {
// Input source.
r Reader
roffset int64
woffset int64
// Input bits, in top of b.
b uint32
nb uint
// Huffman decoders for literal/length, distance.
h1, h2 huffmanDecoder
// Length arrays used to define Huffman codes.
bits *[maxNumLit + maxNumDist]int
codebits *[numCodes]int
// Output history, buffer.
hist *[maxHist]byte
hp int // current output position in buffer
hw int // have written hist[0:hw] already
hfull bool // buffer has filled at least once
// Temporary buffer (avoids repeated allocation).
buf [4]byte
// Next step in the decompression,
// and decompression state.
step func(*decompressor)
final bool
err error
toRead []byte
hl, hd *huffmanDecoder
copyLen int
copyDist int
}
func (f *decompressor) nextBlock() {
if f.final {
if f.hw != f.hp {
f.flush((*decompressor).nextBlock)
return
}
f.err = io.EOF
return
}
for f.nb < 1+2 {
if f.err = f.moreBits(); f.err != nil {
return
}
}
f.final = f.b&1 == 1
f.b >>= 1
typ := f.b & 3
f.b >>= 2
f.nb -= 1 + 2
switch typ {
case 0:
f.dataBlock()
case 1:
// compressed, fixed Huffman tables
f.hl = &fixedHuffmanDecoder
f.hd = nil
f.huffmanBlock()
case 2:
// compressed, dynamic Huffman tables
if f.err = f.readHuffman(); f.err != nil {
break
}
f.hl = &f.h1
f.hd = &f.h2
f.huffmanBlock()
default:
// 3 is reserved.
f.err = CorruptInputError(f.roffset)
}
}
func (f *decompressor) Read(b []byte) (int, error) {
for {
if len(f.toRead) > 0 {
n := copy(b, f.toRead)
f.toRead = f.toRead[n:]
return n, nil
}
if f.err != nil {
return 0, f.err
}
f.step(f)
}
}
// Support the io.WriteTo interface for io.Copy and friends.
func (f *decompressor) WriteTo(w io.Writer) (int64, error) {
total := int64(0)
for {
if f.err != nil {
if f.err == io.EOF {
return total, nil
}
return total, f.err
}
if len(f.toRead) > 0 {
var n int
n, f.err = w.Write(f.toRead)
if f.err != nil {
return total, f.err
}
if n != len(f.toRead) {
return total, io.ErrShortWrite
}
f.toRead = f.toRead[:0]
total += int64(n)
}
f.step(f)
}
}
func (f *decompressor) Close() error {
if f.err == io.EOF {
return nil
}
return f.err
}
// RFC 1951 section 3.2.7.
// Compression with dynamic Huffman codes
var codeOrder = [...]int{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}
func (f *decompressor) readHuffman() error {
// HLIT[5], HDIST[5], HCLEN[4].
for f.nb < 5+5+4 {
if err := f.moreBits(); err != nil {
return err
}
}
nlit := int(f.b&0x1F) + 257
if nlit > maxNumLit {
return CorruptInputError(f.roffset)
}
f.b >>= 5
ndist := int(f.b&0x1F) + 1
if ndist > maxNumDist {
return CorruptInputError(f.roffset)
}
f.b >>= 5
nclen := int(f.b&0xF) + 4
// numCodes is 19, so nclen is always valid.
f.b >>= 4
f.nb -= 5 + 5 + 4
// (HCLEN+4)*3 bits: code lengths in the magic codeOrder order.
for i := 0; i < nclen; i++ {
for f.nb < 3 {
if err := f.moreBits(); err != nil {
return err
}
}
f.codebits[codeOrder[i]] = int(f.b & 0x7)
f.b >>= 3
f.nb -= 3
}
for i := nclen; i < len(codeOrder); i++ {
f.codebits[codeOrder[i]] = 0
}
if !f.h1.init(f.codebits[0:]) {
return CorruptInputError(f.roffset)
}
// HLIT + 257 code lengths, HDIST + 1 code lengths,
// using the code length Huffman code.
for i, n := 0, nlit+ndist; i < n; {
x, err := f.huffSym(&f.h1)
if err != nil {
return err
}
if x < 16 {
// Actual length.
f.bits[i] = x
i++
continue
}
// Repeat previous length or zero.
var rep int
var nb uint
var b int
switch x {
default:
return InternalError("unexpected length code")
case 16:
rep = 3
nb = 2
if i == 0 {
return CorruptInputError(f.roffset)
}
b = f.bits[i-1]
case 17:
rep = 3
nb = 3
b = 0
case 18:
rep = 11
nb = 7
b = 0
}
for f.nb < nb {
if err := f.moreBits(); err != nil {
return err
}
}
rep += int(f.b & uint32(1<<nb-1))
f.b >>= nb
f.nb -= nb
if i+rep > n {
return CorruptInputError(f.roffset)
}
for j := 0; j < rep; j++ {
f.bits[i] = b
i++
}
}
if !f.h1.init(f.bits[0:nlit]) || !f.h2.init(f.bits[nlit:nlit+ndist]) {
return CorruptInputError(f.roffset)
}
// In order to preserve the property that we never read any extra bytes
// after the end of the DEFLATE stream, huffSym conservatively reads min
// bits at a time until it decodes the symbol. However, since every block
// must end with an EOB marker, we can use that as the minimum number of<|fim▁hole|> if f.bits[endBlockMarker] > 0 {
f.h1.min = f.bits[endBlockMarker] // Length of EOB marker
}
return nil
}
// Decode a single Huffman block from f.
// hl and hd are the Huffman states for the lit/length values
// and the distance values, respectively. If hd == nil, using the
// fixed distance encoding associated with fixed Huffman blocks.
func (f *decompressor) huffmanBlock() {
for {
v, err := f.huffSym(f.hl)
if err != nil {
f.err = err
return
}
var n uint // number of bits extra
var length int
switch {
case v < 256:
f.hist[f.hp] = byte(v)
f.hp++
if f.hp == len(f.hist) {
// After the flush, continue this loop.
f.flush((*decompressor).huffmanBlock)
return
}
continue
case v == 256:
// Done with huffman block; read next block.
f.step = (*decompressor).nextBlock
return
// otherwise, reference to older data
case v < 265:
length = v - (257 - 3)
n = 0
case v < 269:
length = v*2 - (265*2 - 11)
n = 1
case v < 273:
length = v*4 - (269*4 - 19)
n = 2
case v < 277:
length = v*8 - (273*8 - 35)
n = 3
case v < 281:
length = v*16 - (277*16 - 67)
n = 4
case v < 285:
length = v*32 - (281*32 - 131)
n = 5
case v < maxNumLit:
length = 258
n = 0
default:
f.err = CorruptInputError(f.roffset)
return
}
if n > 0 {
for f.nb < n {
if err = f.moreBits(); err != nil {
f.err = err
return
}
}
length += int(f.b & uint32(1<<n-1))
f.b >>= n
f.nb -= n
}
var dist int
if f.hd == nil {
for f.nb < 5 {
if err = f.moreBits(); err != nil {
f.err = err
return
}
}
dist = int(reverseByte[(f.b&0x1F)<<3])
f.b >>= 5
f.nb -= 5
} else {
if dist, err = f.huffSym(f.hd); err != nil {
f.err = err
return
}
}
switch {
case dist < 4:
dist++
case dist < maxNumDist:
nb := uint(dist-2) >> 1
// have 1 bit in bottom of dist, need nb more.
extra := (dist & 1) << nb
for f.nb < nb {
if err = f.moreBits(); err != nil {
f.err = err
return
}
}
extra |= int(f.b & uint32(1<<nb-1))
f.b >>= nb
f.nb -= nb
dist = 1<<(nb+1) + 1 + extra
default:
f.err = CorruptInputError(f.roffset)
return
}
// Copy history[-dist:-dist+length] into output.
if dist > len(f.hist) {
f.err = InternalError("bad history distance")
return
}
// No check on length; encoding can be prescient.
if !f.hfull && dist > f.hp {
f.err = CorruptInputError(f.roffset)
return
}
f.copyLen, f.copyDist = length, dist
if f.copyHist() {
return
}
}
}
// copyHist copies f.copyLen bytes from f.hist (f.copyDist bytes ago) to itself.
// It reports whether the f.hist buffer is full.
func (f *decompressor) copyHist() bool {
p := f.hp - f.copyDist
if p < 0 {
p += len(f.hist)
}
for f.copyLen > 0 {
n := f.copyLen
if x := len(f.hist) - f.hp; n > x {
n = x
}
if x := len(f.hist) - p; n > x {
n = x
}
forwardCopy(f.hist[:], f.hp, p, n)
p += n
f.hp += n
f.copyLen -= n
if f.hp == len(f.hist) {
// After flush continue copying out of history.
f.flush((*decompressor).copyHuff)
return true
}
if p == len(f.hist) {
p = 0
}
}
return false
}
func (f *decompressor) copyHuff() {
if f.copyHist() {
return
}
f.huffmanBlock()
}
// Copy a single uncompressed data block from input to output.
func (f *decompressor) dataBlock() {
// Uncompressed.
// Discard current half-byte.
f.nb = 0
f.b = 0
// Length then ones-complement of length.
nr, err := io.ReadFull(f.r, f.buf[0:4])
f.roffset += int64(nr)
if err != nil {
f.err = &ReadError{f.roffset, err}
return
}
n := int(f.buf[0]) | int(f.buf[1])<<8
nn := int(f.buf[2]) | int(f.buf[3])<<8
if uint16(nn) != uint16(^n) {
f.err = CorruptInputError(f.roffset)
return
}
if n == 0 {
// 0-length block means sync
f.flush((*decompressor).nextBlock)
return
}
f.copyLen = n
f.copyData()
}
// copyData copies f.copyLen bytes from the underlying reader into f.hist.
// It pauses for reads when f.hist is full.
func (f *decompressor) copyData() {
n := f.copyLen
for n > 0 {
m := len(f.hist) - f.hp
if m > n {
m = n
}
m, err := io.ReadFull(f.r, f.hist[f.hp:f.hp+m])
f.roffset += int64(m)
if err != nil {
f.err = &ReadError{f.roffset, err}
return
}
n -= m
f.hp += m
if f.hp == len(f.hist) {
f.copyLen = n
f.flush((*decompressor).copyData)
return
}
}
f.step = (*decompressor).nextBlock
}
func (f *decompressor) setDict(dict []byte) {
if len(dict) > len(f.hist) {
// Will only remember the tail.
dict = dict[len(dict)-len(f.hist):]
}
f.hp = copy(f.hist[:], dict)
if f.hp == len(f.hist) {
f.hp = 0
f.hfull = true
}
f.hw = f.hp
}
func (f *decompressor) moreBits() error {
c, err := f.r.ReadByte()
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return err
}
f.roffset++
f.b |= uint32(c) << f.nb
f.nb += 8
return nil
}
// Read the next Huffman-encoded symbol from f according to h.
func (f *decompressor) huffSym(h *huffmanDecoder) (int, error) {
// Since a huffmanDecoder can be empty or be composed of a degenerate tree
// with single element, huffSym must error on these two edge cases. In both
// cases, the chunks slice will be 0 for the invalid sequence, leading it
// satisfy the n == 0 check below.
n := uint(h.min)
for {
for f.nb < n {
if err := f.moreBits(); err != nil {
return 0, err
}
}
chunk := h.chunks[f.b&(huffmanNumChunks-1)]
n = uint(chunk & huffmanCountMask)
if n > huffmanChunkBits {
chunk = h.links[chunk>>huffmanValueShift][(f.b>>huffmanChunkBits)&h.linkMask]
n = uint(chunk & huffmanCountMask)
}
if n <= f.nb {
if n == 0 {
f.err = CorruptInputError(f.roffset)
return 0, f.err
}
f.b >>= n
f.nb -= n
return int(chunk >> huffmanValueShift), nil
}
}
}
// Flush any buffered output to the underlying writer.
func (f *decompressor) flush(step func(*decompressor)) {
f.toRead = f.hist[f.hw:f.hp]
f.woffset += int64(f.hp - f.hw)
f.hw = f.hp
if f.hp == len(f.hist) {
f.hp = 0
f.hw = 0
f.hfull = true
}
f.step = step
}
func makeReader(r io.Reader) Reader {
if rr, ok := r.(Reader); ok {
return rr
}
return bufio.NewReader(r)
}
func (f *decompressor) Reset(r io.Reader, dict []byte) error {
*f = decompressor{
r: makeReader(r),
bits: f.bits,
codebits: f.codebits,
hist: f.hist,
step: (*decompressor).nextBlock,
}
if dict != nil {
f.setDict(dict)
}
return nil
}
// NewReader returns a new ReadCloser that can be used
// to read the uncompressed version of r.
// If r does not also implement io.ByteReader,
// the decompressor may read more data than necessary from r.
// It is the caller's responsibility to call Close on the ReadCloser
// when finished reading.
//
// The ReadCloser returned by NewReader also implements Resetter.
func NewReader(r io.Reader) io.ReadCloser {
var f decompressor
f.bits = new([maxNumLit + maxNumDist]int)
f.codebits = new([numCodes]int)
f.r = makeReader(r)
f.hist = new([maxHist]byte)
f.step = (*decompressor).nextBlock
return &f
}
// NewReaderDict is like NewReader but initializes the reader
// with a preset dictionary. The returned Reader behaves as if
// the uncompressed data stream started with the given dictionary,
// which has already been read. NewReaderDict is typically used
// to read data compressed by NewWriterDict.
//
// The ReadCloser returned by NewReader also implements Resetter.
func NewReaderDict(r io.Reader, dict []byte) io.ReadCloser {
var f decompressor
f.r = makeReader(r)
f.hist = new([maxHist]byte)
f.bits = new([maxNumLit + maxNumDist]int)
f.codebits = new([numCodes]int)
f.step = (*decompressor).nextBlock
f.setDict(dict)
return &f
}<|fim▁end|> | // bits to read and guarantee we never read past the end of the stream. |
<|file_name|>hash_matcher.py<|end_file_name|><|fim▁begin|>import hashlib
import re
import os
import pickle
from functools import partial
from externals.lib.misc import file_scan, update_dict
import logging
log = logging.getLogger(__name__)
VERSION = "0.0"
# Constants --------------------------------------------------------------------
DEFAULT_DESTINATION = './files/'
DEFAULT_CACHE_FILENAME = 'hash_cache.pickle'
DEFAULT_FILE_EXTS = {'mp4', 'avi', 'rm', 'mkv', 'ogm', 'ssa', 'srt', 'ass'}
# Utils ------------------------------------------------------------------------
def hash_files(folder, file_regex=None, hasher=hashlib.sha256):
return {<|fim▁hole|> for f in file_scan(folder, file_regex=file_regex, hasher=hasher)
}
# ------------------------------------------------------------------------------
def hash_source_dest(source_folder=None, destination_folder=None, hasher=hashlib.sha256, file_exts=DEFAULT_FILE_EXTS, **kwargs):
file_regex = re.compile(r'.*\.({})$'.format('|'.join(file_exts)))
gen_hashs_folder = partial(hash_files, **dict(hasher=hasher, file_regex=file_regex))
return {
'source_files': gen_hashs_folder(source_folder),
'destination_files': gen_hashs_folder(destination_folder),
}
def symlink_matched_files(source_files=None, destination_files=None, destination_folder=None, dry_run=False, **kwargs):
for key in sorted(set(source_files.keys()).difference(set(destination_files.keys())), key=lambda key: source_files[key].file):
f = source_files[key]
log.debug(f.file)
if not dry_run:
try:
os.symlink(f.absolute, os.path.join(destination_folder, f.file))
except OSError:
log.info('unable to symlink {0}'.format(f.file))
# ------------------------------------------------------------------------------
def move_files():
pass
# Command Line -----------------------------------------------------------------
def get_args():
import argparse
parser = argparse.ArgumentParser(
description="""
Find the duplicates
""",
epilog=""" """
)
# Folders
parser.add_argument('-d', '--destination_folder', action='store', help='', default=DEFAULT_DESTINATION)
parser.add_argument('-s', '--source_folder', action='store', help='', required=True)
parser.add_argument('-e', '--file_exts', nargs='*', help='file exts to find', default=DEFAULT_FILE_EXTS)
# Operation
#parser.add_argument('-c', '--copy', action='store_true', help='copy files to destination (to be ready for importing)', default=False)
# Cache
parser.add_argument('--cache_filename', action='store', help='', default=DEFAULT_CACHE_FILENAME)
# Common
parser.add_argument('--dry_run', action='store_true', help='', default=False)
parser.add_argument('-v', '--verbose', action='store_true', help='', default=False)
parser.add_argument('--version', action='version', version=VERSION)
args = vars(parser.parse_args())
return args
def main():
args = get_args()
logging.basicConfig(level=logging.DEBUG if args['verbose'] else logging.INFO)
try:
with open(args['cache_filename'], 'rb') as f:
data = pickle.load(f)
except IOError:
with open(args['cache_filename'], 'wb') as f:
data = hash_source_dest(**args)
pickle.dump(data, f)
symlink_matched_files(**update_dict(args.copy(), data))
if __name__ == "__main__":
main()<|fim▁end|> | f.hash: f |
<|file_name|>items.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 https://mozilla.org/MPL/2.0/. */
//! Servo heavily uses display lists, which are retained-mode lists of painting commands to
//! perform. Using a list instead of painting elements in immediate mode allows transforms, hit
//! testing, and invalidation to be performed using the same primitives as painting. It also allows
//! Servo to aggressively cull invisible and out-of-bounds painting elements, to reduce overdraw.
//!
//! Display items describe relatively high-level drawing operations (for example, entire borders
//! and shadows instead of lines and blur operations), to reduce the amount of allocation required.
//! They are therefore not exactly analogous to constructs like Skia pictures, which consist of
//! low-level drawing primitives.
use euclid::{SideOffsets2D, Vector2D};
use gfx_traits::print_tree::PrintTree;
use gfx_traits::{self, StackingContextId};
use msg::constellation_msg::PipelineId;
use net_traits::image::base::Image;
use servo_geometry::MaxRect;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::f32;
use std::fmt;
use style::computed_values::_servo_top_layer::T as InTopLayer;
use webrender_api as wr;
use webrender_api::units::{LayoutPixel, LayoutRect, LayoutTransform};
use webrender_api::{
BorderRadius, ClipId, ClipMode, CommonItemProperties, ComplexClipRegion, ExternalScrollId,
FilterOp, GlyphInstance, GradientStop, ImageKey, MixBlendMode, PrimitiveFlags,
ScrollSensitivity, Shadow, SpatialId, StickyOffsetBounds, TransformStyle,
};
pub use style::dom::OpaqueNode;
/// The factor that we multiply the blur radius by in order to inflate the boundaries of display
/// items that involve a blur. This ensures that the display item boundaries include all the ink.
pub static BLUR_INFLATION_FACTOR: i32 = 3;
/// An index into the vector of ClipScrollNodes. During WebRender conversion these nodes
/// are given ClipIds.
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub struct ClipScrollNodeIndex(usize);
impl ClipScrollNodeIndex {
pub fn root_scroll_node() -> ClipScrollNodeIndex {
ClipScrollNodeIndex(1)
}
pub fn root_reference_frame() -> ClipScrollNodeIndex {
ClipScrollNodeIndex(0)
}
pub fn new(index: usize) -> ClipScrollNodeIndex {
assert_ne!(index, 0, "Use the root_reference_frame constructor");
assert_ne!(index, 1, "Use the root_scroll_node constructor");
ClipScrollNodeIndex(index)
}
pub fn is_root_scroll_node(&self) -> bool {
*self == Self::root_scroll_node()
}
pub fn to_define_item(&self) -> DisplayItem {
DisplayItem::DefineClipScrollNode(Box::new(DefineClipScrollNodeItem {
base: BaseDisplayItem::empty(),
node_index: *self,
}))
}
pub fn to_index(self) -> usize {
self.0
}
}
/// A set of indices into the clip scroll node vector for a given item.
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub struct ClippingAndScrolling {
pub scrolling: ClipScrollNodeIndex,
pub clipping: Option<ClipScrollNodeIndex>,
}
impl ClippingAndScrolling {
pub fn simple(scrolling: ClipScrollNodeIndex) -> ClippingAndScrolling {
ClippingAndScrolling {
scrolling,
clipping: None,
}
}
pub fn new(scrolling: ClipScrollNodeIndex, clipping: ClipScrollNodeIndex) -> Self {
ClippingAndScrolling {
scrolling,
clipping: Some(clipping),
}
}
}
#[derive(Serialize)]
pub struct DisplayList {
pub list: Vec<DisplayItem>,
pub clip_scroll_nodes: Vec<ClipScrollNode>,
}
impl DisplayList {
/// Return the bounds of this display list based on the dimensions of the root
/// stacking context.
pub fn bounds(&self) -> LayoutRect {
match self.list.get(0) {
Some(&DisplayItem::PushStackingContext(ref item)) => item.stacking_context.bounds,
Some(_) => unreachable!("Root element of display list not stacking context."),
None => LayoutRect::zero(),
}
}
pub fn print(&self) {
let mut print_tree = PrintTree::new("Display List".to_owned());
self.print_with_tree(&mut print_tree);
}
pub fn print_with_tree(&self, print_tree: &mut PrintTree) {
print_tree.new_level("ClipScrollNodes".to_owned());
for node in &self.clip_scroll_nodes {
print_tree.add_item(format!("{:?}", node));
}
print_tree.end_level();
print_tree.new_level("Items".to_owned());
for item in &self.list {
print_tree.add_item(format!(
"{:?} StackingContext: {:?} {:?}",
item,
item.base().stacking_context_id,
item.clipping_and_scrolling()
));
}
print_tree.end_level();
}
}
/// Display list sections that make up a stacking context. Each section here refers
/// to the steps in CSS 2.1 Appendix E.
///
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum DisplayListSection {
BackgroundAndBorders,
BlockBackgroundsAndBorders,
Content,
Outlines,
}
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum StackingContextType {
Real,
PseudoPositioned,
PseudoFloat,
}
#[derive(Clone, Serialize)]
/// Represents one CSS stacking context, which may or may not have a hardware layer.
pub struct StackingContext {
/// The ID of this StackingContext for uniquely identifying it.
pub id: StackingContextId,
/// The type of this StackingContext. Used for collecting and sorting.
pub context_type: StackingContextType,
/// The position and size of this stacking context.
pub bounds: LayoutRect,
/// The overflow rect for this stacking context in its coordinate system.
pub overflow: LayoutRect,
/// The `z-index` for this stacking context.
pub z_index: i32,
/// Whether this is the top layer.
pub in_top_layer: InTopLayer,
/// CSS filters to be applied to this stacking context (including opacity).
pub filters: Vec<FilterOp>,
/// The blend mode with which this stacking context blends with its backdrop.
pub mix_blend_mode: MixBlendMode,
/// A transform to be applied to this stacking context.
pub transform: Option<LayoutTransform>,
/// The transform style of this stacking context.
pub transform_style: TransformStyle,
/// The perspective matrix to be applied to children.
pub perspective: Option<LayoutTransform>,
/// The clip and scroll info for this StackingContext.
pub parent_clipping_and_scrolling: ClippingAndScrolling,
/// The index of the reference frame that this stacking context establishes.
pub established_reference_frame: Option<ClipScrollNodeIndex>,
}
impl StackingContext {
/// Creates a new stacking context.
#[inline]
pub fn new(
id: StackingContextId,
context_type: StackingContextType,
bounds: LayoutRect,
overflow: LayoutRect,
z_index: i32,
in_top_layer: InTopLayer,
filters: Vec<FilterOp>,
mix_blend_mode: MixBlendMode,
transform: Option<LayoutTransform>,
transform_style: TransformStyle,
perspective: Option<LayoutTransform>,
parent_clipping_and_scrolling: ClippingAndScrolling,
established_reference_frame: Option<ClipScrollNodeIndex>,
) -> StackingContext {
if let Some(ref t) = transform {
// These are used as scale values by webrender, and it can't handle
// divisors of 0 when scaling.
assert_ne!(t.m11, 0.);
assert_ne!(t.m22, 0.);
}
StackingContext {
id,
context_type,
bounds,
overflow,
z_index,
in_top_layer,
filters,
mix_blend_mode,
transform,
transform_style,
perspective,
parent_clipping_and_scrolling,
established_reference_frame,
}
}
#[inline]
pub fn root() -> StackingContext {
StackingContext::new(
StackingContextId::root(),
StackingContextType::Real,
LayoutRect::zero(),
LayoutRect::zero(),
0,
InTopLayer::None,
vec![],
MixBlendMode::Normal,
None,
TransformStyle::Flat,
None,
ClippingAndScrolling::simple(ClipScrollNodeIndex::root_scroll_node()),
None,
)
}
pub fn to_display_list_items(self) -> (DisplayItem, DisplayItem) {
let mut base_item = BaseDisplayItem::empty();
base_item.stacking_context_id = self.id;
base_item.clipping_and_scrolling = self.parent_clipping_and_scrolling;
let pop_item = DisplayItem::PopStackingContext(Box::new(PopStackingContextItem {
base: base_item.clone(),
stacking_context_id: self.id,
established_reference_frame: self.established_reference_frame.is_some(),
}));
let push_item = DisplayItem::PushStackingContext(Box::new(PushStackingContextItem {
base: base_item,
stacking_context: self,
}));
(push_item, pop_item)
}
}
impl Ord for StackingContext {
fn cmp(&self, other: &Self) -> Ordering {
if self.in_top_layer == InTopLayer::Top {
if other.in_top_layer == InTopLayer::Top {
return Ordering::Equal;
} else {
return Ordering::Greater;
}
} else if other.in_top_layer == InTopLayer::Top {
return Ordering::Less;
}
if self.z_index != 0 || other.z_index != 0 {
return self.z_index.cmp(&other.z_index);
}
match (self.context_type, other.context_type) {
(StackingContextType::PseudoFloat, StackingContextType::PseudoFloat) => Ordering::Equal,
(StackingContextType::PseudoFloat, _) => Ordering::Less,
(_, StackingContextType::PseudoFloat) => Ordering::Greater,
(_, _) => Ordering::Equal,
}
}
}
impl PartialOrd for StackingContext {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Eq for StackingContext {}
impl PartialEq for StackingContext {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
impl fmt::Debug for StackingContext {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let type_string = if self.context_type == StackingContextType::Real {
"StackingContext"
} else {
"Pseudo-StackingContext"
};
write!(
f,
"{} at {:?} with overflow {:?}: {:?}",
type_string, self.bounds, self.overflow, self.id
)
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct StickyFrameData {
pub margins: SideOffsets2D<Option<f32>, LayoutPixel>,
pub vertical_offset_bounds: StickyOffsetBounds,
pub horizontal_offset_bounds: StickyOffsetBounds,
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub enum ClipType {
Rounded(ComplexClipRegion),
Rect,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum ClipScrollNodeType {
Placeholder,
ScrollFrame(ScrollSensitivity, ExternalScrollId),
StickyFrame(StickyFrameData),
Clip(ClipType),
}
/// Defines a clip scroll node.
#[derive(Clone, Debug, Serialize)]
pub struct ClipScrollNode {
/// The index of the parent of this ClipScrollNode.
pub parent_index: ClipScrollNodeIndex,
/// The position of this scroll root's frame in the parent stacking context.
pub clip: ClippingRegion,
/// The rect of the contents that can be scrolled inside of the scroll root.
pub content_rect: LayoutRect,
/// The type of this ClipScrollNode.
pub node_type: ClipScrollNodeType,
}
impl ClipScrollNode {
pub fn placeholder() -> ClipScrollNode {
ClipScrollNode {
parent_index: ClipScrollNodeIndex(0),
clip: ClippingRegion::from_rect(LayoutRect::zero()),
content_rect: LayoutRect::zero(),
node_type: ClipScrollNodeType::Placeholder,
}
}
pub fn is_placeholder(&self) -> bool {
self.node_type == ClipScrollNodeType::Placeholder
}
pub fn rounded(
clip_rect: LayoutRect,
radii: BorderRadius,
parent_index: ClipScrollNodeIndex,
) -> ClipScrollNode {
let complex_region = ComplexClipRegion {
rect: clip_rect,
radii,
mode: ClipMode::Clip,
};
ClipScrollNode {
parent_index,
clip: ClippingRegion::from_rect(clip_rect),
content_rect: LayoutRect::zero(), // content_rect isn't important for clips.
node_type: ClipScrollNodeType::Clip(ClipType::Rounded(complex_region)),
}
}
}
/// One drawing command in the list.
#[derive(Clone, Serialize)]
pub enum DisplayItem {
Rectangle(Box<CommonDisplayItem<wr::RectangleDisplayItem>>),
Text(Box<CommonDisplayItem<wr::TextDisplayItem, Vec<GlyphInstance>>>),
Image(Box<CommonDisplayItem<wr::ImageDisplayItem>>),
RepeatingImage(Box<CommonDisplayItem<wr::RepeatingImageDisplayItem>>),
Border(Box<CommonDisplayItem<wr::BorderDisplayItem, Vec<GradientStop>>>),
Gradient(Box<CommonDisplayItem<wr::GradientDisplayItem, Vec<GradientStop>>>),
RadialGradient(Box<CommonDisplayItem<wr::RadialGradientDisplayItem, Vec<GradientStop>>>),
Line(Box<CommonDisplayItem<wr::LineDisplayItem>>),
BoxShadow(Box<CommonDisplayItem<wr::BoxShadowDisplayItem>>),
PushTextShadow(Box<PushTextShadowDisplayItem>),
PopAllTextShadows(Box<PopAllTextShadowsDisplayItem>),
Iframe(Box<IframeDisplayItem>),
PushStackingContext(Box<PushStackingContextItem>),
PopStackingContext(Box<PopStackingContextItem>),
DefineClipScrollNode(Box<DefineClipScrollNodeItem>),
}
/// Information common to all display items.
#[derive(Clone, Serialize)]
pub struct BaseDisplayItem {
/// Metadata attached to this display item.
pub metadata: DisplayItemMetadata,
/// The clip rectangle to use for this item.
pub clip_rect: LayoutRect,
/// The section of the display list that this item belongs to.
pub section: DisplayListSection,
/// The id of the stacking context this item belongs to.
pub stacking_context_id: StackingContextId,
/// The clip and scroll info for this item.
pub clipping_and_scrolling: ClippingAndScrolling,
}
impl BaseDisplayItem {
#[inline(always)]
pub fn new(
metadata: DisplayItemMetadata,
clip_rect: LayoutRect,
section: DisplayListSection,
stacking_context_id: StackingContextId,
clipping_and_scrolling: ClippingAndScrolling,
) -> BaseDisplayItem {
BaseDisplayItem {
metadata,
clip_rect,
section,
stacking_context_id,
clipping_and_scrolling,
}
}
#[inline(always)]
pub fn empty() -> BaseDisplayItem {
BaseDisplayItem {
metadata: DisplayItemMetadata {
node: OpaqueNode(0),
pointing: None,
},
// Create a rectangle of maximal size.
clip_rect: LayoutRect::max_rect(),
section: DisplayListSection::Content,
stacking_context_id: StackingContextId::root(),
clipping_and_scrolling: ClippingAndScrolling::simple(
ClipScrollNodeIndex::root_scroll_node(),
),
}
}
}
pub fn empty_common_item_properties() -> CommonItemProperties {
CommonItemProperties {
clip_rect: LayoutRect::max_rect(),
clip_id: ClipId::root(wr::PipelineId::dummy()),
spatial_id: SpatialId::root_scroll_node(wr::PipelineId::dummy()),
hit_info: None,
flags: PrimitiveFlags::empty(),
}
}
/// A clipping region for a display item. Currently, this can describe rectangles, rounded
/// rectangles (for `border-radius`), or arbitrary intersections of the two. Arbitrary transforms
/// are not supported because those are handled by the higher-level `StackingContext` abstraction.
#[derive(Clone, PartialEq, Serialize)]
pub struct ClippingRegion {
/// The main rectangular region. This does not include any corners.
pub main: LayoutRect,
}
impl ClippingRegion {
/// Returns an empty clipping region that, if set, will result in no pixels being visible.
#[inline]
pub fn empty() -> ClippingRegion {
ClippingRegion {
main: LayoutRect::zero(),
}
}
/// Returns an all-encompassing clipping region that clips no pixels out.
#[inline]
pub fn max() -> ClippingRegion {
ClippingRegion {
main: LayoutRect::max_rect(),
}
}
/// Returns a clipping region that represents the given rectangle.
#[inline]
pub fn from_rect(rect: LayoutRect) -> ClippingRegion {
ClippingRegion { main: rect }
}
}
impl fmt::Debug for ClippingRegion {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if *self == ClippingRegion::max() {
write!(f, "ClippingRegion::Max")
} else if *self == ClippingRegion::empty() {
write!(f, "ClippingRegion::Empty")
} else {
write!(f, "ClippingRegion(Rect={:?})", self.main,)
}
}
}
/// Metadata attached to each display item. This is useful for performing auxiliary threads with
/// the display list involving hit testing: finding the originating DOM node and determining the
/// cursor to use when the element is hovered over.
#[derive(Clone, Copy, Serialize)]
pub struct DisplayItemMetadata {
/// The DOM node from which this display item originated.
pub node: OpaqueNode,
/// The value of the `cursor` property when the mouse hovers over this display item. If `None`,
/// this display item is ineligible for pointer events (`pointer-events: none`).
pub pointing: Option<u16>,
}
#[derive(Clone, Eq, PartialEq, Serialize)]
pub enum TextOrientation {
Upright,
SidewaysLeft,
SidewaysRight,
}
/// Paints an iframe.
#[derive(Clone, Serialize)]
pub struct IframeDisplayItem {
pub base: BaseDisplayItem,
pub iframe: PipelineId,
pub bounds: LayoutRect,
}
#[derive(Clone, Serialize)]
pub struct CommonDisplayItem<T, U = ()> {
pub base: BaseDisplayItem,
pub item: T,
pub data: U,
}
impl<T> CommonDisplayItem<T> {
pub fn new(base: BaseDisplayItem, item: T) -> Box<CommonDisplayItem<T>> {
Box::new(CommonDisplayItem {
base,
item,
data: (),
})
}
}
impl<T, U> CommonDisplayItem<T, U> {
pub fn with_data(base: BaseDisplayItem, item: T, data: U) -> Box<CommonDisplayItem<T, U>> {
Box::new(CommonDisplayItem { base, item, data })
}
}
/// Defines a text shadow that affects all items until the paired PopTextShadow.
#[derive(Clone, Serialize)]
pub struct PushTextShadowDisplayItem {
/// Fields common to all display items.
pub base: BaseDisplayItem,
pub shadow: Shadow,
}
/// Defines a text shadow that affects all items until the next PopTextShadow.
#[derive(Clone, Serialize)]
pub struct PopAllTextShadowsDisplayItem {
/// Fields common to all display items.
pub base: BaseDisplayItem,
}
/// Defines a stacking context.
#[derive(Clone, Serialize)]
pub struct PushStackingContextItem {
/// Fields common to all display items.
pub base: BaseDisplayItem,
pub stacking_context: StackingContext,
}
/// Defines a stacking context.
#[derive(Clone, Serialize)]
pub struct PopStackingContextItem {
/// Fields common to all display items.
pub base: BaseDisplayItem,
pub stacking_context_id: StackingContextId,
pub established_reference_frame: bool,
}
/// Starts a group of items inside a particular scroll root.
#[derive(Clone, Serialize)]
pub struct DefineClipScrollNodeItem {
/// Fields common to all display items.
pub base: BaseDisplayItem,
/// The scroll root that this item starts.
pub node_index: ClipScrollNodeIndex,
}
impl DisplayItem {
pub fn base(&self) -> &BaseDisplayItem {
match *self {
DisplayItem::Rectangle(ref rect) => &rect.base,
DisplayItem::Text(ref text) => &text.base,
DisplayItem::Image(ref image_item) => &image_item.base,
DisplayItem::RepeatingImage(ref image_item) => &image_item.base,
DisplayItem::Border(ref border) => &border.base,
DisplayItem::Gradient(ref gradient) => &gradient.base,
DisplayItem::RadialGradient(ref gradient) => &gradient.base,
DisplayItem::Line(ref line) => &line.base,
DisplayItem::BoxShadow(ref box_shadow) => &box_shadow.base,
DisplayItem::PushTextShadow(ref push_text_shadow) => &push_text_shadow.base,
DisplayItem::PopAllTextShadows(ref pop_text_shadow) => &pop_text_shadow.base,
DisplayItem::Iframe(ref iframe) => &iframe.base,
DisplayItem::PushStackingContext(ref stacking_context) => &stacking_context.base,
DisplayItem::PopStackingContext(ref item) => &item.base,
DisplayItem::DefineClipScrollNode(ref item) => &item.base,
}
}
pub fn clipping_and_scrolling(&self) -> ClippingAndScrolling {
self.base().clipping_and_scrolling
}
pub fn stacking_context_id(&self) -> StackingContextId {
self.base().stacking_context_id
}
pub fn section(&self) -> DisplayListSection {
self.base().section
}
pub fn bounds(&self) -> LayoutRect {
match *self {
DisplayItem::Rectangle(ref item) => item.item.common.clip_rect,
DisplayItem::Text(ref item) => item.item.bounds,<|fim▁hole|> DisplayItem::Gradient(ref item) => item.item.bounds,
DisplayItem::RadialGradient(ref item) => item.item.bounds,
DisplayItem::Line(ref item) => item.item.area,
DisplayItem::BoxShadow(ref item) => item.item.box_bounds,
DisplayItem::PushTextShadow(_) => LayoutRect::zero(),
DisplayItem::PopAllTextShadows(_) => LayoutRect::zero(),
DisplayItem::Iframe(ref item) => item.bounds,
DisplayItem::PushStackingContext(ref item) => item.stacking_context.bounds,
DisplayItem::PopStackingContext(_) => LayoutRect::zero(),
DisplayItem::DefineClipScrollNode(_) => LayoutRect::zero(),
}
}
}
impl fmt::Debug for DisplayItem {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if let DisplayItem::PushStackingContext(ref item) = *self {
return write!(f, "PushStackingContext({:?})", item.stacking_context);
}
if let DisplayItem::PopStackingContext(ref item) = *self {
return write!(f, "PopStackingContext({:?}", item.stacking_context_id);
}
if let DisplayItem::DefineClipScrollNode(ref item) = *self {
return write!(f, "DefineClipScrollNode({:?}", item.node_index);
}
write!(
f,
"{} @ {:?} {:?}",
match *self {
DisplayItem::Rectangle(_) => "Rectangle",
DisplayItem::Text(_) => "Text",
DisplayItem::Image(_) => "Image",
DisplayItem::RepeatingImage(_) => "RepeatingImage",
DisplayItem::Border(_) => "Border",
DisplayItem::Gradient(_) => "Gradient",
DisplayItem::RadialGradient(_) => "RadialGradient",
DisplayItem::Line(_) => "Line",
DisplayItem::BoxShadow(_) => "BoxShadow",
DisplayItem::PushTextShadow(_) => "PushTextShadow",
DisplayItem::PopAllTextShadows(_) => "PopTextShadow",
DisplayItem::Iframe(_) => "Iframe",
DisplayItem::PushStackingContext(_) |
DisplayItem::PopStackingContext(_) |
DisplayItem::DefineClipScrollNode(_) => "",
},
self.bounds(),
self.base().clip_rect
)
}
}
#[derive(Clone, Copy, Serialize)]
pub struct WebRenderImageInfo {
pub width: u32,
pub height: u32,
pub key: Option<ImageKey>,
}
impl WebRenderImageInfo {
#[inline]
pub fn from_image(image: &Image) -> WebRenderImageInfo {
WebRenderImageInfo {
width: image.width,
height: image.height,
key: image.id,
}
}
}
/// The type of the scroll offset list. This is only populated if WebRender is in use.
pub type ScrollOffsetMap = HashMap<ExternalScrollId, Vector2D<f32, LayoutPixel>>;<|fim▁end|> | DisplayItem::Image(ref item) => item.item.bounds,
DisplayItem::RepeatingImage(ref item) => item.item.bounds,
DisplayItem::Border(ref item) => item.item.bounds, |
<|file_name|>serial_pyboard_to_python.py<|end_file_name|><|fim▁begin|>#HV Control &
#Read and Plot from the PMT
#This code is to record the data that is received into the Teensy's ADC.
#Includes the HV control and replotting the results at the end.
#See CSV Dataplot notebook to plot old experiment data.
from __future__ import division
from __future__ import print_function
from pyqtgraph import QtGui, QtCore #Provides usage of PyQt4's libraries which aids in UI design
import pyqtgraph as pg #Initiation of plotting code
import serial #Communication with the serial port is done using the pySerial 2.7 package
from datetime import datetime #Allows us to look at current date and time
#import dataprocessing #code for plotting the data from the CSV
## Always start by initializing Qt (only once per application)
app = QtGui.QApplication([])
## Define a top-level widget to hold everything (a window)
w = QtGui.QWidget()
w.resize(1000,600)
w.setWindowTitle('Voltage Plots')
startBtnClicked = False
quitBtnClicked = False
firstupdate = 0
## This function contains the behavior we want to see when the start button is clicked
def startButtonClicked():
global startBtnClicked
global startBtn
if (startBtnClicked == False):
teensySerialData.flushInput() #empty serial buffer for input from the teensy
startBtnClicked = True
startBtn.setText('Stop')
elif (startBtnClicked == True):
startBtnClicked = False
startBtn.setText('Start')
## Below at the end of the update function we check the value of quitBtnClicked
def quitButtonClicked():
global quitBtnClicked
quitBtnClicked = True
## Buttons to control the High Voltage
def HVoffButtonClicked():
teensySerialData.write('0')
print("HV Off")
def HVonButtonClicked():
teensySerialData.write('1')
print("HV On")
def insertionButtonClicked():
teensySerialData.write('3')
print("Insertion")
def separationButtonClicked():
teensySerialData.write('2')
print("Separation")
#Start Recording in Widget
## Create widgets to be placed inside
startBtn = QtGui.QPushButton('Start')
startBtn.setToolTip('Click to begin graphing') #This message appears while hovering mouse over button
quitBtn = QtGui.QPushButton('Quit')
quitBtn.setToolTip('Click to quit program')
HVonBtn = QtGui.QPushButton("HV on")
HVonBtn.setToolTip('Click to turn the high voltage on')
HVoffBtn = QtGui.QPushButton("HV off")
HVoffBtn.setToolTip('Click to turn the high voltage off')
insBtn = QtGui.QPushButton("Insertion")
insBtn.setToolTip('Click to start insertion (#3)')
sepBtn = QtGui.QPushButton("Separation")
sepBtn.setToolTip('Click to start separation (#2)')
## Functions in parantheses are to be called when buttons are clicked
startBtn.clicked.connect(startButtonClicked)
quitBtn.clicked.connect(quitButtonClicked)
HVonBtn.clicked.connect(HVonButtonClicked)
HVoffBtn.clicked.connect(HVoffButtonClicked)
insBtn.clicked.connect(insertionButtonClicked)
sepBtn.clicked.connect(separationButtonClicked)
## xSamples is the maximum amount of samples we want graphed at a time
xSamples = 300
## Create plot widget for peak detector plot
pmtPlotWidget = pg.PlotWidget()
pmtPlotWidget.setYRange(0, 4096)
pmtPlotWidget.setXRange(0, xSamples)
pmtPlotWidget.setLabel('top', text = "PMT") #Title to appear at top of widget
## Create a grid layout to manage the widgets size and position
## The grid layout allows us to place a widget in a given column and row
layout = QtGui.QGridLayout()
w.setLayout(layout)
## Add widgets to the layout in their proper positions
## The first number in parantheses is the row, the second is the column
layout.addWidget(quitBtn, 0, 0)
layout.addWidget(startBtn, 2, 0)
layout.addWidget(HVonBtn, 0, 2)
layout.addWidget(insBtn, 2, 2)
layout.addWidget(sepBtn, 3, 2)
layout.addWidget(HVoffBtn, 4, 2)
layout.addWidget(pmtPlotWidget, 1, 1)
## Display the widget as a new window
w.show()
## Initialize all global variables
## Whenever we plot a range of samples, xLeftIndex is the x value on the
## PlotWidget where we start plotting the samples, xRightIndex is where we stop
## These values will reset when they reach the value of xSamples
xRightIndex = 0
xLeftIndex = 0
## These arrays will hold the unplotted voltage values from the pmt
## and the peak detector until we are able to update the plot
pmtData = []
## Used to determine how often we plot a range of values
graphCount = 0
## Time values in microseconds read from the teensy are stored in these variables
## Before timeElapsed is updated, we store its old value in timeElapsedPrev
timeElapsed = 0
timeElapsedPrev = 0
## Determines if we are running through the update loop for the first time
firstRun = True
## Create new file, with the name being today's date and current time and write headings to file in CSV format
i = datetime.now()
fileName = str(i.year) + str(i.month) + str(i.day) + "_" + str(i.hour) + str(i.minute) + str(i.second) + ".csv"
## File is saved to Documents/IPython Notebooks/RecordedData
#f = open('RecordedData\\' + fileName, 'a')
#f.write("#Data from " + str(i.year) + "-" + str(i.month) + "-" + str(i.day) + " at " + str(i.hour) + ":" + str(i.minute) + ":" + str(i.second) + '\n')
#f.write("Timestamp,PMT\n")
## Initialize the container for our voltage values read in from the teensy
## IMPORTANT NOTE: The com port value needs to be updated if the com value
## changes. It's the same number that appears on the bottom right corner of the
## window containing the TeensyDataWrite.ino code
teensySerialData = serial.Serial("/dev/tty.usbmodem1452", 115200)
def update():
## Set global precedence to previously defined values
global xSamples
global xRightIndex
global xLeftIndex
global pmtData
global graphCount
global timeElapsed
global timeElapsedPrev
global firstRun
global firstupdate
if firstupdate == 0:
teensySerialData.flushInput()
firstupdate += 1
## The number of bytes currently waiting to be read in.
## We want to read these values as soon as possible, because
## we will lose them if the buffer fills up
bufferSize = teensySerialData.inWaiting()
runCount = bufferSize//8 # since we write 8 bytes at a time, we similarly want to read them 8 at a time
#print(bufferSize, runCount)
while (runCount > 0):
if (startBtnClicked == True):
#Read in time (int) and PMT output (float with up to 5 decimal places)
temp = []
temp.append(teensySerialData.readline().strip().split(',') )
print(bufferSize, runCount, temp[-1][0], temp[-1][1])
timeElapsedPrev = timeElapsed
timeElapsed = int (temp[0][0])
if (firstRun == True):
## Only run once to ensure buffer is completely flushed
firstRun = False
teensySerialData.flushInput()
break
# We'll add all our values to this string until we're ready to exit the loop, at which point it will be written to a file
stringToWrite = str(timeElapsed) + ","
## This difference calucalted in the if statement is the amount of time in microseconds since the last value
## we read in and wrote to a file. If this value is significantly greater than 100, we know we have missed some
## values, probably as a result of the buffer filling up and scrapping old values to make room for new values.
## The number we print out will be the approximate number of values we failed to read in.
## This is useful to determine if your code is running too slow
#if (timeElapsed - timeElapsedPrev > 8000):
#print(str((timeElapsed-timeElapsedPrev)/7400))
numData = float (temp[0][1])
<|fim▁hole|> xRightIndex = xRightIndex + 1
runCount = runCount - 1
## We will start plotting when the start button is clicked
if startBtnClicked == True:
if (graphCount >= 1): #We will plot new values once we have this many values to plot
if (xLeftIndex == 0):
# Remove all PlotDataItems from the PlotWidgets.
# This will effectively reset the graphs (approximately every 30000 samples)
#pmtPlotWidget.clear()
pmtPlotWidget.clear()
## pmtCurve are of the PlotDataItem type and are added to the PlotWidget.
## Documentation for these types can be found on pyqtgraph's website
pmtCurve = pmtPlotWidget.plot()
xRange = range(xLeftIndex,xRightIndex)
pmtCurve.setData(xRange, pmtData)
## Now that we've plotting the values, we no longer need these arrays to store them
pmtData = []
xLeftIndex = xRightIndex
graphCount = 0
if(xRightIndex >= xSamples):
xRightIndex = 0
xLeftIndex = 0
pmtData = []
if(quitBtnClicked == True):
## Close the file and close the window. Performing this action here ensures values we want to write to the file won't be cut off
#f.close()
w.close()
teensySerialData.close()
#dataprocessing.CSVDataPlot(fileName)
## Run update function in response to a timer
timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(0)
## Start the Qt event loop
app.exec_()<|fim▁end|> | pmtData.append(numData)
stringToWrite = stringToWrite + str(numData) + '\n'
#f.write(stringToWrite)
graphCount = graphCount + 1 |
<|file_name|>test-gauge.ts<|end_file_name|><|fim▁begin|>/**
* Copyright 2018, OpenCensus 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.
*/
import * as assert from 'assert';
import { TEST_ONLY } from '../src/common/time-util';
import {
LabelKey,
LabelValue,
MetricDescriptorType,
Timestamp,
} from '../src/metrics/export/types';
import { Gauge } from '../src/metrics/gauges/gauge';
const METRIC_NAME = 'metric-name';
const METRIC_DESCRIPTION = 'metric-description';
const UNIT = '1';
const GAUGE_INT64 = MetricDescriptorType.GAUGE_INT64;
const GAUGE_DOUBLE = MetricDescriptorType.GAUGE_DOUBLE;
const LABEL_KEYS: LabelKey[] = [{ key: 'code', description: 'desc' }];
const LABEL_VALUES_200: LabelValue[] = [{ value: '200' }];
const LABEL_VALUES_400: LabelValue[] = [{ value: '400' }];
const LABEL_VALUES_EXRTA: LabelValue[] = [{ value: '200' }, { value: '400' }];
const UNSET_LABEL_VALUE: LabelValue = {
value: null,
};
const EMPTY_CONSTANT_LABELS = new Map();
const CONSTANT_LABELS = new Map();
CONSTANT_LABELS.set(
{ key: 'host', description: 'host' },
{ value: 'localhost' }
);
describe('GAUGE_INT64', () => {
let instance: Gauge;
const realHrtimeFn = process.hrtime;
const realNowFn = Date.now;
const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 };
const expectedMetricDescriptor = {
name: METRIC_NAME,
description: METRIC_DESCRIPTION,
unit: UNIT,
type: GAUGE_INT64,
labelKeys: LABEL_KEYS,
};
beforeEach(() => {
instance = new Gauge(
METRIC_NAME,<|fim▁hole|> GAUGE_INT64,
LABEL_KEYS,
EMPTY_CONSTANT_LABELS
);
// @ts-expect-error ts-migrate(2741) FIXME: Property 'bigint' is missing in type '() => [numbe... Remove this comment to see the full error message
process.hrtime = () => [100, 1e7];
Date.now = () => 1450000000000;
// Force the clock to recalibrate the time offset with the mocked time
TEST_ONLY.setHrtimeReference();
});
afterEach(() => {
process.hrtime = realHrtimeFn;
Date.now = realNowFn;
// Reset the hrtime reference so that it uses a real clock again.
TEST_ONLY.resetHrtimeFunctionCache();
});
describe('getOrCreateTimeSeries()', () => {
it('should throw an error when the keys and values dont have same size', () => {
assert.throws(() => {
instance.getOrCreateTimeSeries(LABEL_VALUES_EXRTA);
}, /^Error: Label Keys and Label Values don't have same size$/);
});
it('should return a Metric', () => {
const point = instance.getOrCreateTimeSeries(LABEL_VALUES_200);
point.add(10);
let metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
assert.strictEqual(metric!.timeseries.length, 1);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: LABEL_VALUES_200,
points: [
{
value: 10,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
// add value and create new timeseries.
point.add(5);
const point1 = instance.getOrCreateTimeSeries(LABEL_VALUES_400);
point1.set(-8);
metric = instance.getMetric();
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
assert.strictEqual(metric!.timeseries.length, 2);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: LABEL_VALUES_200,
points: [
{
value: 15,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
{
labelValues: LABEL_VALUES_400,
points: [
{
value: -8,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
});
it('should not create same timeseries again', () => {
const point = instance.getOrCreateTimeSeries(LABEL_VALUES_200);
point.add(10);
let metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
assert.strictEqual(metric!.timeseries.length, 1);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: LABEL_VALUES_200,
points: [
{
value: 10,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
// create timeseries with same labels.
const point1 = instance.getOrCreateTimeSeries(LABEL_VALUES_200);
point1.add(30);
metric = instance.getMetric();
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
assert.strictEqual(metric!.timeseries.length, 1);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: LABEL_VALUES_200,
points: [
{
value: 40,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
});
});
describe('getDefaultTimeSeries()', () => {
it('should create new default timeseries', () => {
const point = instance.getDefaultTimeSeries();
point.add(10);
const metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
assert.strictEqual(metric!.timeseries.length, 1);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: [UNSET_LABEL_VALUE],
points: [
{
value: 10,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
});
it('should return same timeseries for interchanged labels', () => {
instance = new Gauge(
METRIC_NAME,
METRIC_DESCRIPTION,
UNIT,
GAUGE_INT64,
[
{ key: 'k1', description: 'desc' },
{ key: 'k2', description: 'desc' },
],
EMPTY_CONSTANT_LABELS
);
const point = instance.getOrCreateTimeSeries([
{ value: '200' },
{ value: '400' },
]);
point.add(200);
const point1 = instance.getOrCreateTimeSeries([
{ value: '400' },
{ value: '200' },
]);
point1.add(400);
const metric = instance.getMetric();
assert.strictEqual(metric!.timeseries.length, 1);
});
it('should add constant labels', () => {
instance = new Gauge(
METRIC_NAME,
METRIC_DESCRIPTION,
UNIT,
GAUGE_INT64,
[
{ key: 'k1', description: 'desc' },
{ key: 'k2', description: 'desc' },
],
CONSTANT_LABELS
);
const point = instance.getOrCreateTimeSeries([
{ value: '200' },
{ value: '400' },
]);
point.add(200);
const metric = instance.getMetric();
assert.strictEqual(metric!.timeseries.length, 1);
assert.deepStrictEqual(metric!.descriptor.labelKeys, [
{ key: 'k1', description: 'desc' },
{ key: 'k2', description: 'desc' },
{ key: 'host', description: 'host' },
]);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: [
{ value: '200' },
{ value: '400' },
{ value: 'localhost' },
],
points: [
{
value: 200,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
});
it('should create same labelValues as labelKeys', () => {
instance = new Gauge(
METRIC_NAME,
METRIC_DESCRIPTION,
UNIT,
GAUGE_INT64,
[
{ key: 'k1', description: 'desc' },
{ key: 'k2', description: 'desc' },
{ key: 'k3', description: 'desc' },
],
EMPTY_CONSTANT_LABELS
);
const point = instance.getDefaultTimeSeries();
point.add(200);
const metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor.labelKeys.length, 3);
assert.deepStrictEqual(metric!.descriptor.type, 1);
assert.strictEqual(metric!.timeseries.length, 1);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: [
UNSET_LABEL_VALUE,
UNSET_LABEL_VALUE,
UNSET_LABEL_VALUE,
],
points: [
{
value: 200,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
});
it('should use previously created default timeseries', () => {
const point = instance.getDefaultTimeSeries();
point.add(300);
let metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
assert.strictEqual(metric!.timeseries.length, 1);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: [UNSET_LABEL_VALUE],
points: [
{
value: 300,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
// get default timeseries again.
const point1 = instance.getDefaultTimeSeries();
point1.add(400);
metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
assert.strictEqual(metric!.timeseries.length, 1);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: [UNSET_LABEL_VALUE],
points: [
{
value: 700,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
});
});
describe('removeTimeSeries()', () => {
it('should remove TimeSeries', () => {
const point = instance.getOrCreateTimeSeries(LABEL_VALUES_200);
point.add(10);
let metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
instance.removeTimeSeries(LABEL_VALUES_200);
metric = instance.getMetric();
assert.deepStrictEqual(metric, null);
});
});
describe('clear()', () => {
it('should clear all TimeSeries', () => {
const point = instance.getOrCreateTimeSeries(LABEL_VALUES_200);
point.add(10);
const point1 = instance.getOrCreateTimeSeries(LABEL_VALUES_400);
point1.add(10);
let metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
assert.strictEqual(metric!.timeseries.length, 2);
instance.clear();
metric = instance.getMetric();
assert.deepStrictEqual(metric, null);
});
});
});
describe('GAUGE_DOUBLE', () => {
let instance: Gauge;
const realHrtimeFn = process.hrtime;
const realNowFn = Date.now;
const mockedTime: Timestamp = { seconds: 1450000100, nanos: 1e7 };
const expectedMetricDescriptor = {
name: METRIC_NAME,
description: METRIC_DESCRIPTION,
unit: UNIT,
type: GAUGE_DOUBLE,
labelKeys: LABEL_KEYS,
};
beforeEach(() => {
instance = new Gauge(
METRIC_NAME,
METRIC_DESCRIPTION,
UNIT,
GAUGE_DOUBLE,
LABEL_KEYS,
EMPTY_CONSTANT_LABELS
);
// @ts-expect-error ts-migrate(2741) FIXME: Property 'bigint' is missing in type '() => [numbe... Remove this comment to see the full error message
process.hrtime = () => [100, 1e7];
Date.now = () => 1450000000000;
// Force the clock to recalibrate the time offset with the mocked time
TEST_ONLY.setHrtimeReference();
});
afterEach(() => {
process.hrtime = realHrtimeFn;
Date.now = realNowFn;
// Reset the hrtime reference so that it uses a real clock again.
TEST_ONLY.resetHrtimeFunctionCache();
});
describe('getOrCreateTimeSeries()', () => {
it('should throw an error when the keys and values dont have same size', () => {
assert.throws(() => {
instance.getOrCreateTimeSeries(LABEL_VALUES_EXRTA);
}, /^Error: Label Keys and Label Values don't have same size$/);
});
it('should return a Metric', () => {
const point = instance.getOrCreateTimeSeries(LABEL_VALUES_200);
point.add(10.34);
let metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
assert.strictEqual(metric!.timeseries.length, 1);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: LABEL_VALUES_200,
points: [
{
value: 10.34,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
// add value and create new timeseries.
point.add(5.12);
const point1 = instance.getOrCreateTimeSeries(LABEL_VALUES_400);
point1.set(-8.3);
metric = instance.getMetric();
assert.strictEqual(metric!.timeseries.length, 2);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: LABEL_VALUES_200,
points: [
{
value: 15.46,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
{
labelValues: LABEL_VALUES_400,
points: [
{
value: -8.3,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
});
it('should not create same timeseries again', () => {
const point = instance.getOrCreateTimeSeries(LABEL_VALUES_200);
point.add(12.1);
let metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
assert.strictEqual(metric!.timeseries.length, 1);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: LABEL_VALUES_200,
points: [
{
value: 12.1,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
// create timeseries with same labels.
const point1 = instance.getOrCreateTimeSeries(LABEL_VALUES_200);
point1.add(30.18);
metric = instance.getMetric();
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
assert.strictEqual(metric!.timeseries.length, 1);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: LABEL_VALUES_200,
points: [
{
value: 42.28,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
});
});
describe('getDefaultTimeSeries()', () => {
it('should create new default timeseries', () => {
const point = instance.getDefaultTimeSeries();
point.add(10.1);
const metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
assert.strictEqual(metric!.timeseries.length, 1);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: [UNSET_LABEL_VALUE],
points: [
{
value: 10.1,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
});
it('should use previously created default timeseries', () => {
const point = instance.getDefaultTimeSeries();
point.add(300.1);
let metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
assert.strictEqual(metric!.timeseries.length, 1);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: [UNSET_LABEL_VALUE],
points: [
{
value: 300.1,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
// get default timeseries again.
const point1 = instance.getDefaultTimeSeries();
point1.add(400.1);
metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
assert.strictEqual(metric!.timeseries.length, 1);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: [UNSET_LABEL_VALUE],
points: [
{
value: 700.2,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
});
it('should create same labelValues as labelKeys', () => {
instance = new Gauge(
METRIC_NAME,
METRIC_DESCRIPTION,
UNIT,
GAUGE_DOUBLE,
[
{ key: 'k1', description: 'desc' },
{ key: 'k2', description: 'desc' },
{ key: 'k3', description: 'desc' },
],
EMPTY_CONSTANT_LABELS
);
const point = instance.getDefaultTimeSeries();
point.add(10.1);
const metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor.labelKeys.length, 3);
assert.deepStrictEqual(metric!.descriptor.type, 2);
assert.strictEqual(metric!.timeseries.length, 1);
assert.deepStrictEqual(metric!.timeseries, [
{
labelValues: [
UNSET_LABEL_VALUE,
UNSET_LABEL_VALUE,
UNSET_LABEL_VALUE,
],
points: [
{
value: 10.1,
timestamp: {
nanos: mockedTime.nanos,
seconds: mockedTime.seconds,
},
},
],
},
]);
});
});
describe('removeTimeSeries()', () => {
it('should remove TimeSeries', () => {
const point = instance.getOrCreateTimeSeries(LABEL_VALUES_200);
point.add(10.23);
let metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
instance.removeTimeSeries(LABEL_VALUES_200);
metric = instance.getMetric();
assert.deepStrictEqual(metric, null);
});
});
describe('clear()', () => {
it('should clear all TimeSeries', () => {
const point = instance.getOrCreateTimeSeries(LABEL_VALUES_200);
point.add(10.34);
const point1 = instance.getOrCreateTimeSeries(LABEL_VALUES_400);
point1.add(15.2);
let metric = instance.getMetric();
assert.notStrictEqual(metric, null);
assert.deepStrictEqual(metric!.descriptor, expectedMetricDescriptor);
assert.strictEqual(metric!.timeseries.length, 2);
instance.clear();
metric = instance.getMetric();
assert.deepStrictEqual(metric, null);
});
});
});<|fim▁end|> | METRIC_DESCRIPTION,
UNIT, |
<|file_name|>jsonp.py<|end_file_name|><|fim▁begin|>import urllib
from cyclone.web import asynchronous
from twisted.python import log
from sockjs.cyclone import proto
from sockjs.cyclone.transports import pollingbase
class JSONPTransport(pollingbase.PollingTransportBase):
name = 'jsonp'
@asynchronous
def get(self, session_id):
# Start response <|fim▁hole|>
# Grab callback parameter
self.callback = self.get_argument('c', None)
if not self.callback:
self.write('"callback" parameter required')
self.set_status(500)
self.finish()
return
# Get or create session without starting heartbeat
if not self._attach_session(session_id):
return
# Might get already detached because connection was closed in
# connectionMade
if not self.session:
return
if self.session.send_queue.is_empty():
self.session.start_heartbeat()
else:
self.session.flush()
def connectionLost(self, reason):
self.session.delayed_close()
def send_pack(self, message):
# TODO: Just escape
msg = '%s(%s);\r\n' % (self.callback, proto.json_encode(message))
self.set_header('Content-Type',
'application/javascript; charset=UTF-8')
self.set_header('Content-Length', len(msg))
# FIXME
self.set_header('Etag', 'dummy')
self.write(msg)
self._detach()
self.safe_finish()
class JSONPSendHandler(pollingbase.PollingTransportBase):
def post(self, session_id):
self.preflight()
self.handle_session_cookie()
self.disable_cache()
session = self._get_session(session_id)
if session is None:
self.set_status(404)
return
#data = self.request.body.decode('utf-8')
data = self.request.body
ctype = self.request.headers.get('Content-Type', '').lower()
if ctype == 'application/x-www-form-urlencoded':
if not data.startswith('d='):
log.msg('jsonp_send: Invalid payload.')
self.write("Payload expected.")
self.set_status(500)
return
data = urllib.unquote_plus(data[2:])
if not data:
log.msg('jsonp_send: Payload expected.')
self.write("Payload expected.")
self.set_status(500)
return
try:
messages = proto.json_decode(data)
except:
# TODO: Proper error handling
log.msg('jsonp_send: Invalid json encoding')
self.write("Broken JSON encoding.")
self.set_status(500)
return
try:
session.messagesReceived(messages)
except Exception:
log.msg('jsonp_send: messagesReceived() failed')
session.close()
self.write('Message handler failed.')
self.set_status(500)
return
self.write('ok')
self.set_header('Content-Type', 'text/plain; charset=UTF-8')
self.set_status(200)<|fim▁end|> | self.handle_session_cookie()
self.disable_cache() |
<|file_name|>TypeCheckProtocolInference.cpp<|end_file_name|><|fim▁begin|>//===--- TypeCheckProtocolInference.cpp - Associated Type Inference -------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for protocols, in particular, checking
// whether a given type conforms to a given protocol.
//===----------------------------------------------------------------------===//
#include "TypeCheckProtocol.h"
#include "DerivedConformances.h"
#include "TypeChecker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/AST/TypeMatcher.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Defer.h"
#include "swift/ClangImporter/ClangModule.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/TinyPtrVector.h"
#define DEBUG_TYPE "Associated type inference"
#include "llvm/Support/Debug.h"
STATISTIC(NumSolutionStates, "# of solution states visited");
STATISTIC(NumSolutionStatesFailedCheck,
"# of solution states that failed constraints check");
STATISTIC(NumConstrainedExtensionChecks,
"# of constrained extension checks");
STATISTIC(NumConstrainedExtensionChecksFailed,
"# of constrained extension checks failed");
STATISTIC(NumDuplicateSolutionStates,
"# of duplicate solution states ");
using namespace swift;
void InferredAssociatedTypesByWitness::dump() const {
dump(llvm::errs(), 0);
}
void InferredAssociatedTypesByWitness::dump(llvm::raw_ostream &out,
unsigned indent) const {
out << "\n";
out.indent(indent) << "(";
if (Witness) {
Witness->dumpRef(out);
}
for (const auto &inferred : Inferred) {
out << "\n";
out.indent(indent + 2);
out << inferred.first->getName() << " := "
<< inferred.second.getString();
}
for (const auto &inferred : NonViable) {
out << "\n";
out.indent(indent + 2);
out << std::get<0>(inferred)->getName() << " := "
<< std::get<1>(inferred).getString();
auto type = std::get<2>(inferred).getRequirement();
out << " [failed constraint " << type.getString() << "]";
}
out << ")";
}
void InferredTypeWitnessesSolution::dump() const {
llvm::errs() << "Type Witnesses:\n";
for (auto &typeWitness : TypeWitnesses) {
llvm::errs() << " " << typeWitness.first->getName() << " := ";
typeWitness.second.first->print(llvm::errs());
llvm::errs() << " value " << typeWitness.second.second << '\n';
}
llvm::errs() << "Value Witnesses:\n";
for (unsigned i : indices(ValueWitnesses)) {
auto &valueWitness = ValueWitnesses[i];
llvm::errs() << i << ": " << (Decl*)valueWitness.first
<< ' ' << valueWitness.first->getBaseName() << '\n';
valueWitness.first->getDeclContext()->dumpContext();
llvm::errs() << " for " << (Decl*)valueWitness.second
<< ' ' << valueWitness.second->getBaseName() << '\n';
valueWitness.second->getDeclContext()->dumpContext();
}
}
namespace {
void dumpInferredAssociatedTypesByWitnesses(
const InferredAssociatedTypesByWitnesses &inferred,
llvm::raw_ostream &out,
unsigned indent) {
for (const auto &value : inferred) {
value.dump(out, indent);
}
}
void dumpInferredAssociatedTypesByWitnesses(
const InferredAssociatedTypesByWitnesses &inferred) LLVM_ATTRIBUTE_USED;
void dumpInferredAssociatedTypesByWitnesses(
const InferredAssociatedTypesByWitnesses &inferred) {
dumpInferredAssociatedTypesByWitnesses(inferred, llvm::errs(), 0);
}
void dumpInferredAssociatedTypes(const InferredAssociatedTypes &inferred,
llvm::raw_ostream &out,
unsigned indent) {
for (const auto &value : inferred) {
out << "\n";
out.indent(indent) << "(";
value.first->dumpRef(out);
dumpInferredAssociatedTypesByWitnesses(value.second, out, indent + 2);
out << ")";
}
out << "\n";
}
void dumpInferredAssociatedTypes(
const InferredAssociatedTypes &inferred) LLVM_ATTRIBUTE_USED;
void dumpInferredAssociatedTypes(const InferredAssociatedTypes &inferred) {
dumpInferredAssociatedTypes(inferred, llvm::errs(), 0);
}
}
AssociatedTypeInference::AssociatedTypeInference(
TypeChecker &tc,
NormalProtocolConformance *conformance)
: tc(tc), conformance(conformance), proto(conformance->getProtocol()),
dc(conformance->getDeclContext()),
adoptee(conformance->getType())
{
}
static bool associatedTypesAreSameEquivalenceClass(AssociatedTypeDecl *a,
AssociatedTypeDecl *b) {
if (a == b)
return true;
// TODO: Do a proper equivalence check here by looking for some relationship
// between a and b's protocols. In practice today, it's unlikely that
// two same-named associated types can currently be independent, since we
// don't have anything like `@implements(P.foo)` to rename witnesses (and
// we still fall back to name lookup for witnesses in more cases than we
// should).
if (a->getName() == b->getName())
return true;
return false;
}
InferredAssociatedTypesByWitnesses
AssociatedTypeInference::inferTypeWitnessesViaValueWitnesses(
ConformanceChecker &checker,
const llvm::SetVector<AssociatedTypeDecl *> &allUnresolved,
ValueDecl *req) {
// Conformances constructed by the ClangImporter should have explicit type
// witnesses already.
if (isa<ClangModuleUnit>(conformance->getDeclContext()->getModuleScopeContext())) {
llvm::errs() << "Cannot infer associated types for imported conformance:\n";
conformance->getType().dump(llvm::errs());
for (auto assocTypeDecl : allUnresolved)
assocTypeDecl->dump(llvm::errs());
abort();
}
InferredAssociatedTypesByWitnesses result;
auto isExtensionUsableForInference = [&](ExtensionDecl *extension) -> bool {
// The extension where the conformance being checked is declared.
auto conformanceExtension = checker.Conformance->
getDeclContext()->getAsDecl();
if (extension == conformanceExtension)
return true;
tc.bindExtension(extension);
// Assume unconstrained concrete extensions we found witnesses in are
// always viable.
if (!extension->getExtendedType()->isAnyExistentialType()) {
// TODO: When constrained extensions are a thing, we'll need an "is
// as specialized as" kind of check here.
return !extension->isConstrainedExtension();
}
// The extension may not have a generic signature set up yet, as a
// recursion breaker, in which case we can't yet confidently reject its
// witnesses.
if (!extension->getGenericSignature())
return true;
// The condition here is a bit more fickle than
// `isExtensionApplied`. That check would prematurely reject
// extensions like `P where AssocType == T` if we're relying on a
// default implementation inside the extension to infer `AssocType == T`
// in the first place. Only check conformances on the `Self` type,
// because those have to be explicitly declared on the type somewhere
// so won't be affected by whatever answer inference comes up with.
auto selfTy = extension->getSelfInterfaceType();
for (const Requirement &reqt
: extension->getGenericSignature()->getRequirements()) {
switch (reqt.getKind()) {
case RequirementKind::Conformance:
case RequirementKind::Superclass:
// FIXME: This is the wrong check
if (selfTy->isEqual(reqt.getFirstType())
&& !tc.isSubtypeOf(conformance->getType(),reqt.getSecondType(), dc))
return false;
break;
case RequirementKind::Layout:
case RequirementKind::SameType:
break;
}
}
return true;
};
auto typeInContext =
conformance->getDeclContext()->mapTypeIntoContext(conformance->getType());
for (auto witness :
checker.lookupValueWitnesses(req, /*ignoringNames=*/nullptr)) {
LLVM_DEBUG(llvm::dbgs() << "Inferring associated types from decl:\n";
witness->dump(llvm::dbgs()));
// If the potential witness came from an extension, and our `Self`
// type can't use it regardless of what associated types we end up
// inferring, skip the witness.
if (auto extension = dyn_cast<ExtensionDecl>(witness->getDeclContext()))
if (!isExtensionUsableForInference(extension))
continue;
// Try to resolve the type witness via this value witness.
auto witnessResult = inferTypeWitnessesViaValueWitness(req, witness);
// Filter out duplicated inferred types as well as inferred types
// that don't meet the requirements placed on the associated type.
llvm::DenseSet<std::pair<AssociatedTypeDecl *, CanType>> known;
for (unsigned i = 0; i < witnessResult.Inferred.size(); /*nothing*/) {
#define REJECT {\
witnessResult.Inferred.erase(witnessResult.Inferred.begin() + i); \
continue; \
}
auto &result = witnessResult.Inferred[i];
LLVM_DEBUG(llvm::dbgs() << "Considering whether "
<< result.first->getName()
<< " can infer to:\n";
result.second->dump(llvm::dbgs()));
// Filter out errors.
if (result.second->hasError()) {
LLVM_DEBUG(llvm::dbgs() << "-- has error type\n");
REJECT;
}
// Filter out duplicates.
if (!known.insert({result.first, result.second->getCanonicalType()})
.second) {
LLVM_DEBUG(llvm::dbgs() << "-- duplicate\n");
REJECT;
}
// Filter out circular possibilities, e.g. that
// AssocType == S.AssocType or
// AssocType == Foo<S.AssocType>.
bool canInferFromOtherAssociatedType = false;
bool containsTautologicalType =
result.second.findIf([&](Type t) -> bool {
auto dmt = t->getAs<DependentMemberType>();
if (!dmt)
return false;
if (!associatedTypesAreSameEquivalenceClass(dmt->getAssocType(),
result.first))
return false;
if (!dmt->getBase()->isEqual(typeInContext))
return false;
// If this associated type is same-typed to another associated type
// on `Self`, then it may still be an interesting candidate if we find
// an answer for that other type.
auto witnessContext = witness->getDeclContext();
if (witnessContext->getExtendedProtocolDecl()
&& witnessContext->getGenericSignatureOfContext()) {
auto selfTy = witnessContext->getSelfInterfaceType();
auto selfAssocTy = DependentMemberType::get(selfTy,
dmt->getAssocType());
for (auto &reqt : witnessContext->getGenericSignatureOfContext()
->getRequirements()) {
switch (reqt.getKind()) {
case RequirementKind::Conformance:
case RequirementKind::Superclass:
case RequirementKind::Layout:
break;
case RequirementKind::SameType:
Type other;
if (reqt.getFirstType()->isEqual(selfAssocTy)) {
other = reqt.getSecondType();
} else if (reqt.getSecondType()->isEqual(selfAssocTy)) {
other = reqt.getFirstType();
} else {
break;
}
if (auto otherAssoc = other->getAs<DependentMemberType>()) {
if (otherAssoc->getBase()->isEqual(selfTy)) {
auto otherDMT = DependentMemberType::get(dmt->getBase(),
otherAssoc->getAssocType());
// We may be able to infer one associated type from the
// other.
result.second = result.second.transform([&](Type t) -> Type{
if (t->isEqual(dmt))
return otherDMT;
return t;
});
canInferFromOtherAssociatedType = true;
LLVM_DEBUG(llvm::dbgs() << "++ we can same-type to:\n";
result.second->dump(llvm::dbgs()));
return false;
}
}
break;
}
}
}
return true;
});
if (containsTautologicalType) {
LLVM_DEBUG(llvm::dbgs() << "-- tautological\n");
REJECT;
}
// Check that the type witness doesn't contradict an
// explicitly-given type witness. If it does contradict, throw out the
// witness completely.
if (!allUnresolved.count(result.first)) {
auto existingWitness =
conformance->getTypeWitness(result.first, nullptr);
existingWitness = dc->mapTypeIntoContext(existingWitness);
// If the deduced type contains an irreducible
// DependentMemberType, that indicates a dependency
// on another associated type we haven't deduced,
// so we can't tell whether there's a contradiction
// yet.
auto newWitness = result.second->getCanonicalType();
if (!newWitness->hasTypeParameter() &&
!newWitness->hasDependentMember() &&
!existingWitness->isEqual(newWitness)) {
LLVM_DEBUG(llvm::dbgs() << "** contradicts explicit type witness, "
"rejecting inference from this decl\n");
goto next_witness;
}
}
// If we same-typed to another unresolved associated type, we won't
// be able to check conformances yet.
if (!canInferFromOtherAssociatedType) {
// Check that the type witness meets the
// requirements on the associated type.
if (auto failed = checkTypeWitness(tc, dc, proto, result.first,
result.second)) {
witnessResult.NonViable.push_back(
std::make_tuple(result.first,result.second,failed));
LLVM_DEBUG(llvm::dbgs() << "-- doesn't fulfill requirements\n");
REJECT;
}
}
LLVM_DEBUG(llvm::dbgs() << "++ seems legit\n");
++i;
}
#undef REJECT
// If no inferred types remain, skip this witness.
if (witnessResult.Inferred.empty() && witnessResult.NonViable.empty())
continue;
// If there were any non-viable inferred associated types, don't
// infer anything from this witness.
if (!witnessResult.NonViable.empty())
witnessResult.Inferred.clear();
result.push_back(std::move(witnessResult));
next_witness:;
}
return result;
}
InferredAssociatedTypes
AssociatedTypeInference::inferTypeWitnessesViaValueWitnesses(
ConformanceChecker &checker,
const llvm::SetVector<AssociatedTypeDecl *> &assocTypes)
{
InferredAssociatedTypes result;
for (auto member : proto->getMembers()) {
auto req = dyn_cast<ValueDecl>(member);
if (!req)
continue;
// Infer type witnesses for associated types.
if (auto assocType = dyn_cast<AssociatedTypeDecl>(req)) {
// If this is not one of the associated types we are trying to infer,
// just continue.
if (assocTypes.count(assocType) == 0)
continue;
auto reqInferred = inferTypeWitnessesViaAssociatedType(checker,
assocTypes,
assocType);
if (!reqInferred.empty())
result.push_back({req, std::move(reqInferred)});
continue;
}
// Skip operator requirements, because they match globally and
// therefore tend to cause deduction mismatches.
// FIXME: If we had some basic sanity checking of Self, we might be able to
// use these.
if (auto func = dyn_cast<FuncDecl>(req)) {
if (func->isOperator() || isa<AccessorDecl>(func))
continue;
}
// Validate the requirement.
tc.validateDecl(req);
if (req->isInvalid() || !req->hasValidSignature())
continue;
// Check whether any of the associated types we care about are
// referenced in this value requirement.
bool anyAssocTypeMatches = false;
for (auto assocType : checker.getReferencedAssociatedTypes(req)) {
if (assocTypes.count(assocType) > 0) {
anyAssocTypeMatches = true;
break;
}
}
// We cannot deduce anything from the witnesses of this
// requirement; skip it.
if (!anyAssocTypeMatches)
continue;
// Infer associated types from the potential value witnesses for
// this requirement.
auto reqInferred =
inferTypeWitnessesViaValueWitnesses(checker, assocTypes, req);
if (reqInferred.empty())
continue;
result.push_back({req, std::move(reqInferred)});
}
return result;
}
/// Map error types back to their original types.
static Type mapErrorTypeToOriginal(Type type) {
if (auto errorType = type->getAs<ErrorType>()) {
if (auto originalType = errorType->getOriginalType())
return originalType.transform(mapErrorTypeToOriginal);
}
return type;
}
/// Produce the type when matching a witness.
static Type getWitnessTypeForMatching(TypeChecker &tc,
NormalProtocolConformance *conformance,
ValueDecl *witness) {
if (!witness->hasInterfaceType())
tc.validateDecl(witness);
if (witness->isInvalid() || !witness->hasValidSignature())
return Type();
if (!witness->getDeclContext()->isTypeContext()) {
// FIXME: Could we infer from 'Self' to make these work?
return witness->getInterfaceType();
}
// Retrieve the set of substitutions to be applied to the witness.
Type model =
conformance->getDeclContext()->mapTypeIntoContext(conformance->getType());
TypeSubstitutionMap substitutions = model->getMemberSubstitutions(witness);
Type type = witness->getInterfaceType()->getReferenceStorageReferent();
if (substitutions.empty())
return type;
// Strip off the requirements of a generic function type.
// FIXME: This doesn't actually break recursion when substitution
// looks for an inferred type witness, but it makes it far less
// common, because most of the recursion involves the requirements
// of the generic type.
if (auto genericFn = type->getAs<GenericFunctionType>()) {
type = FunctionType::get(genericFn->getParams(),
genericFn->getResult(),
genericFn->getExtInfo());
}
// Remap associated types that reference other protocols into this
// protocol.
auto proto = conformance->getProtocol();
type = type.transformRec([proto](TypeBase *type) -> Optional<Type> {
if (auto depMemTy = dyn_cast<DependentMemberType>(type)) {
if (depMemTy->getAssocType() &&
depMemTy->getAssocType()->getProtocol() != proto) {
for (auto member : proto->lookupDirect(depMemTy->getName())) {
if (auto assocType = dyn_cast<AssociatedTypeDecl>(member)) {
auto origProto = depMemTy->getAssocType()->getProtocol();
if (proto->inheritsFrom(origProto))
return Type(DependentMemberType::get(depMemTy->getBase(),
assocType));
}
}
}
}
return None;
});
ModuleDecl *module = conformance->getDeclContext()->getParentModule();
auto resultType = type.subst(QueryTypeSubstitutionMap{substitutions},
LookUpConformanceInModule(module),
SubstFlags::UseErrorType);
if (!resultType->hasError()) return resultType;
// Map error types with original types *back* to the original, dependent type.
return resultType.transform(mapErrorTypeToOriginal);
}
/// Remove the 'self' type from the given type, if it's a method type.
static Type removeSelfParam(ValueDecl *value, Type type) {
if (auto func = dyn_cast<AbstractFunctionDecl>(value)) {
if (func->getDeclContext()->isTypeContext())
return type->castTo<AnyFunctionType>()->getResult();
}
return type;
}
InferredAssociatedTypesByWitnesses
AssociatedTypeInference::inferTypeWitnessesViaAssociatedType(
ConformanceChecker &checker,
const llvm::SetVector<AssociatedTypeDecl *> &allUnresolved,
AssociatedTypeDecl *assocType) {
auto &tc = checker.TC;
// Form the default name _Default_Foo.
Identifier defaultName;
{
SmallString<32> defaultNameStr;
{
llvm::raw_svector_ostream out(defaultNameStr);
out << "_Default_";
out << assocType->getName().str();
}
defaultName = tc.Context.getIdentifier(defaultNameStr);
}
// Look for types with the given default name that have appropriate
// @_implements attributes.
InferredAssociatedTypesByWitnesses result;
auto lookupOptions = defaultMemberTypeLookupOptions;
lookupOptions -= NameLookupFlags::PerformConformanceCheck;
for (auto candidate : tc.lookupMember(dc, adoptee, defaultName,
lookupOptions)) {
// We want type declarations.
auto typeDecl = dyn_cast<TypeDecl>(candidate.getValueDecl());
if (!typeDecl || isa<AssociatedTypeDecl>(typeDecl))
continue;
// We only find these within a protocol extension.
auto defaultProto = typeDecl->getDeclContext()->getSelfProtocolDecl();
if (!defaultProto)
continue;
// Determine the witness type.
Type witnessType = getWitnessTypeForMatching(tc, conformance, typeDecl);
if (!witnessType) continue;
if (auto witnessMetaType = witnessType->getAs<AnyMetatypeType>())
witnessType = witnessMetaType->getInstanceType();
else
continue;
// Add this result.
InferredAssociatedTypesByWitness inferred;
inferred.Witness = typeDecl;
inferred.Inferred.push_back({assocType, witnessType});
result.push_back(std::move(inferred));
}
return result;
}
Type swift::adjustInferredAssociatedType(Type type, bool &noescapeToEscaping) {
// If we have an optional type, adjust its wrapped type.
if (auto optionalObjectType = type->getOptionalObjectType()) {
auto newOptionalObjectType =
adjustInferredAssociatedType(optionalObjectType, noescapeToEscaping);
if (newOptionalObjectType.getPointer() == optionalObjectType.getPointer())
return type;
return OptionalType::get(newOptionalObjectType);
}
// If we have a noescape function type, make it escaping.
if (auto funcType = type->getAs<FunctionType>()) {
if (funcType->isNoEscape()) {
noescapeToEscaping = true;
return FunctionType::get(funcType->getParams(), funcType->getResult(),
funcType->getExtInfo().withNoEscape(false));
}
}
return type;
}
/// Attempt to resolve a type witness via a specific value witness.
InferredAssociatedTypesByWitness
AssociatedTypeInference::inferTypeWitnessesViaValueWitness(ValueDecl *req,
ValueDecl *witness) {
InferredAssociatedTypesByWitness inferred;
inferred.Witness = witness;
// Compute the requirement and witness types we'll use for matching.
Type fullWitnessType = getWitnessTypeForMatching(tc, conformance, witness);
if (!fullWitnessType) {
return inferred;
}
auto setup = [&]() -> std::tuple<Optional<RequirementMatch>, Type, Type> {
fullWitnessType = removeSelfParam(witness, fullWitnessType);
return std::make_tuple(
None,
removeSelfParam(req, req->getInterfaceType()),
fullWitnessType);
};
/// Visits a requirement type to match it to a potential witness for
/// the purpose of deducing associated types.
///
/// The visitor argument is the witness type. If there are any
/// obvious conflicts between the structure of the two types,
/// returns true. The conflict checking is fairly conservative, only
/// considering rough structure.
class MatchVisitor : public TypeMatcher<MatchVisitor> {
NormalProtocolConformance *Conformance;
InferredAssociatedTypesByWitness &Inferred;
public:
MatchVisitor(NormalProtocolConformance *conformance,
InferredAssociatedTypesByWitness &inferred)
: Conformance(conformance), Inferred(inferred) { }
/// Structural mismatches imply that the witness cannot match.
bool mismatch(TypeBase *firstType, TypeBase *secondType,
Type sugaredFirstType) {
// If either type hit an error, don't stop yet.
if (firstType->hasError() || secondType->hasError())
return true;
// FIXME: Check whether one of the types is dependent?
return false;
}
/// Deduce associated types from dependent member types in the witness.
bool mismatch(DependentMemberType *firstDepMember,
TypeBase *secondType, Type sugaredFirstType) {
// If the second type is an error, don't look at it further.
if (secondType->hasError())
return true;
// Adjust the type to a type that can be written explicitly.
bool noescapeToEscaping = false;
Type inferredType =
adjustInferredAssociatedType(secondType, noescapeToEscaping);
if (!inferredType->isMaterializable())
return true;
auto proto = Conformance->getProtocol();
if (auto assocType = getReferencedAssocTypeOfProtocol(firstDepMember,
proto)) {
Inferred.Inferred.push_back({assocType, inferredType});
}
// Always allow mismatches here.
return true;
}
/// FIXME: Recheck the type of Self against the second type?
bool mismatch(GenericTypeParamType *selfParamType,
TypeBase *secondType, Type sugaredFirstType) {
return true;
}
};
// Match a requirement and witness type.
MatchVisitor matchVisitor(conformance, inferred);
auto matchTypes = [&](Type reqType, Type witnessType)
-> Optional<RequirementMatch> {
if (!matchVisitor.match(reqType, witnessType)) {
return RequirementMatch(witness, MatchKind::TypeConflict,
fullWitnessType);
}
return None;
};
// Finalization of the checking is pretty trivial; just bundle up a
// result we can look at.
auto finalize = [&](bool anyRenaming, ArrayRef<OptionalAdjustment>)
-> RequirementMatch {
return RequirementMatch(witness,
anyRenaming ? MatchKind::RenamedMatch
: MatchKind::ExactMatch,
fullWitnessType);
};
// Match the witness. If we don't succeed, throw away the inference
// information.
// FIXME: A renamed match might be useful to retain for the failure case.
if (matchWitness(tc, dc, req, witness, setup, matchTypes, finalize)
.Kind != MatchKind::ExactMatch) {
inferred.Inferred.clear();
}
return inferred;
}
/// Find an associated type declarations that provides a default definition.
static AssociatedTypeDecl *findDefaultedAssociatedType(
TypeChecker &tc,
AssociatedTypeDecl *assocType) {
// If this associated type has a default, we're done.
tc.validateDecl(assocType);
if (!assocType->getDefaultDefinitionLoc().isNull())
return assocType;
// Look at overridden associated types.
SmallPtrSet<CanType, 4> canonicalTypes;
SmallVector<AssociatedTypeDecl *, 2> results;
for (auto overridden : assocType->getOverriddenDecls()) {
auto overriddenDefault = findDefaultedAssociatedType(tc, overridden);
if (!overriddenDefault) continue;
Type overriddenType =
overriddenDefault->getDefaultDefinitionLoc().getType();
assert(overriddenType);
if (!overriddenType) continue;
CanType key = overriddenType->mapTypeOutOfContext()->getCanonicalType();
if (canonicalTypes.insert(key).second)
results.push_back(overriddenDefault);
}
// If there was a single result, return it.
// FIXME: We could find *all* of the non-covered, defaulted associated types.
return results.size() == 1 ? results.front() : nullptr;
}
Type AssociatedTypeInference::computeFixedTypeWitness(
AssociatedTypeDecl *assocType) {
// Look at all of the inherited protocols to determine whether they
// require a fixed type for this associated type.
Type dependentType = assocType->getDeclaredInterfaceType();
Type resultType;
for (auto conformedProto : adoptee->getAnyNominal()->getAllProtocols()) {
if (!conformedProto->inheritsFrom(assocType->getProtocol()))
continue;
auto genericSig = conformedProto->getGenericSignature();
if (!genericSig) return Type();
Type concreteType = genericSig->getConcreteType(dependentType);
if (!concreteType) continue;
if (!resultType) {
resultType = concreteType;
continue;
}
// FIXME: Bailing out on ambiguity.
if (!resultType->isEqual(concreteType))
return Type();
}
return resultType;
}
Type AssociatedTypeInference::computeDefaultTypeWitness(
AssociatedTypeDecl *assocType) {
// Go find a default definition.
auto defaultedAssocType = findDefaultedAssociatedType(tc, assocType);
if (!defaultedAssocType) return Type();
// If we don't have a default definition, we're done.
auto selfType = proto->getSelfInterfaceType();
// Create a set of type substitutions for all known associated type.
// FIXME: Base this on dependent types rather than archetypes?
TypeSubstitutionMap substitutions;
substitutions[proto->mapTypeIntoContext(selfType)
->castTo<ArchetypeType>()] = dc->mapTypeIntoContext(adoptee);
for (auto assocType : proto->getAssociatedTypeMembers()) {
auto archetype = proto->mapTypeIntoContext(
assocType->getDeclaredInterfaceType())
->getAs<ArchetypeType>();
if (!archetype)
continue;
if (conformance->hasTypeWitness(assocType)) {
substitutions[archetype] =
dc->mapTypeIntoContext(
conformance->getTypeWitness(assocType, nullptr));
} else {
auto known = typeWitnesses.begin(assocType);
if (known != typeWitnesses.end())
substitutions[archetype] = known->first;
else
substitutions[archetype] = ErrorType::get(archetype);
}
}
Type defaultType = defaultedAssocType->getDefaultDefinitionLoc().getType();
// FIXME: Circularity
if (!defaultType)
return Type();
// If the associated type came from a different protocol, map it into our
// protocol's context.
if (defaultedAssocType->getDeclContext() != proto) {
defaultType = defaultType->mapTypeOutOfContext();<|fim▁hole|>
defaultType = defaultType.subst(
QueryTypeSubstitutionMap{substitutions},
LookUpConformanceInModule(dc->getParentModule()));
if (!defaultType)
return Type();
if (auto failed = checkTypeWitness(tc, dc, proto, assocType, defaultType)) {
// Record the failure, if we haven't seen one already.
if (!failedDefaultedAssocType && !failed.isError()) {
failedDefaultedAssocType = defaultedAssocType;
failedDefaultedWitness = defaultType;
failedDefaultedResult = failed;
}
return Type();
}
return defaultType;
}
Type AssociatedTypeInference::computeDerivedTypeWitness(
AssociatedTypeDecl *assocType) {
if (adoptee->hasError())
return Type();
// Can we derive conformances for this protocol and adoptee?
NominalTypeDecl *derivingTypeDecl = adoptee->getAnyNominal();
if (!DerivedConformance::derivesProtocolConformance(dc, derivingTypeDecl,
proto))
return Type();
// Try to derive the type witness.
Type derivedType = tc.deriveTypeWitness(dc, derivingTypeDecl, assocType);
if (!derivedType)
return Type();
// Make sure that the derived type is sane.
if (checkTypeWitness(tc, dc, proto, assocType, derivedType)) {
/// FIXME: Diagnose based on this.
failedDerivedAssocType = assocType;
failedDerivedWitness = derivedType;
return Type();
}
return derivedType;
}
Type
AssociatedTypeInference::computeAbstractTypeWitness(
AssociatedTypeDecl *assocType,
bool allowDerived) {
// We don't have a type witness for this associated type, so go
// looking for more options.
if (Type concreteType = computeFixedTypeWitness(assocType))
return concreteType;
// If we can form a default type, do so.
if (Type defaultType = computeDefaultTypeWitness(assocType))
return defaultType;
// If we can derive a type witness, do so.
if (allowDerived) {
if (Type derivedType = computeDerivedTypeWitness(assocType))
return derivedType;
}
// If there is a generic parameter of the named type, use that.
if (auto gpList = dc->getGenericParamsOfContext()) {
GenericTypeParamDecl *foundGP = nullptr;
for (auto gp : *gpList) {
if (gp->getName() == assocType->getName()) {
foundGP = gp;
break;
}
}
if (foundGP)
return dc->mapTypeIntoContext(foundGP->getDeclaredInterfaceType());
}
return Type();
}
Type AssociatedTypeInference::substCurrentTypeWitnesses(Type type) {
// Local function that folds dependent member types with non-dependent
// bases into actual member references.
std::function<Type(Type)> foldDependentMemberTypes;
llvm::DenseSet<AssociatedTypeDecl *> recursionCheck;
foldDependentMemberTypes = [&](Type type) -> Type {
if (auto depMemTy = type->getAs<DependentMemberType>()) {
auto baseTy = depMemTy->getBase().transform(foldDependentMemberTypes);
if (baseTy.isNull() || baseTy->hasTypeParameter())
return nullptr;
auto assocType = depMemTy->getAssocType();
if (!assocType)
return nullptr;
if (!recursionCheck.insert(assocType).second)
return nullptr;
SWIFT_DEFER { recursionCheck.erase(assocType); };
// Try to substitute into the base type.
if (Type result = depMemTy->substBaseType(dc->getParentModule(), baseTy)){
return result;
}
// If that failed, check whether it's because of the conformance we're
// evaluating.
auto localConformance
= tc.conformsToProtocol(
baseTy, assocType->getProtocol(), dc,
ConformanceCheckFlags::SkipConditionalRequirements);
if (!localConformance || localConformance->isAbstract() ||
(localConformance->getConcrete()->getRootNormalConformance()
!= conformance)) {
return nullptr;
}
// Find the tentative type witness for this associated type.
auto known = typeWitnesses.begin(assocType);
if (known == typeWitnesses.end())
return nullptr;
return known->first.transform(foldDependentMemberTypes);
}
// The presence of a generic type parameter indicates that we
// cannot use this type binding.
if (type->is<GenericTypeParamType>()) {
return nullptr;
}
return type;
};
return type.transform(foldDependentMemberTypes);
}
/// "Sanitize" requirements for conformance checking, removing any requirements
/// that unnecessarily refer to associated types of other protocols.
static void sanitizeProtocolRequirements(
ProtocolDecl *proto,
ArrayRef<Requirement> requirements,
SmallVectorImpl<Requirement> &sanitized) {
std::function<Type(Type)> sanitizeType;
sanitizeType = [&](Type outerType) {
return outerType.transformRec([&] (TypeBase *type) -> Optional<Type> {
if (auto depMemTy = dyn_cast<DependentMemberType>(type)) {
if (!depMemTy->getAssocType() ||
depMemTy->getAssocType()->getProtocol() != proto) {
for (auto member : proto->lookupDirect(depMemTy->getName())) {
if (auto assocType = dyn_cast<AssociatedTypeDecl>(member)) {
Type sanitizedBase = sanitizeType(depMemTy->getBase());
if (!sanitizedBase)
return Type();
return Type(DependentMemberType::get(sanitizedBase,
assocType));
}
}
if (depMemTy->getBase()->is<GenericTypeParamType>())
return Type();
}
}
return None;
});
};
for (const auto &req : requirements) {
switch (req.getKind()) {
case RequirementKind::Conformance:
case RequirementKind::SameType:
case RequirementKind::Superclass: {
Type firstType = sanitizeType(req.getFirstType());
Type secondType = sanitizeType(req.getSecondType());
if (firstType && secondType) {
sanitized.push_back({req.getKind(), firstType, secondType});
}
break;
}
case RequirementKind::Layout: {
Type firstType = sanitizeType(req.getFirstType());
if (firstType) {
sanitized.push_back({req.getKind(), firstType,
req.getLayoutConstraint()});
}
break;
}
}
}
}
SubstOptions
AssociatedTypeInference::getSubstOptionsWithCurrentTypeWitnesses() {
SubstOptions options(None);
AssociatedTypeInference *self = this;
options.getTentativeTypeWitness =
[self](const NormalProtocolConformance *conformance,
AssociatedTypeDecl *assocType) -> TypeBase * {
auto thisProto = self->conformance->getProtocol();
if (conformance == self->conformance) {
// Okay: we have the associated type we need.
} else if (conformance->getType()->isEqual(
self->conformance->getType()) &&
thisProto->inheritsFrom(conformance->getProtocol())) {
// Find an associated type with the same name in the given
// protocol.
AssociatedTypeDecl *foundAssocType = nullptr;
for (auto result : thisProto->lookupDirect(
assocType->getName(),
/*ignoreNewExtensions=*/true)) {
foundAssocType = dyn_cast<AssociatedTypeDecl>(result);
if (foundAssocType) break;
}
if (!foundAssocType) return nullptr;
assocType = foundAssocType;
} else {
return nullptr;
}
Type type = self->typeWitnesses.begin(assocType)->first;
return type->mapTypeOutOfContext().getPointer();
};
return options;
}
bool AssociatedTypeInference::checkCurrentTypeWitnesses(
const SmallVectorImpl<std::pair<ValueDecl *, ValueDecl *>>
&valueWitnesses) {
// If we don't have a requirement signature for this protocol, bail out.
// FIXME: We should never get to this point. Or we should always fail.
if (!proto->isRequirementSignatureComputed()) return false;
// Check any same-type requirements in the protocol's requirement signature.
SubstOptions options = getSubstOptionsWithCurrentTypeWitnesses();
auto typeInContext = dc->mapTypeIntoContext(adoptee);
auto substitutions =
SubstitutionMap::getProtocolSubstitutions(
proto, typeInContext,
ProtocolConformanceRef(conformance));
SmallVector<Requirement, 4> sanitizedRequirements;
sanitizeProtocolRequirements(proto, proto->getRequirementSignature(),
sanitizedRequirements);
auto result =
tc.checkGenericArguments(dc, SourceLoc(), SourceLoc(),
typeInContext,
{ Type(proto->getProtocolSelfType()) },
sanitizedRequirements,
QuerySubstitutionMap{substitutions},
TypeChecker::LookUpConformance(dc),
None, nullptr, options);
switch (result) {
case RequirementCheckResult::Failure:
++NumSolutionStatesFailedCheck;
return true;
case RequirementCheckResult::Success:
case RequirementCheckResult::SubstitutionFailure:
break;
}
// Check for extra requirements in the constrained extensions that supply
// defaults.
SmallPtrSet<ExtensionDecl *, 4> checkedExtensions;
for (const auto &valueWitness : valueWitnesses) {
// We only perform this additional checking for default associated types.
if (!isa<TypeDecl>(valueWitness.first)) continue;
auto witness = valueWitness.second;
if (!witness) continue;
auto ext = dyn_cast<ExtensionDecl>(witness->getDeclContext());
if (!ext) continue;
if (!ext->isConstrainedExtension()) continue;
if (!checkedExtensions.insert(ext).second) continue;
++NumConstrainedExtensionChecks;
if (checkConstrainedExtension(ext)) {
++NumConstrainedExtensionChecksFailed;
return true;
}
}
return false;
}
bool AssociatedTypeInference::checkConstrainedExtension(ExtensionDecl *ext) {
auto typeInContext = dc->mapTypeIntoContext(adoptee);
auto subs = typeInContext->getContextSubstitutions(ext);
SubstOptions options = getSubstOptionsWithCurrentTypeWitnesses();
switch (tc.checkGenericArguments(
dc, SourceLoc(), SourceLoc(), adoptee,
ext->getGenericSignature()->getGenericParams(),
ext->getGenericSignature()->getRequirements(),
QueryTypeSubstitutionMap{subs},
LookUpConformanceInModule(ext->getModuleContext()),
ConformanceCheckFlags::InExpression,
nullptr, options)) {
case RequirementCheckResult::Success:
case RequirementCheckResult::SubstitutionFailure:
return false;
case RequirementCheckResult::Failure:
return true;
}
}
void AssociatedTypeInference::findSolutions(
ArrayRef<AssociatedTypeDecl *> unresolvedAssocTypes,
SmallVectorImpl<InferredTypeWitnessesSolution> &solutions) {
SmallVector<InferredTypeWitnessesSolution, 4> nonViableSolutions;
SmallVector<std::pair<ValueDecl *, ValueDecl *>, 4> valueWitnesses;
findSolutionsRec(unresolvedAssocTypes, solutions, nonViableSolutions,
valueWitnesses, 0, 0, 0);
}
void AssociatedTypeInference::findSolutionsRec(
ArrayRef<AssociatedTypeDecl *> unresolvedAssocTypes,
SmallVectorImpl<InferredTypeWitnessesSolution> &solutions,
SmallVectorImpl<InferredTypeWitnessesSolution> &nonViableSolutions,
SmallVector<std::pair<ValueDecl *, ValueDecl *>, 4> &valueWitnesses,
unsigned numTypeWitnesses,
unsigned numValueWitnessesInProtocolExtensions,
unsigned reqDepth) {
using TypeWitnessesScope = decltype(typeWitnesses)::ScopeTy;
// If we hit the last requirement, record and check this solution.
if (reqDepth == inferred.size()) {
// Introduce a hash table scope; we may add type witnesses here.
TypeWitnessesScope typeWitnessesScope(typeWitnesses);
// Check for completeness of the solution
for (auto assocType : unresolvedAssocTypes) {
// Local function to record a missing associated type.
auto recordMissing = [&] {
if (!missingTypeWitness)
missingTypeWitness = assocType;
};
auto typeWitness = typeWitnesses.begin(assocType);
if (typeWitness != typeWitnesses.end()) {
// The solution contains an error.
if (typeWitness->first->hasError()) {
recordMissing();
return;
}
continue;
}
// Try to compute the type without the aid of a specific potential
// witness.
if (Type type = computeAbstractTypeWitness(assocType,
/*allowDerived=*/true)) {
if (type->hasError()) {
recordMissing();
return;
}
typeWitnesses.insert(assocType, {type, reqDepth});
continue;
}
// The solution is incomplete.
recordMissing();
return;
}
++NumSolutionStates;
// Fold the dependent member types within this type.
for (auto assocType : proto->getAssociatedTypeMembers()) {
if (conformance->hasTypeWitness(assocType))
continue;
// If the type binding does not have a type parameter, there's nothing
// to do.
auto known = typeWitnesses.begin(assocType);
assert(known != typeWitnesses.end());
if (!known->first->hasTypeParameter() &&
!known->first->hasDependentMember())
continue;
Type replaced = substCurrentTypeWitnesses(known->first);
if (replaced.isNull())
return;
known->first = replaced;
}
// Check whether our current solution matches the given solution.
auto matchesSolution =
[&](const InferredTypeWitnessesSolution &solution) {
for (const auto &existingTypeWitness : solution.TypeWitnesses) {
auto typeWitness = typeWitnesses.begin(existingTypeWitness.first);
if (!typeWitness->first->isEqual(existingTypeWitness.second.first))
return false;
}
return true;
};
// If we've seen this solution already, bail out; there's no point in
// checking further.
if (llvm::any_of(solutions, matchesSolution) ||
llvm::any_of(nonViableSolutions, matchesSolution)) {
++NumDuplicateSolutionStates;
return;
}
/// Check the current set of type witnesses.
bool invalid = checkCurrentTypeWitnesses(valueWitnesses);
auto &solutionList = invalid ? nonViableSolutions : solutions;
solutionList.push_back(InferredTypeWitnessesSolution());
auto &solution = solutionList.back();
// Copy the type witnesses.
for (auto assocType : unresolvedAssocTypes) {
auto typeWitness = typeWitnesses.begin(assocType);
solution.TypeWitnesses.insert({assocType, *typeWitness});
}
// Copy the value witnesses.
solution.ValueWitnesses = valueWitnesses;
solution.NumValueWitnessesInProtocolExtensions
= numValueWitnessesInProtocolExtensions;
// We're done recording the solution.
return;
}
// Iterate over the potential witnesses for this requirement,
// looking for solutions involving each one.
const auto &inferredReq = inferred[reqDepth];
for (const auto &witnessReq : inferredReq.second) {
llvm::SaveAndRestore<unsigned> savedNumTypeWitnesses(numTypeWitnesses);
// If we inferred a type witness via a default, try both with and without
// the default.
if (isa<TypeDecl>(inferredReq.first)) {
// Recurse without considering this type.
valueWitnesses.push_back({inferredReq.first, nullptr});
findSolutionsRec(unresolvedAssocTypes, solutions, nonViableSolutions,
valueWitnesses, numTypeWitnesses,
numValueWitnessesInProtocolExtensions, reqDepth + 1);
valueWitnesses.pop_back();
++numTypeWitnesses;
for (const auto &typeWitness : witnessReq.Inferred) {
auto known = typeWitnesses.begin(typeWitness.first);
if (known != typeWitnesses.end()) continue;
// Enter a new scope for the type witnesses hash table.
TypeWitnessesScope typeWitnessesScope(typeWitnesses);
typeWitnesses.insert(typeWitness.first, {typeWitness.second, reqDepth});
valueWitnesses.push_back({inferredReq.first, witnessReq.Witness});
findSolutionsRec(unresolvedAssocTypes, solutions, nonViableSolutions,
valueWitnesses, numTypeWitnesses,
numValueWitnessesInProtocolExtensions, reqDepth + 1);
valueWitnesses.pop_back();
}
continue;
}
// Enter a new scope for the type witnesses hash table.
TypeWitnessesScope typeWitnessesScope(typeWitnesses);
// Record this value witness, popping it when we exit the current scope.
valueWitnesses.push_back({inferredReq.first, witnessReq.Witness});
if (!isa<TypeDecl>(inferredReq.first) &&
witnessReq.Witness->getDeclContext()->getExtendedProtocolDecl())
++numValueWitnessesInProtocolExtensions;
SWIFT_DEFER {
if (!isa<TypeDecl>(inferredReq.first) &&
witnessReq.Witness->getDeclContext()->getExtendedProtocolDecl())
--numValueWitnessesInProtocolExtensions;
valueWitnesses.pop_back();
};
// Introduce each of the type witnesses into the hash table.
bool failed = false;
for (const auto &typeWitness : witnessReq.Inferred) {
// If we've seen a type witness for this associated type that
// conflicts, there is no solution.
auto known = typeWitnesses.begin(typeWitness.first);
if (known != typeWitnesses.end()) {
// Don't overwrite a defaulted associated type witness.
if (isa<TypeDecl>(valueWitnesses[known->second].second))
continue;
// If witnesses for two different requirements inferred the same
// type, we're okay.
if (known->first->isEqual(typeWitness.second))
continue;
// If one has a type parameter remaining but the other does not,
// drop the one with the type parameter.
if ((known->first->hasTypeParameter() ||
known->first->hasDependentMember())
!= (typeWitness.second->hasTypeParameter() ||
typeWitness.second->hasDependentMember())) {
if (typeWitness.second->hasTypeParameter() ||
typeWitness.second->hasDependentMember())
continue;
known->first = typeWitness.second;
continue;
}
if (!typeWitnessConflict ||
numTypeWitnesses > numTypeWitnessesBeforeConflict) {
typeWitnessConflict = {typeWitness.first,
typeWitness.second,
inferredReq.first,
witnessReq.Witness,
known->first,
valueWitnesses[known->second].first,
valueWitnesses[known->second].second};
numTypeWitnessesBeforeConflict = numTypeWitnesses;
}
failed = true;
break;
}
// Record the type witness.
++numTypeWitnesses;
typeWitnesses.insert(typeWitness.first, {typeWitness.second, reqDepth});
}
if (failed)
continue;
// Recurse
findSolutionsRec(unresolvedAssocTypes, solutions, nonViableSolutions,
valueWitnesses, numTypeWitnesses,
numValueWitnessesInProtocolExtensions, reqDepth + 1);
}
}
static Comparison
compareDeclsForInference(TypeChecker &TC, DeclContext *DC,
ValueDecl *decl1, ValueDecl *decl2) {
// TC.compareDeclarations assumes that it's comparing two decls that
// apply equally well to a call site. We haven't yet inferred the
// associated types for a type, so the ranking algorithm used by
// compareDeclarations to score protocol extensions is inappropriate,
// since we may have potential witnesses from extensions with mutually
// exclusive associated type constraints, and compareDeclarations will
// consider these unordered since neither extension's generic signature
// is a superset of the other.
// If one of the declarations is null, it implies that we're working with
// a skipped associated type default. Prefer that default to something
// that came from a protocol extension.
if (!decl1 || !decl2) {
if (!decl1 &&
decl2 && decl2->getDeclContext()->getExtendedProtocolDecl())
return Comparison::Worse;
if (!decl2 &&
decl1 && decl1->getDeclContext()->getExtendedProtocolDecl())
return Comparison::Better;
return Comparison::Unordered;
}
// If the witnesses come from the same decl context, score normally.
auto dc1 = decl1->getDeclContext();
auto dc2 = decl2->getDeclContext();
if (dc1 == dc2)
return TC.compareDeclarations(DC, decl1, decl2);
auto isProtocolExt1 = (bool)dc1->getExtendedProtocolDecl();
auto isProtocolExt2 = (bool)dc2->getExtendedProtocolDecl();
// If one witness comes from a protocol extension, favor the one
// from a concrete context.
if (isProtocolExt1 != isProtocolExt2) {
return isProtocolExt1 ? Comparison::Worse : Comparison::Better;
}
// If both witnesses came from concrete contexts, score normally.
// Associated type inference shouldn't impact the result.
// FIXME: It could, if someone constrained to ConcreteType.AssocType...
if (!isProtocolExt1)
return TC.compareDeclarations(DC, decl1, decl2);
// Compare protocol extensions by which protocols they require Self to
// conform to. If one extension requires a superset of the other's
// constraints, it wins.
auto sig1 = dc1->getGenericSignatureOfContext();
auto sig2 = dc2->getGenericSignatureOfContext();
// FIXME: Extensions sometimes have null generic signatures while
// checking the standard library...
if (!sig1 || !sig2)
return TC.compareDeclarations(DC, decl1, decl2);
auto selfParam = GenericTypeParamType::get(0, 0, TC.Context);
// Collect the protocols required by extension 1.
Type class1;
SmallPtrSet<ProtocolDecl*, 4> protos1;
std::function<void (ProtocolDecl*)> insertProtocol;
insertProtocol = [&](ProtocolDecl *p) {
if (!protos1.insert(p).second)
return;
for (auto parent : p->getInheritedProtocols())
insertProtocol(parent);
};
for (auto &reqt : sig1->getRequirements()) {
if (!reqt.getFirstType()->isEqual(selfParam))
continue;
switch (reqt.getKind()) {
case RequirementKind::Conformance: {
auto *proto = reqt.getSecondType()->castTo<ProtocolType>()->getDecl();
insertProtocol(proto);
break;
}
case RequirementKind::Superclass:
class1 = reqt.getSecondType();
break;
case RequirementKind::SameType:
case RequirementKind::Layout:
break;
}
}
// Compare with the protocols required by extension 2.
Type class2;
SmallPtrSet<ProtocolDecl*, 4> protos2;
bool protos2AreSubsetOf1 = true;
std::function<void (ProtocolDecl*)> removeProtocol;
removeProtocol = [&](ProtocolDecl *p) {
if (!protos2.insert(p).second)
return;
protos2AreSubsetOf1 &= protos1.erase(p);
for (auto parent : p->getInheritedProtocols())
removeProtocol(parent);
};
for (auto &reqt : sig2->getRequirements()) {
if (!reqt.getFirstType()->isEqual(selfParam))
continue;
switch (reqt.getKind()) {
case RequirementKind::Conformance: {
auto *proto = reqt.getSecondType()->castTo<ProtocolType>()->getDecl();
removeProtocol(proto);
break;
}
case RequirementKind::Superclass:
class2 = reqt.getSecondType();
break;
case RequirementKind::SameType:
case RequirementKind::Layout:
break;
}
}
auto isClassConstraintAsStrict = [&](Type t1, Type t2) -> bool {
if (!t1)
return !t2;
if (!t2)
return true;
return TC.isSubclassOf(t1, t2, DC);
};
bool protos1AreSubsetOf2 = protos1.empty();
// If the second extension requires strictly more protocols than the
// first, it's better.
if (protos1AreSubsetOf2 > protos2AreSubsetOf1
&& isClassConstraintAsStrict(class2, class1)) {
return Comparison::Worse;
// If the first extension requires strictly more protocols than the
// second, it's better.
} else if (protos2AreSubsetOf1 > protos1AreSubsetOf2
&& isClassConstraintAsStrict(class1, class2)) {
return Comparison::Better;
}
// If they require the same set of protocols, or non-overlapping
// sets, judge them normally.
return TC.compareDeclarations(DC, decl1, decl2);
}
bool AssociatedTypeInference::isBetterSolution(
const InferredTypeWitnessesSolution &first,
const InferredTypeWitnessesSolution &second) {
assert(first.ValueWitnesses.size() == second.ValueWitnesses.size());
bool firstBetter = false;
bool secondBetter = false;
for (unsigned i = 0, n = first.ValueWitnesses.size(); i != n; ++i) {
assert(first.ValueWitnesses[i].first == second.ValueWitnesses[i].first);
auto firstWitness = first.ValueWitnesses[i].second;
auto secondWitness = second.ValueWitnesses[i].second;
if (firstWitness == secondWitness)
continue;
switch (compareDeclsForInference(tc, dc, firstWitness, secondWitness)) {
case Comparison::Better:
if (secondBetter)
return false;
firstBetter = true;
break;
case Comparison::Worse:
if (firstBetter)
return false;
secondBetter = true;
break;
case Comparison::Unordered:
break;
}
}
return firstBetter;
}
bool AssociatedTypeInference::findBestSolution(
SmallVectorImpl<InferredTypeWitnessesSolution> &solutions) {
if (solutions.empty()) return true;
if (solutions.size() == 1) return false;
// Find the smallest number of value witnesses found in protocol extensions.
// FIXME: This is a silly heuristic that should go away.
unsigned bestNumValueWitnessesInProtocolExtensions
= solutions.front().NumValueWitnessesInProtocolExtensions;
for (unsigned i = 1, n = solutions.size(); i != n; ++i) {
bestNumValueWitnessesInProtocolExtensions
= std::min(bestNumValueWitnessesInProtocolExtensions,
solutions[i].NumValueWitnessesInProtocolExtensions);
}
// Erase any solutions with more value witnesses in protocol
// extensions than the best.
solutions.erase(
std::remove_if(solutions.begin(), solutions.end(),
[&](const InferredTypeWitnessesSolution &solution) {
return solution.NumValueWitnessesInProtocolExtensions >
bestNumValueWitnessesInProtocolExtensions;
}),
solutions.end());
// If we're down to one solution, success!
if (solutions.size() == 1) return false;
// Find a solution that's at least as good as the solutions that follow it.
unsigned bestIdx = 0;
for (unsigned i = 1, n = solutions.size(); i != n; ++i) {
if (isBetterSolution(solutions[i], solutions[bestIdx]))
bestIdx = i;
}
// Make sure that solution is better than any of the other solutions.
bool ambiguous = false;
for (unsigned i = 1, n = solutions.size(); i != n; ++i) {
if (i != bestIdx && !isBetterSolution(solutions[bestIdx], solutions[i])) {
ambiguous = true;
break;
}
}
// If the result was ambiguous, fail.
if (ambiguous) {
assert(solutions.size() != 1 && "should have succeeded somewhere above?");
return true;
}
// Keep the best solution, erasing all others.
if (bestIdx != 0)
solutions[0] = std::move(solutions[bestIdx]);
solutions.erase(solutions.begin() + 1, solutions.end());
return false;
}
namespace {
/// A failed type witness binding.
struct FailedTypeWitness {
/// The value requirement that triggered inference.
ValueDecl *Requirement;
/// The corresponding value witness from which the type witness
/// was inferred.
ValueDecl *Witness;
/// The actual type witness that was inferred.
Type TypeWitness;
/// The failed type witness result.
CheckTypeWitnessResult Result;
};
} // end anonymous namespace
bool AssociatedTypeInference::diagnoseNoSolutions(
ArrayRef<AssociatedTypeDecl *> unresolvedAssocTypes,
ConformanceChecker &checker) {
// If a defaulted type witness failed, diagnose it.
if (failedDefaultedAssocType) {
auto failedDefaultedAssocType = this->failedDefaultedAssocType;
auto failedDefaultedWitness = this->failedDefaultedWitness;
auto failedDefaultedResult = this->failedDefaultedResult;
checker.diagnoseOrDefer(failedDefaultedAssocType, true,
[failedDefaultedAssocType, failedDefaultedWitness,
failedDefaultedResult](NormalProtocolConformance *conformance) {
auto proto = conformance->getProtocol();
auto &diags = proto->getASTContext().Diags;
diags.diagnose(failedDefaultedAssocType,
diag::default_associated_type_req_fail,
failedDefaultedWitness,
failedDefaultedAssocType->getFullName(),
proto->getDeclaredType(),
failedDefaultedResult.getRequirement(),
failedDefaultedResult.isConformanceRequirement());
});
return true;
}
// Form a mapping from associated type declarations to failed type
// witnesses.
llvm::DenseMap<AssociatedTypeDecl *, SmallVector<FailedTypeWitness, 2>>
failedTypeWitnesses;
for (const auto &inferredReq : inferred) {
for (const auto &inferredWitness : inferredReq.second) {
for (const auto &nonViable : inferredWitness.NonViable) {
failedTypeWitnesses[std::get<0>(nonViable)]
.push_back({inferredReq.first, inferredWitness.Witness,
std::get<1>(nonViable), std::get<2>(nonViable)});
}
}
}
// Local function to attempt to diagnose potential type witnesses
// that failed requirements.
auto tryDiagnoseTypeWitness = [&](AssociatedTypeDecl *assocType) -> bool {
auto known = failedTypeWitnesses.find(assocType);
if (known == failedTypeWitnesses.end())
return false;
auto failedSet = std::move(known->second);
checker.diagnoseOrDefer(assocType, true,
[assocType, failedSet](NormalProtocolConformance *conformance) {
auto proto = conformance->getProtocol();
auto &diags = proto->getASTContext().Diags;
diags.diagnose(assocType, diag::bad_associated_type_deduction,
assocType->getFullName(), proto->getFullName());
for (const auto &failed : failedSet) {
if (failed.Result.isError())
continue;
diags.diagnose(failed.Witness,
diag::associated_type_deduction_witness_failed,
failed.Requirement->getFullName(),
failed.TypeWitness,
failed.Result.getRequirement(),
failed.Result.isConformanceRequirement());
}
});
return true;
};
// Try to diagnose the first missing type witness we encountered.
if (missingTypeWitness && tryDiagnoseTypeWitness(missingTypeWitness))
return true;
// Failing that, try to diagnose any type witness that failed a
// requirement.
for (auto assocType : unresolvedAssocTypes) {
if (tryDiagnoseTypeWitness(assocType))
return true;
}
// If we saw a conflict, complain about it.
if (typeWitnessConflict) {
auto typeWitnessConflict = this->typeWitnessConflict;
checker.diagnoseOrDefer(typeWitnessConflict->AssocType, true,
[typeWitnessConflict](NormalProtocolConformance *conformance) {
auto &diags = conformance->getDeclContext()->getASTContext().Diags;
diags.diagnose(typeWitnessConflict->AssocType,
diag::ambiguous_associated_type_deduction,
typeWitnessConflict->AssocType->getFullName(),
typeWitnessConflict->FirstType,
typeWitnessConflict->SecondType);
diags.diagnose(typeWitnessConflict->FirstWitness,
diag::associated_type_deduction_witness,
typeWitnessConflict->FirstRequirement->getFullName(),
typeWitnessConflict->FirstType);
diags.diagnose(typeWitnessConflict->SecondWitness,
diag::associated_type_deduction_witness,
typeWitnessConflict->SecondRequirement->getFullName(),
typeWitnessConflict->SecondType);
});
return true;
}
return false;
}
bool AssociatedTypeInference::diagnoseAmbiguousSolutions(
ArrayRef<AssociatedTypeDecl *> unresolvedAssocTypes,
ConformanceChecker &checker,
SmallVectorImpl<InferredTypeWitnessesSolution> &solutions) {
for (auto assocType : unresolvedAssocTypes) {
// Find two types that conflict.
auto &firstSolution = solutions.front();
// Local function to retrieve the value witness for the current associated
// type within the given solution.
auto getValueWitness = [&](InferredTypeWitnessesSolution &solution) {
unsigned witnessIdx = solution.TypeWitnesses[assocType].second;
if (witnessIdx < solution.ValueWitnesses.size())
return solution.ValueWitnesses[witnessIdx];
return std::pair<ValueDecl *, ValueDecl *>(nullptr, nullptr);
};
Type firstType = firstSolution.TypeWitnesses[assocType].first;
// Extract the value witness used to deduce this associated type, if any.
auto firstMatch = getValueWitness(firstSolution);
Type secondType;
std::pair<ValueDecl *, ValueDecl *> secondMatch;
for (auto &solution : solutions) {
Type typeWitness = solution.TypeWitnesses[assocType].first;
if (!typeWitness->isEqual(firstType)) {
secondType = typeWitness;
secondMatch = getValueWitness(solution);
break;
}
}
if (!secondType)
continue;
// We found an ambiguity. diagnose it.
checker.diagnoseOrDefer(assocType, true,
[assocType, firstType, firstMatch, secondType, secondMatch](
NormalProtocolConformance *conformance) {
auto &diags = assocType->getASTContext().Diags;
diags.diagnose(assocType, diag::ambiguous_associated_type_deduction,
assocType->getFullName(), firstType, secondType);
auto diagnoseWitness = [&](std::pair<ValueDecl *, ValueDecl *> match,
Type type){
// If we have a requirement/witness pair, diagnose it.
if (match.first && match.second) {
diags.diagnose(match.second,
diag::associated_type_deduction_witness,
match.first->getFullName(), type);
return;
}
// Otherwise, we have a default.
diags.diagnose(assocType, diag::associated_type_deduction_default,
type)
.highlight(assocType->getDefaultDefinitionLoc().getSourceRange());
};
diagnoseWitness(firstMatch, firstType);
diagnoseWitness(secondMatch, secondType);
});
return true;
}
return false;
}
auto AssociatedTypeInference::solve(ConformanceChecker &checker)
-> Optional<InferredTypeWitnesses> {
// Track when we are checking type witnesses.
ProtocolConformanceState initialState = conformance->getState();
conformance->setState(ProtocolConformanceState::CheckingTypeWitnesses);
SWIFT_DEFER { conformance->setState(initialState); };
// Try to resolve type witnesses via name lookup.
llvm::SetVector<AssociatedTypeDecl *> unresolvedAssocTypes;
for (auto assocType : proto->getAssociatedTypeMembers()) {
// If we already have a type witness, do nothing.
if (conformance->hasTypeWitness(assocType))
continue;
// Try to resolve this type witness via name lookup, which is the
// most direct mechanism, overriding all others.
switch (checker.resolveTypeWitnessViaLookup(assocType)) {
case ResolveWitnessResult::Success:
// Success. Move on to the next.
continue;
case ResolveWitnessResult::ExplicitFailed:
continue;
case ResolveWitnessResult::Missing:
// Note that we haven't resolved this associated type yet.
unresolvedAssocTypes.insert(assocType);
break;
}
}
// Result variable to use for returns so that we get NRVO.
Optional<InferredTypeWitnesses> result = InferredTypeWitnesses();
// If we resolved everything, we're done.
if (unresolvedAssocTypes.empty())
return result;
// Infer potential type witnesses from value witnesses.
inferred = inferTypeWitnessesViaValueWitnesses(checker,
unresolvedAssocTypes);
LLVM_DEBUG(llvm::dbgs() << "Candidates for inference:\n";
dumpInferredAssociatedTypes(inferred));
// Compute the set of solutions.
SmallVector<InferredTypeWitnessesSolution, 4> solutions;
findSolutions(unresolvedAssocTypes.getArrayRef(), solutions);
// Go make sure that type declarations that would act as witnesses
// did not get injected while we were performing checks above. This
// can happen when two associated types in different protocols have
// the same name, and validating a declaration (above) triggers the
// type-witness generation for that second protocol, introducing a
// new type declaration.
// FIXME: This is ridiculous.
for (auto assocType : unresolvedAssocTypes) {
switch (checker.resolveTypeWitnessViaLookup(assocType)) {
case ResolveWitnessResult::Success:
case ResolveWitnessResult::ExplicitFailed:
// A declaration that can become a witness has shown up. Go
// perform the resolution again now that we have more
// information.
return solve(checker);
case ResolveWitnessResult::Missing:
// The type witness is still missing. Keep going.
break;
}
}
// Find the best solution.
if (!findBestSolution(solutions)) {
assert(solutions.size() == 1 && "Not a unique best solution?");
// Form the resulting solution.
auto &typeWitnesses = solutions.front().TypeWitnesses;
for (auto assocType : unresolvedAssocTypes) {
assert(typeWitnesses.count(assocType) == 1 && "missing witness");
auto replacement = typeWitnesses[assocType].first;
// FIXME: We can end up here with dependent types that were not folded
// away for some reason.
if (replacement->hasDependentMember())
return None;
if (replacement->hasArchetype())
replacement = replacement->mapTypeOutOfContext();
result->push_back({assocType, replacement});
}
return result;
}
// Diagnose the complete lack of solutions.
if (solutions.empty() &&
diagnoseNoSolutions(unresolvedAssocTypes.getArrayRef(), checker))
return None;
// Diagnose ambiguous solutions.
if (!solutions.empty() &&
diagnoseAmbiguousSolutions(unresolvedAssocTypes.getArrayRef(), checker,
solutions))
return None;
// Save the missing type witnesses for later diagnosis.
checker.GlobalMissingWitnesses.insert(unresolvedAssocTypes.begin(),
unresolvedAssocTypes.end());
return None;
}
void ConformanceChecker::resolveTypeWitnesses() {
SWIFT_DEFER {
// Resolution attempts to have the witnesses be correct by construction, but
// this isn't guaranteed, so let's double check.
ensureRequirementsAreSatisfied(/*failUnsubstituted=*/false);
};
// Attempt to infer associated type witnesses.
AssociatedTypeInference inference(TC, Conformance);
if (auto inferred = inference.solve(*this)) {
for (const auto &inferredWitness : *inferred) {
recordTypeWitness(inferredWitness.first, inferredWitness.second,
/*typeDecl=*/nullptr);
}
ensureRequirementsAreSatisfied(/*failUnsubstituted=*/false);
return;
}
// Conformance failed. Record errors for each of the witnesses.
Conformance->setInvalid();
// We're going to produce an error below. Mark each unresolved
// associated type witness as erroneous.
for (auto assocType : Proto->getAssociatedTypeMembers()) {
// If we already have a type witness, do nothing.
if (Conformance->hasTypeWitness(assocType))
continue;
recordTypeWitness(assocType, ErrorType::get(TC.Context), nullptr);
}
}
void ConformanceChecker::resolveSingleTypeWitness(
AssociatedTypeDecl *assocType) {
// Ensure we diagnose if the witness is missing.
SWIFT_DEFER {
diagnoseMissingWitnesses(MissingWitnessDiagnosisKind::ErrorFixIt);
};
switch (resolveTypeWitnessViaLookup(assocType)) {
case ResolveWitnessResult::Success:
case ResolveWitnessResult::ExplicitFailed:
// We resolved this type witness one way or another.
return;
case ResolveWitnessResult::Missing:
// The type witness is still missing. Resolve all of the type witnesses.
resolveTypeWitnesses();
return;
}
}
void ConformanceChecker::resolveSingleWitness(ValueDecl *requirement) {
assert(!isa<AssociatedTypeDecl>(requirement) && "Not a value witness");
assert(!Conformance->hasWitness(requirement) && "Already resolved");
// Note that we're resolving this witness.
assert(ResolvingWitnesses.count(requirement) == 0 && "Currently resolving");
ResolvingWitnesses.insert(requirement);
SWIFT_DEFER { ResolvingWitnesses.erase(requirement); };
// Make sure we've validated the requirement.
if (!requirement->hasInterfaceType())
TC.validateDecl(requirement);
if (requirement->isInvalid() || !requirement->hasValidSignature()) {
Conformance->setInvalid();
return;
}
if (!requirement->isProtocolRequirement())
return;
// Resolve all associated types before trying to resolve this witness.
resolveTypeWitnesses();
// If any of the type witnesses was erroneous, don't bother to check
// this value witness: it will fail.
for (auto assocType : getReferencedAssociatedTypes(requirement)) {
if (Conformance->getTypeWitness(assocType, nullptr)->hasError()) {
Conformance->setInvalid();
return;
}
}
// Try to resolve the witness via explicit definitions.
switch (resolveWitnessViaLookup(requirement)) {
case ResolveWitnessResult::Success:
return;
case ResolveWitnessResult::ExplicitFailed:
Conformance->setInvalid();
recordInvalidWitness(requirement);
return;
case ResolveWitnessResult::Missing:
// Continue trying below.
break;
}
// Try to resolve the witness via derivation.
switch (resolveWitnessViaDerivation(requirement)) {
case ResolveWitnessResult::Success:
return;
case ResolveWitnessResult::ExplicitFailed:
Conformance->setInvalid();
recordInvalidWitness(requirement);
return;
case ResolveWitnessResult::Missing:
// Continue trying below.
break;
}
// Try to resolve the witness via defaults.
switch (resolveWitnessViaDefault(requirement)) {
case ResolveWitnessResult::Success:
return;
case ResolveWitnessResult::ExplicitFailed:
Conformance->setInvalid();
recordInvalidWitness(requirement);
return;
case ResolveWitnessResult::Missing:
llvm_unreachable("Should have failed");
break;
}
}<|fim▁end|> | defaultType = proto->mapTypeIntoContext(defaultType);
if (!defaultType) return Type();
} |
<|file_name|>ParticleSystemEmitters.hpp<|end_file_name|><|fim▁begin|>/*
Copyright (C) 2013-2014 by Kristina Simpson <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#pragma once
#include "ParticleSystemFwd.hpp"
namespace KRE
{
namespace Particles
{
enum class EmitsType {
VISUAL,
EMITTER,
AFFECTOR,
TECHNIQUE,
SYSTEM,
};
class Emitter : public EmitObject
{
public:
explicit Emitter(ParticleSystemContainer* parent, const variant& node);
virtual ~Emitter();
Emitter(const Emitter&);
int getEmittedParticleCountPerCycle(float t);
color_vector getColor() const;
Technique* getTechnique() { return technique_; }
void setParentTechnique(Technique* tq) {
technique_ = tq;
}<|fim▁hole|> virtual Emitter* clone() = 0;
static Emitter* factory(ParticleSystemContainer* parent, const variant& node);
protected:
virtual void internalCreate(Particle& p, float t) = 0;
virtual bool durationExpired() { return can_be_deleted_; }
private:
virtual void handleEmitProcess(float t) override;
virtual void handleDraw() const override;
Technique* technique_;
// These are generation parameters.
ParameterPtr emission_rate_;
ParameterPtr time_to_live_;
ParameterPtr velocity_;
ParameterPtr angle_;
ParameterPtr mass_;
// This is the duration that the emitter lives for
ParameterPtr duration_;
// this is the delay till the emitter repeats.
ParameterPtr repeat_delay_;
std::unique_ptr<std::pair<glm::quat, glm::quat>> orientation_range_;
typedef std::pair<color_vector,color_vector> color_range;
std::shared_ptr<color_range> color_range_;
glm::vec4 color_;
ParameterPtr particle_width_;
ParameterPtr particle_height_;
ParameterPtr particle_depth_;
bool force_emission_;
bool force_emission_processed_;
bool can_be_deleted_;
EmitsType emits_type_;
std::string emits_name_;
void initParticle(Particle& p, float t);
void setParticleStartingValues(const std::vector<Particle>::iterator& start, const std::vector<Particle>::iterator& end);
void createParticles(std::vector<Particle>& particles, std::vector<Particle>::iterator& start, std::vector<Particle>::iterator& end, float t);
size_t calculateParticlesToEmit(float t, size_t quota, size_t current_size);
float generateAngle() const;
glm::vec3 getInitialDirection() const;
//BoxOutlinePtr debug_draw_outline_;
// working items
// Any "left over" fractional count of emitted particles
float emission_fraction_;
// time till the emitter stops emitting.
float duration_remaining_;
// time remaining till a stopped emitter restarts.
float repeat_delay_remaining_;
Emitter();
};
}
}<|fim▁end|> | |
<|file_name|>bitcoin_el_GR.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="el_GR" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Lolcockscoin</source>
<translation>Σχετικά με το Lolcockscoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>Lolcockscoin</b> version</source>
<translation>Έκδοση Lolcockscoin</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>
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.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Πνευματική ιδιοκτησία </translation>
</message>
<message>
<location line="+0"/>
<source>The Lolcockscoin developers</source>
<translation>Οι Lolcockscoin προγραμματιστές </translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Βιβλίο Διευθύνσεων</translation>
</message>
<message>
<location line="+19"/>
<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>&Νέα διεύθυνση</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Lolcockscoin 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>Αυτές είναι οι Lolcockscoin διευθύνσεις σας για να λαμβάνετε πληρωμές. Δίνοντας μία ξεχωριστή διεύθυνση σε κάθε αποστολέα, θα μπορείτε να ελέγχετε ποιος σας πληρώνει.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Αντιγραφή διεύθυνσης</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Δείξε &QR κωδικα</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Lolcockscoin address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως σας ανήκει μια συγκεκριμένη διεύθυνση Lolcockscoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Υπέγραψε το μήνυμα</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Αντιγραφη της επιλεγμενης διεύθυνσης στο πρόχειρο του συστηματος</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Εξαγωγή δεδομένων καρτέλας σε αρχείο</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Εξαγωγή</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Lolcockscoin address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως ανήκει μια συγκεκριμένη διεύθυνση Lolcockscoin</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Επιβεβαίωση μηνύματος</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Διαγραφή</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Lolcockscoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Αυτές είναι οι Lolcockscoin διευθύνσεις σας για να λαμβάνετε πληρωμές. Δίνοντας μία ξεχωριστή διεύθυνση σε κάθε αποστολέα, θα μπορείτε να ελέγχετε ποιος σας πληρώνει.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Αντιγραφή &επιγραφής</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Επεξεργασία</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Αποστολή νομισμάτων</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Εξαγωγή Δεδομενων Βιβλίου Διευθύνσεων</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Αρχείο οριοθετημένο με κόμματα (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Εξαγωγή λαθών</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Αδυναμία εγγραφής στο αρχείο %1.</translation>
</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>Φράση πρόσβασης </translation>
</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 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>Εισάγετε τον νέο κωδικό πρόσβασης στον πορτοφόλι <br/> Παρακαλώ χρησιμοποιείστε ένα κωδικό με <b> 10 ή περισσότερους τυχαίους χαρακτήρες</b> ή <b> οχτώ ή παραπάνω λέξεις</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Κρυπτογράφησε το πορτοφόλι</translation>
</message>
<message>
<location line="+3"/>
<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 LITECOINS</b>!</source>
<translation>Προσοχη: Εαν κρυπτογραφησεις το πορτοφολι σου και χάσεις τον κωδικο σου θα χάσεις <b> ΟΛΑ ΣΟΥ ΤΑ LITECOINS</b>!
Είσαι σίγουρος ότι θέλεις να κρυπτογραφησεις το πορτοφολι;</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Είστε σίγουροι ότι θέλετε να κρυπτογραφήσετε το πορτοφόλι σας;</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>ΣΗΜΑΝΤΙΚΟ: Τα προηγούμενα αντίγραφα ασφαλείας που έχετε κάνει από το αρχείο του πορτοφόλιου σας θα πρέπει να αντικατασταθουν με το νέο που δημιουργείται, κρυπτογραφημένο αρχείο πορτοφόλιου. Για λόγους ασφαλείας, τα προηγούμενα αντίγραφα ασφαλείας του μη κρυπτογραφημένου αρχείου πορτοφόλιου θα καταστουν άχρηστα μόλις αρχίσετε να χρησιμοποιείτε το νέο κρυπτογραφημένο πορτοφόλι. </translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Προσοχη: το πλήκτρο Caps Lock είναι ενεργο.</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Κρυπτογραφημενο πορτοφολι</translation>
</message>
<message>
<location line="-56"/>
<source>Lolcockscoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your lolcockscoins from being stolen by malware infecting your computer.</source>
<translation>Το Lolcockscoin θα κλεισει τώρα για να τελειώσει την διαδικασία κρυπτογραφησης. Θυμησου ότι κρυπτογραφώντας το πορτοφολι σου δεν μπορείς να προστατέψεις πλήρως τα lolcockscoins σου από κλοπή στην περίπτωση όπου μολυνθεί ο υπολογιστής σου με κακόβουλο λογισμικο.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Η κρυπτογραφηση του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Η κρυπτογράφηση του πορτοφολιού απέτυχε λογω εσωτερικού σφάλματος. Το πορτοφολι δεν κρυπτογραφηθηκε.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Οι εισαχθέντες κωδικοί δεν ταιριάζουν.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>το ξεκλείδωμα του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Ο κωδικος που εισήχθη για την αποκρυπτογραφηση του πορτοφολιού ήταν λαθος.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Η αποκρυπτογραφηση του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Ο κωδικος του πορτοφολιού άλλαξε με επιτυχία.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Υπογραφή &Μηνύματος...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Συγχρονισμός με το δίκτυο...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Επισκόπηση</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Εμφάνισε γενική εικονα του πορτοφολιού</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Συναλλαγές</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Περιήγηση στο ιστορικο συνναλαγων</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>Εξεργασια της λιστας των αποθηκευμενων διευθύνσεων και ετικετων</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Εμφάνισε την λίστα των διευθύνσεων για την παραλαβή πληρωμων</translation>
</message>
<message>
<location line="+31"/>
<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 Lolcockscoin</source>
<translation>Εμφάνισε πληροφορίες σχετικά με το Lolcockscoin</translation>
</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="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Κρυπτογράφησε το πορτοφόλι</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>&Αντίγραφο ασφαλείας του πορτοφολιού</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Άλλαξε κωδικο πρόσβασης</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Εισαγωγή μπλοκ από τον σκληρο δίσκο ... </translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Φόρτωση ευρετηρίου μπλοκ στον σκληρο δισκο...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Lolcockscoin address</source>
<translation>Στείλε νομισματα σε μια διεύθυνση lolcockscoin</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Lolcockscoin</source>
<translation>Επεργασία ρυθμισεων επιλογών για το Lolcockscoin</translation>
</message>
<message>
<location line="+9"/>
<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="+6"/>
<source>&Debug window</source>
<translation>&Παράθυρο αποσφαλμάτωσης</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Άνοιγμα κονσόλας αποσφαλμάτωσης και διαγνωστικών</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Επιβεβαίωση μηνύματος</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Lolcockscoin</source>
<translation>Lolcockscoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Πορτοφόλι</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Αποστολή</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Παραλαβή </translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Διεύθυνσεις</translation>
</message>
<message>
<location line="+22"/>
<source>&About Lolcockscoin</source>
<translation>&Σχετικα:Lolcockscoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&Εμφάνισε/Κρύψε</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Εμφάνιση ή αποκρύψη του κεντρικου παράθυρου </translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Κρυπτογραφήστε τα ιδιωτικά κλειδιά που ανήκουν στο πορτοφόλι σας </translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Lolcockscoin addresses to prove you own them</source>
<translation>Υπογράψτε ένα μήνυμα για να βεβαιώσετε πως είστε ο κάτοχος αυτής της διεύθυνσης</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Lolcockscoin addresses</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως ανήκει μια συγκεκριμένη διεύθυνση Lolcockscoin</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Αρχείο</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Ρυθμίσεις</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Βοήθεια</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Εργαλειοθήκη καρτελών</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>Lolcockscoin client</source>
<translation>Πελάτης Lolcockscoin</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Lolcockscoin network</source>
<translation><numerusform>%n ενεργή σύνδεση στο δίκτυο Lolcockscoin</numerusform><numerusform>%n ενεργές συνδέσεις στο δίκτυο Βitcoin</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>Η πηγή του μπλοκ δεν ειναι διαθέσιμη... </translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>Μεταποιημένα %1 απο % 2 (κατ 'εκτίμηση) μπλοκ της ιστορίας της συναλλαγής. </translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Έγινε λήψη %1 μπλοκ ιστορικού συναλλαγών</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n ώρες </numerusform><numerusform>%n ώρες </numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n ημέρες </numerusform><numerusform>%n ημέρες </numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n εβδομαδες</numerusform><numerusform>%n εβδομαδες</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 πίσω</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>Το τελευταίο μπλοκ που ελήφθη δημιουργήθηκε %1 πριν.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Οι συναλλαγές μετά από αυτό δεν θα είναι ακόμη ορατες.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Σφάλμα</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Προειδοποίηση</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Πληροφορία</translation>
</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>Η συναλλαγή ξεπερνάει το όριο.
Μπορεί να ολοκληρωθεί με μια αμοιβή των %1, η οποία αποδίδεται στους κόμβους που επεξεργάζονται τις συναλλαγές και βοηθούν στην υποστήριξη του δικτύου.
Θέλετε να συνεχίσετε;</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Ενημερωμένο</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Ενημέρωση...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Επιβεβαίωση αμοιβής συναλλαγής</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Η συναλλαγή απεστάλη</translation>
</message>
<message>
<location line="+0"/>
<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="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>Χειρισμός URI</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Lolcockscoin address or malformed URI parameters.</source>
<translation>Το URI δεν μπορεί να αναλυθεί! Αυτό μπορεί να προκληθεί από μια μη έγκυρη διεύθυνση Lolcockscoin ή ακατάλληλη παραμέτρο URI.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Το πορτοφόλι είναι <b>κρυπτογραφημένο</b> και <b>ξεκλείδωτο</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Το πορτοφόλι είναι <b>κρυπτογραφημένο</b> και <b>κλειδωμένο</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Lolcockscoin can no longer continue safely and will quit.</source>
<translation>Παρουσιάστηκε ανεπανόρθωτο σφάλμα. Το Lolcockscoin δεν μπορεί πλέον να συνεχίσει με ασφάλεια και θα τερματισθει.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Ειδοποίηση Δικτύου</translation>
</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>Η επιγραφή που σχετίζεται με αυτή την καταχώρηση του βιβλίου διευθύνσεων</translation>
</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>Η διεύθυνση που σχετίζεται με αυτή την καταχώρηση του βιβλίου διευθύνσεων. Μπορεί να τροποποιηθεί μόνο για τις διευθύνσεις αποστολής.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<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 Lolcockscoin address.</source>
<translation>Η διεύθυνση "%1" δεν είναι έγκυρη Lolcockscoin διεύθυνση.</translation>
</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="+424"/>
<location line="+12"/>
<source>Lolcockscoin-Qt</source>
<translation>lolcockscoin-qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>έκδοση</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Χρήση:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>επιλογής γραμμής εντολών</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>επιλογές UI</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Όρισε γλώσσα, για παράδειγμα "de_DE"(προεπιλογή:τοπικές ρυθμίσεις)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Έναρξη ελαχιστοποιημένο</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Εμφάνισε την οθόνη εκκίνησης κατά την εκκίνηση(προεπιλογή:1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Ρυθμίσεις</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Κύριο</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation>Η προαιρετική αμοιβή για κάθε kB επισπεύδει την επεξεργασία των συναλλαγών σας. Οι περισσότερες συναλλαγές είναι 1 kB. </translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Αμοιβή &συναλλαγής</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Lolcockscoin after logging in to the system.</source>
<translation>Αυτόματη εκκίνηση του Lolcockscoin μετά την εισαγωγή στο σύστημα</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Lolcockscoin on system login</source>
<translation>&Έναρξη του Βιtcoin κατά την εκκίνηση του συστήματος</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Επαναφορα όλων των επιλογων του πελάτη σε default.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>Επαναφορα ρυθμίσεων</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Δίκτυο</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Lolcockscoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Αυτόματο άνοιγμα των θυρών Lolcockscoin στον δρομολογητή. Λειτουργεί μόνο αν ο δρομολογητής σας υποστηρίζει τη λειτουργία UPnP.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Απόδοση θυρών με χρήστη &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Lolcockscoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Σύνδεση στο Lolcockscoin δίκτυο μέσω διαμεσολαβητή SOCKS4 (π.χ. για σύνδεση μέσω Tor)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Σύνδεση μέσω διαμεσολαβητή SOCKS</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>&IP διαμεσολαβητή:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Διεύθυνση IP του διαμεσολαβητή (π.χ. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Θύρα:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Θύρα διαμεσολαβητή</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS &Έκδοση:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>SOCKS εκδοση του διαμεσολαβητη (e.g. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Παράθυρο</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Εμφάνιση μόνο εικονιδίου στην περιοχή ειδοποιήσεων κατά την ελαχιστοποίηση</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Ελαχιστοποίηση στην περιοχή ειδοποιήσεων αντί της γραμμής εργασιών</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Ελαχιστοποίηση αντί για έξοδο κατά το κλείσιμο του παραθύρου</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>Ε&λαχιστοποίηση κατά το κλείσιμο</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>%Απεικόνιση</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>Γλώσσα περιβάλλοντος εργασίας: </translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Lolcockscoin.</source>
<translation>Εδώ μπορεί να ρυθμιστεί η γλώσσα διεπαφής χρήστη. Αυτή η ρύθμιση θα ισχύσει μετά την επανεκκίνηση του Lolcockscoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>&Μονάδα μέτρησης:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Διαλέξτε την προεπιλεγμένη υποδιαίρεση που θα εμφανίζεται όταν στέλνετε νομίσματα.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Lolcockscoin addresses in the transaction list or not.</source>
<translation>Επιλέξτε αν θέλετε να εμφανίζονται οι διευθύνσεις Lolcockscoin στη λίστα συναλλαγών.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>Εμφάνιση διευθύνσεων στη λίστα συναλλαγών</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&ΟΚ</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Ακύρωση</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Εφαρμογή</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>προεπιλογή</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Επιβεβαιώση των επιλογων επαναφοράς </translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Για ορισμένες ρυθμίσεις πρεπει η επανεκκίνηση να τεθεί σε ισχύ.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>Θέλετε να προχωρήσετε;</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Προειδοποίηση</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Lolcockscoin.</source>
<translation>Αυτή η ρύθμιση θα ισχύσει μετά την επανεκκίνηση του Lolcockscoin.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>Δεν είναι έγκυρη η διεύθυνση διαμεσολαβητή</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Φόρμα</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Lolcockscoin network after a connection is established, but this process has not completed yet.</source>
<translation>Οι πληροφορίες που εμφανίζονται μπορεί να είναι ξεπερασμένες. Το πορτοφόλι σας συγχρονίζεται αυτόματα με το δίκτυο Lolcockscoin μετά από μια σύνδεση, αλλά αυτή η διαδικασία δεν έχει ακόμη ολοκληρωθεί. </translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Υπόλοιπο</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Ανεπιβεβαίωτες</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Πορτοφόλι</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>Ανώριμος</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Εξορυγμενο υπόλοιπο που δεν έχει ακόμα ωριμάσει </translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Πρόσφατες συναλλαγές</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Το τρέχον υπόλοιπο</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>Το άθροισμα των συναλλαγών που δεν έχουν ακόμα επιβεβαιωθεί και δεν προσμετρώνται στο τρέχον υπόλοιπό σας</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>εκτός συγχρονισμού</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start lolcockscoin: click-to-pay handler</source>
<translation>Δεν είναι δυνατή η εκκίνηση του Lolcockscoin: click-to-pay handler</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Κώδικας QR</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Αίτηση πληρωμής</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Ποσό:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Επιγραφή:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Μήνυμα:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Αποθήκευση ως...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Σφάλμα κατά την κωδικοποίηση του URI σε κώδικα QR</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>Το αναγραφόμενο ποσό δεν είναι έγκυρο, παρακαλούμε να το ελέγξετε.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>Το αποτέλεσμα της διεύθυνσης είναι πολύ μεγάλο. Μειώστε το μέγεθος για το κείμενο της ετικέτας/ μηνύματος.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Αποθήκευση κώδικα QR</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Εικόνες PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Όνομα Πελάτη</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>Μη διαθέσιμο</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Έκδοση Πελάτη</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Πληροφορία</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Χρησιμοποιηση της OpenSSL εκδοσης</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Χρόνος εκκίνησης</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Δίκτυο</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Αριθμός συνδέσεων</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>Στο testnet</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>αλυσίδα εμποδισμού</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Τρέχον αριθμός μπλοκ</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Κατ' εκτίμηση συνολικά μπλοκς</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Χρόνος τελευταίου μπλοκ</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Άνοιγμα</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>επιλογής γραμμής εντολών</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Lolcockscoin-Qt help message to get a list with possible Lolcockscoin command-line options.</source>
<translation>Εμφανιση του Lolcockscoin-Qt μήνυματος βοήθειας για να πάρετε μια λίστα με τις πιθανές επιλογές Lolcockscoin γραμμής εντολών.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Εμφάνιση</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Κονσόλα</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Ημερομηνία κατασκευής</translation>
</message>
<message>
<location line="-104"/>
<source>Lolcockscoin - Debug window</source>
<translation>Lolcockscoin - Παράθυρο αποσφαλμάτωσης</translation>
</message>
<message>
<location line="+25"/>
<source>Lolcockscoin Core</source>
<translation>Lolcockscoin Core</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Αρχείο καταγραφής εντοπισμού σφαλμάτων </translation>
</message>
<message>
<location line="+7"/>
<source>Open the Lolcockscoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Ανοίξτε το αρχείο καταγραφής εντοπισμού σφαλμάτων από τον τρέχοντα κατάλογο δεδομένων. Αυτό μπορεί να πάρει μερικά δευτερόλεπτα για τα μεγάλα αρχεία καταγραφής. </translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Καθαρισμός κονσόλας</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Lolcockscoin RPC console.</source>
<translation>Καλώς ήρθατε στην Lolcockscoin RPC κονσόλα.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Χρησιμοποιήστε το πάνω και κάτω βέλος για να περιηγηθείτε στο ιστορικο, και <b>Ctrl-L</b> για εκκαθαριση οθονης.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Γράψτε <b>βοήθεια</b> για μια επισκόπηση των διαθέσιμων εντολών</translation>
</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>Αποστολή νομισμάτων</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Αποστολή σε πολλούς αποδέκτες ταυτόχρονα</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>&Προσθήκη αποδέκτη</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Διαγραφή όλων των πεδίων συναλλαγής</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Καθαρισμός &Όλων</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Υπόλοιπο:</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>Επιβεβαίωση αποστολής</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>Αποστολη</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> σε %2 (%3)</translation>
</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>Είστε βέβαιοι για την αποστολή %1;</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>και</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>Η διεύθυνση του αποδέκτη δεν είναι σωστή. Παρακαλώ ελέγξτε ξανά.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>Το ποσό πληρωμής πρέπει να είναι μεγαλύτερο από 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>Το ποσό ξεπερνάει το διαθέσιμο υπόλοιπο</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>Το σύνολο υπερβαίνει το υπόλοιπό σας όταν συμπεριληφθεί και η αμοιβή %1</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Βρέθηκε η ίδια διεύθυνση δύο φορές. Επιτρέπεται μία μόνο εγγραφή για κάθε διεύθυνση, σε κάθε διαδικασία αποστολής.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Σφάλμα: Η δημιουργία της συναλλαγής απέτυχε</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>Σφάλμα: Η συναλλαγή απερρίφθη. Αυτό ενδέχεται να συμβαίνει αν κάποια από τα νομίσματα έχουν ήδη ξοδευθεί, όπως αν χρησιμοποιήσατε αντίγραφο του wallet.dat και τα νομίσματα ξοδεύθηκαν εκεί.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Φόρμα</translation>
</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="+34"/><|fim▁hole|> <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>Εισάγετε μια επιγραφή για αυτή τη διεύθυνση ώστε να καταχωρηθεί στο βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Επιγραφή</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Επιλογή διεύθυνσης από το βιβλίο διευθύνσεων</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>Επικόλληση διεύθυνσης από το πρόχειρο</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>Αφαίρεση αποδέκτη</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Lolcockscoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Εισάγετε μια διεύθυνση Lolcockscoin (π.χ. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Υπογραφές - Είσοδος / Επαλήθευση μήνυματος </translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Υπογραφή Μηνύματος</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>Μπορείτε να υπογράφετε μηνύματα με τις διευθύνσεις σας, ώστε ν' αποδεικνύετε πως αυτές σας ανήκουν. Αποφεύγετε να υπογράφετε κάτι αόριστο καθώς ενδέχεται να εξαπατηθείτε. Υπογράφετε μόνο πλήρης δηλώσεις με τις οποίες συμφωνείτε.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Εισάγετε μια διεύθυνση Lolcockscoin (π.χ. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Επιλογή διεύθυνσης από το βιβλίο διευθύνσεων</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>Επικόλληση διεύθυνσης από το βιβλίο διευθύνσεων</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>Εισάγετε εδώ το μήνυμα που θέλετε να υπογράψετε</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Υπογραφή</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Αντέγραφη της επιλεγμενης διεύθυνσης στο πρόχειρο του συστηματος</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Lolcockscoin address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως σας ανήκει μια συγκεκριμένη διεύθυνση Lolcockscoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Υπογραφη μήνυματος</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Επαναφορά όλων των πεδίων μήνυματος</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Καθαρισμός &Όλων</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Επιβεβαίωση μηνύματος</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>Πληκτρολογήστε την υπογραφή διεύθυνσης, μήνυμα (βεβαιωθείτε ότι έχετε αντιγράψει τις αλλαγές γραμμής, κενά, tabs, κ.λπ. ακριβώς) και την υπογραφή παρακάτω, για να ελέγξει το μήνυμα. Να είστε προσεκτικοί για να μην διαβάσετε περισσότερα στην υπογραφή ό, τι είναι στην υπογραφή ίδιο το μήνυμα , για να μην εξαπατηθούν από έναν άνθρωπο -in - the-middle επίθεση.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Εισάγετε μια διεύθυνση Lolcockscoin (π.χ. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Lolcockscoin address</source>
<translation>Υπογράψτε ένα μήνυμα για ν' αποδείξετε πως υπογραφθηκε απο μια συγκεκριμένη διεύθυνση Lolcockscoin</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Επιβεβαίωση μηνύματος</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Επαναφορά όλων επαλήθευμενων πεδίων μήνυματος </translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Lolcockscoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Εισάγετε μια διεύθυνση Lolcockscoin (π.χ. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Κάντε κλικ στο "Υπογραφή Μηνύματος" για να λάβετε την υπογραφή</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Lolcockscoin signature</source>
<translation>Εισαγωγή υπογραφής Lolcockscoin</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>Η διεύθυνση που εισήχθη είναι λάθος.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Παρακαλούμε ελέγξτε την διεύθυνση και δοκιμάστε ξανά.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>Η διεύθυνση που έχει εισαχθεί δεν αναφέρεται σε ένα πλήκτρο.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>το ξεκλείδωμα του πορτοφολιού απέτυχε</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>Το προσωπικό κλειδί εισαγμενης διευθυνσης δεν είναι διαθέσιμο.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Η υπογραφή του μηνύματος απέτυχε.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Μήνυμα υπεγράφη.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>Η υπογραφή δεν μπόρεσε να αποκρυπτογραφηθεί.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Παρακαλούμε ελέγξτε την υπογραφή και δοκιμάστε ξανά.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>Η υπογραφή δεν ταιριάζει με το μήνυμα. </translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>Η επιβεβαίωση του μηνύματος απέτυχε</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Μήνυμα επιβεβαιώθηκε.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Lolcockscoin developers</source>
<translation>Οι Lolcockscoin προγραμματιστές </translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Ανοιχτό μέχρι %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/χωρίς σύνδεση;</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/χωρίς επιβεβαίωση</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 επιβεβαιώσεις</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Κατάσταση</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, έχει μεταδοθεί μέσω %n κόμβων</numerusform><numerusform>, έχει μεταδοθεί μέσω %n κόμβων</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Ημερομηνία</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Πηγή</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Δημιουργία </translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>Από</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Προς</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation> δική σας διεύθυνση </translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>eπιγραφή</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Πίστωση </translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>ωρίμανση σε %n επιπλέον μπλοκ</numerusform><numerusform>ωρίμανση σε %n επιπλέον μπλοκ</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>μη αποδεκτό</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Debit</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Τέλος συναλλαγής </translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Καθαρό ποσό</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Μήνυμα</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Σχόλιο:</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>ID Συναλλαγής:</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 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>Πρέπει να περιμένετε 120 μπλοκ πριν μπορέσετε να χρησιμοποιήσετε τα νομίσματα που έχετε δημιουργήσει. Το μπλοκ που δημιουργήσατε μεταδόθηκε στο δίκτυο για να συμπεριληφθεί στην αλυσίδα των μπλοκ. Αν δεν μπει σε αυτή θα μετατραπεί σε "μη αποδεκτό" και δε θα μπορεί να καταναλωθεί. Αυτό συμβαίνει σπάνια όταν κάποιος άλλος κόμβος δημιουργήσει ένα μπλοκ λίγα δευτερόλεπτα πριν από εσάς.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Πληροφορίες αποσφαλμάτωσης</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Συναλλαγή</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>εισροές </translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Ποσό</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>αληθής</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>αναληθής </translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, δεν έχει ακόμα μεταδοθεί μ' επιτυχία</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Ανοιχτό για %n μπλοκ</numerusform><numerusform>Ανοιχτό για %n μπλοκ</numerusform></translation>
</message>
<message>
<location line="+70"/>
<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="+225"/>
<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 numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Ανοιχτό για %n μπλοκ</numerusform><numerusform>Ανοιχτό για %n μπλοκ</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Ανοιχτό μέχρι %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Χωρίς σύνδεση (%1 επικυρώσεις)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>Χωρίς επιβεβαίωση (%1 από %2 επικυρώσεις)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Επικυρωμένη (%1 επικυρώσεις)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>Το υπόλοιπο από την εξόρυξη θα είναι διαθέσιμο μετά από %n μπλοκ</numerusform><numerusform>Το υπόλοιπο από την εξόρυξη θα είναι διαθέσιμο μετά από %n μπλοκ</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>Αυτό το μπλοκ δεν έχει παραληφθεί από κανέναν άλλο κόμβο και κατά πάσα πιθανότητα θα απορριφθεί!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Δημιουργήθηκε αλλά απορρίφθηκε</translation>
</message>
<message>
<location line="+43"/>
<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>(δ/α)</translation>
</message>
<message>
<location line="+199"/>
<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="+52"/>
<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>Εμφάνιση λεπτομερειών συναλλαγής</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Εξαγωγή Στοιχείων Συναλλαγών</translation>
</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>Σφάλμα εξαγωγής</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Αδυναμία εγγραφής στο αρχείο %1.</translation>
</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="+193"/>
<source>Send Coins</source>
<translation>Αποστολή νομισμάτων</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Εξαγωγή</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Εξαγωγή δεδομένων καρτέλας σε αρχείο</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Αντίγραφο ασφαλείας του πορτοφολιού</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Αρχεία δεδομένων πορτοφολιού (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Αποτυχία κατά τη δημιουργία αντιγράφου</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Παρουσιάστηκε σφάλμα κατά την αποθήκευση των δεδομένων πορτοφολιού στη νέα τοποθεσία.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Η δημιουργια αντιγραφου ασφαλειας πετυχε</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Τα δεδομένα πορτοφόλιου αποθηκεύτηκαν με επιτυχία στη νέα θέση. </translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Lolcockscoin version</source>
<translation>Έκδοση Lolcockscoin</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Χρήση:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or lolcockscoind</source>
<translation>Αποστολή εντολής στον εξυπηρετητή ή στο lolcockscoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Λίστα εντολών</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Επεξήγηση εντολής</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Επιλογές:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: lolcockscoin.conf)</source>
<translation>Ορίστε αρχείο ρυθμίσεων (προεπιλογή: lolcockscoin.conf)</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: lolcockscoind.pid)</source>
<translation>Ορίστε αρχείο pid (προεπιλογή: lolcockscoind.pid)</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Ορισμός φακέλου δεδομένων</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Όρισε το μέγεθος της βάσης προσωρινής αποθήκευσης σε megabytes(προεπιλογή:25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9864 or testnet: 19863)</source>
<translation>Εισερχόμενες συνδέσεις στη θύρα <port> (προεπιλογή: 9864 ή στο testnet: 19863)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Μέγιστες αριθμός συνδέσεων με τους peers <n> (προεπιλογή: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Σύνδεση σε έναν κόμβο για την ανάκτηση διευθύνσεων από ομοτίμους, και αποσυνδέσh</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Διευκρινίστε τη δικιά σας δημόσια διεύθυνση.</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Όριο αποσύνδεσης προβληματικών peers (προεπιλογή: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Δευτερόλεπτα πριν επιτραπεί ξανά η σύνδεση των προβληματικών peers (προεπιλογή: 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>Ένα σφάλμα συνέβη καθώς προετοιμαζόταν η πόρτα RPC %u για αναμονή IPv4: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9862 or testnet: 19862)</source>
<translation>Εισερχόμενες συνδέσεις JSON-RPC στη θύρα <port> (προεπιλογή: 9862 or testnet: 19862)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Αποδοχή εντολών κονσόλας και JSON-RPC</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Εκτέλεση στο παρασκήνιο κι αποδοχή εντολών</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Χρήση του δοκιμαστικού δικτύου</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Να δέχεσαι συνδέσεις από έξω(προεπιλογή:1)</translation>
</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=lolcockscoinrpc
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 "Lolcockscoin Alert" [email protected]
</source>
<translation>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=lolcockscoinrpc
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 "Lolcockscoin Alert" [email protected]
</translation>
</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>Ένα σφάλμα συνέβη καθώς προετοιμαζόταν η υποδοχη RPC %u για αναμονη του IPv6, επεσε πισω στο IPv4:%s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Αποθηκευση σε συγκεκριμένη διεύθυνση. Χρησιμοποιήστε τα πλήκτρα [Host] : συμβολισμός θύρα για IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Lolcockscoin is probably already running.</source>
<translation>Αδυναμία κλειδώματος του φακέλου δεδομένων %s. Πιθανώς το Lolcockscoin να είναι ήδη ενεργό.</translation>
</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>Σφάλμα: Η συναλλαγή απορρίφθηκε.
Αυτό ίσως οφείλεται στο ότι τα νομίσματά σας έχουν ήδη ξοδευτεί, π.χ. με την αντιγραφή του wallet.dat σε άλλο σύστημα και την χρήση τους εκεί, χωρίς η συναλλαγή να έχει καταγραφεί στο παρόν σύστημα.</translation>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation>Σφάλμα: Αυτή η συναλλαγή απαιτεί αμοιβή συναλλαγής τουλάχιστον %s λόγω του μεγέθους, πολυπλοκότητας ή της χρήσης πρόσφατης παραλαβής κεφαλαίου</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Εκτέλεση της εντολής όταν το καλύτερο μπλοκ αλλάξει(%s στην εντολή αντικαθίσταται από το hash του μπλοκ)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Εκτέλεσε την εντολή όταν το καλύτερο μπλοκ αλλάξει(%s στην εντολή αντικαθίσταται από το hash του μπλοκ)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Ορίστε το μέγιστο μέγεθος των high-priority/low-fee συναλλαγων σε bytes (προεπιλογή: 27000)</translation>
</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>Αυτό είναι ένα προ-τεστ κυκλοφορίας - χρησιμοποιήστε το με δική σας ευθύνη - δεν χρησιμοποιείτε για εξόρυξη ή για αλλες εφαρμογές</translation>
</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>Προειδοποίηση: Η παράμετρος -paytxfee είναι πολύ υψηλή. Πρόκειται για την αμοιβή που θα πληρώνετε για κάθε συναλλαγή που θα στέλνετε.</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>Προειδοποίηση: Εμφανίσεις συναλλαγων δεν μπορεί να είναι σωστες! Μπορεί να χρειαστεί να αναβαθμίσετε, ή άλλοι κόμβοι μπορεί να χρειαστεί να αναβαθμίστουν. </translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Lolcockscoin will not work properly.</source>
<translation>Προειδοποίηση: Παρακαλώ βεβαιωθείτε πως η ημερομηνία κι ώρα του συστήματός σας είναι σωστές. Αν το ρολόι του υπολογιστή σας πάει λάθος, ενδέχεται να μη λειτουργεί σωστά το Lolcockscoin.</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>Προειδοποίηση : Σφάλμα wallet.dat κατα την ανάγνωση ! Όλα τα κλειδιά αναγνωρισθηκαν σωστά, αλλά τα δεδομένα των συναλλαγών ή καταχωρήσεις στο βιβλίο διευθύνσεων μπορεί να είναι ελλιπείς ή λανθασμένα. </translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>Προειδοποίηση : το αρχειο wallet.dat ειναι διεφθαρμένο, τα δεδομένα σώζονται ! Original wallet.dat αποθηκεύονται ως πορτοφόλι { timestamp } bak στο % s ? . . Αν το υπόλοιπο του ή τις συναλλαγές σας, είναι λάθος θα πρέπει να επαναφέρετε από ένα αντίγραφο ασφαλείας</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Προσπάθεια για ανακτησει ιδιωτικων κλειδιων από ενα διεφθαρμένο αρχειο wallet.dat </translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Αποκλεισμός επιλογων δημιουργίας: </translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Σύνδεση μόνο με ορισμένους κόμβους</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Εντοπισθηκε διεφθαρμενη βαση δεδομενων των μπλοκ</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Ανακαλύψτε την δικη σας IP διεύθυνση (προεπιλογή: 1 όταν ακούει και δεν - externalip) </translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>Θελετε να δημιουργηθει τωρα η βαση δεδομενων του μπλοκ? </translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Σφάλμα κατά την ενεργοποίηση της βάσης δεδομένων μπλοκ</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Σφάλμα κατά την ενεργοποίηση της βάσης δεδομένων πορτοφόλιου %s!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Σφάλμα φορτωσης της βασης δεδομενων των μπλοκ</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Σφάλμα φορτωσης της βασης δεδομενων των μπλοκ</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Προειδοποίηση: Χαμηλός χώρος στο δίσκο </translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Σφάλμα: το πορτοφόλι είναι κλειδωμένο, δεν μπορεί να δημιουργηθεί συναλλαγή</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Λάθος: λάθος συστήματος:</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>ταλαιπωρηθειτε για να ακούσετε σε οποιαδήποτε θύρα. Χρήση - ακούστε = 0 , αν θέλετε αυτό.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>Αποτυχία αναγνωσης των block πληροφοριων</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>Η αναγνωση του μπλοκ απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>Ο συγχρονισμος του μπλοκ ευρετηριου απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>Η δημιουργια του μπλοκ ευρετηριου απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>Η δημιουργια των μπλοκ πληροφοριων απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>Η δημιουργια του μπλοκ απετυχε</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>Αδυναμία εγγραφής πληροφοριων αρχειου</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>Αποτυχία εγγραφής στη βάση δεδομένων νομίσματος</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>Αποτυχία εγγραφής δείκτη συναλλαγών </translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>Αποτυχία εγγραφής αναίρεσης δεδομένων </translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Βρες ομότιμους υπολογιστές χρησιμοποιώντας αναζήτηση DNS(προεπιλογή:1)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Δημιουργία νομισμάτων (προκαθορισμος: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Πόσα μπλοκ να ελέγχθουν κατά την εκκίνηση (προεπιλογή:288,0=όλα)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>Πόσο εξονυχιστική να είναι η επιβεβαίωση του μπλοκ(0-4, προεπιλογή:3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>Δεν ειναι αρκετες περιγραφες αρχείων διαθέσιμες.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Εισαγωγή μπλοκ από εξωτερικό αρχείο blk000?.dat</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Ορίσμος του αριθμόυ θεματων στην υπηρεσία κλήσεων RPC (προεπιλογή: 4) </translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Επαλήθευση των μπλοκ... </translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Επαλήθευση πορτοφολιου... </translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Εισαγωγή μπλοκ από εξωτερικό αρχείο blk000?.dat</translation>
</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>Ορίσμος του αριθμό των νημάτων ελέγχου σεναρίου (μέχρι 16, 0 = auto, <0 = αφήνουν τους πολλους πυρήνες δωρεάν, default: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Πληροφορία</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Δεν είναι έγκυρη η διεύθυνση διαμεσολαβητή: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Μη έγκυρο ποσό για την παράμετρο -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Μη έγκυρο ποσό για την παράμετρο -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Διατηρήση ένος πλήρες ευρετήριου συναλλαγών (προεπιλογή: 0) </translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Μέγιστος buffer λήψης ανά σύνδεση, <n>*1000 bytes (προεπιλογή: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Μέγιστος buffer αποστολής ανά σύνδεση, <n>*1000 bytes (προεπιλογή: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Μονο αποδοχη αλυσίδας μπλοκ που ταιριάζει με τα ενσωματωμένα σημεία ελέγχου (προεπιλογή: 1) </translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation> Συνδέση μόνο σε κόμβους του δικτύου <net> (IPv4, IPv6 ή Tor) </translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Έξοδος επιπλέον πληροφοριών εντοπισμού σφαλμάτων</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Έξοδος επιπλέον πληροφοριών εντοπισμού σφαλμάτων</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>Χρονοσφραγίδα πληροφοριών εντοπισμού σφαλμάτων</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Lolcockscoin Wiki for SSL setup instructions)</source>
<translation>Ρυθμίσεις SSL: (ανατρέξτε στο Lolcockscoin Wiki για οδηγίες ρυθμίσεων SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Επιλέξτε την έκδοση του διαμεσολαβητη για να χρησιμοποιήσετε (4-5 , προεπιλογή: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Αποστολή πληροφοριών εντοπισμού σφαλμάτων στην κονσόλα αντί του αρχείου debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Αποστολή πληροφοριών εντοπισμού σφαλμάτων στον debugger</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Ορίσμος του μέγιστου μέγεθος block σε bytes (προεπιλογή: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Ορίστε το μέγιστο μέγεθος block σε bytes (προεπιλογή: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Συρρίκνωση του αρχείο debug.log κατα την εκκίνηση του πελάτη (προεπιλογή: 1 όταν δεν-debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Η υπογραφή συναλλαγής απέτυχε </translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Ορισμός λήξης χρονικού ορίου σε χιλιοστά του δευτερολέπτου(προεπιλογή:5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Λάθος Συστήματος:</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Το ποσό της συναλλαγής είναι πολύ μικρο </translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Τα ποσά των συναλλαγών πρέπει να είναι θετικα</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Η συναλλαγή ειναι πολύ μεγάλη </translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Χρησιμοποίηση του UPnP για την χρήση της πόρτας αναμονής (προεπιλογή:0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Χρησιμοποίηση του UPnP για την χρήση της πόρτας αναμονής (προεπιλογή:1)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Χρήση διακομιστή μεσολάβησης για την επίτευξη των Tor κρυμμένων υπηρεσιων (προεπιλογή: ίδιο με το-proxy) </translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Όνομα χρήστη για τις συνδέσεις JSON-RPC</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Προειδοποίηση</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Προειδοποίηση: Αυτή η έκδοση είναι ξεπερασμένη, απαιτείται αναβάθμιση </translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>Θα πρέπει να ξαναχτίστουν οι βάσεις δεδομένων που χρησιμοποιούντε-Αναδημιουργία αλλάγων-txindex </translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>Το αρχειο wallet.dat ειναι διεφθαρμένο, η διάσωση απέτυχε</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Κωδικός για τις συνδέσεις JSON-RPC</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Αποδοχή συνδέσεων JSON-RPC από συγκεκριμένη διεύθυνση IP</translation>
</message>
<message>
<location line="+76"/>
<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="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Εκτέλεσε την εντολή όταν το καλύτερο μπλοκ αλλάξει(%s στην εντολή αντικαθίσταται από το hash του μπλοκ)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Αναβάθμισε το πορτοφόλι στην τελευταία έκδοση</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Όριο πλήθους κλειδιών pool <n> (προεπιλογή: 100)</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Επανέλεγχος της αλυσίδας μπλοκ για απούσες συναλλαγές</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Χρήση του OpenSSL (https) για συνδέσεις JSON-RPC</translation>
</message>
<message>
<location line="-26"/>
<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="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Αποδεκτά κρυπτογραφήματα (προεπιλογή: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Αυτό το κείμενο βοήθειας</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>Αδύνατη η σύνδεση με τη θύρα %s αυτού του υπολογιστή (bind returned error %d, %s) </translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Σύνδεση μέσω διαμεσολαβητή socks</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Να επιτρέπονται οι έλεγχοι DNS για προσθήκη και σύνδεση κόμβων</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Φόρτωση διευθύνσεων...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Σφάλμα φόρτωσης wallet.dat: Κατεστραμμένο Πορτοφόλι</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Lolcockscoin</source>
<translation>Σφάλμα φόρτωσης wallet.dat: Το Πορτοφόλι απαιτεί μια νεότερη έκδοση του Lolcockscoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Lolcockscoin to complete</source>
<translation>Απαιτείται η επανεγγραφή του Πορτοφολιού, η οποία θα ολοκληρωθεί στην επανεκκίνηση του Lolcockscoin</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Σφάλμα φόρτωσης αρχείου wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Δεν είναι έγκυρη η διεύθυνση διαμεσολαβητή: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Άγνωστo δίκτυο ορίζεται σε onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Άγνωστo δίκτυο ορίζεται: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Δεν μπορώ να γράψω την προεπιλεγμένη διεύθυνση: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Δεν μπορώ να γράψω την προεπιλεγμένη διεύθυνση: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Μη έγκυρο ποσό για την παράμετρο -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Λάθος ποσότητα</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Ανεπαρκές κεφάλαιο</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Φόρτωση ευρετηρίου μπλοκ...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Προσέθεσε ένα κόμβο για σύνδεση και προσπάθησε να κρατήσεις την σύνδεση ανοιχτή</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Lolcockscoin is probably already running.</source>
<translation>Αδύνατη η σύνδεση με τη θύρα %s αυτού του υπολογιστή. Το Lolcockscoin είναι πιθανώς ήδη ενεργό.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Αμοιβή ανά KB που θα προστίθεται στις συναλλαγές που στέλνεις</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Φόρτωση πορτοφολιού...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>Δεν μπορώ να υποβαθμίσω το πορτοφόλι</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>Δεν μπορώ να γράψω την προεπιλεγμένη διεύθυνση</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Ανίχνευση...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Η φόρτωση ολοκληρώθηκε</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Χρήση της %s επιλογής</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Σφάλμα</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>Πρέπει να βάλεις ένα κωδικό στο αρχείο παραμέτρων: %s
Εάν το αρχείο δεν υπάρχει, δημιούργησε το με δικαιώματα μόνο για ανάγνωση από τον δημιουργό</translation>
</message>
</context>
</TS><|fim▁end|> | <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>Διεύθυνση αποστολής της πληρωμής (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message> |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of<|fim▁hole|>// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Bloom operations.
extern crate bigint;
use bigint::{H64, H160, H256, H512, H520, H2048};
use std::mem;
use std::ops::DerefMut;
/// Returns log2.
pub fn log2(x: usize) -> u32 {
if x <= 1 {
return 0;
}
let n = x.leading_zeros();
mem::size_of::<usize>() as u32 * 8 - n
}
/// Bloom operations.
pub trait Bloomable: Sized + Default + DerefMut<Target = [u8]> {
/// When interpreting self as a bloom output, augment (bit-wise OR) with the a bloomed version of `b`.
fn shift_bloomed<'a, T>(&'a mut self, b: &T) -> &'a mut Self
where
T: Bloomable;
/// Same as `shift_bloomed` except that `self` is consumed and a new value returned.
fn with_bloomed<T>(mut self, b: &T) -> Self
where
T: Bloomable,
{
self.shift_bloomed(b);
self
}
/// Construct new instance equal to the bloomed value of `b`.
fn from_bloomed<T>(b: &T) -> Self
where
T: Bloomable;
/// Bloom the current value using the bloom parameter `m`.
fn bloom_part<T>(&self, m: usize) -> T
where
T: Bloomable;
/// Check to see whether this hash, interpreted as a bloom, contains the value `b` when bloomed.
fn contains_bloomed<T>(&self, b: &T) -> bool
where
T: Bloomable;
}
macro_rules! impl_bloomable_for_hash {
($name: ident, $size: expr) => {
impl Bloomable for $name {
fn shift_bloomed<'a, T>(&'a mut self, b: &T) -> &'a mut Self where T: Bloomable {
let bp: Self = b.bloom_part($size);
let new_self = &bp | self;
self.0 = new_self.0;
self
}
fn bloom_part<T>(&self, m: usize) -> T where T: Bloomable + Default {
// numbers of bits
// TODO: move it to some constant
let p = 3;
let bloom_bits = m * 8;
let mask = bloom_bits - 1;
let bloom_bytes = (log2(bloom_bits) + 7) / 8;
// must be a power of 2
assert_eq!(m & (m - 1), 0);
// out of range
assert!(p * bloom_bytes <= $size);
// return type
let mut ret = T::default();
// 'ptr' to out slice
let mut ptr = 0;
// set p number of bits,
// p is equal 3 according to yellowpaper
for _ in 0..p {
let mut index = 0 as usize;
for _ in 0..bloom_bytes {
index = (index << 8) | self.0[ptr] as usize;
ptr += 1;
}
index &= mask;
ret[m - 1 - index / 8] |= 1 << (index % 8);
}
ret
}
fn contains_bloomed<T>(&self, b: &T) -> bool where T: Bloomable {
let bp: Self = b.bloom_part($size);
self.contains(&bp)
}
fn from_bloomed<T>(b: &T) -> Self where T: Bloomable {
b.bloom_part($size)
}
}
}
}
impl_bloomable_for_hash!(H64, 8);
impl_bloomable_for_hash!(H160, 20);
impl_bloomable_for_hash!(H256, 32);
impl_bloomable_for_hash!(H512, 64);
impl_bloomable_for_hash!(H520, 65);
impl_bloomable_for_hash!(H2048, 256);<|fim▁end|> | // 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 |
<|file_name|>dataset.py<|end_file_name|><|fim▁begin|>import functools
import warnings
from collections import Mapping, Sequence
from numbers import Number
import numpy as np
import pandas as pd
from . import ops
from . import utils
from . import common
from . import groupby
from . import indexing
from . import alignment
from . import formatting
from .. import conventions
from .alignment import align, partial_align
from .coordinates import DatasetCoordinates, Indexes
from .common import ImplementsDatasetReduce, BaseDataObject
from .utils import (Frozen, SortedKeysDict, ChainMap, maybe_wrap_array)
from .variable import as_variable, Variable, Coordinate, broadcast_variables
from .pycompat import (iteritems, itervalues, basestring, OrderedDict,
dask_array_type)
from .combine import concat
# list of attributes of pd.DatetimeIndex that are ndarrays of time info
_DATETIMEINDEX_COMPONENTS = ['year', 'month', 'day', 'hour', 'minute',
'second', 'microsecond', 'nanosecond', 'date',
'time', 'dayofyear', 'weekofyear', 'dayofweek',
'quarter']
def _get_virtual_variable(variables, key):
"""Get a virtual variable (e.g., 'time.year') from a dict of xray.Variable
objects (if possible)
"""
if not isinstance(key, basestring):
raise KeyError(key)
split_key = key.split('.', 1)
if len(split_key) != 2:
raise KeyError(key)
ref_name, var_name = split_key
ref_var = variables[ref_name]
if ref_var.ndim == 1:
date = ref_var.to_index()
elif ref_var.ndim == 0:
date = pd.Timestamp(ref_var.values)
else:
raise KeyError(key)
if var_name == 'season':
# TODO: move 'season' into pandas itself
seasons = np.array(['DJF', 'MAM', 'JJA', 'SON'])
month = date.month
data = seasons[(month // 3) % 4]
else:
data = getattr(date, var_name)
return ref_name, var_name, Variable(ref_var.dims, data)
def _as_dataset_variable(name, var):
"""Prepare a variable for adding it to a Dataset
"""
try:
var = as_variable(var, key=name)
except TypeError:
raise TypeError('Dataset variables must be an array or a tuple of '
'the form (dims, data[, attrs, encoding])')
if name in var.dims:
# convert the into an Index
if var.ndim != 1:
raise ValueError('an index variable must be defined with '
'1-dimensional data')
var = var.to_coord()
return var
def _align_variables(variables, join='outer'):
"""Align all DataArrays in the provided dict, leaving other values alone.
"""
alignable = [k for k, v in variables.items() if hasattr(v, 'indexes')]
aligned = align(*[variables[a] for a in alignable],
join=join, copy=False)
new_variables = OrderedDict(variables)
new_variables.update(zip(alignable, aligned))
return new_variables
def _expand_variables(raw_variables, old_variables={}, compat='identical'):
"""Expand a dictionary of variables.
Returns a dictionary of Variable objects suitable for inserting into a
Dataset._variables dictionary.
This includes converting tuples (dims, data) into Variable objects,
converting coordinate variables into Coordinate objects and expanding
DataArray objects into Variables plus coordinates.
Raises ValueError if any conflicting values are found, between any of the
new or old variables.
"""
new_variables = OrderedDict()
new_coord_names = set()
variables = ChainMap(new_variables, old_variables)
def maybe_promote_or_replace(name, var):
existing_var = variables[name]
if name not in existing_var.dims:
if name in var.dims:
variables[name] = var
else:
common_dims = OrderedDict(zip(existing_var.dims,
existing_var.shape))
common_dims.update(zip(var.dims, var.shape))
variables[name] = existing_var.expand_dims(common_dims)
new_coord_names.update(var.dims)
def add_variable(name, var):
var = _as_dataset_variable(name, var)
if name not in variables:
variables[name] = var
new_coord_names.update(variables[name].dims)
else:
if not getattr(variables[name], compat)(var):
raise ValueError('conflicting value for variable %s:\n'
'first value: %r\nsecond value: %r'
% (name, variables[name], var))
if compat == 'broadcast_equals':
maybe_promote_or_replace(name, var)
for name, var in iteritems(raw_variables):
if hasattr(var, 'coords'):
# it's a DataArray
new_coord_names.update(var.coords)
for dim, coord in iteritems(var.coords):
if dim != name:
add_variable(dim, coord.variable)
var = var.variable
add_variable(name, var)
return new_variables, new_coord_names
def _calculate_dims(variables):
"""Calculate the dimensions corresponding to a set of variables.
Returns dictionary mapping from dimension names to sizes. Raises ValueError
if any of the dimension sizes conflict.
"""
dims = {}
last_used = {}
scalar_vars = set(k for k, v in iteritems(variables) if not v.dims)
for k, var in iteritems(variables):
for dim, size in zip(var.dims, var.shape):
if dim in scalar_vars:
raise ValueError('dimension %s already exists as a scalar '
'variable' % dim)
if dim not in dims:
dims[dim] = size
last_used[dim] = k
elif dims[dim] != size:
raise ValueError('conflicting sizes for dimension %r: '
'length %s on %r and length %s on %r' %
(dim, size, k, dims[dim], last_used[dim]))
return dims
def _merge_expand(aligned_self, other, overwrite_vars, compat):
possible_conflicts = dict((k, v) for k, v in aligned_self._variables.items()
if k not in overwrite_vars)
new_vars, new_coord_names = _expand_variables(other, possible_conflicts, compat)
replace_vars = aligned_self._variables.copy()
replace_vars.update(new_vars)
return replace_vars, new_vars, new_coord_names
def _merge_dataset(self, other, overwrite_vars, compat, join):
aligned_self, other = partial_align(self, other, join=join, copy=False)
replace_vars, new_vars, new_coord_names = _merge_expand(
aligned_self, other._variables, overwrite_vars, compat)
new_coord_names.update(other._coord_names)
return replace_vars, new_vars, new_coord_names
def _merge_dict(self, other, overwrite_vars, compat, join):
other = _align_variables(other, join='outer')
alignable = [k for k, v in other.items() if hasattr(v, 'indexes')]
aligned = partial_align(self, *[other[a] for a in alignable],
join=join, copy=False, exclude=overwrite_vars)
aligned_self = aligned[0]
other = OrderedDict(other)
other.update(zip(alignable, aligned[1:]))
return _merge_expand(aligned_self, other, overwrite_vars, compat)
def _assert_empty(args, msg='%s'):
if args:
raise ValueError(msg % args)
def as_dataset(obj):
"""Cast the given object to a Dataset.
Handles DataArrays, Datasets and dictionaries of variables. A new Dataset
object is only created in the last case.
"""
obj = getattr(obj, '_dataset', obj)
if not isinstance(obj, Dataset):
obj = Dataset(obj)
return obj
class Variables(Mapping):
def __init__(self, dataset):
self._dataset = dataset
def __iter__(self):
return (key for key in self._dataset._variables
if key not in self._dataset._coord_names)
def __len__(self):
return len(self._dataset._variables) - len(self._dataset._coord_names)
def __contains__(self, key):
return (key in self._dataset._variables
and key not in self._dataset._coord_names)
def __getitem__(self, key):
if key not in self._dataset._coord_names:
return self._dataset[key]
else:
raise KeyError(key)
def __repr__(self):
return formatting.vars_repr(self)
class _LocIndexer(object):
def __init__(self, dataset):
self.dataset = dataset
def __getitem__(self, key):
if not utils.is_dict_like(key):
raise TypeError('can only lookup dictionaries from Dataset.loc')
return self.dataset.sel(**key)
class Dataset(Mapping, ImplementsDatasetReduce, BaseDataObject):
"""A multi-dimensional, in memory, array database.
A dataset resembles an in-memory representation of a NetCDF file, and
consists of variables, coordinates and attributes which together form a
self describing dataset.
Dataset implements the mapping interface with keys given by variable names
and values given by DataArray objects for each variable name.
One dimensional variables with name equal to their dimension are index
coordinates used for label based indexing.
"""
# class properties defined for the benefit of __setstate__, which otherwise
# runs into trouble because we overrode __getattr__
_attrs = None
_variables = Frozen({})
groupby_cls = groupby.DatasetGroupBy
def __init__(self, variables=None, coords=None, attrs=None,
compat='broadcast_equals'):
"""To load data from a file or file-like object, use the `open_dataset`
function.
Parameters
----------
variables : dict-like, optional
A mapping from variable names to :py:class:`~xray.DataArray`
objects, :py:class:`~xray.Variable` objects or tuples of the
form ``(dims, data[, attrs])`` which can be used as arguments to
create a new ``Variable``. Each dimension must have the same length
in all variables in which it appears.
coords : dict-like, optional
Another mapping in the same form as the `variables` argument,
except the each item is saved on the dataset as a "coordinate".
These variables have an associated meaning: they describe
constant/fixed/independent quantities, unlike the
varying/measured/dependent quantities that belong in `variables`.
Coordinates values may be given by 1-dimensional arrays or scalars,
in which case `dims` do not need to be supplied: 1D arrays will be
assumed to give index values along the dimension with the same
name.
attrs : dict-like, optional
Global attributes to save on this dataset.
compat : {'broadcast_equals', 'equals', 'identical'}, optional
String indicating how to compare variables of the same name for
potential conflicts:
- 'broadcast_equals': all values must be equal when variables are
broadcast against each other to ensure common dimensions.
- 'equals': all values and dimensions must be the same.
- 'identical': all values, dimensions and attributes must be the
same.
"""
self._variables = OrderedDict()
self._coord_names = set()
self._dims = {}
self._attrs = None
self._file_obj = None
if variables is None:
variables = {}
if coords is None:
coords = set()
if variables or coords:
self._set_init_vars_and_dims(variables, coords, compat)
if attrs is not None:
self.attrs = attrs
def _add_missing_coords_inplace(self):
"""Add missing coordinates to self._variables
"""
for dim, size in iteritems(self.dims):
if dim not in self._variables:
# This is equivalent to np.arange(size), but
# waits to create the array until its actually accessed.
data = indexing.LazyIntegerRange(size)
coord = Coordinate(dim, data)
self._variables[dim] = coord
def _update_vars_and_coords(self, new_variables, new_coord_names={},
needs_copy=True, check_coord_names=True):
"""Add a dictionary of new variables to this dataset.
Raises a ValueError if any dimensions have conflicting lengths in the
new dataset. Otherwise will update this dataset's _variables and
_dims attributes in-place.
Set `needs_copy=False` only if this dataset is brand-new and hence
can be thrown away if this method fails.
"""
# default to creating another copy of variables so can unroll if we end
# up with inconsistent dimensions
variables = self._variables.copy() if needs_copy else self._variables
if check_coord_names:
_assert_empty([k for k in self.data_vars if k in new_coord_names],
'coordinates with these names already exist as '
'variables: %s')
variables.update(new_variables)
dims = _calculate_dims(variables)
# all checks are complete: it's safe to update
self._variables = variables
self._dims = dims
self._add_missing_coords_inplace()
self._coord_names.update(new_coord_names)
def _set_init_vars_and_dims(self, vars, coords, compat):
"""Set the initial value of Dataset variables and dimensions
"""
_assert_empty([k for k in vars if k in coords],
'redundant variables and coordinates: %s')
variables = ChainMap(vars, coords)
aligned = _align_variables(variables)
new_variables, new_coord_names = _expand_variables(aligned,
compat=compat)
new_coord_names.update(coords)
self._update_vars_and_coords(new_variables, new_coord_names,
needs_copy=False, check_coord_names=False)
@classmethod
def load_store(cls, store, decoder=None):
"""Create a new dataset from the contents of a backends.*DataStore
object
"""
variables, attributes = store.load()
if decoder:
variables, attributes = decoder(variables, attributes)
obj = cls(variables, attrs=attributes)
obj._file_obj = store
return obj
def close(self):
"""Close any files linked to this dataset
"""
if self._file_obj is not None:
self._file_obj.close()
self._file_obj = None
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def __getstate__(self):
"""Always load data in-memory before pickling"""
self.load()
# self.__dict__ is the default pickle object, we don't need to
# implement our own __setstate__ method to make pickle work
state = self.__dict__.copy()
# throw away any references to datastores in the pickle
state['_file_obj'] = None
return state
@property
def variables(self):
"""Frozen dictionary of xray.Variable objects constituting this
dataset's data
"""
return Frozen(self._variables)
def _attrs_copy(self):
return None if self._attrs is None else OrderedDict(self._attrs)
@property
def attrs(self):
"""Dictionary of global attributes on this dataset
"""
if self._attrs is None:
self._attrs = OrderedDict()
return self._attrs
@attrs.setter
def attrs(self, value):
self._attrs = OrderedDict(value)
@property
def dims(self):
"""Mapping from dimension names to lengths.
This dictionary cannot be modified directly, but is updated when adding
new variables.
"""
return Frozen(SortedKeysDict(self._dims))
def load(self):
"""Manually trigger loading of this dataset's data from disk or a
remote source into memory and return this dataset.
Normally, it should not be necessary to call this method in user code,
because all xray functions should either work on deferred data or
load data automatically. However, this method can be necessary when
working with many file objects on disk.
"""
# access .data to coerce everything to numpy or dask arrays
all_data = dict((k, v.data) for k, v in self.variables.items())
lazy_data = dict((k, v) for k, v in all_data.items()
if isinstance(v, dask_array_type))
if lazy_data:
import dask.array as da
# evaluate all the dask arrays simultaneously
evaluated_data = da.compute(*lazy_data.values())
evaluated_variables = {}
for k, data in zip(lazy_data, evaluated_data):
self.variables[k].data = data
return self
def load_data(self): # pragma: no cover
warnings.warn('the Dataset method `load_data` has been deprecated; '
'use `load` instead',
FutureWarning, stacklevel=2)
return self.load()
@classmethod
def _construct_direct(cls, variables, coord_names, dims, attrs,
file_obj=None):
"""Shortcut around __init__ for internal use when we want to skip
costly validation
"""
obj = object.__new__(cls)
obj._variables = variables
obj._coord_names = coord_names
obj._dims = dims
obj._attrs = attrs
obj._file_obj = file_obj
return obj
__default_attrs = object()
def _replace_vars_and_dims(self, variables, coord_names=None,
attrs=__default_attrs, inplace=False):
"""Fastpath constructor for internal use.
Preserves coord names and attributes; dimensions are recalculated from
the supplied variables.
The arguments are *not* copied when placed on the new dataset. It is up
to the caller to ensure that they have the right type and are not used
elsewhere.
Parameters
----------
variables : OrderedDict
coord_names : set or None, optional
attrs : OrderedDict or None, optional
Returns
-------
new : Dataset
"""
dims = _calculate_dims(variables)
if inplace:
self._dims = dims
self._variables = variables
if coord_names is not None:
self._coord_names = coord_names
if attrs is not self.__default_attrs:
self._attrs = attrs
obj = self
else:
if coord_names is None:
coord_names = self._coord_names.copy()
if attrs is self.__default_attrs:
attrs = self._attrs_copy()
obj = self._construct_direct(variables, coord_names, dims, attrs)
return obj
def copy(self, deep=False):
"""Returns a copy of this dataset.
If `deep=True`, a deep copy is made of each of the component variables.
Otherwise, a shallow copy is made, so each variable in the new dataset
is also a variable in the original dataset.
"""
if deep:
variables = OrderedDict((k, v.copy(deep=True))
for k, v in iteritems(self._variables))
else:
variables = self._variables.copy()
# skip __init__ to avoid costly validation
return self._construct_direct(variables, self._coord_names.copy(),
self._dims.copy(), self._attrs_copy())
def _copy_listed(self, names, keep_attrs=True):
"""Create a new Dataset with the listed variables from this dataset and
the all relevant coordinates. Skips all validation.
"""
variables = OrderedDict()
coord_names = set()
for name in names:
try:
variables[name] = self._variables[name]
except KeyError:
ref_name, var_name, var = _get_virtual_variable(
self._variables, name)
variables[var_name] = var
if ref_name in self._coord_names:
coord_names.add(var_name)
needed_dims = set()
for v in variables.values():
needed_dims.update(v._dims)
for k in self._coord_names:
if set(self._variables[k]._dims) <= needed_dims:
variables[k] = self._variables[k]
coord_names.add(k)
dims = dict((k, self._dims[k]) for k in needed_dims)
attrs = self.attrs.copy() if keep_attrs else None
return self._construct_direct(variables, coord_names, dims, attrs)
def __copy__(self):
return self.copy(deep=False)
def __deepcopy__(self, memo=None):
# memo does nothing but is required for compatibility with
# copy.deepcopy
return self.copy(deep=True)
def __contains__(self, key):
"""The 'in' operator will return true or false depending on whether
'key' is an array in the dataset or not.
"""
return key in self._variables
def __len__(self):
return len(self._variables)
def __iter__(self):
return iter(self._variables)
@property
def nbytes(self):
return sum(v.nbytes for v in self.variables.values())
@property
def loc(self):
"""Attribute for location based indexing. Only supports __getitem__,
and only when the key is a dict of the form {dim: labels}.
"""
return _LocIndexer(self)
def __getitem__(self, key):
"""Access variables or coordinates this dataset as a
:py:class:`~xray.DataArray`.
Indexing with a list of names will return a new ``Dataset`` object.
"""
from .dataarray import DataArray
if utils.is_dict_like(key):
return self.isel(**key)
key = np.asarray(key)
if key.ndim == 0:
return DataArray._new_from_dataset(self, key.item())
else:
return self._copy_listed(key)
def __setitem__(self, key, value):
"""Add an array to this dataset.
If value is a `DataArray`, call its `select_vars()` method, rename it
to `key` and merge the contents of the resulting dataset into this
dataset.
If value is an `Variable` object (or tuple of form
``(dims, data[, attrs])``), add it to this dataset as a new
variable.
"""
if utils.is_dict_like(key):
raise NotImplementedError('cannot yet use a dictionary as a key '
'to set Dataset values')
self.update({key: value})
def __delitem__(self, key):
"""Remove a variable from this dataset.
If this variable is a dimension, all variables containing this
dimension are also removed.
"""
def remove(k):
del self._variables[k]
self._coord_names.discard(k)
remove(key)
if key in self._dims:
del self._dims[key]
also_delete = [k for k, v in iteritems(self._variables)
if key in v.dims]
for key in also_delete:
remove(key)
# mutable objects should not be hashable
__hash__ = None
def _all_compat(self, other, compat_str):
"""Helper function for equals and identical"""
# some stores (e.g., scipy) do not seem to preserve order, so don't
# require matching order for equality
compat = lambda x, y: getattr(x, compat_str)(y)
return (self._coord_names == other._coord_names
and utils.dict_equiv(self._variables, other._variables,
compat=compat))
def broadcast_equals(self, other):
"""Two Datasets are broadcast equal if they are equal after
broadcasting all variables against each other.
For example, variables that are scalar in one dataset but non-scalar in
the other dataset can still be broadcast equal if the the non-scalar
variable is a constant.
See Also
--------
Dataset.equals
Dataset.identical
"""
try:
return self._all_compat(other, 'broadcast_equals')
except (TypeError, AttributeError):
return False
def equals(self, other):
"""Two Datasets are equal if they have matching variables and
coordinates, all of which are equal.
Datasets can still be equal (like pandas objects) if they have NaN
values in the same locations.
This method is necessary because `v1 == v2` for ``Dataset``
does element-wise comparisions (like numpy.ndarrays).
See Also
--------
Dataset.broadcast_equals
Dataset.identical
"""
try:
return self._all_compat(other, 'equals')
except (TypeError, AttributeError):
return False
def identical(self, other):
"""Like equals, but also checks all dataset attributes and the
attributes on all variables and coordinates.
See Also
--------
Dataset.broadcast_equals
Dataset.equals
"""
try:
return (utils.dict_equiv(self.attrs, other.attrs)
and self._all_compat(other, 'identical'))
except (TypeError, AttributeError):
return False
@property
def indexes(self):
"""OrderedDict of pandas.Index objects used for label based indexing
"""
return Indexes(self)
@property
def coords(self):
"""Dictionary of xray.DataArray objects corresponding to coordinate
variables
"""
return DatasetCoordinates(self)
@property
def data_vars(self):
"""Dictionary of xray.DataArray objects corresponding to data variables
"""
return Variables(self)
@property
def vars(self): # pragma: no cover
warnings.warn('the Dataset property `vars` has been deprecated; '
'use `data_vars` instead',
FutureWarning, stacklevel=2)
return self.data_vars
def set_coords(self, names, inplace=False):
"""Given names of one or more variables, set them as coordinates
Parameters
----------
names : str or list of str
Name(s) of variables in this dataset to convert into coordinates.
inplace : bool, optional
If True, modify this dataset inplace. Otherwise, create a new
object.
Returns
-------
Dataset
"""
# TODO: allow inserting new coordinates with this method, like
# DataFrame.set_index?
# nb. check in self._variables, not self.data_vars to insure that the
# operation is idempotent
if isinstance(names, basestring):
names = [names]
self._assert_all_in_dataset(names)
obj = self if inplace else self.copy()
obj._coord_names.update(names)
return obj
def reset_coords(self, names=None, drop=False, inplace=False):
"""Given names of coordinates, reset them to become variables
Parameters
----------
names : str or list of str, optional
Name(s) of non-index coordinates in this dataset to reset into
variables. By default, all non-index coordinates are reset.
drop : bool, optional
If True, remove coordinates instead of converting them into
variables.
inplace : bool, optional
If True, modify this dataset inplace. Otherwise, create a new
object.
Returns
-------
Dataset
"""
if names is None:
names = self._coord_names - set(self.dims)
else:
if isinstance(names, basestring):
names = [names]
self._assert_all_in_dataset(names)
_assert_empty(
set(names) & set(self.dims),
'cannot remove index coordinates with reset_coords: %s')
obj = self if inplace else self.copy()
obj._coord_names.difference_update(names)
if drop:
for name in names:
del obj._variables[name]
return obj
def dump_to_store(self, store, encoder=None, sync=True):
"""Store dataset contents to a backends.*DataStore object."""
variables, attrs = conventions.encode_dataset_coordinates(self)
if encoder:
variables, attrs = encoder(variables, attrs)
store.store(variables, attrs)
if sync:
store.sync()
def to_netcdf(self, path=None, mode='w', format=None, group=None,
engine=None):
"""Write dataset contents to a netCDF file.
Parameters
----------
path : str, optional
Path to which to save this dataset. If no path is provided, this
function returns the resulting netCDF file as a bytes object; in
this case, we need to use scipy.io.netcdf, which does not support
netCDF version 4 (the default format becomes NETCDF3_64BIT).
mode : {'w', 'a'}, optional
Write ('w') or append ('a') mode. If mode='w', any existing file at
this location will be overwritten.
format : {'NETCDF4', 'NETCDF4_CLASSIC', 'NETCDF3_64BIT', 'NETCDF3_CLASSIC'}, optional
File format for the resulting netCDF file:
* NETCDF4: Data is stored in an HDF5 file, using netCDF4 API
features.
* NETCDF4_CLASSIC: Data is stored in an HDF5 file, using only
netCDF 3 compatibile API features.
* NETCDF3_64BIT: 64-bit offset version of the netCDF 3 file format,
which fully supports 2+ GB files, but is only compatible with
clients linked against netCDF version 3.6.0 or later.
* NETCDF3_CLASSIC: The classic netCDF 3 file format. It does not
handle 2+ GB files very well.
All formats are supported by the netCDF4-python library.
scipy.io.netcdf only supports the last two formats.
The default format is NETCDF4 if you are saving a file to disk and
have the netCDF4-python library available. Otherwise, xray falls
back to using scipy to write netCDF files and defaults to the
NETCDF3_64BIT format (scipy does not support netCDF4).
group : str, optional
Path to the netCDF4 group in the given file to open (only works for
format='NETCDF4'). The group(s) will be created if necessary.
engine : {'netcdf4', 'scipy', 'h5netcdf'}, optional
Engine to use when writing netCDF files. If not provided, the
default engine is chosen based on available dependencies, with a
preference for 'netcdf4' if writing to a file on disk.
"""
from ..backends.api import to_netcdf
return to_netcdf(self, path, mode, format, group, engine)
dump = utils.function_alias(to_netcdf, 'dumps')
dumps = utils.function_alias(to_netcdf, 'dumps')
def __repr__(self):
return formatting.dataset_repr(self)
@property
def chunks(self):
"""Block dimensions for this dataset's data or None if it's not a dask
array.
"""
chunks = {}
for v in self.variables.values():
if v.chunks is not None:
new_chunks = list(zip(v.dims, v.chunks))
if any(chunk != chunks[d] for d, chunk in new_chunks
if d in chunks):
raise ValueError('inconsistent chunks')
chunks.update(new_chunks)
return Frozen(SortedKeysDict(chunks))
def chunk(self, chunks=None, lock=False):
"""Coerce all arrays in this dataset into dask arrays with the given
chunks.
Non-dask arrays in this dataset will be converted to dask arrays. Dask
arrays will be rechunked to the given chunk sizes.
If neither chunks is not provided for one or more dimensions, chunk
sizes along that dimension will not be updated; non-dask arrays will be
converted into dask arrays with a single block.
Parameters
----------
chunks : int or dict, optional
Chunk sizes along each dimension, e.g., ``5`` or
``{'x': 5, 'y': 5}``.
lock : optional
Passed on to :py:func:`dask.array.from_array`, if the array is not
already as dask array.
Returns
-------
chunked : xray.Dataset
"""
if isinstance(chunks, Number):
chunks = dict.fromkeys(self.dims, chunks)
if chunks is not None:
bad_dims = [d for d in chunks if d not in self.dims]
if bad_dims:
raise ValueError('some chunks keys are not dimensions on this '
'object: %s' % bad_dims)
def selkeys(dict_, keys):
if dict_ is None:<|fim▁hole|> def maybe_chunk(name, var, chunks):
chunks = selkeys(chunks, var.dims)
if not chunks:
chunks = None
if var.ndim > 0:
return var.chunk(chunks, name=name, lock=lock)
else:
return var
variables = OrderedDict([(k, maybe_chunk(k, v, chunks))
for k, v in self.variables.items()])
return self._replace_vars_and_dims(variables)
def isel(self, **indexers):
"""Returns a new dataset with each array indexed along the specified
dimension(s).
This method selects values from each array using its `__getitem__`
method, except this method does not require knowing the order of
each array's dimensions.
Parameters
----------
**indexers : {dim: indexer, ...}
Keyword arguments with names matching dimensions and values given
by integers, slice objects or arrays.
Returns
-------
obj : Dataset
A new Dataset with the same contents as this dataset, except each
array and dimension is indexed by the appropriate indexers. In
general, each array's data will be a view of the array's data
in this dataset, unless numpy fancy indexing was triggered by using
an array indexer, in which case the data will be a copy.
See Also
--------
Dataset.sel
DataArray.isel
DataArray.sel
"""
invalid = [k for k in indexers if not k in self.dims]
if invalid:
raise ValueError("dimensions %r do not exist" % invalid)
# all indexers should be int, slice or np.ndarrays
indexers = [(k, (np.asarray(v)
if not isinstance(v, (int, np.integer, slice))
else v))
for k, v in iteritems(indexers)]
variables = OrderedDict()
for name, var in iteritems(self._variables):
var_indexers = dict((k, v) for k, v in indexers if k in var.dims)
variables[name] = var.isel(**var_indexers)
return self._replace_vars_and_dims(variables)
def sel(self, method=None, **indexers):
"""Returns a new dataset with each array indexed by tick labels
along the specified dimension(s).
In contrast to `Dataset.isel`, indexers for this method should use
labels instead of integers.
Under the hood, this method is powered by using Panda's powerful Index
objects. This makes label based indexing essentially just as fast as
using integer indexing.
It also means this method uses pandas's (well documented) logic for
indexing. This means you can use string shortcuts for datetime indexes
(e.g., '2000-01' to select all values in January 2000). It also means
that slices are treated as inclusive of both the start and stop values,
unlike normal Python indexing.
Parameters
----------
method : {None, 'nearest', 'pad'/'ffill', 'backfill'/'bfill'}, optional
Method to use for inexact matches (requires pandas>=0.16):
* default: only exact matches
* pad / ffill: propgate last valid index value forward
* backfill / bfill: propagate next valid index value backward
* nearest: use nearest valid index value
**indexers : {dim: indexer, ...}
Keyword arguments with names matching dimensions and values given
by scalars, slices or arrays of tick labels.
Returns
-------
obj : Dataset
A new Dataset with the same contents as this dataset, except each
variable and dimension is indexed by the appropriate indexers. In
general, each variable's data will be a view of the variable's data
in this dataset, unless numpy fancy indexing was triggered by using
an array indexer, in which case the data will be a copy.
See Also
--------
Dataset.isel
DataArray.isel
DataArray.sel
"""
return self.isel(**indexing.remap_label_indexers(self, indexers,
method=method))
def isel_points(self, dim='points', **indexers):
"""Returns a new dataset with each array indexed pointwise along the
specified dimension(s).
This method selects pointwise values from each array and is akin to
the NumPy indexing behavior of `arr[[0, 1], [0, 1]]`, except this
method does not require knowing the order of each array's dimensions.
Parameters
----------
dim : str or DataArray or pandas.Index or other list-like object, optional
Name of the dimension to concatenate along. If dim is provided as a
string, it must be a new dimension name, in which case it is added
along axis=0. If dim is provided as a DataArray or Index or
list-like object, its name, which must not be present in the
dataset, is used as the dimension to concatenate along and the
values are added as a coordinate.
**indexers : {dim: indexer, ...}
Keyword arguments with names matching dimensions and values given
by array-like objects. All indexers must be the same length and
1 dimensional.
Returns
-------
obj : Dataset
A new Dataset with the same contents as this dataset, except each
array and dimension is indexed by the appropriate indexers. With
pointwise indexing, the new Dataset will always be a copy of the
original.
See Also
--------
Dataset.sel
DataArray.isel
DataArray.sel
DataArray.isel_points
"""
indexer_dims = set(indexers)
def relevant_keys(mapping):
return [k for k, v in mapping.items()
if any(d in indexer_dims for d in v.dims)]
data_vars = relevant_keys(self.data_vars)
coords = relevant_keys(self.coords)
# all the indexers should be iterables
keys = indexers.keys()
indexers = [(k, np.asarray(v)) for k, v in iteritems(indexers)]
# Check that indexers are valid dims, integers, and 1D
for k, v in indexers:
if k not in self.dims:
raise ValueError("dimension %s does not exist" % k)
if v.dtype.kind != 'i':
raise TypeError('Indexers must be integers')
if v.ndim != 1:
raise ValueError('Indexers must be 1 dimensional')
# all the indexers should have the same length
lengths = set(len(v) for k, v in indexers)
if len(lengths) > 1:
raise ValueError('All indexers must be the same length')
# Existing dimensions are not valid choices for the dim argument
if isinstance(dim, basestring):
if dim in self.dims:
# dim is an invalid string
raise ValueError('Existing dimension names are not valid '
'choices for the dim argument in sel_points')
elif hasattr(dim, 'dims'):
# dim is a DataArray or Coordinate
if dim.name in self.dims:
# dim already exists
raise ValueError('Existing dimensions are not valid choices '
'for the dim argument in sel_points')
else:
# try to cast dim to DataArray with name = points
from .dataarray import DataArray
dim = DataArray(dim, dims='points', name='points')
# TODO: This would be sped up with vectorized indexing. This will
# require dask to support pointwise indexing as well.
return concat([self.isel(**d) for d in
[dict(zip(keys, inds)) for inds in
zip(*[v for k, v in indexers])]],
dim=dim, coords=coords, data_vars=data_vars)
def reindex_like(self, other, method=None, copy=True):
"""Conform this object onto the indexes of another object, filling
in missing values with NaN.
Parameters
----------
other : Dataset or DataArray
Object with an 'indexes' attribute giving a mapping from dimension
names to pandas.Index objects, which provides coordinates upon
which to index the variables in this dataset. The indexes on this
other object need not be the same as the indexes on this
dataset. Any mis-matched index values will be filled in with
NaN, and any mis-matched dimension names will simply be ignored.
method : {None, 'nearest', 'pad'/'ffill', 'backfill'/'bfill'}, optional
Method to use for filling index values from other not found in this
dataset:
* default: don't fill gaps
* pad / ffill: propgate last valid index value forward
* backfill / bfill: propagate next valid index value backward
* nearest: use nearest valid index value (requires pandas>=0.16)
copy : bool, optional
If `copy=True`, the returned dataset contains only copied
variables. If `copy=False` and no reindexing is required then
original variables from this dataset are returned.
Returns
-------
reindexed : Dataset
Another dataset, with this dataset's data but coordinates from the
other object.
See Also
--------
Dataset.reindex
align
"""
return self.reindex(method=method, copy=copy, **other.indexes)
def reindex(self, indexers=None, method=None, copy=True, **kw_indexers):
"""Conform this object onto a new set of indexes, filling in
missing values with NaN.
Parameters
----------
indexers : dict. optional
Dictionary with keys given by dimension names and values given by
arrays of coordinates tick labels. Any mis-matched coordinate values
will be filled in with NaN, and any mis-matched dimension names will
simply be ignored.
method : {None, 'nearest', 'pad'/'ffill', 'backfill'/'bfill'}, optional
Method to use for filling index values in ``indexers`` not found in
this dataset:
* default: don't fill gaps
* pad / ffill: propgate last valid index value forward
* backfill / bfill: propagate next valid index value backward
* nearest: use nearest valid index value (requires pandas>=0.16)
copy : bool, optional
If `copy=True`, the returned dataset contains only copied
variables. If `copy=False` and no reindexing is required then
original variables from this dataset are returned.
**kw_indexers : optional
Keyword arguments in the same form as ``indexers``.
Returns
-------
reindexed : Dataset
Another dataset, with this dataset's data but replaced coordinates.
See Also
--------
Dataset.reindex_like
align
pandas.Index.get_indexer
"""
indexers = utils.combine_pos_and_kw_args(indexers, kw_indexers,
'reindex')
if not indexers:
# shortcut
return self.copy(deep=True) if copy else self
variables = alignment.reindex_variables(
self.variables, self.indexes, indexers, method, copy=copy)
return self._replace_vars_and_dims(variables)
def rename(self, name_dict, inplace=False):
"""Returns a new object with renamed variables and dimensions.
Parameters
----------
name_dict : dict-like
Dictionary whose keys are current variable or dimension names and
whose values are new names.
inplace : bool, optional
If True, rename variables and dimensions in-place. Otherwise,
return a new dataset object.
Returns
-------
renamed : Dataset
Dataset with renamed variables and dimensions.
See Also
--------
Dataset.swap_dims
DataArray.rename
"""
for k in name_dict:
if k not in self:
raise ValueError("cannot rename %r because it is not a "
"variable in this dataset" % k)
variables = OrderedDict()
coord_names = set()
for k, v in iteritems(self._variables):
name = name_dict.get(k, k)
dims = tuple(name_dict.get(dim, dim) for dim in v.dims)
var = v.copy(deep=False)
var.dims = dims
variables[name] = var
if k in self._coord_names:
coord_names.add(name)
return self._replace_vars_and_dims(variables, coord_names,
inplace=inplace)
def swap_dims(self, dims_dict, inplace=False):
"""Returns a new object with swapped dimensions.
Parameters
----------
dims_dict : dict-like
Dictionary whose keys are current dimension names and whose values
are new names. Each value must already be a variable in the
dataset.
inplace : bool, optional
If True, swap dimensions in-place. Otherwise, return a new dataset
object.
Returns
-------
renamed : Dataset
Dataset with swapped dimensions.
See Also
--------
Dataset.rename
DataArray.swap_dims
"""
for k, v in dims_dict.items():
if k not in self.dims:
raise ValueError('cannot swap from dimension %r because it is '
'not an existing dimension' % k)
if self.variables[v].dims != (k,):
raise ValueError('replacement dimension %r is not a 1D '
'variable along the old dimension %r'
% (v, k))
result_dims = set(dims_dict.get(dim, dim) for dim in self.dims)
variables = OrderedDict()
coord_names = self._coord_names.copy()
coord_names.update(dims_dict.values())
for k, v in iteritems(self.variables):
dims = tuple(dims_dict.get(dim, dim) for dim in v.dims)
var = v.to_coord() if k in result_dims else v.to_variable()
var.dims = dims
variables[k] = var
return self._replace_vars_and_dims(variables, coord_names,
inplace=inplace)
def update(self, other, inplace=True):
"""Update this dataset's variables with those from another dataset.
Parameters
----------
other : Dataset or castable to Dataset
Dataset or variables with which to update this dataset.
inplace : bool, optional
If True, merge the other dataset into this dataset in-place.
Otherwise, return a new dataset object.
Returns
-------
updated : Dataset
Updated dataset.
Raises
------
ValueError
If any dimensions would have inconsistent sizes in the updated
dataset.
"""
return self.merge(
other, inplace=inplace, overwrite_vars=list(other), join='left')
def merge(self, other, inplace=False, overwrite_vars=set(),
compat='broadcast_equals', join='outer'):
"""Merge the arrays of two datasets into a single dataset.
This method generally not allow for overriding data, with the exception
of attributes, which are ignored on the second dataset. Variables with
the same name are checked for conflicts via the equals or identical
methods.
Parameters
----------
other : Dataset or castable to Dataset
Dataset or variables to merge with this dataset.
inplace : bool, optional
If True, merge the other dataset into this dataset in-place.
Otherwise, return a new dataset object.
overwrite_vars : str or sequence, optional
If provided, update variables of these name(s) without checking for
conflicts in this dataset.
compat : {'broadcast_equals', 'equals', 'identical'}, optional
String indicating how to compare variables of the same name for
potential conflicts:
- 'broadcast_equals': all values must be equal when variables are
broadcast against each other to ensure common dimensions.
- 'equals': all values and dimensions must be the same.
- 'identical': all values, dimensions and attributes must be the
same.
join : {'outer', 'inner', 'left', 'right'}, optional
Method for joining ``self`` and ``other`` along shared dimensions:
- 'outer': use the union of the indexes
- 'inner': use the intersection of the indexes
- 'left': use indexes from ``self``
- 'right': use indexes from ``other``
Returns
-------
merged : Dataset
Merged dataset.
Raises
------
ValueError
If any variables conflict (see ``compat``).
"""
if compat not in ['broadcast_equals', 'equals', 'identical']:
raise ValueError("compat=%r invalid: must be 'broadcast_equals', "
"'equals' or 'identical'" % compat)
if isinstance(overwrite_vars, basestring):
overwrite_vars = [overwrite_vars]
overwrite_vars = set(overwrite_vars)
merge = _merge_dataset if isinstance(other, Dataset) else _merge_dict
replace_vars, new_vars, new_coord_names = merge(
self, other, overwrite_vars, compat=compat, join=join)
newly_coords = new_coord_names & (set(self) - set(self.coords))
no_longer_coords = set(self.coords) & (set(new_vars) - new_coord_names)
ambiguous_coords = (newly_coords | no_longer_coords) - overwrite_vars
if ambiguous_coords:
raise ValueError('cannot merge: the following variables are '
'coordinates on one dataset but not the other: %s'
% list(ambiguous_coords))
obj = self if inplace else self.copy()
obj._update_vars_and_coords(replace_vars, new_coord_names)
return obj
def _assert_all_in_dataset(self, names, virtual_okay=False):
bad_names = set(names) - set(self._variables)
if virtual_okay:
bad_names -= self.virtual_variables
if bad_names:
raise ValueError('One or more of the specified variables '
'cannot be found in this dataset')
def drop(self, labels, dim=None):
"""Drop variables or index labels from this dataset.
If a variable corresponding to a dimension is dropped, all variables
that use that dimension are also dropped.
Parameters
----------
labels : str
Names of variables or index labels to drop.
dim : None or str, optional
Dimension along which to drop index labels. By default (if
``dim is None``), drops variables rather than index labels.
Returns
-------
dropped : Dataset
"""
if utils.is_scalar(labels):
labels = [labels]
if dim is None:
return self._drop_vars(labels)
else:
new_index = self.indexes[dim].drop(labels)
return self.loc[{dim: new_index}]
def _drop_vars(self, names):
self._assert_all_in_dataset(names)
drop = set(names)
drop |= set(k for k, v in iteritems(self._variables)
if any(name in v.dims for name in names))
variables = OrderedDict((k, v) for k, v in iteritems(self._variables)
if k not in drop)
coord_names = set(k for k in self._coord_names if k in variables)
return self._replace_vars_and_dims(variables, coord_names)
def drop_vars(self, *names): # pragma: no cover
warnings.warn('the Dataset method `drop_vars` has been deprecated; '
'use `drop` instead',
FutureWarning, stacklevel=2)
return self.drop(names)
def transpose(self, *dims):
"""Return a new Dataset object with all array dimensions transposed.
Although the order of dimensions on each array will change, the dataset
dimensions themselves will remain in fixed (sorted) order.
Parameters
----------
*dims : str, optional
By default, reverse the dimensions on each array. Otherwise,
reorder the dimensions to this order.
Returns
-------
transposed : Dataset
Each array in the dataset (including) coordinates will be
transposed to the given order.
Notes
-----
Although this operation returns a view of each array's data, it
is not lazy -- the data will be fully loaded into memory.
See Also
--------
numpy.transpose
DataArray.transpose
"""
if dims:
if set(dims) ^ set(self.dims):
raise ValueError('arguments to transpose (%s) must be '
'permuted dataset dimensions (%s)'
% (dims, tuple(self.dims)))
ds = self.copy()
for name, var in iteritems(self._variables):
var_dims = tuple(dim for dim in dims if dim in var.dims)
ds._variables[name] = var.transpose(*var_dims)
return ds
@property
def T(self):
return self.transpose()
def squeeze(self, dim=None):
"""Returns a new dataset with squeezed data.
Parameters
----------
dim : None or str or tuple of str, optional
Selects a subset of the length one dimensions. If a dimension is
selected with length greater than one, an error is raised. If
None, all length one dimensions are squeezed.
Returns
-------
squeezed : Dataset
This dataset, but with with all or a subset of the dimensions of
length 1 removed.
Notes
-----
Although this operation returns a view of each variable's data, it is
not lazy -- all variable data will be fully loaded.
See Also
--------
numpy.squeeze
"""
return common.squeeze(self, self.dims, dim)
def dropna(self, dim, how='any', thresh=None, subset=None):
"""Returns a new dataset with dropped labels for missing values along
the provided dimension.
Parameters
----------
dim : str
Dimension along which to drop missing values. Dropping along
multiple dimensions simultaneously is not yet supported.
how : {'any', 'all'}, optional
* any : if any NA values are present, drop that label
* all : if all values are NA, drop that label
thresh : int, default None
If supplied, require this many non-NA values.
subset : sequence, optional
Subset of variables to check for missing values. By default, all
variables in the dataset are checked.
Returns
-------
Dataset
"""
# TODO: consider supporting multiple dimensions? Or not, given that
# there are some ugly edge cases, e.g., pandas's dropna differs
# depending on the order of the supplied axes.
if dim not in self.dims:
raise ValueError('%s must be a single dataset dimension' % dim)
if subset is None:
subset = list(self.data_vars)
count = np.zeros(self.dims[dim], dtype=np.int64)
size = 0
for k in subset:
array = self._variables[k]
if dim in array.dims:
dims = [d for d in array.dims if d != dim]
count += array.count(dims)
size += np.prod([self.dims[d] for d in dims])
if thresh is not None:
mask = count >= thresh
elif how == 'any':
mask = count == size
elif how == 'all':
mask = count > 0
elif how is not None:
raise ValueError('invalid how option: %s' % how)
else:
raise TypeError('must specify how or thresh')
return self.isel(**{dim: mask})
def fillna(self, value):
"""Fill missing values in this object.
This operation follows the normal broadcasting and alignment rules that
xray uses for binary arithmetic, except the result is aligned to this
object (``join='left'``) instead of aligned to the intersection of
index coordinates (``join='inner'``).
Parameters
----------
value : scalar, ndarray, DataArray, dict or Dataset
Used to fill all matching missing values in this dataset's data
variables. Scalars, ndarrays or DataArrays arguments are used to
fill all data with aligned coordinates (for DataArrays).
Dictionaries or datasets match data variables and then align
coordinates if necessary.
Returns
-------
Dataset
"""
return self._fillna(value)
def reduce(self, func, dim=None, keep_attrs=False, numeric_only=False,
allow_lazy=False, **kwargs):
"""Reduce this dataset by applying `func` along some dimension(s).
Parameters
----------
func : function
Function which can be called in the form
`f(x, axis=axis, **kwargs)` to return the result of reducing an
np.ndarray over an integer valued axis.
dim : str or sequence of str, optional
Dimension(s) over which to apply `func`. By default `func` is
applied over all dimensions.
keep_attrs : bool, optional
If True, the datasets's attributes (`attrs`) will be copied from
the original object to the new one. If False (default), the new
object will be returned without attributes.
numeric_only : bool, optional
If True, only apply ``func`` to variables with a numeric dtype.
**kwargs : dict
Additional keyword arguments passed on to ``func``.
Returns
-------
reduced : Dataset
Dataset with this object's DataArrays replaced with new DataArrays
of summarized data and the indicated dimension(s) removed.
"""
if isinstance(dim, basestring):
dims = set([dim])
elif dim is None:
dims = set(self.dims)
else:
dims = set(dim)
_assert_empty([dim for dim in dims if dim not in self.dims],
'Dataset does not contain the dimensions: %s')
variables = OrderedDict()
for name, var in iteritems(self._variables):
reduce_dims = [dim for dim in var.dims if dim in dims]
if reduce_dims or not var.dims:
if name not in self.coords:
if (not numeric_only
or np.issubdtype(var.dtype, np.number)
or var.dtype == np.bool_):
if len(reduce_dims) == 1:
# unpack dimensions for the benefit of functions
# like np.argmin which can't handle tuple arguments
reduce_dims, = reduce_dims
elif len(reduce_dims) == var.ndim:
# prefer to aggregate over axis=None rather than
# axis=(0, 1) if they will be equivalent, because
# the former is often more efficient
reduce_dims = None
variables[name] = var.reduce(func, dim=reduce_dims,
keep_attrs=keep_attrs,
allow_lazy=allow_lazy,
**kwargs)
else:
variables[name] = var
coord_names = set(k for k in self.coords if k in variables)
attrs = self.attrs if keep_attrs else None
return self._replace_vars_and_dims(variables, coord_names, attrs)
def apply(self, func, keep_attrs=False, args=(), **kwargs):
"""Apply a function over the data variables in this dataset.
Parameters
----------
func : function
Function which can be called in the form `f(x, **kwargs)` to
transform each DataArray `x` in this dataset into another
DataArray.
keep_attrs : bool, optional
If True, the dataset's attributes (`attrs`) will be copied from
the original object to the new one. If False, the new object will
be returned without attributes.
args : tuple, optional
Positional arguments passed on to `func`.
**kwargs : dict
Keyword arguments passed on to `func`.
Returns
-------
applied : Dataset
Resulting dataset from applying ``func`` over each data variable.
"""
variables = OrderedDict(
(k, maybe_wrap_array(v, func(v, *args, **kwargs)))
for k, v in iteritems(self.data_vars))
attrs = self.attrs if keep_attrs else None
return type(self)(variables, attrs=attrs)
def assign(self, **kwargs):
"""Assign new data variables to a Dataset, returning a new object
with all the original variables in addition to the new ones.
Parameters
----------
kwargs : keyword, value pairs
keywords are the variables names. If the values are callable, they
are computed on the Dataset and assigned to new data variables. If
the values are not callable, (e.g. a DataArray, scalar, or array),
they are simply assigned.
Returns
-------
ds : Dataset
A new Dataset with the new variables in addition to all the
existing variables.
Notes
-----
Since ``kwargs`` is a dictionary, the order of your arguments may not
be preserved, and so the order of the new variables is not well
defined. Assigning multiple variables within the same ``assign`` is
possible, but you cannot reference other variables created within the
same ``assign`` call.
See Also
--------
pandas.DataFrame.assign
"""
data = self.copy()
# do all calculations first...
results = data._calc_assign_results(kwargs)
# ... and then assign
data.update(results)
return data
def to_array(self, dim='variable', name=None):
"""Convert this dataset into an xray.DataArray
The data variables of this dataset will be broadcast against each other
and stacked along the first axis of the new array. All coordinates of
this dataset will remain coordinates.
Parameters
----------
dim : str, optional
Name of the new dimension.
name : str, optional
Name of the new data array.
Returns
-------
array : xray.DataArray
"""
from .dataarray import DataArray
data_vars = [self.variables[k] for k in self.data_vars]
broadcast_vars = broadcast_variables(*data_vars)
data = ops.stack([b.data for b in broadcast_vars], axis=0)
coords = dict(self.coords)
coords[dim] = list(self.data_vars)
dims = (dim,) + broadcast_vars[0].dims
return DataArray(data, coords, dims, attrs=self.attrs, name=name)
def _to_dataframe(self, ordered_dims):
columns = [k for k in self if k not in self.dims]
data = [self._variables[k].expand_dims(ordered_dims).values.reshape(-1)
for k in columns]
index = self.coords.to_index(ordered_dims)
return pd.DataFrame(OrderedDict(zip(columns, data)), index=index)
def to_dataframe(self):
"""Convert this dataset into a pandas.DataFrame.
Non-index variables in this dataset form the columns of the
DataFrame. The DataFrame is be indexed by the Cartesian product of
this dataset's indices.
"""
return self._to_dataframe(self.dims)
@classmethod
def from_dataframe(cls, dataframe):
"""Convert a pandas.DataFrame into an xray.Dataset
Each column will be converted into an independent variable in the
Dataset. If the dataframe's index is a MultiIndex, it will be expanded
into a tensor product of one-dimensional indices (filling in missing
values with NaN). This method will produce a Dataset very similar to
that on which the 'to_dataframe' method was called, except with
possibly redundant dimensions (since all dataset variables will have
the same dimensionality).
"""
# TODO: Add an option to remove dimensions along which the variables
# are constant, to enable consistent serialization to/from a dataframe,
# even if some variables have different dimensionality.
idx = dataframe.index
obj = cls()
if hasattr(idx, 'levels'):
# it's a multi-index
# expand the DataFrame to include the product of all levels
full_idx = pd.MultiIndex.from_product(idx.levels, names=idx.names)
dataframe = dataframe.reindex(full_idx)
dims = [name if name is not None else 'level_%i' % n
for n, name in enumerate(idx.names)]
for dim, lev in zip(dims, idx.levels):
obj[dim] = (dim, lev)
shape = [lev.size for lev in idx.levels]
else:
if idx.size:
dims = (idx.name if idx.name is not None else 'index',)
obj[dims[0]] = (dims, idx)
else:
dims = []
shape = -1
for name, series in iteritems(dataframe):
data = series.values.reshape(shape)
obj[name] = (dims, data)
return obj
@staticmethod
def _unary_op(f):
@functools.wraps(f)
def func(self, *args, **kwargs):
ds = self.coords.to_dataset()
for k in self.data_vars:
ds._variables[k] = f(self._variables[k], *args, **kwargs)
return ds
return func
@staticmethod
def _binary_op(f, reflexive=False, join='inner', drop_na_vars=True):
@functools.wraps(f)
def func(self, other):
if isinstance(other, groupby.GroupBy):
return NotImplemented
if hasattr(other, 'indexes'):
self, other = align(self, other, join=join, copy=False)
empty_indexes = [d for d, s in self.dims.items() if s == 0]
if empty_indexes:
raise ValueError('no overlapping labels for some '
'dimensions: %s' % empty_indexes)
g = f if not reflexive else lambda x, y: f(y, x)
ds = self._calculate_binary_op(g, other, drop_na_vars=drop_na_vars)
return ds
return func
@staticmethod
def _inplace_binary_op(f):
@functools.wraps(f)
def func(self, other):
if isinstance(other, groupby.GroupBy):
raise TypeError('in-place operations between a Dataset and '
'a grouped object are not permitted')
if hasattr(other, 'indexes'):
other = other.reindex_like(self, copy=False)
# we don't want to actually modify arrays in-place
g = ops.inplace_to_noninplace_op(f)
ds = self._calculate_binary_op(g, other, inplace=True)
self._replace_vars_and_dims(ds._variables, ds._coord_names,
ds._attrs, inplace=True)
return self
return func
def _calculate_binary_op(self, f, other, inplace=False, drop_na_vars=True):
def apply_over_both(lhs_data_vars, rhs_data_vars, lhs_vars, rhs_vars):
dest_vars = OrderedDict()
performed_op = False
for k in lhs_data_vars:
if k in rhs_data_vars:
dest_vars[k] = f(lhs_vars[k], rhs_vars[k])
performed_op = True
elif inplace:
raise ValueError(
'datasets must have the same data variables '
'for in-place arithmetic operations: %s, %s'
% (list(lhs_data_vars), list(rhs_data_vars)))
elif not drop_na_vars:
# this shortcuts left alignment of variables for fillna
dest_vars[k] = lhs_vars[k]
if not performed_op:
raise ValueError(
'datasets have no overlapping data variables: %s, %s'
% (list(lhs_data_vars), list(rhs_data_vars)))
return dest_vars
if utils.is_dict_like(other) and not isinstance(other, Dataset):
# can't use our shortcut of doing the binary operation with
# Variable objects, so apply over our data vars instead.
new_data_vars = apply_over_both(self.data_vars, other,
self.data_vars, other)
return Dataset(new_data_vars)
other_coords = getattr(other, 'coords', None)
ds = self.coords.merge(other_coords)
if isinstance(other, Dataset):
new_vars = apply_over_both(self.data_vars, other.data_vars,
self.variables, other.variables)
else:
other_variable = getattr(other, 'variable', other)
new_vars = OrderedDict((k, f(self.variables[k], other_variable))
for k in self.data_vars)
ds._variables.update(new_vars)
return ds
ops.inject_all_ops_and_reduce_methods(Dataset, array_only=False)<|fim▁end|> | return None
return dict((d, dict_[d]) for d in keys if d in dict_)
|
<|file_name|>geojson_test.py<|end_file_name|><|fim▁begin|>"""Example process file."""
from mapchete.errors import MapcheteNodataTile
from shapely.geometry import shape<|fim▁hole|> # Reading and writing data works like this:
with mp.open("file1") as vector_file:
if vector_file.is_empty():
raise MapcheteNodataTile
return [
dict(
geometry=feature["geometry"],
properties=dict(
name=feature["properties"].get("NAME_0", None),
id=feature["properties"].get("ID_0", None),
area=shape(feature["geometry"]).area,
),
)
for feature in vector_file.read()
]<|fim▁end|> |
def execute(mp):
"""User defined process.""" |
<|file_name|>broadcast.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import
import os
import zmq
import uuid as uuid_pkg
import time
import binascii
import random
import socket
import struct
import marshal
import mmap
from multiprocessing import Manager, Condition
from mmap import ACCESS_WRITE, ACCESS_READ
from dpark.utils.log import get_logger
from dpark.utils import compress, decompress, spawn
from dpark.cache import Cache
from dpark.serialize import marshalable
from dpark.env import env
import six
from six.moves import range, map, cPickle
try:
from itertools import izip
except ImportError:
izip = zip
logger = get_logger(__name__)
MARSHAL_TYPE, PICKLE_TYPE = list(range(2))
BLOCK_SHIFT = 20
BLOCK_SIZE = 1 << BLOCK_SHIFT
GUIDE_ADDR = 'NewBroadcastGuideAddr'
DOWNLOAD_ADDR = 'NewDownloadAddr'
BATCHED_BLOCKS = 3
GUIDE_STOP, GUIDE_GET_SOURCES, GUIDE_SET_SOURCES, GUIDE_REPORT_BAD = list(range(4))
SERVER_STOP, SERVER_FETCH, SERVER_FETCH_FAIL, SERVER_FETCH_OK, \
DATA_GET, DATA_GET_OK, DATA_GET_FAIL, DATA_DOWNLOADING, SERVER_CLEAR_ITEM = list(range(9))
class GuideManager(object):
def __init__(self):
self._started = False
self.guides = {}
self.host = socket.gethostname()
self.guide_thread = None
self.guide_addr = None
self.register_addr = {}
self.ctx = zmq.Context()
def start(self):
if self._started:
return
self._started = True
self.guide_thread = self.start_guide()
env.register(GUIDE_ADDR, self.guide_addr)
def start_guide(self):
sock = self.ctx.socket(zmq.REP)
port = sock.bind_to_random_port('tcp://0.0.0.0')
self.guide_addr = 'tcp://%s:%d' % (self.host, port)
def run():
logger.debug("guide start at %s", self.guide_addr)
while self._started:
if not sock.poll(1000, zmq.POLLIN):
continue
type_, msg = sock.recv_pyobj()
if type_ == GUIDE_STOP:
sock.send_pyobj(0)
break
elif type_ == GUIDE_GET_SOURCES:
uuid = msg
sources = None
if uuid in self.guides:
sources = self.guides[uuid]
else:
logger.warning('uuid %s NOT REGISTERED in guide server', uuid)
sock.send_pyobj(sources)
elif type_ == GUIDE_SET_SOURCES:
uuid, addr, bitmap = msg
if any(bitmap):
sources = None
if uuid in self.guides:
sources = self.guides[uuid]
if sources:
sources[addr] = bitmap
else:
self.guides[uuid] = {addr: bitmap}
self.register_addr[uuid] = addr
sock.send_pyobj(None)
elif type_ == GUIDE_REPORT_BAD:
uuid, addr = msg
sources = self.guides[uuid]
if addr in sources:
if addr != self.register_addr[uuid]:
del sources[addr]
else:
logger.warning('The addr %s to delete is the register Quit!!!', addr)
sock.send_pyobj(None)
else:
logger.error('Unknown guide message: %s %s', type_, msg)
sock.send_pyobj(None)
return spawn(run)
def shutdown(self):
if not self._started:
return
self._started = False
if self.guide_thread and self.guide_addr. \
startswith('tcp://%s:' % socket.gethostname()):
self.guide_thread.join(timeout=1)
if self.guide_thread.is_alive():
logger.warning("guide_thread not stopped.")
self.guide_addr = None
def check_memory(location):
try:
import psutil
pid = os.getpid()
p = psutil.Process(pid)
rss = p.memory_info().rss >> 20
logger.info('memory rss %d MB in host %s at ',
rss, socket.gethostname(), location)
except ImportError:
logger.warning('import psutil failed')
class DownloadManager(object):
def __init__(self):
self._started = False
self.server_thread = None
self.download_threads = {}
self.uuid_state_dict = None
self.uuid_map_dict = None
self.guide_addr = None
self.server_addr = None
self.host = None
self.ctx = None
self.random_inst = None
self.master_broadcast_blocks = {}
def start(self):
if self._started:
return
self.manager = manager = Manager()
self.shared_uuid_fn_dict = manager.dict()
self.shared_uuid_map_dict = manager.dict()
self.shared_master_blocks = manager.dict()
self.download_cond = Condition()
self._started = True
self.ctx = zmq.Context()
self.host = socket.gethostname()
if GUIDE_ADDR not in env.environ:
start_guide_manager()
self.guide_addr = env.get(GUIDE_ADDR)
self.random_inst = random.SystemRandom()
self.server_addr, self.server_thread = self.start_server()
self.uuid_state_dict = {}
self.uuid_map_dict = {}
self.master_broadcast_blocks = {}
env.register(DOWNLOAD_ADDR, self.server_addr)
def start_server(self):
sock = self.ctx.socket(zmq.REP)
sock.setsockopt(zmq.LINGER, 0)
port = sock.bind_to_random_port("tcp://0.0.0.0")
server_addr = 'tcp://%s:%d' % (self.host, port)
guide_sock = self.ctx.socket(zmq.REQ)
guide_sock.setsockopt(zmq.LINGER, 0)
guide_sock.connect(self.guide_addr)
def run():
logger.debug("server started at %s", server_addr)
while self._started:
if not sock.poll(1000, zmq.POLLIN):
continue
type_, msg = sock.recv_pyobj()
logger.debug('server recv: %s %s', type_, msg)
if type_ == SERVER_STOP:
sock.send_pyobj(None)
break
elif type_ == SERVER_FETCH:
uuid, indices, client_addr = msg
if uuid in self.master_broadcast_blocks:
block_num = len(self.master_broadcast_blocks[uuid])
bls = []
for index in indices:
if index >= block_num:
logger.warning('input index too big %s for '
'len of blocks %d from host %s',
str(indices), block_num, client_addr)
sock.send_pyobj((SERVER_FETCH_FAIL, None))
else:
bls.append(self.master_broadcast_blocks[uuid][index])
sock.send_pyobj((SERVER_FETCH_OK, (indices, bls)))
elif uuid in self.uuid_state_dict:
fd = os.open(self.uuid_state_dict[uuid][0], os.O_RDONLY)
mmfp = mmap.mmap(fd, 0, access=ACCESS_READ)
os.close(fd)
bitmap = self.uuid_map_dict[uuid]
block_num = len(bitmap)
bls = []
for index in indices:
if index >= block_num:
logger.warning('input index too big %s for '
'len of blocks %d from host %s',
str(indices), block_num, client_addr)
sock.send_pyobj((SERVER_FETCH_FAIL, None))
else:
mmfp.seek(bitmap[index][0])
block = mmfp.read(bitmap[index][1])
bls.append(block)
mmfp.close()
sock.send_pyobj((SERVER_FETCH_OK, (indices, bls)))
else:
logger.warning('server fetch failed for uuid %s '
'not exists in server %s from host %s',
uuid, socket.gethostname(), client_addr)
sock.send_pyobj((SERVER_FETCH_FAIL, None))
elif type_ == DATA_GET:
uuid, compressed_size = msg
if uuid not in self.uuid_state_dict or not self.uuid_state_dict[uuid][1]:
if uuid not in self.download_threads:
sources = self._get_sources(uuid, guide_sock)
if not sources:
logger.warning('get sources from guide server failed in host %s',
socket.gethostname())
sock.send_pyobj(DATA_GET_FAIL)
continue
self.download_threads[uuid] = spawn(self._download_blocks,
*[sources, uuid, compressed_size])
sock.send_pyobj(DATA_DOWNLOADING)
else:
sock.send_pyobj(DATA_DOWNLOADING)
else:
sock.send_pyobj(DATA_GET_OK)
elif type_ == SERVER_CLEAR_ITEM:
uuid = msg
self.clear(uuid)
sock.send_pyobj(None)
else:
logger.error('Unknown server message: %s %s', type_, msg)
sock.send_pyobj(None)
sock.close()
logger.debug("stop Broadcast server %s", server_addr)
for uuid in list(self.uuid_state_dict.keys()):
self.clear(uuid)
return server_addr, spawn(run)
def get_blocks(self, uuid):
if uuid in self.master_broadcast_blocks:
return self.master_broadcast_blocks[uuid]
if uuid in self.shared_master_blocks:
return self.shared_master_blocks[uuid]
def register_blocks(self, uuid, blocks):
if uuid in self.master_broadcast_blocks:
logger.warning('the block uuid %s exists in dict', uuid)
return
self.master_broadcast_blocks[uuid] = blocks
self.shared_master_blocks[uuid] = blocks
def _get_sources(self, uuid, source_sock):
try:
source_sock.send_pyobj((GUIDE_GET_SOURCES,
uuid))
sources = source_sock.recv_pyobj()
except:
logger.warning('GET sources failed for addr %s with ZMQ ERR',
self.server_addr)
sources = {}
return sources
def _update_sources(self, uuid, bitmap, source_sock):
try:
source_sock.send_pyobj((GUIDE_SET_SOURCES,
(uuid, self.server_addr, bitmap)))
source_sock.recv_pyobj()
except:
pass
def _download_blocks(self, sources, uuid, compressed_size):
block_num = 0
bitmap = [0]
write_mmap_handler = None
download_guide_sock = self.ctx.socket(zmq.REQ)
download_guide_sock.setsockopt(zmq.LINGER, 0)
download_guide_sock.connect(self.guide_addr)
<|fim▁hole|> logger.debug('fetch blocks failed from server %s', addr)
download_guide_sock.send_pyobj((GUIDE_REPORT_BAD, (uuid, addr)))
download_guide_sock.recv_pyobj()
def _fetch(addr, indices, bit_map):
sock = self.ctx.socket(zmq.REQ)
try:
sock.setsockopt(zmq.LINGER, 0)
sock.connect(addr)
sock.send_pyobj((SERVER_FETCH, (uuid, indices, self.server_addr)))
avail = sock.poll(1 * 1000, zmq.POLLIN)
check_sock = None
if not avail:
try:
check_sock = socket.socket()
addr_list = addr[len('tcp://'):].split(':')
addr_list[1] = int(addr_list[1])
check_sock.connect(tuple(addr_list))
except Exception as e:
logger.warning('connect the addr %s failed with exception %s',
addr, e)
_report_bad(addr)
else:
logger.debug("%s recv broadcast %s from %s timeout",
self.server_addr, str(indices), addr)
finally:
if check_sock:
check_sock.close()
return
result, msg = sock.recv_pyobj()
if result == SERVER_FETCH_FAIL:
_report_bad(addr)
return
if result == SERVER_FETCH_OK:
indices, blocks = msg
for rank, index in enumerate(indices):
if blocks[rank] is not None:
write_mmap_handler.seek(bit_map[index][0])
write_mmap_handler.write(blocks[rank])
bitmap[index] = bit_map[index]
else:
raise RuntimeError('Unknown server response: %s %s' % (result, msg))
finally:
sock.close()
final_path = env.workdir.alloc_tmp_file("broadcast")
self.uuid_state_dict[uuid] = (final_path, False)
fp = open(final_path, 'wb')
fp.truncate(compressed_size)
fp.close()
fd = os.open(final_path, os.O_RDWR)
write_mmap_handler = mmap.mmap(fd, 0,
access=ACCESS_WRITE)
os.close(fd)
while not all(bitmap):
remote = []
for _addr, _bitmap in six.iteritems(sources):
if block_num == 0:
block_num = len(_bitmap)
bitmap = [0] * block_num
self.uuid_map_dict[uuid] = bitmap
if not _addr.startswith('tcp://%s:' % self.host):
remote.append((_addr, _bitmap))
self.random_inst.shuffle(remote)
for _addr, _bitmap in remote:
_indices = [i for i in range(block_num) if not bitmap[i] and _bitmap[i]]
if _indices:
self.random_inst.shuffle(_indices)
_fetch(_addr, _indices[:BATCHED_BLOCKS], _bitmap)
self._update_sources(uuid, bitmap, download_guide_sock)
sources = self._get_sources(uuid, download_guide_sock)
write_mmap_handler.flush()
write_mmap_handler.close()
self.shared_uuid_map_dict[uuid] = bitmap
self.shared_uuid_fn_dict[uuid] = self.uuid_state_dict[uuid][0]
self.uuid_state_dict[uuid] = self.uuid_state_dict[uuid][0], True
download_guide_sock.close()
with self.download_cond:
self.download_cond.notify_all()
def clear(self, uuid):
if uuid in self.master_broadcast_blocks:
del self.master_broadcast_blocks[uuid]
del self.shared_master_blocks[uuid]
if uuid in self.uuid_state_dict:
del self.uuid_state_dict[uuid]
if uuid in self.shared_uuid_fn_dict:
del self.shared_uuid_fn_dict[uuid]
del self.shared_uuid_map_dict[uuid]
def shutdown(self):
if not self._started:
return
self._started = False
if self.server_thread and self.server_addr. \
startswith('tcp://%s:' % socket.gethostname()):
for _, th in six.iteritems(self.download_threads):
th.join(timeout=0.1) # only in executor, not needed
self.server_thread.join(timeout=1)
if self.server_thread.is_alive():
logger.warning("Download mananger server_thread not stopped.")
self.manager.shutdown() # shutdown will try join and terminate server process
def accumulate_list(l):
acc = 0
acc_l = []
for item in l:
acc_l.append(acc)
acc += item
acc_l.append(acc)
return acc_l
class BroadcastManager(object):
header_fmt = '>BI'
header_len = struct.calcsize(header_fmt)
def __init__(self):
self._started = False
self.guide_addr = None
self.download_addr = None
self.cache = None
self.shared_uuid_fn_dict = None
self.shared_uuid_map_dict = None
self.download_cond = None
self.ctx = None
def start(self):
if self._started:
return
self._started = True
start_download_manager()
self.guide_addr = env.get(GUIDE_ADDR)
self.download_addr = env.get(DOWNLOAD_ADDR)
self.cache = Cache()
self.ctx = zmq.Context()
self.shared_uuid_fn_dict = _download_manager.shared_uuid_fn_dict
self.shared_uuid_map_dict = _download_manager.shared_uuid_map_dict
self.download_cond = _download_manager.download_cond
def register(self, uuid, value):
self.start()
if uuid in self.shared_uuid_fn_dict:
raise RuntimeError('broadcast %s has already registered' % uuid)
blocks, size, block_map = self.to_blocks(uuid, value)
_download_manager.register_blocks(uuid, blocks)
self._update_sources(uuid, block_map)
self.cache.put(uuid, value)
return size
def _update_sources(self, uuid, bitmap):
guide_sock = self.ctx.socket(zmq.REQ)
try:
guide_sock.setsockopt(zmq.LINGER, 0)
guide_sock.connect(self.guide_addr)
guide_sock.send_pyobj((GUIDE_SET_SOURCES,
(uuid, self.download_addr, bitmap)))
guide_sock.recv_pyobj()
finally:
guide_sock.close()
def clear(self, uuid):
assert self._started
self.cache.put(uuid, None)
sock = self.ctx.socket(zmq.REQ)
sock.connect(self.download_addr)
sock.send_pyobj((SERVER_CLEAR_ITEM, uuid))
sock.recv_pyobj()
sock.close()
def fetch(self, uuid, compressed_size):
start_download_manager()
self.start()
value = self.cache.get(uuid)
if value is not None:
return value
blocks = _download_manager.get_blocks(uuid)
if blocks is None:
blocks = self.fetch_blocks(uuid, compressed_size)
value = self.from_blocks(uuid, blocks)
return value
@staticmethod
def _get_blocks_by_filename(file_name, block_map):
fp = open(file_name, 'rb')
buf = fp.read()
blocks = [buf[offset: offset + size] for offset, size in block_map]
fp.close()
return blocks
def fetch_blocks(self, uuid, compressed_size):
if uuid in self.shared_uuid_fn_dict:
return self._get_blocks_by_filename(self.shared_uuid_fn_dict[uuid],
self.shared_uuid_map_dict[uuid])
download_sock = self.ctx.socket(zmq.REQ)
download_sock.connect(self.download_addr)
download_sock.send_pyobj((DATA_GET,
(uuid, compressed_size)))
res = download_sock.recv_pyobj()
if res == DATA_GET_OK:
return self._get_blocks_by_filename(self.shared_uuid_fn_dict[uuid],
self.shared_uuid_map_dict[uuid])
if res == DATA_GET_FAIL:
raise RuntimeError('Data GET failed for uuid:%s' % uuid)
while True:
with self.download_cond:
if uuid not in self.shared_uuid_fn_dict:
self.download_cond.wait()
else:
break
if uuid in self.shared_uuid_fn_dict:
return self._get_blocks_by_filename(self.shared_uuid_fn_dict[uuid],
self.shared_uuid_map_dict[uuid])
else:
raise RuntimeError('get blocks failed')
def to_blocks(self, uuid, obj):
try:
if marshalable(obj):
buf = marshal.dumps((uuid, obj))
type_ = MARSHAL_TYPE
else:
buf = cPickle.dumps((uuid, obj), -1)
type_ = PICKLE_TYPE
except Exception:
buf = cPickle.dumps((uuid, obj), -1)
type_ = PICKLE_TYPE
checksum = binascii.crc32(buf) & 0xFFFF
stream = struct.pack(self.header_fmt, type_, checksum) + buf
blockNum = (len(stream) + (BLOCK_SIZE - 1)) >> BLOCK_SHIFT
blocks = [compress(stream[i * BLOCK_SIZE:(i + 1) * BLOCK_SIZE]) for i in range(blockNum)]
sizes = [len(block) for block in blocks]
size_l = accumulate_list(sizes)
block_map = list(izip(size_l[:-1], sizes))
return blocks, size_l[-1], block_map
def from_blocks(self, uuid, blocks):
stream = b''.join(map(decompress, blocks))
type_, checksum = struct.unpack(self.header_fmt, stream[:self.header_len])
buf = stream[self.header_len:]
_checksum = binascii.crc32(buf) & 0xFFFF
if _checksum != checksum:
raise RuntimeError('Wrong blocks: checksum: %s, expected: %s' % (
_checksum, checksum))
if type_ == MARSHAL_TYPE:
_uuid, value = marshal.loads(buf)
elif type_ == PICKLE_TYPE:
_uuid, value = cPickle.loads(buf)
else:
raise RuntimeError('Unknown serialization type: %s' % type_)
if uuid != _uuid:
raise RuntimeError('Wrong blocks: uuid: %s, expected: %s' % (_uuid, uuid))
return value
def shutdown(self):
if not self._started:
return
self._started = False
_manager = BroadcastManager()
_download_manager = DownloadManager()
_guide_manager = GuideManager()
def start_guide_manager():
_guide_manager.start()
def start_download_manager():
_download_manager.start()
def stop_manager():
_manager.shutdown()
_download_manager.shutdown()
_guide_manager.shutdown()
env.environ.pop(GUIDE_ADDR, None)
env.environ.pop(DOWNLOAD_ADDR, None)
class Broadcast(object):
def __init__(self, value):
assert value is not None, 'broadcast object should not been None'
self.uuid = str(uuid_pkg.uuid4())
self.value = value
self.compressed_size = _manager.register(self.uuid, self.value)
block_num = (self.compressed_size + BLOCK_SIZE - 1) >> BLOCK_SHIFT
self.bytes = block_num * BLOCK_SIZE
logger.info("broadcast %s in %d blocks, %d bytes", self.uuid, block_num, self.compressed_size)
def clear(self):
_manager.clear(self.uuid)
def __getstate__(self):
return self.uuid, self.compressed_size
def __setstate__(self, v):
self.uuid, self.compressed_size = v
def __getattr__(self, name):
if name != 'value':
return getattr(self.value, name)
t = time.time()
value = _manager.fetch(self.uuid, self.compressed_size)
if value is None:
raise RuntimeError("fetch broadcast failed")
env.task_stats.secs_broadcast += time.time() - t
self.value = value
return value
def __len__(self):
return len(self.value)
def __iter__(self):
return self.value.__iter__()
def __getitem__(self, key):
return self.value.__getitem__(key)
def __contains__(self, item):
return self.value.__contains__(item)
def __missing__(self, key):
return self.value.__missing__(key)
def __reversed__(self):
return self.value.__reversed__()<|fim▁end|> | def _report_bad(addr): |
<|file_name|>SectionSelectInput.js<|end_file_name|><|fim▁begin|>import React from 'react'
import { connect } from 'react-redux'
import ItemSelectInput from './ItemSelectInput'
import sectionsActions from '../../../actions/SectionsActions'
class SectionSelectInputComponent extends React.Component {
listSections(query) {
let queryObj = {}
if (query) {
queryObj['q'] = query
}
this.props.listSections(this.props.token, queryObj)
}
render() {
return (
<ItemSelectInput
many={false}
value={this.props.value}
inline={this.props.inline}
showSortableList={this.props.showSortableList}
results={this.props.sections.ids}
entities={this.props.entities.sections}
onChange={(value) => this.props.update(value)}
fetchResults={(query) => this.listSections(query)}
attribute='name'
editMessage={this.props.value ? 'Edit section' : 'Add section'} />
)
}
}
const mapStateToProps = (state) => {
return {
sections: state.app.sections.list,
entities: {
sections: state.app.entities.sections
},<|fim▁hole|> token: state.app.auth.token
}
}
const mapDispatchToProps = (dispatch) => {
return {
listSections: (token, query) => {
dispatch(sectionsActions.list(token, query))
}
}
}
const SectionSelectInput = connect(
mapStateToProps,
mapDispatchToProps
)(SectionSelectInputComponent)
export default SectionSelectInput<|fim▁end|> | |
<|file_name|>ESConstants.java<|end_file_name|><|fim▁begin|>package nikita.common.config;
/**
* Constants used for ElasticSearch queries
*/<|fim▁hole|>public class ESConstants {
public static final String QUERY_SIZE = "size";
public static final String QUERY_FROM = "from";
public static final String QUERY_QUERY = "query";
public static final String QUERY_PREFIX = "prefix";
public static final String QUERY_MATCH_PHRASE = "match_phrase";
}<|fim▁end|> | |
<|file_name|>gateway-s3.go<|end_file_name|><|fim▁begin|>/*
* Minio Cloud Storage, (C) 2017 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cmd
import (
"io"
"net/http"
"path"
"encoding/hex"
minio "github.com/minio/minio-go"
"github.com/minio/minio-go/pkg/policy"
)
// s3ToObjectError converts Minio errors to minio object layer errors.
func s3ToObjectError(err error, params ...string) error {
if err == nil {
return nil
}
e, ok := err.(*Error)
if !ok {
// Code should be fixed if this function is called without doing traceError()
// Else handling different situations in this function makes this function complicated.
errorIf(err, "Expected type *Error")
return err
}
err = e.e
bucket := ""
object := ""
if len(params) >= 1 {
bucket = params[0]
}
if len(params) == 2 {
object = params[1]
}
minioErr, ok := err.(minio.ErrorResponse)
if !ok {
// We don't interpret non Minio errors. As minio errors will
// have StatusCode to help to convert to object errors.
return e
}
switch minioErr.Code {
case "BucketAlreadyOwnedByYou":
err = BucketAlreadyOwnedByYou{}
case "BucketNotEmpty":
err = BucketNotEmpty{}
case "NoSuchBucketPolicy":
err = PolicyNotFound{}
case "InvalidBucketName":
err = BucketNameInvalid{Bucket: bucket}
case "NoSuchBucket":
err = BucketNotFound{Bucket: bucket}
case "NoSuchKey":
if object != "" {
err = ObjectNotFound{Bucket: bucket, Object: object}
} else {
err = BucketNotFound{Bucket: bucket}
}
case "XMinioInvalidObjectName":
err = ObjectNameInvalid{}
case "AccessDenied":
err = PrefixAccessDenied{
Bucket: bucket,
Object: object,
}
case "XAmzContentSHA256Mismatch":
err = SHA256Mismatch{}
}
e.e = err
return e
}
// s3Objects implements gateway for Minio and S3 compatible object storage servers.
type s3Objects struct {
Client *minio.Core
anonClient *minio.Core
}
// newS3Gateway returns s3 gatewaylayer
func newS3Gateway(host string) (GatewayLayer, error) {
var err error
var endpoint string
var secure = true
// Validate host parameters.
if host != "" {
// Override default params if the host is provided
endpoint, secure, err = parseGatewayEndpoint(host)
if err != nil {
return nil, err
}
}
// Default endpoint parameters
if endpoint == "" {
endpoint = "s3.amazonaws.com"
}
creds := serverConfig.GetCredential()
// Initialize minio client object.
client, err := minio.NewCore(endpoint, creds.AccessKey, creds.SecretKey, secure)
if err != nil {
return nil, err
}
anonClient, err := minio.NewCore(endpoint, "", "", secure)
if err != nil {
return nil, err
}
return &s3Objects{<|fim▁hole|>
// Shutdown saves any gateway metadata to disk
// if necessary and reload upon next restart.
func (l *s3Objects) Shutdown() error {
// TODO
return nil
}
// StorageInfo is not relevant to S3 backend.
func (l *s3Objects) StorageInfo() (si StorageInfo) {
return si
}
// MakeBucket creates a new container on S3 backend.
func (l *s3Objects) MakeBucketWithLocation(bucket, location string) error {
err := l.Client.MakeBucket(bucket, location)
if err != nil {
return s3ToObjectError(traceError(err), bucket)
}
return err
}
// GetBucketInfo gets bucket metadata..
func (l *s3Objects) GetBucketInfo(bucket string) (bi BucketInfo, e error) {
buckets, err := l.Client.ListBuckets()
if err != nil {
return bi, s3ToObjectError(traceError(err), bucket)
}
for _, bi := range buckets {
if bi.Name != bucket {
continue
}
return BucketInfo{
Name: bi.Name,
Created: bi.CreationDate,
}, nil
}
return bi, traceError(BucketNotFound{Bucket: bucket})
}
// ListBuckets lists all S3 buckets
func (l *s3Objects) ListBuckets() ([]BucketInfo, error) {
buckets, err := l.Client.ListBuckets()
if err != nil {
return nil, err
}
b := make([]BucketInfo, len(buckets))
for i, bi := range buckets {
b[i] = BucketInfo{
Name: bi.Name,
Created: bi.CreationDate,
}
}
return b, err
}
// DeleteBucket deletes a bucket on S3
func (l *s3Objects) DeleteBucket(bucket string) error {
err := l.Client.RemoveBucket(bucket)
if err != nil {
return s3ToObjectError(traceError(err), bucket)
}
return nil
}
// ListObjects lists all blobs in S3 bucket filtered by prefix
func (l *s3Objects) ListObjects(bucket string, prefix string, marker string, delimiter string, maxKeys int) (loi ListObjectsInfo, e error) {
result, err := l.Client.ListObjects(bucket, prefix, marker, delimiter, maxKeys)
if err != nil {
return loi, s3ToObjectError(traceError(err), bucket)
}
return fromMinioClientListBucketResult(bucket, result), nil
}
// ListObjectsV2 lists all blobs in S3 bucket filtered by prefix
func (l *s3Objects) ListObjectsV2(bucket, prefix, continuationToken string, fetchOwner bool, delimiter string, maxKeys int) (loi ListObjectsV2Info, e error) {
result, err := l.Client.ListObjectsV2(bucket, prefix, continuationToken, fetchOwner, delimiter, maxKeys)
if err != nil {
return loi, s3ToObjectError(traceError(err), bucket)
}
return fromMinioClientListBucketV2Result(bucket, result), nil
}
// fromMinioClientListBucketV2Result converts minio ListBucketResult to ListObjectsInfo
func fromMinioClientListBucketV2Result(bucket string, result minio.ListBucketV2Result) ListObjectsV2Info {
objects := make([]ObjectInfo, len(result.Contents))
for i, oi := range result.Contents {
objects[i] = fromMinioClientObjectInfo(bucket, oi)
}
prefixes := make([]string, len(result.CommonPrefixes))
for i, p := range result.CommonPrefixes {
prefixes[i] = p.Prefix
}
return ListObjectsV2Info{
IsTruncated: result.IsTruncated,
Prefixes: prefixes,
Objects: objects,
ContinuationToken: result.ContinuationToken,
NextContinuationToken: result.NextContinuationToken,
}
}
// fromMinioClientListBucketResult converts minio ListBucketResult to ListObjectsInfo
func fromMinioClientListBucketResult(bucket string, result minio.ListBucketResult) ListObjectsInfo {
objects := make([]ObjectInfo, len(result.Contents))
for i, oi := range result.Contents {
objects[i] = fromMinioClientObjectInfo(bucket, oi)
}
prefixes := make([]string, len(result.CommonPrefixes))
for i, p := range result.CommonPrefixes {
prefixes[i] = p.Prefix
}
return ListObjectsInfo{
IsTruncated: result.IsTruncated,
NextMarker: result.NextMarker,
Prefixes: prefixes,
Objects: objects,
}
}
// GetObject reads an object from S3. Supports additional
// parameters like offset and length which are synonymous with
// HTTP Range requests.
//
// startOffset indicates the starting read location of the object.
// length indicates the total length of the object.
func (l *s3Objects) GetObject(bucket string, key string, startOffset int64, length int64, writer io.Writer) error {
r := minio.NewGetReqHeaders()
if length < 0 && length != -1 {
return s3ToObjectError(traceError(errInvalidArgument), bucket, key)
}
if startOffset >= 0 && length >= 0 {
if err := r.SetRange(startOffset, startOffset+length-1); err != nil {
return s3ToObjectError(traceError(err), bucket, key)
}
}
object, _, err := l.Client.GetObject(bucket, key, r)
if err != nil {
return s3ToObjectError(traceError(err), bucket, key)
}
defer object.Close()
if _, err := io.Copy(writer, object); err != nil {
return s3ToObjectError(traceError(err), bucket, key)
}
return nil
}
// fromMinioClientObjectInfo converts minio ObjectInfo to gateway ObjectInfo
func fromMinioClientObjectInfo(bucket string, oi minio.ObjectInfo) ObjectInfo {
userDefined := fromMinioClientMetadata(oi.Metadata)
userDefined["Content-Type"] = oi.ContentType
return ObjectInfo{
Bucket: bucket,
Name: oi.Key,
ModTime: oi.LastModified,
Size: oi.Size,
ETag: canonicalizeETag(oi.ETag),
UserDefined: userDefined,
ContentType: oi.ContentType,
ContentEncoding: oi.Metadata.Get("Content-Encoding"),
}
}
// GetObjectInfo reads object info and replies back ObjectInfo
func (l *s3Objects) GetObjectInfo(bucket string, object string) (objInfo ObjectInfo, err error) {
r := minio.NewHeadReqHeaders()
oi, err := l.Client.StatObject(bucket, object, r)
if err != nil {
return ObjectInfo{}, s3ToObjectError(traceError(err), bucket, object)
}
return fromMinioClientObjectInfo(bucket, oi), nil
}
// PutObject creates a new object with the incoming data,
func (l *s3Objects) PutObject(bucket string, object string, size int64, data io.Reader, metadata map[string]string, sha256sum string) (objInfo ObjectInfo, e error) {
var sha256sumBytes []byte
var err error
if sha256sum != "" {
sha256sumBytes, err = hex.DecodeString(sha256sum)
if err != nil {
return objInfo, s3ToObjectError(traceError(err), bucket, object)
}
}
var md5sumBytes []byte
md5sum := metadata["etag"]
if md5sum != "" {
md5sumBytes, err = hex.DecodeString(md5sum)
if err != nil {
return objInfo, s3ToObjectError(traceError(err), bucket, object)
}
delete(metadata, "etag")
}
oi, err := l.Client.PutObject(bucket, object, size, data, md5sumBytes, sha256sumBytes, toMinioClientMetadata(metadata))
if err != nil {
return objInfo, s3ToObjectError(traceError(err), bucket, object)
}
return fromMinioClientObjectInfo(bucket, oi), nil
}
// CopyObject copies a blob from source container to destination container.
func (l *s3Objects) CopyObject(srcBucket string, srcObject string, destBucket string, destObject string, metadata map[string]string) (objInfo ObjectInfo, e error) {
err := l.Client.CopyObject(destBucket, destObject, path.Join(srcBucket, srcObject), minio.CopyConditions{})
if err != nil {
return objInfo, s3ToObjectError(traceError(err), srcBucket, srcObject)
}
oi, err := l.GetObjectInfo(destBucket, destObject)
if err != nil {
return objInfo, s3ToObjectError(traceError(err), destBucket, destObject)
}
return oi, nil
}
// DeleteObject deletes a blob in bucket
func (l *s3Objects) DeleteObject(bucket string, object string) error {
err := l.Client.RemoveObject(bucket, object)
if err != nil {
return s3ToObjectError(traceError(err), bucket, object)
}
return nil
}
// fromMinioClientUploadMetadata converts ObjectMultipartInfo to uploadMetadata
func fromMinioClientUploadMetadata(omi minio.ObjectMultipartInfo) uploadMetadata {
return uploadMetadata{
Object: omi.Key,
UploadID: omi.UploadID,
Initiated: omi.Initiated,
}
}
// fromMinioClientListMultipartsInfo converts minio ListMultipartUploadsResult to ListMultipartsInfo
func fromMinioClientListMultipartsInfo(lmur minio.ListMultipartUploadsResult) ListMultipartsInfo {
uploads := make([]uploadMetadata, len(lmur.Uploads))
for i, um := range lmur.Uploads {
uploads[i] = fromMinioClientUploadMetadata(um)
}
commonPrefixes := make([]string, len(lmur.CommonPrefixes))
for i, cp := range lmur.CommonPrefixes {
commonPrefixes[i] = cp.Prefix
}
return ListMultipartsInfo{
KeyMarker: lmur.KeyMarker,
UploadIDMarker: lmur.UploadIDMarker,
NextKeyMarker: lmur.NextKeyMarker,
NextUploadIDMarker: lmur.NextUploadIDMarker,
MaxUploads: int(lmur.MaxUploads),
IsTruncated: lmur.IsTruncated,
Uploads: uploads,
Prefix: lmur.Prefix,
Delimiter: lmur.Delimiter,
CommonPrefixes: commonPrefixes,
EncodingType: lmur.EncodingType,
}
}
// ListMultipartUploads lists all multipart uploads.
func (l *s3Objects) ListMultipartUploads(bucket string, prefix string, keyMarker string, uploadIDMarker string, delimiter string, maxUploads int) (lmi ListMultipartsInfo, e error) {
result, err := l.Client.ListMultipartUploads(bucket, prefix, keyMarker, uploadIDMarker, delimiter, maxUploads)
if err != nil {
return lmi, err
}
return fromMinioClientListMultipartsInfo(result), nil
}
// fromMinioClientMetadata converts minio metadata to map[string]string
func fromMinioClientMetadata(metadata map[string][]string) map[string]string {
mm := map[string]string{}
for k, v := range metadata {
mm[http.CanonicalHeaderKey(k)] = v[0]
}
return mm
}
// toMinioClientMetadata converts metadata to map[string][]string
func toMinioClientMetadata(metadata map[string]string) map[string][]string {
mm := map[string][]string{}
for k, v := range metadata {
mm[http.CanonicalHeaderKey(k)] = []string{v}
}
return mm
}
// NewMultipartUpload upload object in multiple parts
func (l *s3Objects) NewMultipartUpload(bucket string, object string, metadata map[string]string) (uploadID string, err error) {
return l.Client.NewMultipartUpload(bucket, object, toMinioClientMetadata(metadata))
}
// CopyObjectPart copy part of object to other bucket and object
func (l *s3Objects) CopyObjectPart(srcBucket string, srcObject string, destBucket string, destObject string, uploadID string, partID int, startOffset int64, length int64) (info PartInfo, err error) {
// FIXME: implement CopyObjectPart
return PartInfo{}, traceError(NotImplemented{})
}
// fromMinioClientObjectPart converts minio ObjectPart to PartInfo
func fromMinioClientObjectPart(op minio.ObjectPart) PartInfo {
return PartInfo{
Size: op.Size,
ETag: canonicalizeETag(op.ETag),
LastModified: op.LastModified,
PartNumber: op.PartNumber,
}
}
// PutObjectPart puts a part of object in bucket
func (l *s3Objects) PutObjectPart(bucket string, object string, uploadID string, partID int, size int64, data io.Reader, md5Hex string, sha256sum string) (pi PartInfo, e error) {
md5HexBytes, err := hex.DecodeString(md5Hex)
if err != nil {
return pi, err
}
sha256sumBytes, err := hex.DecodeString(sha256sum)
if err != nil {
return pi, err
}
info, err := l.Client.PutObjectPart(bucket, object, uploadID, partID, size, data, md5HexBytes, sha256sumBytes)
if err != nil {
return pi, err
}
return fromMinioClientObjectPart(info), nil
}
// fromMinioClientObjectParts converts minio ObjectPart to PartInfo
func fromMinioClientObjectParts(parts []minio.ObjectPart) []PartInfo {
toParts := make([]PartInfo, len(parts))
for i, part := range parts {
toParts[i] = fromMinioClientObjectPart(part)
}
return toParts
}
// fromMinioClientListPartsInfo converts minio ListObjectPartsResult to ListPartsInfo
func fromMinioClientListPartsInfo(lopr minio.ListObjectPartsResult) ListPartsInfo {
return ListPartsInfo{
UploadID: lopr.UploadID,
Bucket: lopr.Bucket,
Object: lopr.Key,
StorageClass: "",
PartNumberMarker: lopr.PartNumberMarker,
NextPartNumberMarker: lopr.NextPartNumberMarker,
MaxParts: lopr.MaxParts,
IsTruncated: lopr.IsTruncated,
EncodingType: lopr.EncodingType,
Parts: fromMinioClientObjectParts(lopr.ObjectParts),
}
}
// ListObjectParts returns all object parts for specified object in specified bucket
func (l *s3Objects) ListObjectParts(bucket string, object string, uploadID string, partNumberMarker int, maxParts int) (lpi ListPartsInfo, e error) {
result, err := l.Client.ListObjectParts(bucket, object, uploadID, partNumberMarker, maxParts)
if err != nil {
return lpi, err
}
return fromMinioClientListPartsInfo(result), nil
}
// AbortMultipartUpload aborts a ongoing multipart upload
func (l *s3Objects) AbortMultipartUpload(bucket string, object string, uploadID string) error {
return l.Client.AbortMultipartUpload(bucket, object, uploadID)
}
// toMinioClientCompletePart converts completePart to minio CompletePart
func toMinioClientCompletePart(part completePart) minio.CompletePart {
return minio.CompletePart{
ETag: part.ETag,
PartNumber: part.PartNumber,
}
}
// toMinioClientCompleteParts converts []completePart to minio []CompletePart
func toMinioClientCompleteParts(parts []completePart) []minio.CompletePart {
mparts := make([]minio.CompletePart, len(parts))
for i, part := range parts {
mparts[i] = toMinioClientCompletePart(part)
}
return mparts
}
// CompleteMultipartUpload completes ongoing multipart upload and finalizes object
func (l *s3Objects) CompleteMultipartUpload(bucket string, object string, uploadID string, uploadedParts []completePart) (oi ObjectInfo, e error) {
err := l.Client.CompleteMultipartUpload(bucket, object, uploadID, toMinioClientCompleteParts(uploadedParts))
if err != nil {
return oi, s3ToObjectError(traceError(err), bucket, object)
}
return l.GetObjectInfo(bucket, object)
}
// SetBucketPolicies sets policy on bucket
func (l *s3Objects) SetBucketPolicies(bucket string, policyInfo policy.BucketAccessPolicy) error {
if err := l.Client.PutBucketPolicy(bucket, policyInfo); err != nil {
return s3ToObjectError(traceError(err), bucket, "")
}
return nil
}
// GetBucketPolicies will get policy on bucket
func (l *s3Objects) GetBucketPolicies(bucket string) (policy.BucketAccessPolicy, error) {
policyInfo, err := l.Client.GetBucketPolicy(bucket)
if err != nil {
return policy.BucketAccessPolicy{}, s3ToObjectError(traceError(err), bucket, "")
}
return policyInfo, nil
}
// DeleteBucketPolicies deletes all policies on bucket
func (l *s3Objects) DeleteBucketPolicies(bucket string) error {
if err := l.Client.PutBucketPolicy(bucket, policy.BucketAccessPolicy{}); err != nil {
return s3ToObjectError(traceError(err), bucket, "")
}
return nil
}<|fim▁end|> | Client: client,
anonClient: anonClient,
}, nil
} |
<|file_name|>download_era-interim.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
import os
from ecmwfapi import ECMWFDataServer
server = ECMWFDataServer()
time=["06"]
year=["2013"]
param=["129.128","130.128","131.128","132.128","157.128","151.128"]
nam=["hgt","air","uwnd","vwnd","rhum","psl"]
#month=["01","02","03","04","05","06","07","08","09","10","11","12"]
for y in year:
#for m in month:
for p in range(len(param)):
for t in time:
date=y+"-01-01/to/"+y+"-12-31"
print date
print nam[p]+"."+y+"."+t+".nc"
os.system('echo "############################################################# ^_^"')
server.retrieve({
'dataset' : "interim",
'levelist' : "1/2/3/5/7/10/20/30/50/70/100/125/150/175/200/225/250/300/350/400/450/500/550/600/650/700/750/775/800/825/850/875/900/925/950/975/1000",
'step' : "0",
'number' : "all",
'levtype' : "pl", # set to "sl" for surface level<|fim▁hole|> 'param' : "129.128/130.128/131.128/132.128/157.128",
'param' : param[p],
'area' : "0/0/-40/100", # Four values as North/West/South/East
'grid' : "1.5/1.5", # Two values: West-East/North-South increments
'format' : "netcdf", # if grib, just comment this line
'target' : nam[p]+"."+y+"."+t+".nc"
})<|fim▁end|> | 'date' : date,
'time' : t ,
'origin' : "all",
'type' : "an", |
<|file_name|>env.py<|end_file_name|><|fim▁begin|>from operator import itemgetter
import gym
from gym import spaces
from gym.utils import seeding
from .game import Game
from .card import Card
from .player import PlayerAction, PlayerTools
from .agents.random import AgentRandom
class LoveLetterEnv(gym.Env):
"""Love Letter Game Environment
The goal of hotter colder is to guess closer to a randomly selected number
After each step the agent receives an observation of:
0 - No guess yet submitted (only after reset)
1 - Guess is lower than the target
2 - Guess is equal to the target
3 - Guess is higher than the target
The rewards is calculated as:
(min(action, self.number) + self.range) / (max(action, self.number) + self.range)
Ideally an agent will be able to recognize the 'scent' of a higher reward and
increase the rate in which is guesses in that direction until the reward reaches
its maximum
"""
def __init__(self, agent_other, seed=451):
self.action_space = spaces.Discrete(15)
self.observation_space = spaces.Box(low=0, high=1, shape=(24,))
self._agent_other = AgentRandom(
seed) if agent_other is None else agent_other
self._seed(seed)
self._reset()
self._game = Game.new(4, self.np_random.random_integers(5000000))
def _seed(self, seed=None):
self.np_random, seed = seeding.np_random(seed)<|fim▁hole|>
player_action = self.action_from_index(action)
if player_action is None:
return self._game.state(), -1, False, {"round": self._game.round()}
self._game, reward = LoveLetterEnv.advance_game(
self._game, player_action, self._agent_other)
done = self._game.over() or not PlayerTools.is_playing(
self._game.players()[0])
return self._game.state(), reward, done, {"round": self._game.round()}
def _reset(self):
self._game = Game.new(4, self.np_random.random_integers(5000000))
return self._game.state()
def force(self, game):
"""Force the environment to a certain game state"""
self._game = game
return game.state()
@staticmethod
def advance_game(game, action, agent):
"""Advance a game with an action
* Play an action
* Advance the game using the agent
* Return the game pending for the same player turn _unless_ the game ends
returns <game, reward>
"""
if not game.is_action_valid(action):
return game, -1
player_idx = game.player_turn()
game_current, _ = game.move(action)
while game_current.active():
if not game_current.is_current_player_playing():
game_current = game_current.skip_eliminated_player()
elif game_current.player_turn() != player_idx:
game_current, _ = game_current.move(agent.move(game_current))
else:
break
# print("Round", game.round(), '->', game_current.round(), ':', 'OVER' if game_current.over() else 'RUNN')
if game_current.over():
if game_current.winner() == player_idx:
return game_current, 15
else:
return game_current, -5
return game_current, 0
def action_by_score(self, scores, game=None):
"""
Returns best action based on assigned scores
return (action, score, idx)
"""
if len(scores) != 15:
raise Exception("Invalid scores length: {}".format(len(scores)))
game = self._game if game is None else game
assert game.active()
actions_possible = self.actions_set(game)
actions = [(action, score, idx) for action, score, idx in
zip(actions_possible,
scores,
range(len(actions_possible)))
if game.is_action_valid(action)]
action = max(actions, key=itemgetter(2))
return action
def action_from_index(self, action_index, game=None):
"""Returns valid action based on index and game"""
game = self._game if game is None else game
action_candidates = self.actions_set(game)
actions = [(idx, action) for idx, action in
enumerate(action_candidates)
if game.is_action_valid(action) and idx == action_index]
return actions[0][1] if len(actions) == 1 else None
def actions_possible(self, game=None):
"""Returns valid (idx, actions) based on a current game"""
game = self._game if game is None else game
action_candidates = self.actions_set(game)
actions = [(idx, action) for idx, action in
enumerate(action_candidates)
if game.is_action_valid(action)]
return actions
def actions_set(self, game=None):
"""Returns all actions for a game"""
game = self._game if game is None else game
player_self = game.player_turn()
opponents = game.opponent_turn()
actions_possible = [
PlayerAction(Card.guard,
self.np_random.choice(opponents),
Card.priest,
Card.noCard),
PlayerAction(Card.guard,
self.np_random.choice(opponents),
Card.baron,
Card.noCard),
PlayerAction(Card.guard,
self.np_random.choice(opponents),
Card.handmaid,
Card.noCard),
PlayerAction(Card.guard,
self.np_random.choice(opponents),
Card.prince,
Card.noCard),
PlayerAction(Card.guard,
self.np_random.choice(opponents),
Card.king,
Card.noCard),
PlayerAction(Card.guard,
self.np_random.choice(opponents),
Card.countess,
Card.noCard),
PlayerAction(Card.guard,
self.np_random.choice(opponents),
Card.princess,
Card.noCard),
PlayerAction(Card.priest,
self.np_random.choice(opponents),
Card.noCard,
Card.noCard),
PlayerAction(Card.baron,
self.np_random.choice(opponents),
Card.noCard,
Card.noCard),
PlayerAction(Card.king,
self.np_random.choice(opponents),
Card.noCard,
Card.noCard),
PlayerAction(Card.prince,
self.np_random.choice(opponents),
Card.noCard,
Card.noCard),
PlayerAction(Card.prince, player_self, Card.noCard, Card.noCard),
PlayerAction(Card.handmaid, player_self, Card.noCard, Card.noCard),
PlayerAction(Card.countess, player_self, Card.noCard, Card.noCard),
PlayerAction(Card.princess, player_self, Card.noCard, Card.noCard)
]
return actions_possible<|fim▁end|> | return [seed]
def _step(self, action):
assert self.action_space.contains(action) |
<|file_name|>backend.py<|end_file_name|><|fim▁begin|>"""Base material for signature backends."""
from django.urls import reverse
class SignatureBackend(object):
"""Encapsulate signature workflow and integration with vendor backend.
Here is a typical workflow:
* :class:`~django_anysign.models.SignatureType` instance is created. It
encapsulates the backend type and its configuration.
* A :class:`~django_anysign.models.Signature` instance is created.
The signature instance has a signature type attribute, hence a backend.
* Signers are notified, by email, text or whatever. They get an hyperlink
to the "signer view". The URL may vary depending on the signature
backend.
* A signer goes to the backend's "signer view" entry point: typically a
view that integrates backend specific form to sign a document.
* Most backends have a "notification view", for the third-party service to
signal updates.
* Most backends have a "signer return view", where the signer is redirected
when he ends the signature process (whatever signature status).
* The backend's specific workflow can be made of several views. At the
beginning, there is a Signature instance which carries data (typically a
document). At the end, Signature is done.
"""
def __init__(self, name, code, url_namespace='anysign', **kwargs):
"""Configure backend."""
#: Human-readable name.
self.name = name
#: Machine-readable name. Should be lowercase alphanumeric only, i.e.
#: PEP-8 compliant.
self.code = code
#: Namespace for URL resolution.
self.url_namespace = url_namespace
def send_signature(self, signature):
"""Initiate the signature process.
At this state, the signature object has been configured.
Typical implementation consists in sending signer URL to first signer.
Raise ``NotImplementedError`` if the backend does not support such a
feature.
"""
raise NotImplementedError()
def get_signer_url(self, signer):
"""Return URL where signer signs document.
Raise ``NotImplementedError`` in case the backend does not support
"signer view" feature.
Default implementation reverses :meth:`get_signer_url_name` with
``signer.pk`` as argument.
"""
return reverse(self.get_signer_url_name(), args=[signer.pk])
def get_signer_url_name(self):
"""Return URL name where signer signs document.
Raise ``NotImplementedError`` in case the backend does not support
"signer view" feature.
Default implementation returns ``anysign:signer``.
"""
return '{ns}:signer'.format(ns=self.url_namespace)
def get_signer_return_url(self, signer):
"""Return absolute URL where signer is redirected after signing.
The URL must be **absolute** because it is typically used by external
signature service: the signer uses external web UI to sign the<|fim▁hole|> "signer return view" feature.
Default implementation reverses :meth:`get_signer_return_url_name`
with ``signer.pk`` as argument.
"""
return reverse(
self.get_signer_return_url_name(),
args=[signer.pk])
def get_signer_return_url_name(self):
"""Return URL name where signer is redirected once document has been
signed.
Raise ``NotImplementedError`` in case the backend does not support
"signer return view" feature.
Default implementation returns ``anysign:signer_return``.
"""
return '{ns}:signer_return'.format(ns=self.url_namespace)
def get_signature_callback_url(self, signature):
"""Return URL where backend can post signature notifications.
Raise ``NotImplementedError`` in case the backend does not support
"signature callback url" feature.
Default implementation reverses :meth:`get_signature_callback_url_name`
with ``signature.pk`` as argument.
"""
return reverse(
self.get_signature_callback_url_name(),
args=[signature.pk])
def get_signature_callback_url_name(self):
"""Return URL name where backend can post signature notifications.
Raise ``NotImplementedError`` in case the backend does not support
"signer return view" feature.
Default implementation returns ``anysign:signature_callback``.
"""
return '{ns}:signature_callback'.format(ns=self.url_namespace)
def create_signature(self, signature):
"""Register ``signature`` in backend, return updated object.
This method is typically called by views which create
:class:`~django_anysign.models.Signature` instances.
If backend stores a signature object, then implementation should update
:attr:`~django_anysign.models.Signature.signature_backend_id`.
Base implementation does nothing: override this method in backends.
"""
return signature<|fim▁end|> | document(s) and then the signature service redirects the signer to
(this) `Django` website.
Raise ``NotImplementedError`` in case the backend does not support |
<|file_name|>helpers.py<|end_file_name|><|fim▁begin|>from django.conf import settings
from django.template import (Template, Context, TemplateDoesNotExist,
TemplateSyntaxError)
from django.utils.encoding import smart_unicode
from django.utils.hashcompat import md5_constructor
from django.views.debug import ExceptionReporter
class ImprovedExceptionReporter(ExceptionReporter):
def __init__(self, request, exc_type, exc_value, frames):
ExceptionReporter.__init__(self, request, exc_type, exc_value, None)<|fim▁hole|> def get_traceback_frames(self):
return self.frames
def get_traceback_html(self):
"Return HTML code for traceback."
if issubclass(self.exc_type, TemplateDoesNotExist):
self.template_does_not_exist = True
if (settings.TEMPLATE_DEBUG and hasattr(self.exc_value, 'source') and
isinstance(self.exc_value, TemplateSyntaxError)):
self.get_template_exception_info()
frames = self.get_traceback_frames()
unicode_hint = ''
if issubclass(self.exc_type, UnicodeError):
start = getattr(self.exc_value, 'start', None)
end = getattr(self.exc_value, 'end', None)
if start is not None and end is not None:
unicode_str = self.exc_value.args[1]
unicode_hint = smart_unicode(unicode_str[max(start-5, 0):min(end+5, len(unicode_str))], 'ascii', errors='replace')
t = Template(TECHNICAL_500_TEMPLATE, name='Technical 500 template')
c = Context({
'exception_type': self.exc_type.__name__,
'exception_value': smart_unicode(self.exc_value, errors='replace'),
'unicode_hint': unicode_hint,
'frames': frames,
'lastframe': frames[-1],
'request': self.request,
'template_info': self.template_info,
'template_does_not_exist': self.template_does_not_exist,
})
return t.render(c)
def construct_checksum(error):
checksum = md5_constructor(str(error.level))
checksum.update(error.class_name or '')
message = error.traceback or error.message
if isinstance(message, unicode):
message = message.encode('utf-8', 'replace')
checksum.update(message)
return checksum.hexdigest()
TECHNICAL_500_TEMPLATE = """
<div id="summary">
<h1>{{ exception_type }} at {{ request.path_info|escape }}</h1>
<pre class="exception_value">{{ exception_value|escape }}</pre>
<table class="meta">
<tr>
<th>Request Method:</th>
<td>{{ request.META.REQUEST_METHOD }}</td>
</tr>
<tr>
<th>Request URL:</th>
<td>{{ request.build_absolute_uri|escape }}</td>
</tr>
<tr>
<th>Exception Type:</th>
<td>{{ exception_type }}</td>
</tr>
<tr>
<th>Exception Value:</th>
<td><pre>{{ exception_value|escape }}</pre></td>
</tr>
<tr>
<th>Exception Location:</th>
<td>{{ lastframe.filename|escape }} in {{ lastframe.function|escape }}, line {{ lastframe.lineno }}</td>
</tr>
</table>
</div>
{% if unicode_hint %}
<div id="unicode-hint">
<h2>Unicode error hint</h2>
<p>The string that could not be encoded/decoded was: <strong>{{ unicode_hint|escape }}</strong></p>
</div>
{% endif %}
{% if template_info %}
<div id="template">
<h2>Template error</h2>
<p>In template <code>{{ template_info.name }}</code>, error at line <strong>{{ template_info.line }}</strong></p>
<h3>{{ template_info.message }}</h3>
<table class="source{% if template_info.top %} cut-top{% endif %}{% ifnotequal template_info.bottom template_info.total %} cut-bottom{% endifnotequal %}">
{% for source_line in template_info.source_lines %}
{% ifequal source_line.0 template_info.line %}
<tr class="error"><th>{{ source_line.0 }}</th>
<td>{{ template_info.before }}<span class="specific">{{ template_info.during }}</span>{{ template_info.after }}</td></tr>
{% else %}
<tr><th>{{ source_line.0 }}</th>
<td>{{ source_line.1 }}</td></tr>
{% endifequal %}
{% endfor %}
</table>
</div>
{% endif %}
<div id="traceback">
<h2>Traceback <span class="commands"><a href="#" onclick="return switchPastebinFriendly(this);">Switch to copy-and-paste view</a></span></h2>
{% autoescape off %}
<div id="browserTraceback">
<ul class="traceback">
{% for frame in frames %}
<li class="frame">
<code>{{ frame.filename|escape }}</code> in <code>{{ frame.function|escape }}</code>
{% if frame.context_line %}
<div class="context" id="c{{ frame.id }}">
{% if frame.pre_context %}
<ol start="{{ frame.pre_context_lineno }}" class="pre-context" id="pre{{ frame.id }}">{% for line in frame.pre_context %}<li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')">{{ line|escape }}</li>{% endfor %}</ol>
{% endif %}
<ol start="{{ frame.lineno }}" class="context-line"><li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')">{{ frame.context_line|escape }} <span>...</span></li></ol>
{% if frame.post_context %}
<ol start='{{ frame.lineno|add:"1" }}' class="post-context" id="post{{ frame.id }}">{% for line in frame.post_context %}<li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')">{{ line|escape }}</li>{% endfor %}</ol>
{% endif %}
</div>
{% endif %}
{% if frame.vars %}
<div class="commands">
<a href="#" onclick="return varToggle(this, '{{ frame.id }}')"><span>▶</span> Local vars</a>
</div>
<table class="vars" id="v{{ frame.id }}">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for var in frame.vars|dictsort:"0" %}
<tr>
<td>{{ var.0|escape }}</td>
<td class="code"><div>{{ var.1|pprint|escape }}</div></td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
</li>
{% endfor %}
</ul>
</div>
{% endautoescape %}
<div id="pastebinTraceback" class="pastebin">
<textarea id="traceback_area" cols="140" rows="25">
Environment:
{% if request.META %}Request Method: {{ request.META.REQUEST_METHOD }}{% endif %}
Request URL: {{ request.build_absolute_uri|escape }}
Python Version: {{ sys_version_info }}
{% if template_does_not_exist %}Template Loader Error: (Unavailable in db-log)
{% endif %}{% if template_info %}
Template error:
In template {{ template_info.name }}, error at line {{ template_info.line }}
{{ template_info.message }}{% for source_line in template_info.source_lines %}{% ifequal source_line.0 template_info.line %}
{{ source_line.0 }} : {{ template_info.before }} {{ template_info.during }} {{ template_info.after }}
{% else %}
{{ source_line.0 }} : {{ source_line.1 }}
{% endifequal %}{% endfor %}{% endif %}
Traceback:
{% for frame in frames %}File "{{ frame.filename|escape }}" in {{ frame.function|escape }}
{% if frame.context_line %} {{ frame.lineno }}. {{ frame.context_line|escape }}{% endif %}
{% endfor %}
Exception Type: {{ exception_type|escape }} at {{ request.path_info|escape }}
Exception Value: {{ exception_value|escape }}
</textarea>
</div>
</div>
{% if request %}
<div id="requestinfo">
<h2>Request information</h2>
<h3 id="get-info">GET</h3>
{% if request.GET %}
<table class="req">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for var in request.GET.items %}
<tr>
<td>{{ var.0 }}</td>
<td class="code"><div>{{ var.1|pprint }}</div></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No GET data</p>
{% endif %}
<h3 id="post-info">POST</h3>
{% if request.POST %}
<table class="req">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for var in request.POST.items %}
<tr>
<td>{{ var.0 }}</td>
<td class="code"><div>{{ var.1|pprint }}</div></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No POST data</p>
{% endif %}
<h3 id="cookie-info">COOKIES</h3>
{% if request.COOKIES %}
<table class="req">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for var in request.COOKIES.items %}
<tr>
<td>{{ var.0 }}</td>
<td class="code"><div>{{ var.1|pprint }}</div></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No cookie data</p>
{% endif %}
<h3 id="meta-info">META</h3>
{% if request.META %}
<table class="req">
<thead>
<tr>
<th>Variable</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{% for var in request.META.items|dictsort:"0" %}
<tr>
<td>{{ var.0 }}</td>
<td class="code"><div>{{ var.1|pprint }}</div></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No META data</p>
{% endif %}
</div>
{% endif %}
"""<|fim▁end|> | self.frames = frames
|
<|file_name|>FileExporterImplTest.java<|end_file_name|><|fim▁begin|>// -*- mode: java; c-basic-offset: 2; -*-
// Copyright 2009-2011 Google, All Rights reserved
// Copyright 2011-2012 MIT, All rights reserved
// Released under the Apache License, Version 2.0
// http://www.apache.org/licenses/LICENSE-2.0
package com.google.appinventor.server;
import com.google.appinventor.server.storage.StorageIo;
import com.google.appinventor.server.storage.StorageIoInstanceHolder;
import com.google.appinventor.server.storage.UnauthorizedAccessException;
import com.google.appinventor.shared.rpc.project.Project;
import com.google.appinventor.shared.rpc.project.ProjectSourceZip;
import com.google.appinventor.shared.rpc.project.RawFile;
import com.google.appinventor.shared.rpc.project.TextFile;
import com.google.appinventor.shared.storage.StorageUtil;
import com.google.common.io.ByteStreams;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Tests for {@link FileExporterImpl}.
*
*/
public class FileExporterImplTest extends LocalDatastoreTestCase {
private static final String USER_ID = "1";
// The following represent a fake project, containing both source and
// output files, for the purpose of testing.
private static final String FAKE_PROJECT_TYPE = "FakeProjectType";
private static final String PROJECT_NAME = "Project1";
private static final String FORM1_NAME = "Screen1";
private static final String FORM1_QUALIFIED_NAME = "com.yourdomain." + FORM1_NAME;
private static final String FORM1_CONTENT = "Form A\nEnd Form";
private static final String IMAGE1_NAME = "Image.jpg";
private static final byte[] IMAGE_CONTENT = { (byte) 0, (byte) 1, (byte) 32, (byte) 255};
private static final String TARGET1_NAME = "Project1.apk";
private static final String TARGET1_QUALIFIED_NAME = "build/target1/" + TARGET1_NAME;
private static final byte[] TARGET1_CONTENT = "pk1".getBytes();
private static final String TARGET2_NAME = "Project2.pak";
private static final String TARGET2_QUALIFIED_NAME = "build/target2/" + TARGET2_NAME;
private static final byte[] TARGET2_CONTENT = "pk2".getBytes();
private static final String SETTINGS = "";
private static final String HISTORY = "1:History";
private StorageIo storageIo;
private FileExporterImpl exporter;
private long projectId;
@Override
protected void setUp() throws Exception {
super.setUp();
storageIo = StorageIoInstanceHolder.INSTANCE;
exporter = new FileExporterImpl();
Project project = new Project(PROJECT_NAME);
project.setProjectType(FAKE_PROJECT_TYPE);
project.setProjectHistory(HISTORY);
project.addTextFile(new TextFile(FORM1_QUALIFIED_NAME, ""));
projectId = storageIo.createProject(USER_ID, project, SETTINGS);
storageIo.uploadFile(projectId, FORM1_QUALIFIED_NAME, USER_ID, FORM1_CONTENT,
StorageUtil.DEFAULT_CHARSET);
storageIo.addSourceFilesToProject(USER_ID, projectId, false, IMAGE1_NAME);
storageIo.uploadRawFile(projectId, IMAGE1_NAME, USER_ID, true, IMAGE_CONTENT);
storageIo.addOutputFilesToProject(USER_ID, projectId, TARGET1_QUALIFIED_NAME);
storageIo.uploadRawFile(projectId, TARGET1_QUALIFIED_NAME, USER_ID,
true, TARGET1_CONTENT);
storageIo.addOutputFilesToProject(USER_ID, projectId, TARGET2_QUALIFIED_NAME);
storageIo.uploadRawFile(projectId, TARGET2_QUALIFIED_NAME, USER_ID,
true, TARGET2_CONTENT);
}
private Map<String, byte[]> testExportProjectSourceZipHelper(ProjectSourceZip project)
throws IOException {
ZipInputStream zis =
new ZipInputStream(new ByteArrayInputStream(project.getContent()));
Map<String, byte[]> content = new HashMap<String, byte[]>();
ZipEntry zipEntry;
while ((zipEntry = zis.getNextEntry()) != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteStreams.copy(zis, baos);
content.put(zipEntry.getName(), baos.toByteArray());
}
assertEquals(content.size(), project.getFileCount());
assertTrue(content.containsKey(FORM1_QUALIFIED_NAME));
assertTrue(content.containsKey(IMAGE1_NAME));
assertFalse(content.containsKey(TARGET1_NAME));
assertEquals(FORM1_CONTENT, new String(content.get(FORM1_QUALIFIED_NAME),
StorageUtil.DEFAULT_CHARSET));
assertTrue(Arrays.equals(IMAGE_CONTENT, content.get(IMAGE1_NAME)));
return content;
}
public void testExportProjectSourceZipWithoutHistory() throws IOException {
ProjectSourceZip project = exporter.exportProjectSourceZip(USER_ID, projectId,
false, false, null);
Map<String, byte[]> content = testExportProjectSourceZipHelper(project);
assertEquals(2, content.size());
/* Do not expect remix history when includeProjectHistory parameter is false
* as in the publish case. */
assertFalse(content.containsKey(FileExporter.REMIX_INFORMATION_FILE_PATH));
}
// TODO(user): Add test with properly formatted history
public void testExportProjectSourceZipWithHistory() throws IOException {
ProjectSourceZip project = exporter.exportProjectSourceZip(USER_ID, projectId,
true, false, null);
Map<String, byte[]> content = testExportProjectSourceZipHelper(project);
assertEquals(3, content.size());
// Expect the remix file to be in
assertTrue(content.containsKey(FileExporter.REMIX_INFORMATION_FILE_PATH));
assertEquals(HISTORY, new String(content.get(FileExporter.REMIX_INFORMATION_FILE_PATH),
StorageUtil.DEFAULT_CHARSET));
}
public void testExportProjectSourceZipWithNonExistingProject() throws IOException {
try {
exporter.exportProjectSourceZip(USER_ID, projectId + 1, false, false, null);
fail();
} catch (Exception e) {
assertTrue(e instanceof IllegalArgumentException ||
e.getCause() instanceof IllegalArgumentException);
}
}
public void testExportProjectOutputFileWithTarget() throws IOException {
RawFile file = exporter.exportProjectOutputFile(USER_ID, projectId, "target1");
assertEquals(TARGET1_NAME, file.getFileName());
assertTrue(Arrays.equals(TARGET1_CONTENT, file.getContent()));
}
public void testExportProjectOutputFileWithNonExistingTraget() throws IOException {
try {
exporter.exportProjectOutputFile(USER_ID, projectId, "target3");
fail();
} catch (IllegalArgumentException e) {
// expected
}
}
public void testExportFile() throws IOException {
RawFile file = exporter.exportFile(USER_ID, projectId, FORM1_QUALIFIED_NAME);
assertEquals(FORM1_QUALIFIED_NAME, file.getFileName());
assertEquals(FORM1_CONTENT, new String(file.getContent(), StorageUtil.DEFAULT_CHARSET));
}
public void testExportFileWithNonExistingFile() throws IOException {
final String nonExistingFileName = FORM1_QUALIFIED_NAME + "1";
try {
exporter.exportFile(USER_ID, projectId, nonExistingFileName);
fail();
} catch (RuntimeException e) {
// expected<|fim▁hole|> }
// TODO(user): Add test of exportAllProjectsSourceZip().
}<|fim▁end|> | // note that FileExporter throws an explicit RuntimeException
} |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>extern crate futures;
extern crate rpassword;
extern crate ethcore_util as util;
extern crate bigint;
extern crate parity_rpc as rpc;
extern crate parity_rpc_client as client;
use rpc::signer::{U256, ConfirmationRequest};
use client::signer_client::SignerRpc;
use std::io::{Write, BufRead, BufReader, stdout, stdin};
use std::path::PathBuf;
use std::fs::File;
use futures::Future;
fn sign_interactive(
signer: &mut SignerRpc,
password: &str,
request: ConfirmationRequest
) {
print!("\n{}\nSign this transaction? (y)es/(N)o/(r)eject: ", request);
let _ = stdout().flush();
match BufReader::new(stdin()).lines().next() {
Some(Ok(line)) => {
match line.to_lowercase().chars().nth(0) {
Some('y') => {
match sign_transaction(signer, request.id, password) {
Ok(s) | Err(s) => println!("{}", s),
}
}
Some('r') => {
match reject_transaction(signer, request.id) {
Ok(s) | Err(s) => println!("{}", s),
}
}
_ => ()
}
}
_ => println!("Could not read from stdin")
}
}
fn sign_transactions(
signer: &mut SignerRpc,
password: String
) -> Result<String, String> {
signer.requests_to_confirm().map(|reqs| {
match reqs {
Ok(ref reqs) if reqs.is_empty() => {
Ok("No transactions in signing queue".to_owned())
}
Ok(reqs) => {
for r in reqs {
sign_interactive(signer, &password, r)
}
Ok("".to_owned())
}
Err(err) => {
Err(format!("error: {:?}", err))
}
}
}).map_err(|err| {
format!("{:?}", err)
}).wait()?
}
fn list_transactions(signer: &mut SignerRpc) -> Result<String, String> {
signer.requests_to_confirm().map(|reqs| {
match reqs {
Ok(ref reqs) if reqs.is_empty() => {
Ok("No transactions in signing queue".to_owned())
}
Ok(ref reqs) => {
Ok(format!("Transaction queue:\n{}", reqs
.iter()
.map(|r| format!("{}", r))
.collect::<Vec<String>>()
.join("\n")))
}
Err(err) => {
Err(format!("error: {:?}", err))
}
}
}).map_err(|err| {
format!("{:?}", err)
}).wait()?
}
fn sign_transaction(
signer: &mut SignerRpc, id: U256, password: &str
) -> Result<String, String> {<|fim▁hole|> }
}).map_err(|err| {
format!("{:?}", err)
}).wait()?
}
fn reject_transaction(
signer: &mut SignerRpc, id: U256) -> Result<String, String>
{
signer.reject_request(id).map(|res| {
match res {
Ok(true) => Ok(format!("Rejected transaction id {:#x}", id)),
Ok(false) => Err(format!("No such request")),
Err(e) => Err(format!("{:?}", e)),
}
}).map_err(|err| {
format!("{:?}", err)
}).wait()?
}
// cmds
pub fn signer_list(
signerport: u16, authfile: PathBuf
) -> Result<String, String> {
let addr = &format!("ws://127.0.0.1:{}", signerport);
let mut signer = SignerRpc::new(addr, &authfile).map_err(|err| {
format!("{:?}", err)
})?;
list_transactions(&mut signer)
}
pub fn signer_reject(
id: Option<usize>, signerport: u16, authfile: PathBuf
) -> Result<String, String> {
let id = id.ok_or(format!("id required for signer reject"))?;
let addr = &format!("ws://127.0.0.1:{}", signerport);
let mut signer = SignerRpc::new(addr, &authfile).map_err(|err| {
format!("{:?}", err)
})?;
reject_transaction(&mut signer, U256::from(id))
}
pub fn signer_sign(
id: Option<usize>,
pwfile: Option<PathBuf>,
signerport: u16,
authfile: PathBuf
) -> Result<String, String> {
let password;
match pwfile {
Some(pwfile) => {
match File::open(pwfile) {
Ok(fd) => {
match BufReader::new(fd).lines().next() {
Some(Ok(line)) => password = line,
_ => return Err(format!("No password in file"))
}
},
Err(e) =>
return Err(format!("Could not open password file: {}", e))
}
}
None => {
password = match rpassword::prompt_password_stdout("Password: ") {
Ok(p) => p,
Err(e) => return Err(format!("{}", e)),
}
}
}
let addr = &format!("ws://127.0.0.1:{}", signerport);
let mut signer = SignerRpc::new(addr, &authfile).map_err(|err| {
format!("{:?}", err)
})?;
match id {
Some(id) => {
sign_transaction(&mut signer, U256::from(id), &password)
},
None => {
sign_transactions(&mut signer, password)
}
}
}<|fim▁end|> | signer.confirm_request(id, None, None, None, password).map(|res| {
match res {
Ok(u) => Ok(format!("Signed transaction id: {:#x}", u)),
Err(e) => Err(format!("{:?}", e)), |
<|file_name|>parentElement.test.ts<|end_file_name|><|fim▁begin|>import { remote } from '../../../src'
describe('parent element test', () => {
it('should return parent element of an element', async () => {
const browser = await remote({
capabilities: {
browserName: 'foobar'
}
})
const elem = await browser.$('#foo')
const subElem = await elem.$('#bar')
const parentEl = await subElem.parentElement()
expect(parentEl.elementId).toBe('some-parent-elem')
})
it('should throw error if parent element does not exist', async () => {
const browser = await remote({
waitforInterval: 1,
waitforTimeout: 1,
capabilities: {
browserName: 'foobar'
}
})<|fim▁hole|>
const err = await parentElem.click().catch((err) => err)
expect(err.message)
.toContain('parent element of element with selector "#foo"')
})
})<|fim▁end|> | const elem = await browser.$('#foo')
const parentElem = await elem.parentElement() |
<|file_name|>missingCode.test.js<|end_file_name|><|fim▁begin|>describe('A Feature', function() {
it('A Scenario', function() {
// ### Given missing code
});
<|fim▁hole|><|fim▁end|> | }); |
<|file_name|>submissions.js<|end_file_name|><|fim▁begin|>app.controller('submissions', ['$scope', '$http', '$rootScope', 'globalHelpers', function ($scope, $http, $rootScope, globalHelpers) {
$scope.stats = {};
$scope.getUrlLanguages = function(gitUrlId){
globalHelpers.getUrlLanguagesPromise(gitUrlId).then( function (response){
$scope.stats[gitUrlId] = response.data.languages;
});
}
$scope.addForReview = function () {
$scope.showWarning = false;
$scope.showGithubWarning = false;
if (!$scope.newName || !$scope.newUrl) {
$scope.showWarning = true;
return;
}
var _new_name = $scope.newName.trim();
var _new = $scope.newUrl.trim();
if (!_new || !_new_name) {
$scope.showWarning = true;
return;
}
if (!_new || !_new_name) {
$scope.showWarning = true;
return;
}
var _newUrl = globalHelpers.getLocation(_new);
var pathArray = _newUrl.pathname.split('/');
isCommit = pathArray.indexOf('commit') > -1;
isPR = pathArray.indexOf('pull') > -1;
if (_newUrl.hostname != "github.com" || (!isCommit && !isPR)){
$scope.showGithubWarning = true;
return;
}
var obj = JSON.parse('{"github_user": "' + $scope.github_user + '", "name": "' + _new_name + '", "url": "' + _new + '"}');
for (var i=0; i < $scope.existing.length; i++){
if (Object.keys($scope.existing[i])[0] == _new){
return;
}
}
$scope.existing.push(obj);
$http({
method: "post",
url: "/add_for_review",
headers: {'Content-Type': "application/json"},
data: obj
}).success(function () {
// console.log("success!");
});
$scope.showUWarning = false;
$scope.showGithubWarning = false;
$scope._new = '';
$rootScope.$broadcast('urlEntryChange', 'args');
};
$scope.removeUrl = function (url) {
if(confirm("Are you sure you want to delete entry \"" + url["name"] + "\"?")){
for (var i=0; i < $scope.existing.length; i++){
if ($scope.existing[i]["url"] == url['url']){
$scope.existing.splice(i, 1)
$http({
method: "post",
url: "/remove_from_list",
headers: {'Content-Type': "application/json"},
data: url
}).success(function () {
console.log("success!");
});
$rootScope.$broadcast('urlEntryChange', 'args');
}
}
}<|fim▁hole|><|fim▁end|> | };
}]); |
<|file_name|>issue-43692.rs<|end_file_name|><|fim▁begin|>// Copyright 2017 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.
// run-pass
fn main() {<|fim▁hole|>}<|fim▁end|> | assert_eq!('\u{10__FFFF}', '\u{10FFFF}');
assert_eq!("\u{10_F0FF__}foo\u{1_0_0_0__}", "\u{10F0FF}foo\u{1000}"); |
<|file_name|>conftest.py<|end_file_name|><|fim▁begin|># Calliope
# Copyright (C) 2017, 2018 Sam Thursfield <[email protected]><|fim▁hole|># it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import pytest
import testutils
@pytest.fixture()
def cli():
'''Fixture for testing through the `cpe` commandline interface.'''
return testutils.Cli()<|fim▁end|> | #
# This program is free software: you can redistribute it and/or modify |
<|file_name|>cne.d.ts<|end_file_name|><|fim▁begin|>export function cne(t: string): CurriedCNE;
/**<|fim▁hole|> * Curried element creation.
*/
export type CurriedCNE = (P?: HTMLElement) => HTMLElement[];<|fim▁end|> | |
<|file_name|>test_embedded_ansible_actions.py<|end_file_name|><|fim▁begin|>import fauxfactory
import pytest
from cfme import test_requirements
from cfme.control.explorer.policies import VMControlPolicy
from cfme.infrastructure.provider.virtualcenter import VMwareProvider
from cfme.markers.env_markers.provider import ONE_PER_TYPE
from cfme.services.myservice import MyService
from cfme.utils.appliance.implementations.ui import navigate_to
from cfme.utils.conf import cfme_data
from cfme.utils.conf import credentials
from cfme.utils.update import update
from cfme.utils.wait import wait_for
pytestmark = [
pytest.mark.ignore_stream("upstream"),
pytest.mark.long_running,
pytest.mark.provider([VMwareProvider], selector=ONE_PER_TYPE, scope="module"),
test_requirements.ansible,
]
@pytest.fixture(scope="module")
def wait_for_ansible(appliance):
appliance.server.settings.enable_server_roles("embedded_ansible")
appliance.wait_for_embedded_ansible()
yield
appliance.server.settings.disable_server_roles("embedded_ansible")
@pytest.fixture(scope="module")
def ansible_repository(appliance, wait_for_ansible):
repositories = appliance.collections.ansible_repositories
try:
repository = repositories.create(
name=fauxfactory.gen_alpha(),
url=cfme_data.ansible_links.playbook_repositories.embedded_ansible,
description=fauxfactory.gen_alpha())
except KeyError:
pytest.skip("Skipping since no such key found in yaml")
view = navigate_to(repository, "Details")
wait_for(
lambda: view.entities.summary("Properties").get_text_of("Status") == "successful",
timeout=60,
fail_func=view.toolbar.refresh.click
)<|fim▁hole|>
repository.delete_if_exists()
@pytest.fixture(scope="module")
def ansible_catalog_item(appliance, ansible_repository):
cat_item = appliance.collections.catalog_items.create(
appliance.collections.catalog_items.ANSIBLE_PLAYBOOK,
fauxfactory.gen_alphanumeric(),
fauxfactory.gen_alphanumeric(),
display_in_catalog=True,
provisioning={
"repository": ansible_repository.name,
"playbook": "dump_all_variables.yml",
"machine_credential": "CFME Default Credential",
"create_new": True,
"provisioning_dialog_name": fauxfactory.gen_alphanumeric()
}
)
yield cat_item
cat_item.delete_if_exists()
@pytest.fixture(scope="module")
def ansible_action(appliance, ansible_catalog_item):
action_collection = appliance.collections.actions
action = action_collection.create(
fauxfactory.gen_alphanumeric(),
action_type="Run Ansible Playbook",
action_values={
"run_ansible_playbook": {
"playbook_catalog_item": ansible_catalog_item.name
}
}
)
yield action
action.delete_if_exists()
@pytest.fixture(scope="module")
def policy_for_testing(appliance, full_template_vm_modscope, provider, ansible_action):
vm = full_template_vm_modscope
policy = appliance.collections.policies.create(
VMControlPolicy,
fauxfactory.gen_alpha(),
scope="fill_field(VM and Instance : Name, INCLUDES, {})".format(vm.name)
)
policy.assign_actions_to_event("Tag Complete", [ansible_action.description])
policy_profile = appliance.collections.policy_profiles.create(
fauxfactory.gen_alpha(), policies=[policy])
provider.assign_policy_profiles(policy_profile.description)
yield
if policy.exists:
policy.assign_events()
provider.unassign_policy_profiles(policy_profile.description)
policy_profile.delete()
policy.delete()
@pytest.fixture(scope="module")
def ansible_credential(wait_for_ansible, appliance, full_template_modscope):
credential = appliance.collections.ansible_credentials.create(
fauxfactory.gen_alpha(),
"Machine",
username=credentials[full_template_modscope.creds]["username"],
password=credentials[full_template_modscope.creds]["password"]
)
yield credential
credential.delete_if_exists()
@pytest.fixture
def service_request(appliance, ansible_catalog_item):
request_desc = "Provisioning Service [{0}] from [{0}]".format(ansible_catalog_item.name)
_service_request = appliance.collections.requests.instantiate(request_desc)
yield _service_request
_service_request.delete_if_exists()
@pytest.fixture
def service(appliance, ansible_catalog_item):
service_ = MyService(appliance, ansible_catalog_item.name)
yield service_
if service_.exists:
service_.delete()
@pytest.mark.tier(3)
def test_action_run_ansible_playbook_localhost(request, ansible_catalog_item, ansible_action,
policy_for_testing, full_template_vm_modscope, ansible_credential, service_request,
service):
"""Tests a policy with ansible playbook action against localhost.
Polarion:
assignee: sbulage
initialEstimate: 1/6h
casecomponent: Ansible
"""
with update(ansible_action):
ansible_action.run_ansible_playbook = {"inventory": {"localhost": True}}
added_tag = full_template_vm_modscope.add_tag()
request.addfinalizer(lambda: full_template_vm_modscope.remove_tag(added_tag))
wait_for(service_request.exists, num_sec=600)
service_request.wait_for_request()
view = navigate_to(service, "Details")
assert view.provisioning.details.get_text_of("Hosts") == "localhost"
assert view.provisioning.results.get_text_of("Status") == "successful"
@pytest.mark.tier(3)
def test_action_run_ansible_playbook_manual_address(request, ansible_catalog_item, ansible_action,
policy_for_testing, full_template_vm_modscope, ansible_credential, service_request,
service):
"""Tests a policy with ansible playbook action against manual address.
Polarion:
assignee: sbulage
initialEstimate: 1/6h
casecomponent: Ansible
"""
vm = full_template_vm_modscope
with update(ansible_catalog_item):
ansible_catalog_item.provisioning = {"machine_credential": ansible_credential.name}
with update(ansible_action):
ansible_action.run_ansible_playbook = {
"inventory": {
"specific_hosts": True,
"hosts": vm.ip_address
}
}
added_tag = vm.add_tag()
request.addfinalizer(lambda: vm.remove_tag(added_tag))
wait_for(service_request.exists, num_sec=600)
service_request.wait_for_request()
view = navigate_to(service, "Details")
assert view.provisioning.details.get_text_of("Hosts") == vm.ip_address
assert view.provisioning.results.get_text_of("Status") == "successful"
@pytest.mark.tier(3)
def test_action_run_ansible_playbook_target_machine(request, ansible_catalog_item, ansible_action,
policy_for_testing, full_template_vm_modscope, ansible_credential, service_request,
service):
"""Tests a policy with ansible playbook action against target machine.
Polarion:
assignee: sbulage
initialEstimate: 1/6h
casecomponent: Ansible
"""
vm = full_template_vm_modscope
with update(ansible_action):
ansible_action.run_ansible_playbook = {"inventory": {"target_machine": True}}
added_tag = vm.add_tag()
request.addfinalizer(lambda: vm.remove_tag(added_tag))
wait_for(service_request.exists, num_sec=600)
service_request.wait_for_request()
view = navigate_to(service, "Details")
assert view.provisioning.details.get_text_of("Hosts") == vm.ip_address
assert view.provisioning.results.get_text_of("Status") == "successful"
@pytest.mark.tier(3)
def test_action_run_ansible_playbook_unavailable_address(request, ansible_catalog_item,
full_template_vm_modscope, ansible_action, policy_for_testing, ansible_credential,
service_request, service):
"""Tests a policy with ansible playbook action against unavailable address.
Polarion:
assignee: sbulage
initialEstimate: 1/6h
casecomponent: Ansible
"""
vm = full_template_vm_modscope
with update(ansible_catalog_item):
ansible_catalog_item.provisioning = {"machine_credential": ansible_credential.name}
with update(ansible_action):
ansible_action.run_ansible_playbook = {
"inventory": {
"specific_hosts": True,
"hosts": "unavailable_address"
}
}
added_tag = vm.add_tag()
request.addfinalizer(lambda: vm.remove_tag(added_tag))
wait_for(service_request.exists, num_sec=600)
service_request.wait_for_request()
view = navigate_to(service, "Details")
assert view.provisioning.details.get_text_of("Hosts") == "unavailable_address"
assert view.provisioning.results.get_text_of("Status") == "failed"
@pytest.mark.tier(3)
def test_control_action_run_ansible_playbook_in_requests(request,
full_template_vm_modscope, policy_for_testing, service_request):
"""Checks if execution of the Action result in a Task/Request being created.
Polarion:
assignee: sbulage
initialEstimate: 1/6h
casecomponent: Ansible
"""
vm = full_template_vm_modscope
added_tag = vm.add_tag()
request.addfinalizer(lambda: vm.remove_tag(added_tag))
assert service_request.exists<|fim▁end|> | yield repository |
<|file_name|>results.py<|end_file_name|><|fim▁begin|>#
# results.py - Result widget for Yabsc
#
# Copyright (C) 2008 James Oakley <[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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
import os
from PyQt4 import QtGui, QtCore
#
# Data model
#
class ResultModel(QtCore.QAbstractItemModel):
"""ResultModel()
Model for package results
"""
def __init__(self):
QtCore.QAbstractItemModel.__init__(self)
self.results = []
self.targets = []
self.targetfilter = ""
self.resultfilter = ""
self.visibletargets = []
self.packages = []
self.packagefilter = ""
self.visiblepackages = []
def setResults(self, results, targets):
"""
setResults(results, targets)
Set the results dict and targets list of the model, as returned from
BuildService.getResults()
"""
self.results = results
self.targets = targets
self.packages = sorted(results.keys())
self.updateVisiblePackages(reset=False)
self.updateVisibleTargets(reset=False)
self.reset()
def _targetIndexFromName(self, target):
"""
_targetIndexFromName(target)
Returns the column index of the named target in the raw result data
"""
return self.targets.index(target)
def targetFromColumn(self, column):
"""
targetFromColumn(column)
Returns the target represented by the visible 'column'
"""
if column > 0:
return self.targets[self._targetIndexFromName(self.visibletargets[column-1])]
def getPackageTargetsWithStatus(self, package, status):
"""
getPackageTargetsWithStatus(package, status) -> list
Returns a list of failed targets for a package
"""
targets = []
for (i, target) in enumerate(self.results[package]):
if target == status.lower():
targets.append(self.targets[i])
return targets
def _data(self, row, column):
"""
_data(row, column) -> str
Internal method for getting model data. The 0th column is the package name, and subsequent
columns are result codes
"""
package = self.visiblepackages[row]
target = self.visibletargets[column-1]
if column == 0:
return package
else:
return self.results[package][self._targetIndexFromName(target)]
def packageFromRow(self, row):
"""
packageFromRow(row) -> str
Get the package name associated with a row
"""
return self._data(row, 0)
def data(self, index, role):
"""
data(index, role) -> Qvariant
Returns the QVariant model data located at QModelIndex index
This is normally only called within Qt
"""
if not index.isValid():
return QtCore.QVariant()
txt = self._data(index.row(), index.column())
if role == QtCore.Qt.DisplayRole:
return QtCore.QVariant(txt)
elif role == QtCore.Qt.ForegroundRole:
if txt in ("succeeded",):
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.green))
if txt in ("building",):
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.blue))
if txt in ("disabled",):
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.gray))
if txt in ("expansion error", "failed", "broken"):
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.red))
elif role == QtCore.Qt.BackgroundRole:
if txt in ("building", "scheduled"):
return QtCore.QVariant(QtGui.QColor(QtCore.Qt.gray))
return QtCore.QVariant()
def headerData(self, section, orientation, role):
"""
headerData(section, orientation, role) -> QVariant
Returns header for section (column) with orientation (Qt.Horizontal or Qt.Vertical)
This is normally only called within Qt
"""
if role == QtCore.Qt.DisplayRole:
if section == 0:
return QtCore.QVariant("Package")
else:
return QtCore.QVariant(self.visibletargets[section-1])
else:
return QtCore.QVariant()
def index(self, row, column, parent=None):
"""
index(row, column, parent) -> QModelIndex
Returns a QModelIndex object representing row and column
"""
return self.createIndex(row, column, id(self._data(row, column)))
def parent(self, index):
"""
parent(index) -> QModelIndex
Return the parent index of an index (for trees)
"""
return QtCore.QModelIndex()
def rowCount(self, parent=None):
"""
rowCount() -> int
Returns the number of rows of data currently in the model
"""<|fim▁hole|>
def columnCount(self, parent=None):
"""
columnCount() -> int
Returns the number of columns of data currently in the model
"""
return len(self.visibletargets) + 1
def packageHasResult(self, package, result):
"""
packageHasResult(package, result) -> boolean
Return whether a package has a result in one of the visible targets
"""
for (i, target) in enumerate(self.targets):
if target in self.visibletargets and self.results[package][i] == result:
return True
return False
def numPackagesWithResult(self, result):
"""
numPackagesWithResult(result)
Return the number of packages with result in one of the visible targets
"""
packages = [p for p in self.packages if self.packagefilter in p]
result = result.lower()
if result == 'all':
return len(packages)
return len([p for p in packages if self.packageHasResult(p, result)])
def updateVisiblePackages(self, reset=True):
"""
updateVisiblePackages(reset=True)
Update the list of visible packages
"""
# Start with all packages
self.visiblepackages = self.packages
# Apply filter string
if self.packagefilter:
self.visiblepackages = [p for p in self.visiblepackages if self.packagefilter in p]
# Apply result filter
if self.resultfilter:
self.visiblepackages = [p for p in self.visiblepackages if self.packageHasResult(p, self.resultfilter)]
if reset:
self.reset()
def setPackageFilter(self, filterstring, reset=True):
"""
setPackageFilter(filterstring)
Only show packages matching filterstring
"""
self.packagefilter = filterstring
self.updateVisiblePackages(reset)
def setResultFilter(self, result="", reset=True):
"""
setResultFilter(target)
Only show packages with at least one result matching 'result'. If
'result' is undefined or empty, filter is disabled
"""
self.resultfilter = result.lower()
self.updateVisiblePackages(reset)
def updateVisibleTargets(self, reset=True):
"""
updateVisibleTargets(reset=True)
Update the list of visible targets
"""
self.visibletargets = self.targets
if self.targetfilter:
self.visibletargets = [t for t in self.targets if t == self.targetfilter]
if reset:
self.reset()
def setTargetFilter(self, target="", reset=True):
"""
setTargetFilter(target)
Only show results for target. If target is undefined or empty, filter
is disabled
"""
self.targetfilter = target
self.updateVisibleTargets(reset)
#
# API call threads
#
class ProjectListThread(QtCore.QThread):
"""
ProjectListThread(bs)
Thread for retrieving project lists. Requires a BuildService object
"""
def __init__(self, bs):
QtCore.QThread.__init__(self)
self.bs = bs
self.projects = []
self.watched = True
def run(self):
if self.watched:
self.projects = self.bs.getWatchedProjectList()
else:
self.projects = self.bs.getProjectList()
class ProjectResultsThread(QtCore.QThread):
"""
ProjectResultsThread(bs)
Thread for retrieving project results. Requires a BuildService object
"""
def __init__(self, bs):
QtCore.QThread.__init__(self)
self.bs = bs
self.project = None
self.results = []
self.targets = []
def run(self):
(self.results, self.targets) = self.bs.getResults(self.project)
class PackageStatusThread(QtCore.QThread):
"""
PackageStatusThread(bs)
Thread for retrieving package status. Requires a BuildService object
"""
def __init__(self, bs):
QtCore.QThread.__init__(self)
self.bs = bs
self.project = None
self.package = None
self.status = {}
def run(self):
self.status = self.bs.getPackageStatus(self.project, self.package)
class BuildLogThread(QtCore.QThread):
"""
BuildLogThread(bs)
Thread for retrieving build logs. Requires a BuildService object
"""
def __init__(self, bs):
QtCore.QThread.__init__(self)
self.bs = bs
self.project = None
self.target = None
self.package = None
self.offset = 0
self.live = False
self.log_chunk = ""
def run(self):
self.log_chunk = self.bs.getBuildLog(self.project, self.target, self.package, self.offset)
class ProjectTreeView(QtGui.QTreeView):
"""
ProjectTreeView(bs, parent=None)
The project tree view. 'bs' must be a BuildService object
"""
def __init__(self, bs, parent=None):
self.bs = bs
QtGui.QTreeView.__init__(self, parent)
def contextMenuEvent(self, event):
"""
contextMenuEvent(event)
Context menu event handler
"""
index = self.indexAt(event.pos())
project = self.model().data(index, QtCore.Qt.DisplayRole).toString()
if project:
menu = QtGui.QMenu()
watchaction = None
unwatchaction = None
abortaction = QtGui.QAction('Abort all builds for %s' % project, self)
menu.addAction(abortaction)
# Disable until feature is finished
# editflagsaction = QtGui.QAction('Edit flags for %s' % project, self)
# menu.addAction(editflagsaction)
if project in self.bs.getWatchedProjectList():
unwatchaction = QtGui.QAction('Unwatch %s' % project, self)
menu.addAction(unwatchaction)
else:
watchaction = QtGui.QAction('Watch %s' % project, self)
menu.addAction(watchaction)
selectedaction = menu.exec_(self.mapToGlobal(event.pos()))
if selectedaction:
try:
if selectedaction == abortaction:
self.bs.abortBuild(str(project))
# elif selectedaction == editflagsaction:
# self.editFlags(project)
elif selectedaction == watchaction:
self.bs.watchProject(project)
elif selectedaction == unwatchaction:
self.bs.unwatchProject(project)
except Exception, e:
QtGui.QMessageBox.critical(self, "Error",
"Could not perform action on project %s: %s" % (project, e))
raise
if selectedaction in (watchaction, unwatchaction):
self.emit(QtCore.SIGNAL("watchedProjectsChanged()"))
def editFlags(self, project):
"""
editFlags(project)
Edit flags for project
"""
flags = self.bs.projectFlags(project)
dialog = ProjectFlagsDialog(project, flags)
ret = dialog.exec_()
if ret:
flags.save()
class ResultTreeView(QtGui.QTreeView):
"""
ResultTreeView(bs, parent=None)
The result tree view. 'parent' must contain a BuildService object, 'bs' and
the current project, 'currentproject'
"""
def __init__(self, parent=None):
self.parent = parent
QtGui.QTreeView.__init__(self, parent)
def contextMenuEvent(self, event):
"""
contextMenuEvent(event)
Context menu event handler
"""
index = self.indexAt(event.pos())
packageindex = self.model().createIndex(index.row(), 0)
packagename = str(self.model().data(packageindex, QtCore.Qt.DisplayRole).toString())
target = self.model().targetFromColumn(index.column())
failedtargets = self.model().getPackageTargetsWithStatus(packagename, 'failed')
buildingtargets = self.model().getPackageTargetsWithStatus(packagename, 'building')
scheduledtargets = self.model().getPackageTargetsWithStatus(packagename, 'scheduled')
if packagename:
menu = QtGui.QMenu()
rebuildtargetaction = None
rebuildallfailedaction = None
aborttargetaction = None
abortallaction = None
if target:
rebuildtargetaction = QtGui.QAction('Rebuild %s for %s' % (packagename, target), self)
menu.addAction(rebuildtargetaction)
if failedtargets:
rebuildallfailedaction = QtGui.QAction('Rebuild %s for all failed targets' % packagename, self)
menu.addAction(rebuildallfailedaction)
rebuildallaction = QtGui.QAction('Rebuild %s for all targets' % packagename, self)
menu.addAction(rebuildallaction)
if target and (target in buildingtargets or target in scheduledtargets):
aborttargetaction = QtGui.QAction('Abort build of %s for %s' % (packagename, target), self)
menu.addAction(aborttargetaction)
if buildingtargets or scheduledtargets:
abortallaction = QtGui.QAction('Abort all builds of %s' % packagename, self)
menu.addAction(abortallaction)
selectedaction = menu.exec_(self.mapToGlobal(event.pos()))
if selectedaction:
try:
if selectedaction == rebuildtargetaction:
self.parent.bs.rebuild(self.parent.currentproject, packagename, target=target)
elif selectedaction == rebuildallfailedaction:
self.parent.bs.rebuild(self.parent.currentproject, packagename, code='failed')
elif selectedaction == rebuildallaction:
self.parent.bs.rebuild(self.parent.currentproject, packagename)
elif selectedaction == aborttargetaction:
self.parent.bs.abortBuild(self.parent.currentproject, packagename, target)
elif selectedaction == abortallaction:
self.parent.bs.abortBuild(self.parent.currentproject, packagename)
except Exception, e:
QtGui.QMessageBox.critical(self, "Error",
"Could not perform action on package %s: %s" % (packagename, e))
raise
class ProjectFlagsDialog(QtGui.QDialog):
"""
ProjectFlagsDialog()
Project flags configuration dialog
"""
def __init__(self, project, flags, parent=None):
QtGui.QDialog.__init__(self, parent)
self.setWindowTitle("Project Flags for %s" % project)
self.autoscrollcheckbox = QtGui.QCheckBox("Automatically scroll to the bottom of finished build logs")
layout = QtGui.QVBoxLayout()
layout.addWidget(self.autoscrollcheckbox)
buttonlayout = QtGui.QHBoxLayout()
buttonlayout.addStretch(1)
ok = QtGui.QPushButton('Ok')
self.connect(ok, QtCore.SIGNAL('clicked()'), self.accept)
buttonlayout.addWidget(ok)
cancel = QtGui.QPushButton('Cancel')
self.connect(cancel, QtCore.SIGNAL('clicked()'), self.reject)
buttonlayout.addWidget(cancel)
layout.addLayout(buttonlayout)
self.setLayout(layout)
#
# Result widget
#
class ResultWidget(QtGui.QWidget):
"""
ResultWidget(bs, cfg)
Build Service status viewer widget. bs is a BuildService object and cfg is a ConfigParser object
"""
def __init__(self, parent, bs, cfg):
QtGui.QWidget.__init__(self)
self.viewable = False
self.parent = parent
# BuildService object
self.bs = bs
# Config object
self.cfg = cfg
# Convenience attributes
self.currentproject = ''
self.initialprojectrefresh = True
# Project list selector
self.projectlistselector = QtGui.QComboBox()
self.projectlistselector.addItem("Watched Projects")
self.projectlistselector.addItem("All Projects")
if self.cfg.has_option('persistence', 'projectlist'):
self.projectlistselector.setCurrentIndex(self.cfg.getint('persistence', 'projectlist'))
QtCore.QObject.connect(self.projectlistselector, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.refreshProjectList)
# The project list
self.projecttreeview = ProjectTreeView(self.bs)
self.projecttreeview.setRootIsDecorated(False)
self.projectlistmodel = QtGui.QStandardItemModel(0, 1, self)
self.projectlistmodel.setHeaderData(0, QtCore.Qt.Horizontal, QtCore.QVariant("Project"))
self.projectlistthread = ProjectListThread(self.bs)
self.refreshProjectList()
self.projecttreeview.setModel(self.projectlistmodel)
QtCore.QObject.connect(self.projecttreeview, QtCore.SIGNAL("clicked(const QModelIndex&)"), self.projectSelected)
QtCore.QObject.connect(self.projecttreeview, QtCore.SIGNAL("watchedProjectsChanged()"), self.refreshProjectList)
QtCore.QObject.connect(self.projectlistthread, QtCore.SIGNAL("finished()"), self.updateProjectList)
# Filter widgets
searchlabel = QtGui.QLabel("Search")
self.searchedit = QtGui.QLineEdit()
QtCore.QObject.connect(self.searchedit, QtCore.SIGNAL("textChanged(const QString&)"), self.filterPackages)
targetlabel = QtGui.QLabel("Target")
self.targetselector = QtGui.QComboBox()
self.targetselector.setSizeAdjustPolicy(QtGui.QComboBox.AdjustToContents)
self.targetselector.addItem("All")
QtCore.QObject.connect(self.targetselector, QtCore.SIGNAL("currentIndexChanged(const QString&)"), self.filterTarget)
self.resulttab = QtGui.QTabBar()
QtCore.QObject.connect(self.resulttab, QtCore.SIGNAL("currentChanged(int)"), self.filterResult)
self.tabs = []
for tabname in ('All', 'Succeeded', 'Failed', 'Building', 'Blocked', 'Scheduled', 'Expansion Error', 'Broken', 'Disabled'):
self.resulttab.addTab(tabname)
self.tabs.append(tabname)
# Project results
self.resultview = ResultTreeView(self)
self.resultview.setRootIsDecorated(False)
self.resultmodel = ResultModel()
self.resultview.setModel(self.resultmodel)
QtCore.QObject.connect(self.resultview, QtCore.SIGNAL("clicked(const QModelIndex&)"), self.refreshPackageInfo)
# Result refresh
self.refreshtimer = QtCore.QTimer()
QtCore.QObject.connect(self.refreshtimer, QtCore.SIGNAL("timeout()"), self.timerRefresh)
self.projectresultsthread = ProjectResultsThread(self.bs)
QtCore.QObject.connect(self.projectresultsthread, QtCore.SIGNAL("finished()"), self.updatePackageList)
# Package info
self.packageinfo = QtGui.QTextBrowser()
self.packageinfo.setReadOnly(True)
self.packageinfo.setOpenLinks(False)
QtCore.QObject.connect(self.packageinfo, QtCore.SIGNAL("anchorClicked(const QUrl&)"), self.infoClick)
self.packagestatusthread = PackageStatusThread(self.bs)
QtCore.QObject.connect(self.packagestatusthread, QtCore.SIGNAL("finished()"), self.updatePackageInfo)
# Stream parameters and timer
self.streamtimer = QtCore.QTimer()
QtCore.QObject.connect(self.streamtimer, QtCore.SIGNAL("timeout()"), self.requestBuildOutput)
self.buildlogthread = BuildLogThread(self.bs)
QtCore.QObject.connect(self.buildlogthread, QtCore.SIGNAL("finished()"), self.updateBuildOutput)
# Layout
projectlistlayout = QtGui.QVBoxLayout()
projectlistlayout.addWidget(self.projectlistselector)
projectlistlayout.addWidget(self.projecttreeview)
filterlayout = QtGui.QHBoxLayout()
filterlayout.addWidget(searchlabel)
filterlayout.addWidget(self.searchedit)
filterlayout.addWidget(targetlabel)
filterlayout.addWidget(self.targetselector)
packagelistlayout = QtGui.QVBoxLayout()
packagelistlayout.addLayout(filterlayout)
packagelistlayout.addWidget(self.resulttab)
packagelistlayout.addWidget(self.resultview)
packagelistlayout.addWidget(self.packageinfo)
mainlayout = QtGui.QHBoxLayout()
mainlayout.addLayout(projectlistlayout)
mainlayout.addLayout(packagelistlayout, 1)
self.setLayout(mainlayout)
def enableRefresh(self, now=False):
"""
enableRefresh()
Enable widget data refresh
"""
if now:
self.refreshPackageLists(self.currentproject)
else:
self.refreshtimer.start(self.cfg.getint('general', 'refreshinterval')*1000)
def disableRefresh(self):
"""
disableRefresh()
Disable widget data refresh
"""
self.refreshtimer.stop()
#
# Slots
#
def setApiurl(self, apiurl):
"""
setApiurl(apiurl)
Set the buildservice API URL
"""
self.bs.apiurl = apiurl
self.currentproject = ""
self.refreshProjectList()
def refreshProjectList(self, dummy=None):
"""
refreshProjectList(dummy=None)
Refresh the project list from the current buildservice API
"""
if str(self.projectlistselector.currentText()) == "Watched Projects":
self.projectlistthread.watched = True
else:
self.projectlistthread.watched = False
self.parent.statusBar().showMessage("Retrieving project list")
self.projectlistthread.start()
def updateProjectList(self):
"""
updateProjectList()
Update project list from result in self.projectlistthread
"""
if self.viewable:
self.parent.statusBar().clearMessage()
self.projectlistmodel.clear()
for project in sorted(self.projectlistthread.projects):
si = QtGui.QStandardItem(project)
si.setEditable(False)
self.projectlistmodel.appendRow(si)
self.projectlistmodel.setHeaderData(0, QtCore.Qt.Horizontal, QtCore.QVariant("Project"))
self.projecttreeview.sortByColumn(0, QtCore.Qt.AscendingOrder)
if self.initialprojectrefresh:
self.initialprojectrefresh = False
if self.cfg.has_option('persistence', 'project'):
lastproject = self.cfg.get('persistence', 'project')
if lastproject in self.projectlistthread.projects:
self.currentproject = lastproject
self.targetselector.clear()
self.targetselector.addItem("All")
self.targetselector.addItems(self.bs.getTargets(lastproject))
self.refreshPackageLists(lastproject)
def refreshPackageLists(self, project):
"""
refreshPackageLists(project)
Refresh the package lists to show results for the specified project
"""
self.disableRefresh()
self.projectresultsthread.project = project
self.parent.statusBar().showMessage("Retrieving package results for %s" % project)
self.projectresultsthread.start()
def updatePackageList(self):
"""
updatePackageList()
Update package list data from result in self.projectresultsthread
"""
if self.viewable:
self.parent.statusBar().clearMessage()
results = self.projectresultsthread.results
targets = self.projectresultsthread.targets
self.resultmodel.setResults(results, targets)
self.resizeColumns()
self.updateResultCounts()
if self.viewable:
self.enableRefresh()
def projectSelected(self, modelindex):
"""
projectSelected(self, modelindex)
Set the current project to that represented by QModelIndex modelindex and refresh the
package lists
"""
self.currentproject = str(self.projectlistmodel.data(modelindex, QtCore.Qt.DisplayRole).toString())
self.targetselector.clear()
self.targetselector.addItem("All")
self.targetselector.addItems(self.bs.getTargets(self.currentproject))
self.refreshPackageLists(self.currentproject)
def timerRefresh(self):
"""
timerRefresh()
Refresh the package lists from a timer signal
"""
if self.currentproject:
self.refreshPackageLists(self.currentproject)
def refreshPackageInfo(self, modelindex):
"""
refreshPackageInfo(modelindex)
Refresh the package info for the package represented by QModelIndex modelindex
"""
# If we're streaming a log file, stop
self.streamtimer.stop()
tabname = self.tabs[self.resulttab.currentIndex()]
column = modelindex.column()
row = modelindex.row()
package = self.resultmodel.packageFromRow(row)
if column > 0:
statuscode = self.resultmodel._data(row, column)
if statuscode in ("succeeded", "building", "failed"):
target = self.resultmodel.visibletargets[column-1]
self.viewBuildOutput(target, package)
return
self.packagestatusthread.project = self.currentproject
self.packagestatusthread.package = package
self.parent.statusBar().showMessage("Getting package status for %s" % package)
self.packagestatusthread.start()
def updatePackageInfo(self):
"""
updatePackageInfo()
Update the pkginfo pane to the result from self.packagestatusthread
"""
if self.viewable:
self.parent.statusBar().clearMessage()
package = self.packagestatusthread.package
pitext = "<h2>%s</h2>" % package
pitext += "<table width='90%'>"
status = self.packagestatusthread.status
for target in sorted(status.keys()):
statustext = status[target]
code = statustext.split(':')[0]
if code == "succeeded":
color = "green"
elif code == "building":
color = "blue"
elif code == "disabled":
color = "gray"
elif code in ('failed', 'expansion error'):
color = "red"
else:
color = "black"
pitext += "<tr><td><b>%s</b></td><td><font color='%s'><b>" % (target, color)
if code in ('succeeded', 'building', 'failed'):
pitext += "<a href='buildlog,%s,%s'>%s</a>" % (target, package, statustext)
else:
pitext += statustext
pitext += "</b></font></td>"
pitext += "<td><a href='buildhistory,%s,%s'><b>buildhistory</b></a></td>" % (target, package)
pitext += "<td><a href='binaries,%s,%s'><b>binaries</b></a></td></tr>" % (target, package)
pitext += "</table>"
pitext += "<p><a href='commitlog,%s'><b>commitlog</b></a></p>" % package
self.packageinfo.setWordWrapMode(QtGui.QTextOption.WordWrap)
self.packageinfo.setText(pitext)
def infoClick(self, url):
"""
infoClick(url)
Handle url clicks in the package info view
"""
args = str(url.toString()).split(',')
if args[0] == 'buildlog':
self.viewBuildOutput(*args[1:])
elif args[0] == 'binaries':
self.viewBinaries(*args[1:])
elif args[0] == 'getbinary':
self.getBinary(*args[1:])
elif args[0] == 'buildhistory':
self.viewBuildHistory(*args[1:])
elif args[0] == 'commitlog':
self.viewCommitLog(*args[1:])
def viewBinaries(self, target, package):
"""
viewBinaries(target, package)
View binaries for target and package
"""
pitext = "<h2>%s binaries for %s</h2>" % (package, target)
binaries = self.bs.getBinaryList(self.currentproject, target, package)
if binaries:
pitext += "<table>"
for binary in sorted(binaries):
pitext += "<tr><td><a href='getbinary,%s,%s,%s'>%s</a></td></tr>" % (target, package, binary, binary)
pitext += "</table>"
else:
pitext += "<b>No binaries</b>"
self.packageinfo.setWordWrapMode(QtGui.QTextOption.WordWrap)
self.packageinfo.setText(pitext)
def getBinary(self, target, package, file):
"""
getBinary(target, file)
Save 'file' in 'target' to a local path
"""
path = QtGui.QFileDialog.getSaveFileName(self,
"Save binary",
os.path.join(os.environ['HOME'], file),
"RPM Files (*.rpm);;All Files (*.*)")
if path:
try:
self.bs.getBinary(self.currentproject, target, package, file, path)
except Exception, e:
QtGui.QMessageBox.critical(self, "Binary Save Error",
"Could not save binary to %s: %s" % (path, e))
raise
def viewBuildHistory(self, target, package):
"""
viewBuildHistory(target, package)
View build history of package for target
"""
pitext = "<h2>Build History of %s for %s</h2>" % (package, target)
history = self.bs.getBuildHistory(self.currentproject, package, target)
if history:
pitext += "<table width='90%'><tr><td><b>Time</b></td><td><b>Source MD5</b></td><td><b>Revision</b></td><td><b>Version-Release.Buildcount</b></td></tr>"
for entry in history:
pitext += "<tr><td>%s</td><td>%s</td><td>%s</td><td>%s.%s</td></tr>" % entry
pitext += "</table>"
else:
pitext += "<b>No history</b>"
self.packageinfo.setWordWrapMode(QtGui.QTextOption.WordWrap)
self.packageinfo.setText(pitext)
def viewCommitLog(self, package):
"""
viewCommitLog(package)
View commit log of package
"""
pitext = "<h2>Commit Log of %s</h2>" % package
commitlog = self.bs.getCommitLog(self.currentproject, package)
if commitlog:
for entry in commitlog:
pitext += "<hr/><p>Revision <b>%s</b> - MD5 <b>%s</b> - Version <b>%s</b><br/>Modified <em>%s</em> by <em>%s</em><pre>%s</pre></p>" % entry
else:
pitext += "<b>No log</b>"
self.packageinfo.setWordWrapMode(QtGui.QTextOption.WordWrap)
self.packageinfo.setText(pitext)
def viewBuildOutput(self, target, package):
"""
viewBuildOutput(target, package)
Show build output for target and package. If the package is currently
building, stream the output until it is finished
"""
self.packageinfo.clear()
# For some reason, the font is set to whatever the calling link had. Argh
self.packageinfo.setCurrentFont(QtGui.QFont("Bitstream Vera Sans Mono", 7))
self.packageinfo.setTextColor(QtGui.QColor('black'))
self.packageinfo.setWordWrapMode(QtGui.QTextOption.NoWrap)
self.buildlogthread.project = self.currentproject
self.buildlogthread.target = target
self.buildlogthread.package = package
self.buildlogthread.offset = 0
if self.bs.getPackageStatus(self.currentproject, package)[target].startswith('building'):
self.buildlogthread.live = True
else:
self.buildlogthread.live = False
self.parent.statusBar().showMessage("Retrieving build log for %s" % package)
self.requestBuildOutput()
def requestBuildOutput(self):
"""
requestBuildOutput()
Send request to update streaming build output, based on existing buildlogthread parameters
"""
self.buildlogthread.start()
def updateBuildOutput(self):
"""
updateBuildOutput()
Update the build output
"""
if self.viewable:
self.parent.statusBar().clearMessage()
self.streamtimer.stop()
if self.buildlogthread.live:
log_chunk = self.buildlogthread.log_chunk
self.buildlogthread.offset += len(log_chunk)
self.packageinfo.append(log_chunk.strip())
if not len(log_chunk) == 0 and self.viewable:
self.streamtimer.start(1000)
else:
self.packageinfo.setPlainText(self.buildlogthread.log_chunk)
if self.cfg.getboolean('general', 'autoscroll'):
self.packageinfo.moveCursor(QtGui.QTextCursor.End)
def filterPackages(self, filterstring):
"""
filterPackages(filterstring)
Show only packages that match filterstring
"""
self.resultmodel.setPackageFilter(str(filterstring))
self.resizeColumns()
self.updateResultCounts()
def filterTarget(self, target):
if target != 'All':
self.resultmodel.setTargetFilter(str(target))
else:
self.resultmodel.setTargetFilter()
self.resizeColumns()
self.updateResultCounts()
def filterResult(self, resultindex):
if self.tabs:
result = self.tabs[resultindex]
if result != 'All':
self.resultmodel.setResultFilter(result)
else:
self.resultmodel.setResultFilter()
self.resizeColumns()
self.updateResultCounts()
def resizeColumns(self):
"""
resizeColumns()
Resize columns to fit contents
"""
for column in range(self.resultmodel.columnCount()):
self.resultview.resizeColumnToContents(column)
def updateResultCounts(self):
"""
updateResultCounts()
Update package counts for result tabs
"""
for tab in self.tabs:
self.resulttab.setTabText(self.tabs.index(tab), "%s (%d)" % (tab, self.resultmodel.numPackagesWithResult(tab)))<|fim▁end|> | return len(self.visiblepackages) |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>//= require active_admin/base<|fim▁hole|>//= require bootstrap
//= require bootstrap-wysihtml5
//= require ./active_tweaker<|fim▁end|> | //= require jquery.nested-fields
//= require chosen-jquery |
<|file_name|>formatting_helper.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the output module field formatting helper."""
import unittest
from dfdatetime import semantic_time as dfdatetime_semantic_time
from dfvfs.path import fake_path_spec
from plaso.containers import events
from plaso.lib import definitions
from plaso.output import formatting_helper
from tests.containers import test_lib as containers_test_lib
from tests.output import test_lib
class TestFieldFormattingHelper(formatting_helper.FieldFormattingHelper):
"""Field formatter helper for testing purposes."""
_FIELD_FORMAT_CALLBACKS = {'zone': '_FormatTimeZone'}
class FieldFormattingHelperTest(test_lib.OutputModuleTestCase):
"""Test the output module field formatting helper."""
# pylint: disable=protected-access
_TEST_EVENTS = [
{'data_type': 'test:event',
'filename': 'log/syslog.1',
'hostname': 'ubuntu',
'path_spec': fake_path_spec.FakePathSpec(
location='log/syslog.1'),
'text': (
'Reporter <CRON> PID: 8442 (pam_unix(cron:session): session\n '
'closed for user root)'),
'timestamp': '2012-06-27 18:17:01',
'timestamp_desc': definitions.TIME_DESCRIPTION_CHANGE}]
def testFormatDateTime(self):
"""Tests the _FormatDateTime function with dynamic time."""
output_mediator = self._CreateOutputMediator()
test_helper = formatting_helper.FieldFormattingHelper(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0]))
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '2012-06-27T18:17:01.000000+00:00')
output_mediator.SetTimezone('Europe/Amsterdam')
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '2012-06-27T20:17:01.000000+02:00')
output_mediator.SetTimezone('UTC')
event.date_time = dfdatetime_semantic_time.InvalidTime()
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, 'Invalid')
def testFormatDateTimeWithoutDynamicTime(self):
"""Tests the _FormatDateTime function without dynamic time."""
output_mediator = self._CreateOutputMediator(dynamic_time=False)
test_helper = formatting_helper.FieldFormattingHelper(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0]))
# Test with event.date_time
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '2012-06-27T18:17:01.000000+00:00')
output_mediator.SetTimezone('Europe/Amsterdam')
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '2012-06-27T20:17:01.000000+02:00')
output_mediator.SetTimezone('UTC')
event.date_time = dfdatetime_semantic_time.InvalidTime()
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '0000-00-00T00:00:00.000000+00:00')
# Test with event.timestamp
event.date_time = None
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '2012-06-27T18:17:01.000000+00:00')
event.timestamp = 0
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '0000-00-00T00:00:00.000000+00:00')
event.timestamp = -9223372036854775808
date_time_string = test_helper._FormatDateTime(
event, event_data, event_data_stream)
self.assertEqual(date_time_string, '0000-00-00T00:00:00.000000+00:00')
def testFormatDisplayName(self):
"""Tests the _FormatDisplayName function."""
output_mediator = self._CreateOutputMediator()
test_helper = formatting_helper.FieldFormattingHelper(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0]))
display_name_string = test_helper._FormatDisplayName(
event, event_data, event_data_stream)
self.assertEqual(display_name_string, 'FAKE:log/syslog.1')
def testFormatFilename(self):
"""Tests the _FormatFilename function."""
output_mediator = self._CreateOutputMediator()
test_helper = formatting_helper.FieldFormattingHelper(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0]))
filename_string = test_helper._FormatFilename(
event, event_data, event_data_stream)
self.assertEqual(filename_string, 'log/syslog.1')
def testFormatHostname(self):
"""Tests the _FormatHostname function."""
output_mediator = self._CreateOutputMediator()
test_helper = formatting_helper.FieldFormattingHelper(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0]))
hostname_string = test_helper._FormatHostname(
event, event_data, event_data_stream)
self.assertEqual(hostname_string, 'ubuntu')
def testFormatInode(self):
"""Tests the _FormatInode function."""
output_mediator = self._CreateOutputMediator()
test_helper = formatting_helper.FieldFormattingHelper(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0]))
inode_string = test_helper._FormatInode(
event, event_data, event_data_stream)
self.assertEqual(inode_string, '-')
def testFormatMACB(self):
"""Tests the _FormatMACB function."""
output_mediator = self._CreateOutputMediator()
test_helper = formatting_helper.FieldFormattingHelper(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0]))
macb_string = test_helper._FormatMACB(event, event_data, event_data_stream)
self.assertEqual(macb_string, '..C.')
def testFormatMessage(self):
"""Tests the _FormatMessage function."""
output_mediator = self._CreateOutputMediator()
formatters_directory_path = self._GetTestFilePath(['formatters'])
output_mediator.ReadMessageFormattersFromDirectory(
formatters_directory_path)
test_helper = formatting_helper.FieldFormattingHelper(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0]))
message_string = test_helper._FormatMessage(
event, event_data, event_data_stream)
expected_message_string = (
'Reporter <CRON> PID: 8442 (pam_unix(cron:session): session closed '
'for user root)')
self.assertEqual(message_string, expected_message_string)
def testFormatMessageShort(self):
"""Tests the _FormatMessageShort function."""
output_mediator = self._CreateOutputMediator()
formatters_directory_path = self._GetTestFilePath(['formatters'])
output_mediator.ReadMessageFormattersFromDirectory(
formatters_directory_path)
test_helper = formatting_helper.FieldFormattingHelper(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0]))
message_short_string = test_helper._FormatMessageShort(
event, event_data, event_data_stream)
expected_message_short_string = (
'Reporter <CRON> PID: 8442 (pam_unix(cron:session): session closed '
'for user root)')
self.assertEqual(message_short_string, expected_message_short_string)
def testFormatSource(self):
"""Tests the _FormatSource function."""
output_mediator = self._CreateOutputMediator()
test_helper = formatting_helper.FieldFormattingHelper(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0]))
source_string = test_helper._FormatSource(
event, event_data, event_data_stream)
self.assertEqual(source_string, 'Test log file')
def testFormatSourceShort(self):
"""Tests the _FormatSourceShort function."""
output_mediator = self._CreateOutputMediator()
test_helper = formatting_helper.FieldFormattingHelper(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0]))
source_short_string = test_helper._FormatSourceShort(
event, event_data, event_data_stream)
self.assertEqual(source_short_string, 'FILE')
def testFormatTag(self):
"""Tests the _FormatTag function."""
output_mediator = self._CreateOutputMediator()
test_helper = formatting_helper.FieldFormattingHelper(output_mediator)
tag_string = test_helper._FormatTag(None)
self.assertEqual(tag_string, '-')
event_tag = events.EventTag()
event_tag.AddLabel('one')
event_tag.AddLabel('two')
tag_string = test_helper._FormatTag(event_tag)
self.assertEqual(tag_string, 'one two')
def testFormatTime(self):
"""Tests the _FormatTime function."""
output_mediator = self._CreateOutputMediator()
test_helper = formatting_helper.FieldFormattingHelper(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0]))
# Test with event.date_time
time_string = test_helper._FormatTime(
event, event_data, event_data_stream)
self.assertEqual(time_string, '18:17:01')
output_mediator.SetTimezone('Europe/Amsterdam')
time_string = test_helper._FormatTime(
event, event_data, event_data_stream)
self.assertEqual(time_string, '20:17:01')
output_mediator.SetTimezone('UTC')
# Test with event.timestamp
event.date_time = None
time_string = test_helper._FormatTime(
event, event_data, event_data_stream)
self.assertEqual(time_string, '18:17:01')
event.timestamp = 0
time_string = test_helper._FormatTime(
event, event_data, event_data_stream)
self.assertEqual(time_string, '--:--:--')
event.timestamp = -9223372036854775808
time_string = test_helper._FormatTime(
event, event_data, event_data_stream)
self.assertEqual(time_string, '--:--:--')
def testFormatTimeZone(self):
"""Tests the _FormatTimeZone function."""
output_mediator = self._CreateOutputMediator()
test_helper = formatting_helper.FieldFormattingHelper(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0]))
zone_string = test_helper._FormatTimeZone(
event, event_data, event_data_stream)
self.assertEqual(zone_string, 'UTC')
def testFormatUsername(self):
"""Tests the _FormatUsername function."""
output_mediator = self._CreateOutputMediator()
test_helper = formatting_helper.FieldFormattingHelper(output_mediator)
event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0]))
username_string = test_helper._FormatUsername(
event, event_data, event_data_stream)
self.assertEqual(username_string, '-')
# TODO: add coverage for _ReportEventError
def testGetFormattedField(self):
"""Tests the GetFormattedField function."""
output_mediator = self._CreateOutputMediator()
test_helper = TestFieldFormattingHelper(output_mediator)
<|fim▁hole|> 'zone', event, event_data, event_data_stream, None)
self.assertEqual(zone_string, 'UTC')
if __name__ == '__main__':
unittest.main()<|fim▁end|> | event, event_data, event_data_stream = (
containers_test_lib.CreateEventFromValues(self._TEST_EVENTS[0]))
zone_string = test_helper.GetFormattedField( |
<|file_name|>UnknownStrategyRepository.java<|end_file_name|><|fim▁begin|>/*******************************************************************************
* Copyright 2002-2016 the original author or 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<|fim▁hole|>
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
import com.github.lothar.security.acl.elasticsearch.domain.UnknownStrategyObject;
@Repository
public interface UnknownStrategyRepository
extends ElasticsearchRepository<UnknownStrategyObject, Long> {
}<|fim▁end|> | * or implied. See the License for the specific language governing permissions and limitations under
* the License.
*******************************************************************************/
package com.github.lothar.security.acl.elasticsearch.repository; |
<|file_name|>before.js<|end_file_name|><|fim▁begin|>/**
* before : before(el, newEl)<|fim▁hole|> * var before = require('dom101/before');
* var newNode = document.createElement('div');
* var button = document.querySelector('#submit');
*
* before(button, newNode);
*/
function before (el, newEl) {
if (typeof newEl === 'string') {
return el.insertAdjacentHTML('beforebegin', newEl)
} else {
return el.parentNode.insertBefore(newEl, el)
}
}
module.exports = before<|fim▁end|> | * Inserts a new element `newEl` just before `el`.
* |
<|file_name|>EmailFilter.java<|end_file_name|><|fim▁begin|>package com.example.aperture.core.contacts;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import java.util.List;
import java.util.ArrayList;
import com.example.aperture.core.Module;
public class EmailFilter extends Filter {
private final static String[] DATA_PROJECTION = new String[] {
ContactsContract.Contacts.LOOKUP_KEY,
ContactsContract.Contacts.DISPLAY_NAME_PRIMARY,
ContactsContract.Data.DATA1
};
private final static String MIMETYPE_SELECTION =
ContactsContract.Data.MIMETYPE + "=?";
private final static String[] EMAIL_MIMETYPE = new String[] {
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
};
private final static String[] PREFIXES = new String[] {
"send an email to ",
"send email to ",
"email "<|fim▁hole|> private String mFragment;
public EmailComparer(String fragment) {
mFragment = fragment;
}
@Override
public boolean equals(Object o) { return false; }
@Override
public int compare(Intent a, Intent b) {
// Get the emails from the intents.
String x = a.getStringExtra(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
String y = b.getStringExtra(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
// Split the emails into usernames and domains.
String xu = x.substring(0, x.indexOf('@'));
String yu = y.substring(0, y.indexOf('@'));
String xd = x.substring(x.indexOf('@')+1);
String yd = y.substring(y.indexOf('@')+1);
// Get the locations of the query in the usernames and domains.
int ixu = xu.indexOf(mFragment), iyu = yu.indexOf(mFragment);
int ixd = xd.indexOf(mFragment), iyd = yd.indexOf(mFragment);
// TODO refactor this to be less iffy
// Explicitly writing out the comparision logic to avoid violating
// general sorting contract for total ordering.
if(ixu != -1 && iyu != -1) {
if(ixu < iyu) return -1;
else if(iyu < ixu) return 1;
else return xu.compareTo(yu);
}
else if(ixu != -1 && iyu == -1) {
return -1;
}
else if(ixu == -1 && iyu != -1) {
return 1;
}
else {
if(ixd != -1 && iyd != -1) {
if(ixd < iyd) return -1;
else if(iyd < ixd) return 1;
else return xd.compareTo(yd);
}
else if(ixd != -1 && iyd == -1) {
return -1;
}
else if(ixd == -1 && iyd != -1) {
return 1;
}
else
return x.compareTo(y);
}
}
}
private void sort(List<Intent> results, String query) {
Intent[] buffer = new Intent[results.size()];
java.util.Arrays.sort(results.toArray(buffer), 0, buffer.length,
new EmailComparer(query));
results.clear();
for(int i = 0; i < buffer.length; ++i)
results.add(buffer[i]);
}
@Override
public List<Intent> filter(Context context, String query) {
List<Intent> results = new ArrayList<Intent>();
boolean hasPrefix = false;
for(String prefix: PREFIXES) {
if(query.startsWith(prefix)) {
query = query.substring(prefix.length());
hasPrefix = true;
break;
}
}
Cursor data = context.getContentResolver().query(
ContactsContract.Data.CONTENT_URI,
DATA_PROJECTION,
MIMETYPE_SELECTION,
EMAIL_MIMETYPE,
null);
if(hasPrefix)
results.addAll(filterByName(data, query));
results.addAll(filterByAddress(data, query));
data.close();
return results;
}
private List<Intent> filterByName(Cursor data, String query) {
List<Intent> results = new ArrayList<Intent>();
query = query.toLowerCase();
for(data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
String name = data.getString(1).toLowerCase();
if(name.contains(query))
results.add(intentFor(data.getString(1), data.getString(2)));
}
return results;
}
private List<Intent> filterByAddress(Cursor data, String query) {
List<Intent> results = new ArrayList<Intent>();
for(data.moveToFirst(); !data.isAfterLast(); data.moveToNext()) {
String email = data.getString(2);
if(email.contains(query))
results.add(intentFor(data.getString(1), email));
}
sort(results, query);
return results;
}
private Intent intentFor(String displayName, String email) {
Intent result = new Intent(Intent.ACTION_SENDTO,
new Uri.Builder().scheme("mailto").opaquePart(email).build());
result.putExtra(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, email);
result.putExtra(Module.RESPONSE_TEXT,
String.format("%1$s <%2$s>", displayName, email));
return result;
}
}<|fim▁end|> | };
private final static class EmailComparer implements java.util.Comparator<Intent> { |
<|file_name|>ListComprehension-after.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | records = [select.query.decode(r) for r in records] |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from distutils.core import setup
setup(
name = 'moretext',
packages = ['moretext'],
version = '0.1',<|fim▁hole|> description = 'Get dummy Chinese text (lorem ipsum) with Handlino serivce.',
author = 'Pomin Wu',
author_email = '[email protected]',
url = 'https://github.com/pm5/python-moretext',
download_url = 'https://github.com/pm5/python-moretext/tarball/v0.1',
keywords = ['test', 'lorem', 'ipsum', 'placeholder'],
classifiers = [],
)<|fim▁end|> | |
<|file_name|>074_First_Bad_Version.py<|end_file_name|><|fim▁begin|>#class SVNRepo:
# @classmethod
# def isBadVersion(cls, id)
# # Run unit tests to check whether verison `id` is a bad version<|fim▁hole|>class Solution:
"""
@param n: An integers.
@return: An integer which is the first bad version.
"""
def findFirstBadVersion(self, n):
# write your code here
start, end = 1, n
if (n == 1):
return 1
while (start <= end):
i = (start + end) / 2
if (not SVNRepo.isBadVersion(i)):
start = i + 1
else:
end = i - 1
return start<|fim▁end|> | # # return true if unit tests passed else false.
# You can use SVNRepo.isBadVersion(10) to check whether version 10 is a
# bad version. |
<|file_name|>hobbies.js<|end_file_name|><|fim▁begin|>var changeSpan;<|fim▁hole|>
var hobbies = [
'Music',
'HTML5',
'Learning',
'Exploring',
'Art',
'Teaching',
'Virtual Reality',
'The Cosmos',
'Unity3D',
'Tilemaps',
'Reading',
'Butterscotch',
'Drawing',
'Taking Photos',
'Smiles',
'The Poetics of Space',
'Making Sounds',
'Board games',
'Travelling',
'Sweetened condensed milk'
];
function changeWord() {
changeSpan.textContent = hobbies[i];
i++;
if (i >= hobbies.length) i = 0;
}
function init() {
console.log('initialising scrolling text');
changeSpan = document.getElementById("scrollingText");
nIntervId = setInterval(changeWord, 950);
changeWord();
}
if (document.addEventListener) {
init();
} else {
init();
}<|fim▁end|> | var i = 0; |
<|file_name|>test_tag.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import fauxfactory
import pytest
from cfme.configure.configuration import Category, Tag
from cfme.rest.gen_data import a_provider as _a_provider
from cfme.rest.gen_data import categories as _categories
from cfme.rest.gen_data import dialog as _dialog
from cfme.rest.gen_data import services as _services
from cfme.rest.gen_data import service_catalogs as _service_catalogs
from cfme.rest.gen_data import service_templates as _service_templates
from cfme.rest.gen_data import tenants as _tenants
from cfme.rest.gen_data import tags as _tags
from cfme.rest.gen_data import vm as _vm
from utils.update import update
from utils.wait import wait_for
from utils import error
@pytest.yield_fixture
def category():
cg = Category(name=fauxfactory.gen_alphanumeric(8).lower(),
description=fauxfactory.gen_alphanumeric(32),
display_name=fauxfactory.gen_alphanumeric(32))
cg.create()
yield cg
cg.delete()
@pytest.mark.tier(2)
def test_tag_crud(category):
tag = Tag(name=fauxfactory.gen_alphanumeric(8).lower(),
display_name=fauxfactory.gen_alphanumeric(32),
category=category)
tag.create()
with update(tag):
tag.display_name = fauxfactory.gen_alphanumeric(32)
tag.delete(cancel=False)
class TestTagsViaREST(object):
@pytest.fixture(scope="function")
def categories(self, request, rest_api, num=3):
return _categories(request, rest_api, num)
@pytest.fixture(scope="function")
def tags(self, request, rest_api, categories):
return _tags(request, rest_api, categories)
@pytest.fixture(scope="module")
def categories_mod(self, request, rest_api_modscope, num=3):
return _categories(request, rest_api_modscope, num)
@pytest.fixture(scope="module")
def tags_mod(self, request, rest_api_modscope, categories_mod):
return _tags(request, rest_api_modscope, categories_mod)
@pytest.fixture(scope="module")
def service_catalogs(self, request, rest_api_modscope):
return _service_catalogs(request, rest_api_modscope)
@pytest.fixture(scope="module")
def tenants(self, request, rest_api_modscope):
return _tenants(request, rest_api_modscope, num=1)
@pytest.fixture(scope="module")
def a_provider(self):
return _a_provider()
@pytest.fixture(scope="module")
def dialog(self):
return _dialog()
@pytest.fixture(scope="module")
def services(self, request, rest_api_modscope, a_provider, dialog, service_catalogs):
try:
return _services(request, rest_api_modscope, a_provider, dialog, service_catalogs)
except:
pass
@pytest.fixture(scope="module")
def service_templates(self, request, rest_api_modscope, dialog):
return _service_templates(request, rest_api_modscope, dialog)
@pytest.fixture(scope="module")
def vm(self, request, a_provider, rest_api_modscope):
return _vm(request, a_provider, rest_api_modscope)
@pytest.mark.tier(2)
def test_edit_tags(self, rest_api, tags):
"""Tests tags editing from collection.
Metadata:
test_flag: rest
"""
new_names = []
tags_data_edited = []
for tag in tags:
new_name = "test_tag_{}".format(fauxfactory.gen_alphanumeric().lower())
new_names.append(new_name)
tag.reload()<|fim▁hole|> "name": new_name,
})
rest_api.collections.tags.action.edit(*tags_data_edited)
assert rest_api.response.status_code == 200
for new_name in new_names:
wait_for(
lambda: rest_api.collections.tags.find_by(name=new_name),
num_sec=180,
delay=10,
)
@pytest.mark.tier(2)
def test_edit_tag(self, rest_api, tags):
"""Tests tag editing from detail.
Metadata:
test_flag: rest
"""
tag = rest_api.collections.tags.get(name=tags[0].name)
new_name = 'test_tag_{}'.format(fauxfactory.gen_alphanumeric())
tag.action.edit(name=new_name)
assert rest_api.response.status_code == 200
wait_for(
lambda: rest_api.collections.tags.find_by(name=new_name),
num_sec=180,
delay=10,
)
@pytest.mark.tier(3)
@pytest.mark.parametrize("method", ["post", "delete"], ids=["POST", "DELETE"])
def test_delete_tags_from_detail(self, rest_api, tags, method):
"""Tests deleting tags from detail.
Metadata:
test_flag: rest
"""
status = 204 if method == "delete" else 200
for tag in tags:
tag.action.delete(force_method=method)
assert rest_api.response.status_code == status
with error.expected("ActiveRecord::RecordNotFound"):
tag.action.delete(force_method=method)
assert rest_api.response.status_code == 404
@pytest.mark.tier(3)
def test_delete_tags_from_collection(self, rest_api, tags):
"""Tests deleting tags from collection.
Metadata:
test_flag: rest
"""
rest_api.collections.tags.action.delete(*tags)
assert rest_api.response.status_code == 200
with error.expected("ActiveRecord::RecordNotFound"):
rest_api.collections.tags.action.delete(*tags)
assert rest_api.response.status_code == 404
@pytest.mark.tier(3)
def test_create_tag_with_wrong_arguments(self, rest_api):
"""Tests creating tags with missing category "id", "href" or "name".
Metadata:
test_flag: rest
"""
data = {
"name": "test_tag_{}".format(fauxfactory.gen_alphanumeric().lower()),
"description": "test_tag_{}".format(fauxfactory.gen_alphanumeric().lower())
}
with error.expected("BadRequestError: Category id, href or name needs to be specified"):
rest_api.collections.tags.action.create(data)
assert rest_api.response.status_code == 400
@pytest.mark.tier(3)
@pytest.mark.parametrize(
"collection_name", ["clusters", "hosts", "data_stores", "providers", "resource_pools",
"services", "service_templates", "tenants", "vms"])
def test_assign_and_unassign_tag(self, rest_api, tags_mod, a_provider, services,
service_templates, tenants, vm, collection_name):
"""Tests assigning and unassigning tags.
Metadata:
test_flag: rest
"""
collection = getattr(rest_api.collections, collection_name)
collection.reload()
if len(collection.all) == 0:
pytest.skip("No available entity in {} to assign tag".format(collection_name))
entity = collection[-1]
tag = tags_mod[0]
entity.tags.action.assign(tag)
assert rest_api.response.status_code == 200
entity.reload()
assert tag.id in [t.id for t in entity.tags.all]
entity.tags.action.unassign(tag)
assert rest_api.response.status_code == 200
entity.reload()
assert tag.id not in [t.id for t in entity.tags.all]<|fim▁end|> | tags_data_edited.append({
"href": tag.href, |
<|file_name|>TechDraw.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1">
<context>
<name>Cmd2LineCenterLine</name>
<message>
<source>Add Centerline between 2 Lines</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Cmd2PointCenterLine</name>
<message>
<source>Add Centerline between 2 Points</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdMidpoints</name>
<message>
<source>Add Midpoint Vertices</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdQuadrants</name>
<message>
<source>Add Quadrant Vertices</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDraw2LineCenterLine</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Centerline between 2 Lines</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDraw2PointCenterLine</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Centerline between 2 Points</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDraw2PointCosmeticLine</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Cosmetic Line Through 2 Points</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDraw3PtAngleDimension</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert 3-Point Angle Dimension</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawActiveView</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Active View (3D View)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawAngleDimension</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Angle Dimension</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawAnnotation</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Annotation</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawArchView</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Arch Workbench Object</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert a View of a Section Plane from Arch Workbench</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawBalloon</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Balloon Annotation</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawCenterLineGroup</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Center Line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Centerline to Faces</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawClipGroup</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Clip Group</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawClipGroupAdd</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add View to Clip Group</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawClipGroupRemove</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Remove View from Clip Group</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawCosmeticEraser</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Remove Cosmetic Object</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawCosmeticVertex</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Cosmetic Vertex</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawCosmeticVertexGroup</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Cosmetic Vertex</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Cosmetic Vertex</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawDecorateLine</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Change Appearance of Lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Change Appearance of selected Lines</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawDetailView</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Detail View</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawDiameterDimension</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Diameter Dimension</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawDimension</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Dimension</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawDraftView</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Draft Workbench Object</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert a View of a Draft Workbench object</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawExportPageDXF</name>
<message>
<source>File</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Export Page as DXF</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Save Dxf File</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dxf (*.dxf)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawExportPageSVG</name>
<message>
<source>File</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Export Page as SVG</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawExtensionCircleCenterLines</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Draw circle centerlines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Draw circle centerline cross at circles
- select many circles or arcs
- click this button</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawExtensionThreadBoltBottom</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Cosmetic thread bolt bottom view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Draw cosmetic screw thread ground view
- select many circles
- click this button</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawExtensionThreadBoltSide</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Cosmetic thread bolt side view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Draw cosmetic screw thread side view
- select two parallel lines
- click this button</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawExtensionThreadHoleBottom</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Cosmetic thread hole bottom view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Draw cosmetic hole thread ground view
- select many circles
- click this button</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawExtensionThreadHoleSide</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Cosmetic thread hole side view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Draw cosmetic thread hole side view
- select two parallel lines
- click this button</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawExtentGroup</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Extent Dimension</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Horizontal Extent</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Vertical Extent</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawFaceCenterLine</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Centerline to Faces</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawGeometricHatch</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Apply Geometric Hatch to Face</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawHatch</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Hatch a Face using Image File</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawHorizontalDimension</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Horizontal Dimension</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawHorizontalExtentDimension</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Horizontal Extent Dimension</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawImage</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Bitmap Image</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Bitmap from a file into a page</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select an Image File</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Image (*.png *.jpg *.jpeg)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawLandmarkDimension</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Landmark Dimension - EXPERIMENTAL</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawLeaderLine</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Leaderline to View</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawLengthDimension</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Length Dimension</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawLinkDimension</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Link Dimension to 3D Geometry</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawMidpoints</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Midpoint Vertices</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawPageDefault</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Default Page</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawPageTemplate</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Page using Template</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select a Template File</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Template (*.svg *.dxf)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawProjectionGroup</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Projection Group</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert multiple linked views of drawable object(s)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawQuadrants</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Quadrant Vertices</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawRadiusDimension</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Radius Dimension</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawRedrawPage</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Redraw Page</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawRichTextAnnotation</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Rich Text Annotation</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawSectionView</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Section View</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawShowAll</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show/Hide Invisible Edges</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawSpreadsheetView</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Spreadsheet View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert View to a spreadsheet</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawSymbol</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert SVG Symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert symbol from an SVG file</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawToggleFrame</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Turn View Frames On/Off</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawVerticalDimension</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Vertical Dimension</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawVerticalExtentDimension</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert Vertical Extent Dimension</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawView</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Insert a View</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>CmdTechDrawWeldSymbol</name>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Welding Information to Leaderline</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Command</name>
<message>
<source>Drawing create page</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Projection Group</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Clip</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ClipGroupAdd</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ClipGroupRemove</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create DraftView</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create ArchView</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create spreadsheet view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Save page to dxf</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Midpont Vertices</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Quadrant Vertices</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Annotation</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Dimension</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Hatch</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create GeomHatch</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Image</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Drag Balloon</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Drag Dimension</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Balloon</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create ActiveView</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create CenterLine</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Cosmetic Line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Update CosmeticLine</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Detail View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Update Detail</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Leader</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Edit Leader</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Anno</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Edit Anno</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Apply Quick</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Apply Aligned</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create SectionView</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create WeldSymbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Edit WeldSymbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Cosmetic Vertex</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>MRichTextEdit</name>
<message>
<source>Save changes</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Close editor</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Paragraph formatting</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Undo (CTRL+Z)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Undo</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Redo</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Cut (CTRL+X)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Cut</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Copy (CTRL+C)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Copy</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Paste (CTRL+V)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Paste</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Link (CTRL+L)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Link</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Bold</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Italic (CTRL+I)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Italic</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Underline (CTRL+U)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Underline</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Strikethrough</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Strike Out</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Bullet list (CTRL+-)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Ordered list (CTRL+=)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Decrease indentation (CTRL+,)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Decrease indentation</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Increase indentation (CTRL+.)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Increase indentation</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text foreground color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text background color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Background</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Font size</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>More functions</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Standard</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Heading 1</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Heading 2</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Heading 3</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Heading 4</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Monospace</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Remove character formatting</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Remove all formatting</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Edit document source</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Document source</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create a link</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Link URL:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select an image</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>JPEG (*.jpg);; GIF (*.gif);; PNG (*.png);; BMP (*.bmp);; All (*)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<source>Wrong selection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No Shapes, Groups or Links in this selection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select at least 1 DrawViewPart object as Base.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Incorrect selection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select an object first</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Too many objects selected</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create a page first.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No View of a Part in selection.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select one Clip group and one View.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select exactly one View to add to group.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select exactly one Clip group.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Clip and View must be from same Page.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select exactly one View to remove from Group.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>View does not belong to a Clip</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Choose an SVG file to open</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Scalable Vector Graphic</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>All Files</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select at least one object.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>There were no DraftWB objects in the selection.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Please select only 1 Arch Section.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No Arch Sections in selection.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select exactly one Spreadsheet object.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No Drawing View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Open Drawing View before attempting export to SVG.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Can not export selection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Page contains DrawViewArch which will not be exported. Continue?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Ellipse Curve Warning</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Selected edge is an Ellipse. Radius will be approximate. Continue?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>BSpline Curve Warning</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Selected edge is a BSpline. Radius will be approximate. Continue?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Incorrect Selection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Selected edge is an Ellipse. Diameter will be approximate. Continue?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Selected edge is a BSpline. Diameter will be approximate. Continue?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Need two straight edges to make an Angle Dimension</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Need three points to make a 3 point Angle Dimension</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>There is no 3D object in your selection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>There are no 3D Edges or Vertices in your selection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Selection Error</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Please select a View [and Edges].</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select 2 point objects and 1 View. (1)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select 2 point objects and 1 View. (2)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No Feature with Shape in selection.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Task In Progress</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Close active task dialog and try again.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Wrong Selection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Can not attach leader. No base View selected.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>You must select a base View for the line.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No DrawViewPart objects in this selection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No base View in Selection.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>You must select Faces or an existing CenterLine.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No CenterLine in selection.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Selection is not a CenterLine.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Selection not understood.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>You must select 2 Vertexes or an existing CenterLine.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Need 2 Vertices or 1 CenterLine.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Selection is empty.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Not enough points in selection.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Selection is not a Cosmetic Line.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>You must select 2 Vertexes.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Nothing selected</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>At least 1 object in selection is not a part view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Unknown object type in selection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No View in Selection.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>You must select a View and/or lines.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No Part Views in this selection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select exactly one Leader line or one Weld symbol.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Replace Hatch?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Some Faces in selection are already hatched. Replace?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No TechDraw Page</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Need a TechDraw Page for this command</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select a Face first</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No TechDraw object in selection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create a page to insert.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No Faces to hatch in this selection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No page found</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No Drawing Pages in document.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Which page?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Can not determine correct page.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Too many pages</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select only 1 page.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>PDF (*.pdf)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>All Files (*.*)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Export Page As PDF</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>SVG (*.svg)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Export page as SVG</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Are you sure you want to continue?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show drawing</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Toggle KeepUpdated</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Click to update text</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>New Leader Line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Edit Leader Line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Rich text creator</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Rich text editor</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>New Cosmetic Vertex</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select a symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ActiveView to TD View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Center Line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Edit Center Line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Section View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select at first an orientation</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Edit Section View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Operation Failed</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Welding Symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Edit Welding Symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Create Cosmetic Line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Edit Cosmetic Line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>New Detail View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Edit Detail View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Edit %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>TechDraw Circle Centerlines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Selection is empty</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>No object selected</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>TechDraw Thread Hole Side</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>TechDraw Thread Bolt Side</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>TechDraw Thread Hole Bottom</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>TechDraw Tread Bolt Bottom</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Please select two straight lines</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Std_Delete</name>
<message>
<source>You cannot delete this leader line because
it has a weld symbol that would become broken.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Object dependencies</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>You cannot delete the anchor view of a projection group.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>You cannot delete this view because it has a section view that would become broken.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>You cannot delete this view because it has a detail view that would become broken.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>You cannot delete this view because it has a leader line that would become broken.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>The page is not empty, therefore the
following referencing objects might be lost:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>The group cannot be deleted because its items have the following
section or detail views, or leader lines that would get broken:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>The projection group is not empty, therefore
the following referencing objects might be lost:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>The following referencing object might break:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>You cannot delete this weld symbol because
it has a tile weld that would become broken.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TaskActiveView</name>
<message>
<source>ActiveView to TD View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Width</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Width of generated view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Height</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Height of generated view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Border</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Minimal distance of the object from
the top and left view border</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Paint background yes/no</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Background</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Background color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line Width</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Width of lines in generated view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Render Mode</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Drawing style - see SoRenderManager</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>As is</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Wireframe</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Points</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Wireframe overlay</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Hidden Line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Bounding box</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TaskWeldingSymbol</name>
<message>
<source>Welding Symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text before arrow side symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text after arrow side symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Pick arrow side symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text above arrow side symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Pick other side symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text below other side symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text after other side symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Flips the sides</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Flip Sides</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text before other side symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Remove other side symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Delete</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Adds the 'Field Weld' symbol (flag)
at the kink in the leader line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Field Weld</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Adds the 'All Around' symbol (circle)
at the kink in the leader line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>All Around</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Offsets the lower symbol to indicate alternating welds</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Alternating</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Directory to welding symbols.
This directory will be used for the symbol selection.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>*.svg</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text at end of symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Symbol Directory</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Tail Text</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::DlgPrefsTechDrawAdvancedImp</name>
<message>
<source>Advanced</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Include 2D Objects in projection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show Loose 2D Geom</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Include edges with unexpected geometry (zero length etc.) in results</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Allow Crazy Edges</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Edge Fuzz</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Override automatic dimension format</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Shape of line end caps.
Only change unless you know what you are doing!</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Round</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Square</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Flat</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Perform a fuse operation on input shape(s) before Section view processing</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Fuse Before Section</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dimension Format</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line End Cap Shape</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dump intermediate results during Detail view processing</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Debug Detail</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Highlights border of section cut in section views</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show Section Edges</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Limit of 64x64 pixel SVG tiles used to hatch a single face.
For large scalings you might get an error about to many SVG tiles.
Then you need to increase the tile limit.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Max SVG Hatch Tiles</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Max PAT Hatch Segments</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Maximum hatch line segments to use
when hatching a face with a PAT pattern</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dump intermediate results during Section view processing</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Debug Section</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>If checked, TechDraw will attempt to build faces using the
line segments returned by the hidden line removal algorithm.
Faces must be detected in order to use hatching, but there
can be a performance penalty in complex models.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Detect Faces</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Mark Fuzz</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Size of selection area around edges
Each unit is approx. 0.1 mm wide</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Selection area around center marks
Each unit is approx. 0.1 mm wide</source>
<translation type="unfinished"></translation>
</message>
<message>
<source><html><head/><body><p><span style=" font-weight:600;">Note:</span> Items in <span style=" font-style:italic;">italics</span> are default values for new objects. They have no effect on existing objects.</p></body></html></source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::DlgPrefsTechDrawAnnotationImp</name>
<message>
<source>Annotation</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Center Line Style</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Style for section lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>NeverShow</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Continuous</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dash</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dot</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>DashDot</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>DashDotDot</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Section Line Standard</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Section Cut Surface</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Default appearance of cut surface in section view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Hide</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Solid Color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>SVG Hatch</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>PAT Hatch</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Forces last leader line segment to be horizontal</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Leader Line Auto Horizontal</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Length of balloon leader line kink</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Type for centerlines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Shape of balloon annotations</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Circular</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>None</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Triangle</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Inspection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Hexagon</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Square</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Rectangle</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Balloon Leader End</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Standard to be used to draw section lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ANSI</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ISO</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Outline shape for detail views</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Circle</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Section Line Style</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show arc center marks in views</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show Center Marks</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Detail View Outline Shape</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Style for balloon leader line ends</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Length of horizontal portion of Balloon leader</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Ballon Leader Kink Length</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Restrict Filled Triangle line end to vertical or horizontal directions</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Balloon Orthogonal Triangle</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line group used to set line widths</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line Width Group</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Balloon Shape</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show arc centers in printed output</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Print Center Marks</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line style of detail highlight on base view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Detail Highlight Style</source>
<translation type="unfinished"></translation>
</message>
<message>
<source><html><head/><body><p><span style=" font-weight:600;">Note:</span> Items in <span style=" font-style:italic;">italics</span> are default values for new objects. They have no effect on existing objects.</p></body></html></source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::DlgPrefsTechDrawColorsImp</name>
<message>
<source>Colors</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Normal</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Normal line color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Hidden Line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Hidden line color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Preselected</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Preselection color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Section Face</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Section face color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Selected</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Selected item color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Section Line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Section line color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Background</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Background color around pages</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Hatch</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Hatch image color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dimension</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Color of dimension lines and text.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Geometric Hatch</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Geometric hatch pattern color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Centerline</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Centerline color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Vertex</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Color of vertices in views</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Object faces will be transparent</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Transparent Faces</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Face color (if not transparent)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Detail Highlight</source>
<translation type="unfinished"></translation>
</message>
<message><|fim▁hole|> <source>Leaderline</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Default color for leader lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source><html><head/><body><p><span style=" font-weight:600;">Note:</span> Items in <span style=" font-style:italic;">italics</span> are default values for new objects. They have no effect on existing objects.</p></body></html></source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::DlgPrefsTechDrawDimensionsImp</name>
<message>
<source>Dimensions</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Standard to be used for dimensional values</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ISO Oriented</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ISO Referencing</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ASME Inlined</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ASME Referencing</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Arrow Style</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Standard and Style</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Arrowhead style</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Arrow Size</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Character used to indicate diameter dimensions</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>⌀</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Append unit to dimension values</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show Units</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Diameter Symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Use system setting for number of decimals</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Use Global Decimals</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Number of decimals if 'Use Global Decimals' is not used</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dimension text font size</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Arrowhead size</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Alternate Decimals</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Font Size</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Tolerance Text Scale</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Tolerance text scale
Multiplier of 'Font Size'</source>
<translation type="unfinished"></translation>
</message>
<message>
<source><html><head/><body><p><span style=" font-weight:600;">Note:</span> Items in <span style=" font-style:italic;">italics</span> are default values for new objects. They have no effect on existing objects.</p></body></html></source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::DlgPrefsTechDrawGeneralImp</name>
<message>
<source>General</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Drawing Update</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Whether or not pages are updated every time the 3D model is changed</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Update With 3D (global policy)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Whether or not a page's 'Keep Updated' property
can override the global 'Update With 3D' parameter</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Allow Page Override (global policy)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Keep drawing pages in sync with changes of 3D model in real time.
This can slow down the response time.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Keep Page Up To Date</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Automatically distribute secondary views
for ProjectionGroups</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Auto-distribute Secondary Views</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Labels</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>* this font is also used for dimensions
Changes have no effect on existing dimensions.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Label Font*</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Label Size</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Font for labels</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Label size</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Conventions</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Projection Group Angle</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Use first- or third-angle multiview projection convention</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>First</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Third</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Page</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Hidden Line Style</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Style for hidden lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Continuous</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dashed</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Files</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Default Template</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Default template file for new pages</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Template Directory</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Starting directory for menu 'Insert Page using Template'</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Hatch Pattern File</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Default SVG or bitmap file for hatching</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line Group File</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Alternate file for personal LineGroup definition</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Welding Directory</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Default directory for welding symbols</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>PAT File</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Default PAT pattern definition file for geometric hatching</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Pattern Name</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Name of the default PAT pattern</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Diamond</source>
<translation type="unfinished"></translation>
</message>
<message>
<source><html><head/><body><p><span style=" font-weight:600;">Note:</span> Items in <span style=" font-style:italic;">italics</span> are default values for new objects. They have no effect on existing objects.</p></body></html></source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::DlgPrefsTechDrawHLRImp</name>
<message>
<source>HLR</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Hidden Line Removal</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Visible</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Number of ISO lines per face edge</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show seam lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show Seam Lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show smooth lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show Smooth Lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Use an approximation to find hidden lines.
Fast, but result is a collection of short straight lines.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Use Polygon Approximation</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show hidden smooth edges</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show hidden hard and outline edges</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show Hard Lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show hard and outline edges (always shown)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show hidden seam lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show hidden equal parameterization lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show UV ISO Lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Hidden</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ISO Count</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Make lines of equal parameterization</source>
<translation type="unfinished"></translation>
</message>
<message>
<source><html><head/><body><p><span style=" font-weight:600;">Note:</span> Items in <span style=" font-style:italic;">italics</span> are default values for new objects. They have no effect on existing objects.</p></body></html></source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::DlgPrefsTechDrawScaleImp</name>
<message>
<source>Scale</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Page Scale</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Default scale for new pages</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>View Scale Type</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Default scale for new views</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Page</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Auto</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Custom</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>View Custom Scale</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Default scale for views if 'View Scale Type' is 'Custom'</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Size Adjustments</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Vertex Scale</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Size of template field click handles</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Center Mark Scale</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Size of center marks. Multiplier of vertex size.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Template Edit Mark</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Multiplier for size of welding symbols</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Welding Symbol Scale</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Scale of vertex dots. Multiplier of line width.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source><html><head/><body><p><span style=" font-weight:600;">Note:</span> Items in <span style=" font-style:italic;">italics</span> are default values for new objects. They have no effect on existing objects.</p></body></html></source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::MDIViewPage</name>
<message>
<source>Toggle &Keep Updated</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Toggle &Frames</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>&Export SVG</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Export DXF</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Export PDF</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Different orientation</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>The printer uses a different orientation than the drawing.
Do you want to continue?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Different paper size</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>The printer uses a different paper size than the drawing.
Do you want to continue?</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Opening file failed</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Can not open file %1 for writing.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Save Dxf File</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dxf (*.dxf)</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Selected:</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::QGIViewAnnotation</name>
<message>
<source>Text</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::SymbolChooser</name>
<message>
<source>Symbol Chooser</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Select a symbol that should be used</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Symbol Dir</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Directory to welding symbols.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskBalloon</name>
<message>
<source>Balloon</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text to be displayed</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text Color:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Color for 'Text'</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Font Size:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Fontsize for 'Text'</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Bubble Shape:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Shape of the balloon bubble</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Circular</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>None</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Triangle</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Inspection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Hexagon</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Square</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Rectangle</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Shape Scale:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Bubble shape scale factor</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>End Symbol:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>End symbol for the balloon line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>End Symbol Scale:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>End symbol scale factor</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line Visible:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Whether the leader line is visible or not</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>False</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>True</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line Width:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Leader line width</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Leader Kink Length:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Length of balloon leader line kink</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskCenterLine</name>
<message>
<source>Center Line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Base View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Elements</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Orientation</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Top to Bottom line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Vertical</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Left to Right line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Horizontal</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>centerline between
- lines: in equal distance to the lines and with
half of the angle the lines have to each other
- points: in equal distance to the points</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Aligned</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Shift Horizontal</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Move line -Left or +Right</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Shift Vertical</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Move line +Up or -Down</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Rotate</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Rotate line +CCW or -CW</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Extend By</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Make the line a little longer.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>mm</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Weight</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Style</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Continuous</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dash</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dot</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>DashDot</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>DashDotDot</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskCosVertex</name>
<message>
<source>Cosmetic Vertex</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Base View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Point Picker</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Position from the view center</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Position</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>X</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Y</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Pick a point for cosmetic vertex</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Left click to set a point</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>In progress edit abandoned. Start over.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskCosmeticLine</name>
<message>
<source>Cosmetic Line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>2d Point</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>3d Point</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>X:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Y:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Z:</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskDetail</name>
<message>
<source>Detail Anchor</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Base View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Detail View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Click to drag detail highlight to new position</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Drag Highlight</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Reference</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>x position of detail highlight within view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>scale factor for detail view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>X</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>size of detail view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Scale Factor</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Y</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Radius</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>reference label</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>y position of detail highlight within view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Page: scale factor of page is used
Automatic: if the detail view is larger than the page,
it will be scaled down to fit into the page
Custom: custom scale factor is used</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Page</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Automatic</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Custom</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Scale Type</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskDimension</name>
<message>
<source>Dimension</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Tolerancing</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>If theoretical exact (basic) dimension</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Theoretically Exact</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Reverses usual direction of dimension line terminators</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Equal Tolerance</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Overtolerance:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Overtolerance value
If 'Equal Tolerance' is checked this is also
the negated value for 'Under Tolerance'.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Undertolerance:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Undertolerance value
If 'Equal Tolerance' is checked it will be replaced
by negative value of 'Over Tolerance'.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Formatting</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Format Specifier:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text to be displayed</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>If checked the content of 'Format Spec' will
be used instead if the dimension value</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Arbitrary Text</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>OverTolerance Format Specifier:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Specifies the overtolerance format in printf() style, or arbitrary text</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>UnderTolerance Format Specifier:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Specifies the undertolerance format in printf() style, or arbitrary text</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Arbitrary Tolerance Text</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Display Style</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Flip Arrowheads</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Color:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Color of the dimension</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Font Size:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Fontsize for 'Text'</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Drawing Style:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Standard and style according to which dimension is drawn</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ISO Oriented</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ISO Referencing</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ASME Inlined</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>ASME Referencing</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskDlgLineDecor</name>
<message>
<source>Restore Invisible Lines</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskGeomHatch</name>
<message>
<source>Apply Geometric Hatch to Face</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Define your pattern</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>The PAT file containing your pattern</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Pattern File</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Pattern Name</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line Weight</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Pattern Scale</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line Color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Name of pattern within file</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Color of pattern lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Enlarges/shrinks the pattern</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Thickness of lines within the pattern</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskHatch</name>
<message>
<source>Apply Hatch to Face</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Define your pattern</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>The PAT file containing your pattern</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Pattern File</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Color of pattern lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line Color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Enlarges/shrinks the pattern</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Pattern Scale</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskLeaderLine</name>
<message>
<source>Leader Line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Base View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Discard Changes</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>First pick the start point of the line,
then at least a second point.
You can pick further points to get line segments.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Pick Points</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Start Symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>End Symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Width</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line width</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Style</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line style</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>NoLine</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Continuous</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dash</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dot</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>DashDot</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>DashDotDot</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Pick a starting point for leader line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Click and drag markers to adjust leader line</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Left click to set a point</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Press OK or Cancel to continue</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>In progress edit abandoned. Start over.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskLineDecor</name>
<message>
<source>Line Decoration</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>View</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Style</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Continuous</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dash</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dot</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>DashDot</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>DashDotDot</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Weight</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Thickness of pattern lines.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Visible</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>False</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>True</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskLinkDim</name>
<message>
<source>Link Dimension</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Link This 3D Geometry</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Feature2:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Feature1:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Geometry1:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Geometry2: </source>
<translation type="unfinished"></translation>
</message>
<message>
<source>To These Dimensions</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Available</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Selected</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskProjGroup</name>
<message>
<source>Projection Group</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Projection</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>First or Third Angle</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>First Angle</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Third Angle</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Page</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Scale</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Scale Page/Auto/Custom</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Automatic</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Custom</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Custom Scale</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Scale Numerator</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Scale Denominator</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Adjust Primary Direction</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Current primary view direction</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Rotate right</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Rotate up</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Rotate left</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Rotate down</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Secondary Projections</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Bottom</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Primary</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Right</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Left</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>LeftFrontBottom</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Top</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>RightFrontBottom</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>RightFrontTop</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Rear</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>LeftFrontTop</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Spin CW</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Spin CCW</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Distributes projections automatically
using the given X/Y Spacing</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Auto Distribute</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Horizontal space between border of projections</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>X Spacing</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Y Spacing</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Vertical space between border of projections</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskRestoreLines</name>
<message>
<source>Restore Invisible Lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>All</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Geometry</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>CenterLine</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Cosmetic</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>0</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskRichAnno</name>
<message>
<source>Rich Text Annotation Block</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Base Feature</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Max Width</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Maximal width, if -1 then automatic width</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Start Rich Text Editor</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Show Frame</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line color</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Width</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line width</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Style</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Line style</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>NoLine</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Continuous</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dash</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Dot</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>DashDot</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>DashDotDot</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Input the annotation text directly or start the rich text editor</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskSectionView</name>
<message>
<source>Section Parameters</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>BaseView</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Identifier</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Identifier for this section</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Scale</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Scale factor for the section view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Section Orientation</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Looking up</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Looking down</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Looking left</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Looking right</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Position from the 3D origin of the object in the view</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Section Plane Location</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>X</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Y</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Z</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>TaskSectionView - bad parameters. Can not proceed.</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Nothing to apply. No section direction picked yet</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Can not continue. Object * %1 * not found.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::TaskWeldingSymbol</name>
<message>
<source>Symbol</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>arrow</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>other</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDrawGui::dlgTemplateField</name>
<message>
<source>Change Editable Field</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Text Name:</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>TextLabel</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Value:</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDraw_2LineCenterLine</name>
<message>
<source>Adds a Centerline between 2 Lines</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDraw_2PointCenterLine</name>
<message>
<source>Adds a Centerline between 2 Points</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDraw_CosmeticVertex</name>
<message>
<source>Inserts a Cosmetic Vertex into a View</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDraw_FaceCenterLine</name>
<message>
<source>Adds a Centerline to Faces</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDraw_HorizontalExtent</name>
<message>
<source>Insert Horizontal Extent Dimension</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDraw_Midpoints</name>
<message>
<source>Inserts Cosmetic Vertices at Midpoint of selected Edges</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDraw_Quadrants</name>
<message>
<source>Inserts Cosmetic Vertices at Quadrant Points of selected Circles</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>TechDraw_VerticalExtentDimension</name>
<message>
<source>Insert Vertical Extent Dimension</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>Workbench</name>
<message>
<source>Dimensions</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Annotations</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Lines</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Add Vertices</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>TechDraw</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>TechDraw Pages</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>TechDraw Views</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>TechDraw Clips</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>TechDraw Dimensions</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>TechDraw File Access</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>TechDraw Decoration</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>TechDraw Annotation</source>
<translation type="unfinished"></translation>
</message>
<message>
<source>Views</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS><|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>import redis
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.config import Configurator
<|fim▁hole|> authorization_policy = ACLAuthorizationPolicy()
authentication_policy = AuthTktAuthenticationPolicy('not_so_secret')
config = Configurator(settings=settings,
authentication_policy=authentication_policy,
authorization_policy=authorization_policy,
root_factory='appenlight_demo.security.RootFactory',
)
config.include('pyramid_jinja2')
config.include('.models')
config.include('.routes')
config.registry.redis_conn = redis.StrictRedis.from_url(
settings['redis.url'])
config.scan()
return config.make_wsgi_app()<|fim▁end|> | def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
|
<|file_name|>main.ts<|end_file_name|><|fim▁begin|>import * as restify from 'restify';
import logger from './logger';
import settings from './settings';<|fim▁hole|>try {
settings.initialize();
} catch (ex) {
logger.error(ex);
process.exit(1);
}
const server = restify.createServer();
server.get('/', (req, res) => {
res.send(200, { it: 'works' });
});
server.on('NotFound', (req: restify.Request, res: restify.Response) => {
res.send(200, { it: 'works (almost ...)' });
});
server.listen(settings.servicePort,
() => logger.info(`Service listening on port ${settings.servicePort}`));<|fim▁end|> |
// Initialize settings. |
<|file_name|>move-nodetest.js<|end_file_name|><|fim▁begin|>'use strict';
var expect = require('chai').expect;
var ember = require('ember-cli/tests/helpers/ember');
var MockUI = require('ember-cli/tests/helpers/mock-ui');
var MockAnalytics = require('ember-cli/tests/helpers/mock-analytics');
var Command = require('ember-cli/lib/models/command');
var Task = require('ember-cli/lib/models/task');
var Promise = require('ember-cli/lib/ext/promise');
var RSVP = require('rsvp');
var fs = require('fs-extra');
var path = require('path');
var exec = Promise.denodeify(require('child_process').exec);
var remove = Promise.denodeify(fs.remove);
var ensureFile = Promise.denodeify(fs.ensureFile);
var root = process.cwd();
var tmp = require('tmp-sync');
var tmproot = path.join(root, 'tmp');
var MoveCommandBase = require('../../../lib/commands/move');
describe('move command', function() {
var ui;
var tasks;
var analytics;
var project;
var fakeSpawn;
var CommandUnderTest;
var buildTaskCalled;
var buildTaskReceivedProject;
var tmpdir;
before(function() {
CommandUnderTest = Command.extend(MoveCommandBase);
});
beforeEach(function() {
buildTaskCalled = false;
ui = new MockUI();
analytics = new MockAnalytics();
tasks = {
Build: Task.extend({
run: function() {
buildTaskCalled = true;
buildTaskReceivedProject = !!this.project;
return RSVP.resolve();
}
})
};
project = {
isEmberCLIProject: function() {
return true;
}
};
});
function setupGit() {
return exec('git --version')
.then(function(){
return exec('git rev-parse --is-inside-work-tree', { encoding: 'utf8' })
.then(function(result) {
console.log('result',result)
return;
// return exec('git init');
})
.catch(function(e){
return exec('git init');
});
});
}
function generateFile(path) {
return ensureFile(path);
}
function addFileToGit(path) {
return ensureFile(path)
.then(function() {
return exec('git add .');
});
}
function addFilesToGit(files) {
var filesToAdd = files.map(addFileToGit);
return RSVP.all(filesToAdd);
}
function setupForMove() {
return setupTmpDir()
// .then(setupGit)
.then(addFilesToGit.bind(null,['foo.js','bar.js']));
}
function setupTmpDir() {
return Promise.resolve()
.then(function(){
tmpdir = tmp.in(tmproot);
process.chdir(tmpdir);
return tmpdir;
});
}
function cleanupTmpDir() {
return Promise.resolve()
.then(function(){
process.chdir(root);
return remove(tmproot);
});
}
/*
afterEach(function() {
process.chdir(root);
return remove(tmproot);
});
*/
/*
//TODO: fix so this isn't moving the fixtures
it('smoke test', function() {
return new CommandUnderTest({
ui: ui,
analytics: analytics,
project: project,
environment: { },
tasks: tasks,
settings: {},
runCommand: function(command, args) {
expect.deepEqual(args, ['./tests/fixtures/smoke-test/foo.js', './tests/fixtures/smoke-test/bar.js']);
}
}).validateAndRun(['./tests/fixtures/smoke-test/foo.js', './tests/fixtures/smoke-test/bar.js']);
});
*/
it('exits for unversioned file', function() {
return setupTmpDir()
.then(function(){
fs.writeFileSync('foo.js','foo');
return new CommandUnderTest({
ui: ui,
analytics: analytics,
project: project,
environment: { },
tasks: tasks,
settings: {},
runCommand: function(command, args) {
expect.deepEqual(args, ['nope.js']);
}
}).validateAndRun(['nope.js']).then(function() {<|fim▁hole|> expect(ui.output).to.include('The source path: nope.js does not exist.');
});
})
.then(cleanupTmpDir);
});
it('can move a file', function() {
return setupForMove().
then(function(result) {
console.log('result',result);
return new CommandUnderTest({
ui: ui,
analytics: analytics,
project: project,
environment: { },
tasks: tasks,
settings: {},
runCommand: function(command, args) {
expect.deepEqual(args, ['foo.js', 'foo-bar.js']);
}
}).validateAndRun(['foo.js', 'foo-bar.js']).then(function() {
expect(ui.output).to.include('foo.js');
// expect(ui.output).to.include('The source path: nope.js does not exist.');
});
})
.then(cleanupTmpDir);
});
});<|fim▁end|> | expect(ui.output).to.include('nope.js'); |
<|file_name|>networkpolicy.go<|end_file_name|><|fim▁begin|>/*
Copyright 2018 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.<|fim▁hole|>*/
// This file was automatically generated by informer-gen
package internalversion
import (
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
runtime "k8s.io/apimachinery/pkg/runtime"
watch "k8s.io/apimachinery/pkg/watch"
cache "github.com/hyperhq/client-go/tools/cache"
networking "k8s.io/kubernetes/pkg/apis/networking"
internalclientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
internalinterfaces "k8s.io/kubernetes/pkg/client/informers/informers_generated/internalversion/internalinterfaces"
internalversion "k8s.io/kubernetes/pkg/client/listers/networking/internalversion"
time "time"
)
// NetworkPolicyInformer provides access to a shared informer and lister for
// NetworkPolicies.
type NetworkPolicyInformer interface {
Informer() cache.SharedIndexInformer
Lister() internalversion.NetworkPolicyLister
}
type networkPolicyInformer struct {
factory internalinterfaces.SharedInformerFactory
tweakListOptions internalinterfaces.TweakListOptionsFunc
namespace string
}
// NewNetworkPolicyInformer constructs a new informer for NetworkPolicy type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewNetworkPolicyInformer(client internalclientset.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer {
return NewFilteredNetworkPolicyInformer(client, namespace, resyncPeriod, indexers, nil)
}
// NewFilteredNetworkPolicyInformer constructs a new informer for NetworkPolicy type.
// Always prefer using an informer factory to get a shared informer instead of getting an independent
// one. This reduces memory footprint and number of connections to the server.
func NewFilteredNetworkPolicyInformer(client internalclientset.Interface, namespace string, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer {
return cache.NewSharedIndexInformer(
&cache.ListWatch{
ListFunc: func(options v1.ListOptions) (runtime.Object, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.Networking().NetworkPolicies(namespace).List(options)
},
WatchFunc: func(options v1.ListOptions) (watch.Interface, error) {
if tweakListOptions != nil {
tweakListOptions(&options)
}
return client.Networking().NetworkPolicies(namespace).Watch(options)
},
},
&networking.NetworkPolicy{},
resyncPeriod,
indexers,
)
}
func (f *networkPolicyInformer) defaultInformer(client internalclientset.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer {
return NewFilteredNetworkPolicyInformer(client, f.namespace, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions)
}
func (f *networkPolicyInformer) Informer() cache.SharedIndexInformer {
return f.factory.InformerFor(&networking.NetworkPolicy{}, f.defaultInformer)
}
func (f *networkPolicyInformer) Lister() internalversion.NetworkPolicyLister {
return internalversion.NewNetworkPolicyLister(f.Informer().GetIndexer())
}<|fim▁end|> | See the License for the specific language governing permissions and
limitations under the License. |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! Generators for file formats that can be derived from the intercom
//! libraries.
use std::collections::HashMap;
use intercom::type_system::TypeSystemName;
use intercom::typelib::{Interface, TypeInfo, TypeLib};
/// A common error type for all the generators.
#[derive(Fail, Debug)]
pub enum GeneratorError
{
#[fail(display = "IoError: {}", _0)]
IoError(#[cause] ::std::io::Error),
#[fail(display = "Invalid type library: {}", _0)]
LibraryError(String),
}
impl From<::std::io::Error> for GeneratorError
{
fn from(e: ::std::io::Error) -> GeneratorError
{
GeneratorError::IoError(e)
}
}
impl From<String> for GeneratorError
{
fn from(s: String) -> GeneratorError
{
GeneratorError::LibraryError(s)
}
}
pub struct ModelOptions
{
pub type_systems: Vec<TypeSystemOptions>,
}
pub struct TypeSystemOptions
{
pub ts: TypeSystemName,
pub use_full_name: bool,
}
pub struct LibraryContext<'a>
{
pub itfs_by_ref: HashMap<String, &'a Interface>,
pub itfs_by_name: HashMap<String, &'a Interface>,
}
impl<'a> LibraryContext<'a>
{
fn try_from(lib: &'a TypeLib) -> Result<LibraryContext<'a>, GeneratorError><|fim▁hole|> {
let itfs_by_name: HashMap<String, &Interface> = lib
.types
.iter()
.filter_map(|t| match t {
TypeInfo::Interface(itf) => Some(itf),
_ => None,
})
.map(|itf| (itf.as_ref().name.to_string(), &**(itf.as_ref())))
.collect();
let itfs_by_ref: HashMap<String, &Interface> = lib
.types
.iter()
.filter_map(|t| match t {
TypeInfo::Class(cls) => Some(cls),
_ => None,
})
.flat_map(|cls| &cls.as_ref().interfaces)
.map(|itf_ref| {
(
itf_ref.name.to_string(),
itfs_by_name[itf_ref.name.as_ref()],
)
})
.collect();
Ok(LibraryContext {
itfs_by_name,
itfs_by_ref,
})
}
}
/// Convert the Rust identifier from `snake_case` to `PascalCase`
pub fn pascal_case<T: AsRef<str>>(input: T) -> String
{
let input = input.as_ref();
// Allocate the output string. We'll never increase the amount of
// characters so we can reserve string buffer using the input string length.
let mut output = String::new();
output.reserve(input.len());
// Process each character from the input.
let mut capitalize = true;
for c in input.chars() {
// Check the capitalization requirement.
if c == '_' {
// Skip '_' but capitalize the following character.
capitalize = true;
} else if capitalize {
// Capitalize. Add the uppercase characters.
for c_up in c.to_uppercase() {
output.push(c_up)
}
// No need to capitalize any more.
capitalize = false;
} else {
// No need to capitalize. Just add the character as is.
output.push(c);
}
}
output
}
pub mod cpp;
pub mod idl;<|fim▁end|> | |
<|file_name|>thaig2p.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Thai Grapheme-to-Phoneme (Thai G2P)
GitHub : https://github.com/wannaphong/thai-g2p
"""
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pythainlp.corpus import get_corpus_path
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
_MODEL_NAME = "thai-g2p"
class ThaiG2P:
"""
Latin transliteration of Thai words, using International Phonetic Alphabet
"""
def __init__(self):
# get the model, will download if it's not available locally
self.__model_filename = get_corpus_path(_MODEL_NAME)
loader = torch.load(self.__model_filename, map_location=device)
<|fim▁hole|> INPUT_DIM, E_EMB_DIM, E_HID_DIM, E_DROPOUT = loader["encoder_params"]
OUTPUT_DIM, D_EMB_DIM, D_HID_DIM, D_DROPOUT = loader["decoder_params"]
self._maxlength = 100
self._char_to_ix = loader["char_to_ix"]
self._ix_to_char = loader["ix_to_char"]
self._target_char_to_ix = loader["target_char_to_ix"]
self._ix_to_target_char = loader["ix_to_target_char"]
# encoder/ decoder
# Restore the model and construct the encoder and decoder.
self._encoder = Encoder(INPUT_DIM, E_EMB_DIM, E_HID_DIM, E_DROPOUT)
self._decoder = AttentionDecoder(
OUTPUT_DIM, D_EMB_DIM, D_HID_DIM, D_DROPOUT
)
self._network = Seq2Seq(
self._encoder,
self._decoder,
self._target_char_to_ix["<start>"],
self._target_char_to_ix["<end>"],
self._maxlength,
).to(device)
self._network.load_state_dict(loader["model_state_dict"])
self._network.eval()
def _prepare_sequence_in(self, text: str):
"""
Prepare input sequence for PyTorch.
"""
idxs = []
for ch in text:
if ch in self._char_to_ix:
idxs.append(self._char_to_ix[ch])
else:
idxs.append(self._char_to_ix["<UNK>"])
idxs.append(self._char_to_ix["<end>"])
tensor = torch.tensor(idxs, dtype=torch.long)
return tensor.to(device)
def g2p(self, text: str) -> str:
"""
:param str text: Thai text to be romanized
:return: English (more or less) text that spells out how the Thai text
should be pronounced.
"""
input_tensor = self._prepare_sequence_in(text).view(1, -1)
input_length = [len(text) + 1]
target_tensor_logits = self._network(
input_tensor, input_length, None, 0
)
# Seq2seq model returns <END> as the first token,
# As a result, target_tensor_logits.size() is torch.Size([0])
if target_tensor_logits.size(0) == 0:
target = ["<PAD>"]
else:
target_tensor = (
torch.argmax(target_tensor_logits.squeeze(1), 1)
.cpu()
.detach()
.numpy()
)
target = [self._ix_to_target_char[t] for t in target_tensor]
return "".join(target)
class Encoder(nn.Module):
def __init__(
self, vocabulary_size, embedding_size, hidden_size, dropout=0.5
):
"""Constructor"""
super(Encoder, self).__init__()
self.hidden_size = hidden_size
self.character_embedding = nn.Embedding(
vocabulary_size, embedding_size
)
self.rnn = nn.LSTM(
input_size=embedding_size,
hidden_size=hidden_size // 2,
bidirectional=True,
batch_first=True,
)
self.dropout = nn.Dropout(dropout)
def forward(self, sequences, sequences_lengths):
# sequences: (batch_size, sequence_length=MAX_LENGTH)
# sequences_lengths: (batch_size)
batch_size = sequences.size(0)
self.hidden = self.init_hidden(batch_size)
sequences_lengths = np.sort(sequences_lengths)[::-1]
index_sorted = np.argsort(
-sequences_lengths
) # use negation in sort in descending order
index_unsort = np.argsort(index_sorted) # to unsorted sequence
index_sorted = torch.from_numpy(index_sorted)
sequences = sequences.index_select(0, index_sorted.to(device))
sequences = self.character_embedding(sequences)
sequences = self.dropout(sequences)
sequences_packed = nn.utils.rnn.pack_padded_sequence(
sequences, sequences_lengths.copy(), batch_first=True
)
sequences_output, self.hidden = self.rnn(sequences_packed, self.hidden)
sequences_output, _ = nn.utils.rnn.pad_packed_sequence(
sequences_output, batch_first=True
)
index_unsort = torch.from_numpy(index_unsort).to(device)
sequences_output = sequences_output.index_select(
0, index_unsort.clone().detach()
)
return sequences_output, self.hidden
def init_hidden(self, batch_size):
h_0 = torch.zeros(
[2, batch_size, self.hidden_size // 2], requires_grad=True
).to(device)
c_0 = torch.zeros(
[2, batch_size, self.hidden_size // 2], requires_grad=True
).to(device)
return (h_0, c_0)
class Attn(nn.Module):
def __init__(self, method, hidden_size):
super(Attn, self).__init__()
self.method = method
self.hidden_size = hidden_size
if self.method == "general":
self.attn = nn.Linear(self.hidden_size, hidden_size)
elif self.method == "concat":
self.attn = nn.Linear(self.hidden_size * 2, hidden_size)
self.other = nn.Parameter(torch.FloatTensor(1, hidden_size))
def forward(self, hidden, encoder_outputs, mask):
# Calculate energies for each encoder output
if self.method == "dot":
attn_energies = torch.bmm(
encoder_outputs, hidden.transpose(1, 2)
).squeeze(2)
elif self.method == "general":
attn_energies = self.attn(
encoder_outputs.view(-1, encoder_outputs.size(-1))
) # (batch_size * sequence_len, hidden_size)
attn_energies = torch.bmm(
attn_energies.view(*encoder_outputs.size()),
hidden.transpose(1, 2),
).squeeze(
2
) # (batch_size, sequence_len)
elif self.method == "concat":
attn_energies = self.attn(
torch.cat(
(hidden.expand(*encoder_outputs.size()), encoder_outputs),
2,
)
) # (batch_size, sequence_len, hidden_size)
attn_energies = torch.bmm(
attn_energies,
self.other.unsqueeze(0).expand(*hidden.size()).transpose(1, 2),
).squeeze(2)
attn_energies = attn_energies.masked_fill(mask == 0, -1e10)
# Normalize energies to weights in range 0 to 1
return F.softmax(attn_energies, 1)
class AttentionDecoder(nn.Module):
def __init__(
self, vocabulary_size, embedding_size, hidden_size, dropout=0.5
):
"""Constructor"""
super(AttentionDecoder, self).__init__()
self.vocabulary_size = vocabulary_size
self.hidden_size = hidden_size
self.character_embedding = nn.Embedding(
vocabulary_size, embedding_size
)
self.rnn = nn.LSTM(
input_size=embedding_size + self.hidden_size,
hidden_size=hidden_size,
bidirectional=False,
batch_first=True,
)
self.attn = Attn(method="general", hidden_size=self.hidden_size)
self.linear = nn.Linear(hidden_size, vocabulary_size)
self.dropout = nn.Dropout(dropout)
def forward(self, input_character, last_hidden, encoder_outputs, mask):
""""Defines the forward computation of the decoder"""
# input_character: (batch_size, 1)
# last_hidden: (batch_size, hidden_dim)
# encoder_outputs: (batch_size, sequence_len, hidden_dim)
# mask: (batch_size, sequence_len)
hidden = last_hidden.permute(1, 0, 2)
attn_weights = self.attn(hidden, encoder_outputs, mask)
context_vector = attn_weights.unsqueeze(1).bmm(encoder_outputs)
context_vector = torch.sum(context_vector, dim=1)
context_vector = context_vector.unsqueeze(1)
embedded = self.character_embedding(input_character)
embedded = self.dropout(embedded)
rnn_input = torch.cat((context_vector, embedded), -1)
output, hidden = self.rnn(rnn_input)
output = output.view(-1, output.size(2))
x = self.linear(output)
return x, hidden[0], attn_weights
class Seq2Seq(nn.Module):
def __init__(
self,
encoder,
decoder,
target_start_token,
target_end_token,
max_length,
):
super().__init__()
self.encoder = encoder
self.decoder = decoder
self.pad_idx = 0
self.target_start_token = target_start_token
self.target_end_token = target_end_token
self.max_length = max_length
assert encoder.hidden_size == decoder.hidden_size
def create_mask(self, source_seq):
mask = source_seq != self.pad_idx
return mask
def forward(
self, source_seq, source_seq_len, target_seq, teacher_forcing_ratio=0.5
):
# source_seq: (batch_size, MAX_LENGTH)
# source_seq_len: (batch_size, 1)
# target_seq: (batch_size, MAX_LENGTH)
batch_size = source_seq.size(0)
start_token = self.target_start_token
end_token = self.target_end_token
max_len = self.max_length
target_vocab_size = self.decoder.vocabulary_size
outputs = torch.zeros(max_len, batch_size, target_vocab_size).to(
device
)
if target_seq is None:
assert teacher_forcing_ratio == 0, "Must be zero during inference"
inference = True
else:
inference = False
encoder_outputs, encoder_hidden = self.encoder(
source_seq, source_seq_len
)
decoder_input = (
torch.tensor([[start_token] * batch_size])
.view(batch_size, 1)
.to(device)
)
encoder_hidden_h_t = torch.cat(
[encoder_hidden[0][0], encoder_hidden[0][1]], dim=1
).unsqueeze(dim=0)
decoder_hidden = encoder_hidden_h_t
max_source_len = encoder_outputs.size(1)
mask = self.create_mask(source_seq[:, 0:max_source_len])
for di in range(max_len):
decoder_output, decoder_hidden, _ = self.decoder(
decoder_input, decoder_hidden, encoder_outputs, mask
)
topv, topi = decoder_output.topk(1)
outputs[di] = decoder_output.to(device)
teacher_force = random.random() < teacher_forcing_ratio
decoder_input = (
target_seq[:, di].reshape(batch_size, 1)
if teacher_force
else topi.detach()
)
if inference and decoder_input == end_token:
return outputs[:di]
return outputs
_THAI_G2P = ThaiG2P()
def transliterate(text: str) -> str:
global _THAI_G2P
return _THAI_G2P.g2p(text)<|fim▁end|> | |
<|file_name|>issue-17718-const-naming.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<|fim▁hole|>
#[deny(warnings)]
const foo: isize = 3;
//~^ ERROR: should have an upper case name such as
//~^^ ERROR: constant item is never used
fn main() {}<|fim▁end|> | // option. This file may not be copied, modified, or distributed
// except according to those terms. |
<|file_name|>run_tests_py.py<|end_file_name|><|fim▁begin|>#
# run all the regression tests
#
# [or, you can request specific ones by giving their names on the command line]
#
import sys
import compile
import os
import subprocess
import context
def run_test (cmd, *args):
cmd = PJ ('tests', cmd)
p = subprocess.Popen ([cmd] + list(args), stdout=subprocess.PIPE)
out = p.stdout.read()
return out
def test_t17():
lines = run_test ('t17').split ('\n')
# we can't say anything about the address returned by malloc
# but we should expect to read this number
assert (lines[1] == '3141')
# and the sizeof (pxll_int) is random too, since even on the same
# platform we might compile 32 or 64 bit, so just ignore it.
def test_t_dump_image():
# generate the output
run_test ('t_dump_image')
# load the image and run it
exp0 = run_test ('t_dump_image','-l')
exp1 = open ('tests/t_dump_image.exp').read()
assert (exp0 == exp1)
def test_t21():
out = run_test ('t21')
exp = open ('gc.c').read()
# make sure the first part matches the contents of gc.c
assert (out[:len(exp)] == exp)<|fim▁hole|>def test_t22():
out = run_test ('t22')
lines = out.split ('\n')
assert (lines[0].count ('<closure pc=') == 5)
r6 = [ str(x) for x in range (6) ]
assert (lines[1:] == (r6 + r6 + ['#u', '']))
def test_t_lex():
out = run_test ('t_lex')
assert (out.split('\n')[-4:] == ['{u0 NUMBER "42"}', '{u0 NEWLINE "\\0x0a"}', '"done"', ''])
def test_t_vm():
out = run_test ('t_vm', 'vm/tests/t11.byc')
assert (out.split()[-2:] == ['7', '#u'])
PJ = os.path.join
if len(sys.argv) > 1:
# run only these specific tests
files = [x + '.scm' for x in sys.argv[1:]]
else:
files = os.listdir ('tests')
# When looking for things that are broken, I prefer to work with the smallest
# test that reproduces a problem. Thus, run the tests in source-size order...
files = [ (os.stat(PJ ('tests', x)).st_size, x) for x in files ]
files.sort()
# tests that need special handling
special = [x[5:] for x in dir() if x.startswith ('test_')]
failed = []
# nobody wants to wait for a non-optimized tak20
optimize = ['t_vm']
succeeded = 0
for size, file in files:
if file.endswith ('.scm'):
base, ext = os.path.splitext (file)
path = os.path.join ('tests', file)
print 'compiling', path
fail = file.startswith ('f')
c = context.context()
c.verbose = False
c.typetype = True
if base in optimize:
c.optimize = True
try:
compile.compile_file (open (path, 'rb'), path, c)
except:
if not fail:
#raise
failed.append ((base, "compile failed"))
else:
succeeded += 1
else:
if fail:
failed.append ((base, 'compile did not fail like expected'))
#raise ValueError ("oops - expected compilation to fail")
if base not in special:
out = run_test (base)
exp_path = PJ ('tests', base + '.exp')
if os.path.isfile (exp_path):
exp = open (exp_path).read()
if out != exp:
failed.append ((base, 'did not match expected output'))
#raise ValueError ("oops - output didn't match on test '%s'" % (base,))
else:
succeeded += 1
else:
succeeded += 1
else:
# tests that require special handling for whatever reason.
try:
eval ('test_%s()' % (base,))
except:
failed.append ((base, 'assertion failed'))
else:
succeeded += 1
print '%d tests passed' % succeeded
if len(failed):
print '%d tests failed!!' % (len(failed))
for base, reason in failed:
print base, reason<|fim▁end|> | # the chars are too hard to tests for, and unlikely to be wrong.
# should really make a separate char test.
|
<|file_name|>ruutu.py<|end_file_name|><|fim▁begin|># coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urllib_parse_urlparse
from ..utils import (
determine_ext,
int_or_none,
xpath_attr,
xpath_text,
)
class RuutuIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?ruutu\.fi/video/(?P<id>\d+)'
_TESTS = [
{
'url': 'http://www.ruutu.fi/video/2058907',
'md5': 'ab2093f39be1ca8581963451b3c0234f',
'info_dict': {
'id': '2058907',
'ext': 'mp4',
'title': 'Oletko aina halunnut tietää mitä tapahtuu vain hetki ennen lähetystä? - Nyt se selvisi!',
'description': 'md5:cfc6ccf0e57a814360df464a91ff67d6',
'thumbnail': 're:^https?://.*\.jpg$',
'duration': 114,
'age_limit': 0,
},
},
{
'url': 'http://www.ruutu.fi/video/2057306',
'md5': '065a10ae4d5b8cfd9d0c3d332465e3d9',
'info_dict': {
'id': '2057306',
'ext': 'mp4',
'title': 'Superpesis: katso koko kausi Ruudussa',
'description': 'md5:da2736052fef3b2bd5e0005e63c25eac',
'thumbnail': 're:^https?://.*\.jpg$',
'duration': 40,
'age_limit': 0,
},
},
]
def _real_extract(self, url):
video_id = self._match_id(url)
video_xml = self._download_xml(
'http://gatling.ruutu.fi/media-xml-cache?id=%s' % video_id, video_id)
formats = []
processed_urls = []
def extract_formats(node):
for child in node:
if child.tag.endswith('Files'):
extract_formats(child)<|fim▁hole|> if (not video_url or video_url in processed_urls or
any(p in video_url for p in ('NOT_USED', 'NOT-USED'))):
return
processed_urls.append(video_url)
ext = determine_ext(video_url)
if ext == 'm3u8':
formats.extend(self._extract_m3u8_formats(
video_url, video_id, 'mp4', m3u8_id='hls', fatal=False))
elif ext == 'f4m':
formats.extend(self._extract_f4m_formats(
video_url, video_id, f4m_id='hds', fatal=False))
else:
proto = compat_urllib_parse_urlparse(video_url).scheme
if not child.tag.startswith('HTTP') and proto != 'rtmp':
continue
preference = -1 if proto == 'rtmp' else 1
label = child.get('label')
tbr = int_or_none(child.get('bitrate'))
format_id = '%s-%s' % (proto, label if label else tbr) if label or tbr else proto
if not self._is_valid_url(video_url, video_id, format_id):
continue
width, height = [int_or_none(x) for x in child.get('resolution', 'x').split('x')[:2]]
formats.append({
'format_id': format_id,
'url': video_url,
'width': width,
'height': height,
'tbr': tbr,
'preference': preference,
})
extract_formats(video_xml.find('./Clip'))
self._sort_formats(formats)
return {
'id': video_id,
'title': xpath_attr(video_xml, './/Behavior/Program', 'program_name', 'title', fatal=True),
'description': xpath_attr(video_xml, './/Behavior/Program', 'description', 'description'),
'thumbnail': xpath_attr(video_xml, './/Behavior/Startpicture', 'href', 'thumbnail'),
'duration': int_or_none(xpath_text(video_xml, './/Runtime', 'duration')),
'age_limit': int_or_none(xpath_text(video_xml, './/AgeLimit', 'age limit')),
'formats': formats,
}<|fim▁end|> | elif child.tag.endswith('File'):
video_url = child.text |
<|file_name|>continuous.py<|end_file_name|><|fim▁begin|><|fim▁hole|> unicode_literals)
import os
import six
import argparse
from . import Command
from .run import Run
from .compare import Compare
from ..repo import get_repo, NoSuchNameError
from ..console import color_print, log
from .. import results
from .. import util
from . import common_args
class Continuous(Command):
@classmethod
def setup_arguments(cls, subparsers):
parser = subparsers.add_parser(
"continuous", help="Compare two commits directly",
description="""Run a side-by-side comparison of two commits for
continuous integration.""")
parser.add_argument(
'base', nargs='?', default=None,
help="""The commit/branch to compare against. By default, the
parent of the tested commit.""")
parser.add_argument(
'branch', default=None,
help="""The commit/branch to test. By default, the first configured branch.""")
common_args.add_record_samples(parser, record_default=True)
parser.add_argument(
"--quick", "-q", action="store_true",
help="""Do a "quick" run, where each benchmark function is
run only once. This is useful to find basic errors in the
benchmark functions faster. The results are unlikely to
be useful, and thus are not saved.""")
parser.add_argument(
"--interleave-rounds", action="store_true", default=None,
help="""Interleave benchmarks with multiple rounds across
commits. This can avoid measurement biases from commit ordering,
can take longer.""")
parser.add_argument(
"--no-interleave-rounds", action="store_false", dest="interleave_rounds")
# Backward compatibility for '--(no-)interleave-rounds'
parser.add_argument(
"--interleave-processes", action="store_true", default=False, dest="interleave_rounds",
help=argparse.SUPPRESS)
parser.add_argument(
"--no-interleave-processes", action="store_false", dest="interleave_rounds",
help=argparse.SUPPRESS)
parser.add_argument(
"--strict", action="store_true",
help="When set true the run command will exit with a non-zero "
"return code if any benchmark is in a failed state")
common_args.add_compare(parser, sort_default='ratio', only_changed_default=True)
common_args.add_show_stderr(parser)
common_args.add_bench(parser)
common_args.add_machine(parser)
common_args.add_environment(parser)
common_args.add_launch_method(parser)
parser.set_defaults(func=cls.run_from_args)
return parser
@classmethod
def run_from_conf_args(cls, conf, args, **kwargs):
return cls.run(
conf=conf, branch=args.branch, base=args.base,
factor=args.factor, split=args.split,
only_changed=args.only_changed, sort=args.sort,
use_stats=args.use_stats,
show_stderr=args.show_stderr, bench=args.bench, attribute=args.attribute,
machine=args.machine,
env_spec=args.env_spec, record_samples=args.record_samples,
append_samples=args.append_samples,
quick=args.quick, interleave_rounds=args.interleave_rounds,
launch_method=args.launch_method, strict=args.strict, **kwargs
)
@classmethod
def run(cls, conf, branch=None, base=None,
factor=None, split=False, only_changed=True, sort='ratio', use_stats=True,
show_stderr=False, bench=None,
attribute=None, machine=None, env_spec=None, record_samples=False, append_samples=False,
quick=False, interleave_rounds=None, launch_method=None, _machine_file=None,
strict=False):
repo = get_repo(conf)
repo.pull()
if branch is None:
branch = conf.branches[0]
try:
head = repo.get_hash_from_name(branch)
if base is None:
parent = repo.get_hash_from_parent(head)
else:
parent = repo.get_hash_from_name(base)
except NoSuchNameError as exc:
raise util.UserError("Unknown commit {0}".format(exc))
commit_hashes = [head, parent]
run_objs = {}
result = Run.run(
conf, range_spec=commit_hashes, bench=bench, attribute=attribute,
show_stderr=show_stderr, machine=machine, env_spec=env_spec,
record_samples=record_samples, append_samples=append_samples, quick=quick,
interleave_rounds=interleave_rounds,
launch_method=launch_method, strict=strict,
_returns=run_objs, _machine_file=_machine_file)
if result:
return result
log.flush()
def results_iter(commit_hash):
for env in run_objs['environments']:
machine_name = run_objs['machine_params']['machine']
filename = results.get_filename(
machine_name, commit_hash, env.name)
filename = os.path.join(conf.results_dir, filename)
try:
result = results.Results.load(filename, machine_name)
except util.UserError as err:
log.warning(six.text_type(err))
continue
for name, benchmark in six.iteritems(run_objs['benchmarks']):
params = benchmark['params']
version = benchmark['version']
value = result.get_result_value(name, params)
stats = result.get_result_stats(name, params)
samples = result.get_result_samples(name, params)
yield name, params, value, stats, samples, version, machine_name, env.name
commit_names = {parent: repo.get_name_from_hash(parent),
head: repo.get_name_from_hash(head)}
status = Compare.print_table(conf, parent, head,
resultset_1=results_iter(parent),
resultset_2=results_iter(head),
factor=factor, split=split,
use_stats=use_stats,
only_changed=only_changed, sort=sort,
commit_names=commit_names)
worsened, improved = status
color_print("")
if worsened:
color_print("SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY.", 'red')
color_print("PERFORMANCE DECREASED.", 'red')
elif improved:
color_print("SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY.", 'green')
color_print("PERFORMANCE INCREASED.", 'green')
else:
color_print("BENCHMARKS NOT SIGNIFICANTLY CHANGED.", 'green')
return worsened<|fim▁end|> | # -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (absolute_import, division, print_function, |
<|file_name|>dedicatedworkerglobalscope.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 devtools;
use devtools_traits::DevtoolScriptControlMsg;
use dom::abstractworker::{SharedRt, SimpleWorkerErrorHandler, WorkerScriptMsg};
use dom::abstractworkerglobalscope::{SendableWorkerScriptChan, WorkerThreadWorkerChan};
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding;
use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding::DedicatedWorkerGlobalScopeMethods;
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::error::{ErrorInfo, ErrorResult};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{Root, RootCollection};
use dom::bindings::reflector::DomObject;
use dom::bindings::str::DOMString;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::globalscope::GlobalScope;
use dom::messageevent::MessageEvent;
use dom::worker::{TrustedWorkerAddress, WorkerErrorHandler, WorkerMessageHandler};
use dom::workerglobalscope::WorkerGlobalScope;
use dom_struct::dom_struct;
use ipc_channel::ipc::{self, IpcReceiver, IpcSender};
use ipc_channel::router::ROUTER;
use js::jsapi::{HandleValue, JS_SetInterruptCallback};
use js::jsapi::{JSAutoCompartment, JSContext};
use js::jsval::UndefinedValue;
use js::rust::Runtime;
use msg::constellation_msg::TopLevelBrowsingContextId;
use net_traits::{IpcSend, load_whole_resource};
use net_traits::request::{CredentialsMode, Destination, RequestInit, Type as RequestType};
use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort, StackRootTLS, get_reports, new_rt_and_cx};
use script_runtime::ScriptThreadEventCategory::WorkerEvent;
use script_traits::{TimerEvent, TimerSource, WorkerGlobalScopeInit, WorkerScriptLoadOrigin};
use servo_rand::random;
use servo_url::ServoUrl;
use std::mem::replace;
use std::sync::{Arc, Mutex};
use std::sync::atomic::AtomicBool;
use std::sync::mpsc::{Receiver, RecvError, Select, Sender, channel};
use std::thread;
use style::thread_state;
/// Set the `worker` field of a related DedicatedWorkerGlobalScope object to a particular
/// value for the duration of this object's lifetime. This ensures that the related Worker
/// object only lives as long as necessary (ie. while events are being executed), while
/// providing a reference that can be cloned freely.
struct AutoWorkerReset<'a> {
workerscope: &'a DedicatedWorkerGlobalScope,
old_worker: Option<TrustedWorkerAddress>,
}
impl<'a> AutoWorkerReset<'a> {
fn new(workerscope: &'a DedicatedWorkerGlobalScope,
worker: TrustedWorkerAddress)
-> AutoWorkerReset<'a> {
AutoWorkerReset {
workerscope: workerscope,
old_worker: replace(&mut *workerscope.worker.borrow_mut(), Some(worker)),
}
}
}
impl<'a> Drop for AutoWorkerReset<'a> {
fn drop(&mut self) {
*self.workerscope.worker.borrow_mut() = self.old_worker.clone();
}
}
enum MixedMessage {
FromWorker((TrustedWorkerAddress, WorkerScriptMsg)),
FromScheduler((TrustedWorkerAddress, TimerEvent)),
FromDevtools(DevtoolScriptControlMsg)
}
// https://html.spec.whatwg.org/multipage/#dedicatedworkerglobalscope
#[dom_struct]
pub struct DedicatedWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope,
#[ignore_heap_size_of = "Defined in std"]
receiver: Receiver<(TrustedWorkerAddress, WorkerScriptMsg)>,
#[ignore_heap_size_of = "Defined in std"]
own_sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
#[ignore_heap_size_of = "Defined in std"]
timer_event_port: Receiver<(TrustedWorkerAddress, TimerEvent)>,
#[ignore_heap_size_of = "Trusted<T> has unclear ownership like JS<T>"]
worker: DOMRefCell<Option<TrustedWorkerAddress>>,
#[ignore_heap_size_of = "Can't measure trait objects"]
/// Sender to the parent thread.
parent_sender: Box<ScriptChan + Send>,
}
impl DedicatedWorkerGlobalScope {
fn new_inherited(init: WorkerGlobalScopeInit,
worker_url: ServoUrl,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
runtime: Runtime,
parent_sender: Box<ScriptChan + Send>,
own_sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, WorkerScriptMsg)>,
timer_event_chan: IpcSender<TimerEvent>,
timer_event_port: Receiver<(TrustedWorkerAddress, TimerEvent)>,
closing: Arc<AtomicBool>)
-> DedicatedWorkerGlobalScope {
DedicatedWorkerGlobalScope {
workerglobalscope: WorkerGlobalScope::new_inherited(init,
worker_url,
runtime,
from_devtools_receiver,
timer_event_chan,<|fim▁hole|> timer_event_port: timer_event_port,
parent_sender: parent_sender,
worker: DOMRefCell::new(None),
}
}
#[allow(unsafe_code)]
pub fn new(init: WorkerGlobalScopeInit,
worker_url: ServoUrl,
from_devtools_receiver: Receiver<DevtoolScriptControlMsg>,
runtime: Runtime,
parent_sender: Box<ScriptChan + Send>,
own_sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, WorkerScriptMsg)>,
timer_event_chan: IpcSender<TimerEvent>,
timer_event_port: Receiver<(TrustedWorkerAddress, TimerEvent)>,
closing: Arc<AtomicBool>)
-> Root<DedicatedWorkerGlobalScope> {
let cx = runtime.cx();
let scope = box DedicatedWorkerGlobalScope::new_inherited(init,
worker_url,
from_devtools_receiver,
runtime,
parent_sender,
own_sender,
receiver,
timer_event_chan,
timer_event_port,
closing);
unsafe {
DedicatedWorkerGlobalScopeBinding::Wrap(cx, scope)
}
}
#[allow(unsafe_code)]
pub fn run_worker_scope(init: WorkerGlobalScopeInit,
worker_url: ServoUrl,
from_devtools_receiver: IpcReceiver<DevtoolScriptControlMsg>,
worker_rt_for_mainthread: Arc<Mutex<Option<SharedRt>>>,
worker: TrustedWorkerAddress,
parent_sender: Box<ScriptChan + Send>,
own_sender: Sender<(TrustedWorkerAddress, WorkerScriptMsg)>,
receiver: Receiver<(TrustedWorkerAddress, WorkerScriptMsg)>,
worker_load_origin: WorkerScriptLoadOrigin,
closing: Arc<AtomicBool>) {
let serialized_worker_url = worker_url.to_string();
let name = format!("WebWorker for {}", serialized_worker_url);
let top_level_browsing_context_id = TopLevelBrowsingContextId::installed();
let origin = GlobalScope::current().expect("No current global object").origin().immutable().clone();
thread::Builder::new().name(name).spawn(move || {
thread_state::initialize(thread_state::SCRIPT | thread_state::IN_WORKER);
if let Some(top_level_browsing_context_id) = top_level_browsing_context_id {
TopLevelBrowsingContextId::install(top_level_browsing_context_id);
}
let roots = RootCollection::new();
let _stack_roots_tls = StackRootTLS::new(&roots);
let WorkerScriptLoadOrigin { referrer_url, referrer_policy, pipeline_id } = worker_load_origin;
let request = RequestInit {
url: worker_url.clone(),
type_: RequestType::Script,
destination: Destination::Worker,
credentials_mode: CredentialsMode::Include,
use_url_credentials: true,
pipeline_id: pipeline_id,
referrer_url: referrer_url,
referrer_policy: referrer_policy,
origin,
.. RequestInit::default()
};
let (metadata, bytes) = match load_whole_resource(request,
&init.resource_threads.sender()) {
Err(_) => {
println!("error loading script {}", serialized_worker_url);
parent_sender.send(CommonScriptMsg::RunnableMsg(WorkerEvent,
box SimpleWorkerErrorHandler::new(worker))).unwrap();
return;
}
Ok((metadata, bytes)) => (metadata, bytes)
};
let url = metadata.final_url;
let source = String::from_utf8_lossy(&bytes);
let runtime = unsafe { new_rt_and_cx() };
*worker_rt_for_mainthread.lock().unwrap() = Some(SharedRt::new(&runtime));
let (devtools_mpsc_chan, devtools_mpsc_port) = channel();
ROUTER.route_ipc_receiver_to_mpsc_sender(from_devtools_receiver, devtools_mpsc_chan);
let (timer_tx, timer_rx) = channel();
let (timer_ipc_chan, timer_ipc_port) = ipc::channel().unwrap();
let worker_for_route = worker.clone();
ROUTER.add_route(timer_ipc_port.to_opaque(), box move |message| {
let event = message.to().unwrap();
timer_tx.send((worker_for_route.clone(), event)).unwrap();
});
let global = DedicatedWorkerGlobalScope::new(
init, url, devtools_mpsc_port, runtime,
parent_sender.clone(), own_sender, receiver,
timer_ipc_chan, timer_rx, closing);
// FIXME(njn): workers currently don't have a unique ID suitable for using in reporter
// registration (#6631), so we instead use a random number and cross our fingers.
let scope = global.upcast::<WorkerGlobalScope>();
unsafe {
// Handle interrupt requests
JS_SetInterruptCallback(scope.runtime(), Some(interrupt_callback));
}
if scope.is_closing() {
return;
}
{
let _ar = AutoWorkerReset::new(&global, worker.clone());
scope.execute_script(DOMString::from(source));
}
let reporter_name = format!("dedicated-worker-reporter-{}", random::<u64>());
scope.upcast::<GlobalScope>().mem_profiler_chan().run_with_memory_reporting(|| {
// https://html.spec.whatwg.org/multipage/#event-loop-processing-model
// Step 1
while let Ok(event) = global.receive_event() {
if scope.is_closing() {
break;
}
// Step 3
global.handle_event(event);
// Step 6
let _ar = AutoWorkerReset::new(&global, worker.clone());
global.upcast::<WorkerGlobalScope>().perform_a_microtask_checkpoint();
}
}, reporter_name, parent_sender, CommonScriptMsg::CollectReports);
}).expect("Thread spawning failed");
}
pub fn script_chan(&self) -> Box<ScriptChan + Send> {
box WorkerThreadWorkerChan {
sender: self.own_sender.clone(),
worker: self.worker.borrow().as_ref().unwrap().clone(),
}
}
pub fn new_script_pair(&self) -> (Box<ScriptChan + Send>, Box<ScriptPort + Send>) {
let (tx, rx) = channel();
let chan = box SendableWorkerScriptChan {
sender: tx,
worker: self.worker.borrow().as_ref().unwrap().clone(),
};
(chan, box rx)
}
pub fn process_event(&self, msg: CommonScriptMsg) {
self.handle_script_event(WorkerScriptMsg::Common(msg));
}
#[allow(unsafe_code)]
fn receive_event(&self) -> Result<MixedMessage, RecvError> {
let scope = self.upcast::<WorkerGlobalScope>();
let worker_port = &self.receiver;
let timer_event_port = &self.timer_event_port;
let devtools_port = scope.from_devtools_receiver();
let sel = Select::new();
let mut worker_handle = sel.handle(worker_port);
let mut timer_event_handle = sel.handle(timer_event_port);
let mut devtools_handle = sel.handle(devtools_port);
unsafe {
worker_handle.add();
timer_event_handle.add();
if scope.from_devtools_sender().is_some() {
devtools_handle.add();
}
}
let ret = sel.wait();
if ret == worker_handle.id() {
Ok(MixedMessage::FromWorker(worker_port.recv()?))
} else if ret == timer_event_handle.id() {
Ok(MixedMessage::FromScheduler(timer_event_port.recv()?))
} else if ret == devtools_handle.id() {
Ok(MixedMessage::FromDevtools(devtools_port.recv()?))
} else {
panic!("unexpected select result!")
}
}
fn handle_script_event(&self, msg: WorkerScriptMsg) {
match msg {
WorkerScriptMsg::DOMMessage(data) => {
let scope = self.upcast::<WorkerGlobalScope>();
let target = self.upcast();
let _ac = JSAutoCompartment::new(scope.get_cx(),
scope.reflector().get_jsobject().get());
rooted!(in(scope.get_cx()) let mut message = UndefinedValue());
data.read(scope.upcast(), message.handle_mut());
MessageEvent::dispatch_jsval(target, scope.upcast(), message.handle());
},
WorkerScriptMsg::Common(CommonScriptMsg::RunnableMsg(_, runnable)) => {
runnable.handler()
},
WorkerScriptMsg::Common(CommonScriptMsg::CollectReports(reports_chan)) => {
let scope = self.upcast::<WorkerGlobalScope>();
let cx = scope.get_cx();
let path_seg = format!("url({})", scope.get_url());
let reports = get_reports(cx, path_seg);
reports_chan.send(reports);
}
}
}
fn handle_event(&self, event: MixedMessage) {
match event {
MixedMessage::FromDevtools(msg) => {
match msg {
DevtoolScriptControlMsg::EvaluateJS(_pipe_id, string, sender) =>
devtools::handle_evaluate_js(self.upcast(), string, sender),
DevtoolScriptControlMsg::GetCachedMessages(pipe_id, message_types, sender) =>
devtools::handle_get_cached_messages(pipe_id, message_types, sender),
DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, bool_val) =>
devtools::handle_wants_live_notifications(self.upcast(), bool_val),
_ => debug!("got an unusable devtools control message inside the worker!"),
}
},
MixedMessage::FromScheduler((linked_worker, timer_event)) => {
match timer_event {
TimerEvent(TimerSource::FromWorker, id) => {
let _ar = AutoWorkerReset::new(self, linked_worker);
let scope = self.upcast::<WorkerGlobalScope>();
scope.handle_fire_timer(id);
},
TimerEvent(_, _) => {
panic!("A worker received a TimerEvent from a window.")
}
}
}
MixedMessage::FromWorker((linked_worker, msg)) => {
let _ar = AutoWorkerReset::new(self, linked_worker);
self.handle_script_event(msg);
}
}
}
pub fn forward_error_to_worker_object(&self, error_info: ErrorInfo) {
let worker = self.worker.borrow().as_ref().unwrap().clone();
// TODO: Should use the DOM manipulation task source.
self.parent_sender
.send(CommonScriptMsg::RunnableMsg(WorkerEvent,
box WorkerErrorHandler::new(worker, error_info)))
.unwrap();
}
}
#[allow(unsafe_code)]
unsafe extern "C" fn interrupt_callback(cx: *mut JSContext) -> bool {
let worker =
Root::downcast::<WorkerGlobalScope>(GlobalScope::from_context(cx))
.expect("global is not a worker scope");
assert!(worker.is::<DedicatedWorkerGlobalScope>());
// A false response causes the script to terminate
!worker.is_closing()
}
impl DedicatedWorkerGlobalScopeMethods for DedicatedWorkerGlobalScope {
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue) -> ErrorResult {
let data = StructuredCloneData::write(cx, message)?;
let worker = self.worker.borrow().as_ref().unwrap().clone();
self.parent_sender
.send(CommonScriptMsg::RunnableMsg(WorkerEvent,
box WorkerMessageHandler::new(worker, data)))
.unwrap();
Ok(())
}
// https://html.spec.whatwg.org/multipage/#dom-dedicatedworkerglobalscope-close
fn Close(&self) {
// Step 2
self.upcast::<WorkerGlobalScope>().close();
}
// https://html.spec.whatwg.org/multipage/#handler-dedicatedworkerglobalscope-onmessage
event_handler!(message, GetOnmessage, SetOnmessage);
}<|fim▁end|> | Some(closing)),
receiver: receiver,
own_sender: own_sender, |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|># Copyright 2013 Kylin, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT<|fim▁hole|># License for the specific language governing permissions and limitations
# under the License.
from django.conf.urls import patterns
from django.conf.urls import url
from openstack_dashboard.dashboards.admin.defaults import views
urlpatterns = patterns(
'openstack_dashboard.dashboards.admin.defaults.views',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^update_defaults$',
views.UpdateDefaultQuotasView.as_view(), name='update_defaults'))<|fim▁end|> | # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
<|file_name|>log.py<|end_file_name|><|fim▁begin|>import logging
import terminal
INFO = logging.INFO
# between info and debug
VERBOSE = (logging.INFO + logging.DEBUG) / 2
DEBUG = logging.DEBUG
log = logging.getLogger('rdopkg')
log.setLevel(logging.INFO)
if len(log.handlers) < 1:
formatter = logging.Formatter(fmt='%(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
log.addHandler(handler)
class LogTerminal(terminal.Terminal):
@property
def warn(self):
return self.yellow
@property
def important(self):
return self.yellow_bold
@property
def error(self):
return self.red
@property<|fim▁hole|>
@property
def cmd(self):
return self.cyan
term = LogTerminal()
def set_colors(colors):
global term
if colors == 'yes':
if not terminal.COLOR_TERMINAL:
return False
term = LogTerminal(force_styling=True)
return True
elif colors == 'no':
if not terminal.COLOR_TERMINAL:
return True
term = LogTerminal(force_styling=None)
return True
elif colors == 'auto':
term = LogTerminal()
return True
return False
def error(*args, **kwargs):
if args:
largs = list(args)
largs[0] = term.error(args[0])
args = tuple(largs)
log.error(*args, **kwargs)
def warn(*args, **kwargs):
if args:
largs = list(args)
largs[0] = term.warn(args[0])
args = tuple(largs)
log.warning(*args, **kwargs)
def success(*args, **kwargs):
if args:
largs = list(args)
largs[0] = term.good(args[0])
args = tuple(largs)
log.info(*args, **kwargs)
def info(*args, **kwargs):
log.info(*args, **kwargs)
def verbose(*args, **kwargs):
log.log(VERBOSE, *args, **kwargs)
def debug(*args, **kwargs):
log.debug(*args, **kwargs)
def command(*args, **kwargs):
log.info(*args, **kwargs)<|fim▁end|> | def good(self):
return self.green |
<|file_name|>Everwing_data.py<|end_file_name|><|fim▁begin|>from ast import literal_eval
from json import dumps, loads
from urllib2 import Request, urlopen
from requests import post, get
from p3lzstring import LZString
def user_input(data):
i = 0
while i < len(data):
if 'xp' in data[i]['dragondata']['sidekick_name'][9:][5:]:
data[i]['dragondata']['value'] = data[i]['dragondata']['maximum']
print (data[i]['dragondata']['value'])
else:
if 'maturity' in data[i]['dragondata']['sidekick_name'][9:][5:]:
data[i]['dragondata']['value'] = data[i]['dragondata']['maximum']
print (data[i]['dragondata']['value'])
i = i + 1
return data
def lz_string_decode(lzstring):
lz_object = LZString.decompressFromBase64(lzstring)
return lz_object
def dict_loop(p, check_list, scheme_pid):
i = 0
while i < len(state_dict['instances']):
for key in state_dict['instances'].iterkeys():
if p in key:
return state_dict['instances'][key]
i = i + 1
return 'Found Nothing'
def build_xpmat_list(state_dict):
i = 0
while i < len(state_dict['instances']):
list = []
for key in state_dict['instances'].iterkeys():
pg = float((float(i) / float(len(state_dict['instances'])) * float(100)))
# update_progress(pg)
schemePID = state_dict['instances'][str(key)]['schemaPrimativeID']
dict_index = state_dict['instances'][str(key)]
if 'stats' in dict_index.keys() and 'sidekick' in schemePID:
check_list = []
stat_keys = dict_index['stats']
for stats in stat_keys:
data = dict_loop(stats, check_list, schemePID)
check_list.append(schemePID)
if 'maturity' in data['schemaPrimativeID']:
list.append({'Maturity': data})
if 'xp' in data['schemaPrimativeID']:
list.append({'XP': data})
i = i + 1
print "%s / %s" % (i, len(state_dict['instances']))
return list
def conv2Json(jsonString, *args, **kwargs):
jsonObject = literal_eval(jsonString)
return jsonObject
def conv2JsonStr(jsonObject):
jsonString = dumps(dumps(jsonObject))
return jsonString
def ever_wing_token():
req = Request("https://wintermute-151001.appspot.com/game/session/everwing/" + uID)
response = urlopen(req)
data = response.read()
Token = conv2Json(data)
return Token
def ever_wing_defaultaction():
return
def lz_string_encode(object):
lzObject = LZString.compressToBase64(object)
print (lzObject)
return lzObject
def default_state():
url = 'https://wintermute-151001.appspot.com'
gamestate_url = '/game/state/everwing/default/' + uID
state = get(url + gamestate_url)
return state.content
def post_to_winter(user_data, Token):
user_data = unicode(user_data)
headers = {"Host": "wintermute-151001.appspot.com",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate, br",
"Content-Type": "application/json;charset=utf-8",
"x-wintermute-session": str(Token['token']),
"Connection": "keep-alive"}
print (user_data)
print (headers)
post_data = post('https://wintermute-151001.appspot.com/game/action', data=user_data, headers=headers)
return
def rebuild_loop(p, list, x, maturity, XP):
i = 0
if maturity == 'Maturity':
while i < len(state_dict):
for key in state_dict['instances'].iterkeys():
if p in key:
state_dict['instances'][key] = list[x][maturity]
i = i + 1
if XP == 'XP':
while i < len(state_dict):
for key in state_dict['instances'].iterkeys():
if p in key:
state_dict['instances'][key] = list[x][XP]
i = i + 1
return 'THIS IS IT'
def build_state_dict(list):
i = 0
while i < len(list):
try:
if list[i]["Maturity"]:
key_index = list[i]['Maturity']['key']
rebuild_loop(key_index, list, i, maturity='Maturity', XP=2)
pass
<|fim▁hole|> if list[i]['XP']:
key_index = list[i]['XP']['key']
rebuild_loop(key_index, list, i, XP='XP', maturity=3)
i = i + 1
print '%s / %s' % (i, len(list))
return
def fuck_dat_currency():
for instance in state_dict['instances']:
try:
if state_dict['instances'][instance]['schemaPrimativeID'] == "currency:trophy":
state_dict['instances'][instance]['balance'] = 999999
if state_dict['instances'][instance]['schemaPrimativeID'] == "currency:coin":
state_dict['instances'][instance]['balance'] = 999999
except Exception as e:
print "%s" % e
return
def rebuild_state(list, state_dict):
i = 0
while i < len(list):
if list[i]['Maturity']['value']:
list[i]['Maturity']['value'] = 3
if list[i]['Maturity']['value'] == 3:
list[i + 1]['XP']['value'] = 125800
list[i + 1]['XP']['maximum'] = 125800
if list[i]['Maturity']['value'] == 2:
list[i + 1]['XP']['value'] = 62800
list[i + 1]['XP']['maximum'] = 62800
if list[i]['Maturity']['value'] == 1:
list[i + 1]['XP']['value'] = 62800
list[i + 1]['XP']['maximum'] = 62800
i = i + 2
return list
def get_dat_toonies():
characterStrings = ['character:lenore_item_character', 'character:coin_item_character',
'character:sophia_item_character', 'character:jade_item_character',
'character:arcana_item_character', 'character:fiona_item_character',
'character:standard_item_character', 'character:magnet_item_character']
for instance in state_dict['instances']:
try:
if state_dict['instances'][instance]['schemaPrimativeID'] in characterStrings:
characterStat = state_dict['instances'][instance]['stats'][0]
state_dict['instances'][characterStat]['value'] = state_dict['instances'][characterStat]['maximum']
if state_dict['instances'][instance]['state'] == 'locked':
state_dict['instances'][instance]['state'] = 'idle'
except Exception:
print (Exception.message)
return
if __name__ == '__main__':
uID = raw_input('Please Input User ID: ')
user_data = loads(default_state())
state = user_data['state'][11:]
print (state)
state = lz_string_decode(str(state))
state_json_str = conv2Json(state)
state_dict = loads(state_json_str)
input = raw_input('Do you wanna upgrade all current Dragons? (Y/n)')
if input == 'Y':
build_state_dict(rebuild_state(build_xpmat_list(state_dict), state_dict))
else:
print('-------------------------------')
print("You must enter a 'Y' or 'n'!!")
print('-------------------------------')
input = raw_input('Do you wanna fuck da currency? (Y/n)')
if input == 'Y':
fuck_dat_currency()
else:
print('-------------------------------')
print("You must enter a 'Y' or 'n'!!")
print('-------------------------------')
input = raw_input('Do you want all Characters / level 50? (Y/N)')
if input == 'Y':
get_dat_toonies()
else:
print('-------------------------------')
print("You must enter a 'Y' or 'n'!!")
print('-------------------------------')
a = open('statefile.txt', 'w')
a.write(dumps(state_dict, sort_keys=True, indent=4))
a.close()
state_dict = conv2JsonStr(state_dict)
encoded_state = lz_string_encode(state_dict)
encoded_state = 'lz-string::' + encoded_state
user_data['state'] = encoded_state
user_data['timestamp'] = round(float(get('https://wintermute-151001.appspot.com/game/time').content),
ndigits=0)
user_data['server_timestamp'] = round(
float(get('https://wintermute-151001.appspot.com/game/time').content), ndigits=0)
user_data = dumps(user_data)
post_to_winter(user_data, ever_wing_token())
print(user_data)<|fim▁end|> | except KeyError:
|
<|file_name|>test_grocerylist.py<|end_file_name|><|fim▁begin|>from classes import wunderpy_wrapper
from classes import grocerylist
from classes import grocerystore
wp = wunderpy_wrapper.wunderpy_wrapper('../data/tokens.csv')
obj = wp.get_task_positions_obj(wp.WUNDERLIST_GROCERY)
grocery_store = grocerystore.groceryStore('../data/store_order_zehrs.csv', '../data/ingredient_categories.csv') # use the default zehrs store; good enough
groceries = grocerylist.groceryList(wp.WUNDERLIST_GROCERY, wp)
groceries.get_tasks()
groceries.get_category_for_element(groceries.grocery_list[0], grocery_store)
groceries.get_categories(grocery_store)
groceries.reorder_list(wp)
# wp.update_list_order(groceries.wunderlist_order_obj)
<|fim▁hole|><|fim▁end|> | # TODO check reloading of a list when you enter the right sheet
# TODO sort by cat order value, not cat id.
print('done') |
<|file_name|>updater.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
import re
import json
import tempfile
import toml
import os
class RequirementsTXTUpdater(object):
SUB_REGEX = r"^{}(?=\s*\r?\n?$)"
@classmethod
def update(cls, content, dependency, version, spec="==", hashes=()):
"""
Updates the requirement to the latest version for the given content and adds hashes
if neccessary.
:param content: str, content
:return: str, updated content
"""
new_line = "{name}{spec}{version}".format(name=dependency.full_name, spec=spec, version=version)
appendix = ''
# leave environment markers intact
if ";" in dependency.line:
# condense multiline, split out the env marker, strip comments and --hashes
new_line += ";" + dependency.line.splitlines()[0].split(";", 1)[1] \
.split("#")[0].split("--hash")[0].rstrip()
# add the comment
if "#" in dependency.line:
# split the line into parts: requirement and comment
parts = dependency.line.split("#")
requirement, comment = parts[0], "#".join(parts[1:])
# find all whitespaces between the requirement and the comment
whitespaces = (hex(ord('\t')), hex(ord(' ')))
trailing_whitespace = ''
for c in requirement[::-1]:
if hex(ord(c)) in whitespaces:
trailing_whitespace += c
else:
break
appendix += trailing_whitespace + "#" + comment
# if this is a hashed requirement, add a multiline break before the comment
if dependency.hashes and not new_line.endswith("\\"):
new_line += " \\"
# if this is a hashed requirement, add the hashes
if hashes:
for n, new_hash in enumerate(hashes):
new_line += "\n --hash={method}:{hash}".format(
method=new_hash['method'],
hash=new_hash['hash']
)
# append a new multiline break if this is not the last line
if len(hashes) > n + 1:
new_line += " \\"
new_line += appendix
regex = cls.SUB_REGEX.format(re.escape(dependency.line))
return re.sub(regex, new_line, content, flags=re.MULTILINE)
class CondaYMLUpdater(RequirementsTXTUpdater):
SUB_REGEX = r"{}(?=\s*\r?\n?$)"
class ToxINIUpdater(CondaYMLUpdater):
pass
class SetupCFGUpdater(CondaYMLUpdater):
pass
class PipfileUpdater(object):
@classmethod
def update(cls, content, dependency, version, spec="==", hashes=()):
data = toml.loads(content)
if data:
for package_type in ['packages', 'dev-packages']:
if package_type in data:
if dependency.full_name in data[package_type]:
data[package_type][dependency.full_name] = "{spec}{version}".format(
spec=spec, version=version
)
try:
from pipenv.project import Project
except ImportError:
raise ImportError("Updating a Pipfile requires the pipenv extra to be installed. Install it with "
"pip install dparse[pipenv]")
pipfile = tempfile.NamedTemporaryFile(delete=False)
p = Project(chdir=False)
p.write_toml(data=data, path=pipfile.name)
data = open(pipfile.name).read()
os.remove(pipfile.name)<|fim▁hole|>class PipfileLockUpdater(object):
@classmethod
def update(cls, content, dependency, version, spec="==", hashes=()):
data = json.loads(content)
if data:
for package_type in ['default', 'develop']:
if package_type in data:
if dependency.full_name in data[package_type]:
data[package_type][dependency.full_name] = {
'hashes': [
"{method}:{hash}".format(
hash=h['hash'],
method=h['method']
) for h in hashes
],
'version': "{spec}{version}".format(
spec=spec, version=version
)
}
return json.dumps(data, indent=4, separators=(',', ': ')) + "\n"<|fim▁end|> | return data
|
<|file_name|>entity.py<|end_file_name|><|fim▁begin|>"""Base class for Tado entity."""
from homeassistant.helpers.entity import Entity
from .const import DEFAULT_NAME, DOMAIN, TADO_ZONE
class TadoDeviceEntity(Entity):
"""Base implementation for Tado device."""
def __init__(self, device_info):
"""Initialize a Tado device."""
super().__init__()
self._device_info = device_info
self.device_name = device_info["shortSerialNo"]
self.device_id = device_info["serialNo"]
@property
def device_info(self):
"""Return the device_info of the device."""
return {
"identifiers": {(DOMAIN, self.device_id)},
"name": self.device_name,
"manufacturer": DEFAULT_NAME,
"sw_version": self._device_info["currentFwVersion"],
"model": self._device_info["deviceType"],
"via_device": (DOMAIN, self._device_info["serialNo"]),
}
@property
def should_poll(self):
"""Do not poll."""
return False
class TadoZoneEntity(Entity):<|fim▁hole|> super().__init__()
self._device_zone_id = f"{home_id}_{zone_id}"
self.zone_name = zone_name
@property
def device_info(self):
"""Return the device_info of the device."""
return {
"identifiers": {(DOMAIN, self._device_zone_id)},
"name": self.zone_name,
"manufacturer": DEFAULT_NAME,
"model": TADO_ZONE,
}
@property
def should_poll(self):
"""Do not poll."""
return False<|fim▁end|> | """Base implementation for Tado zone."""
def __init__(self, zone_name, home_id, zone_id):
"""Initialize a Tado zone.""" |
<|file_name|>track_metadata.hpp<|end_file_name|><|fim▁begin|>/*
* Turbo Sliders++
* Copyright (C) 2013-2014 Martin Newhouse
*
* 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.
*/
#pragma once
<|fim▁hole|>#ifndef TRACK_METADATA_HPP
#define TRACK_METADATA_HPP
#include "track_identifier.hpp"
namespace ts
{
namespace resources
{
class Track_handle;
struct Track_metadata
{
Track_identifier identifier;
utf8_string gamemode;
};
Track_metadata load_track_metadata(const resources::Track_handle& track_handle);
}
}
#endif<|fim▁end|> | |
<|file_name|>static-mut-reference-across-yield.rs<|end_file_name|><|fim▁begin|>// build-pass
// revisions: mir thir
// [thir]compile-flags: -Zthir-unsafeck
#![feature(generators)]<|fim▁hole|>
static mut A: [i32; 5] = [1, 2, 3, 4, 5];
fn is_send_sync<T: Send + Sync>(_: T) {}
fn main() {
unsafe {
let gen_index = static || {
let u = A[{
yield;
1
}];
};
let gen_match = static || match A {
i if {
yield;
true
} =>
{
()
}
_ => (),
};
is_send_sync(gen_index);
is_send_sync(gen_match);
}
}<|fim▁end|> | |
<|file_name|>elasticache.rs<|end_file_name|><|fim▁begin|>#![cfg(feature = "elasticache")]
extern crate rusoto;
use rusoto::elasticache::{ElastiCacheClient, DescribeCacheClustersMessage};
use rusoto::{DefaultCredentialsProvider, Region};<|fim▁hole|>
#[test]
fn should_describe_cache_clusters() {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = ElastiCacheClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
let request = DescribeCacheClustersMessage::default();
let response = client.describe_cache_clusters(&request).unwrap();
println!("{:#?}", response);
}<|fim▁end|> | use rusoto::default_tls_client; |
<|file_name|>medlemsinput.py<|end_file_name|><|fim▁begin|># Graphical paste and save GUI for adding members
from Tkinter import *
import os
import pdb
import datetime
lday = 04
lmonth = 10
class myDate:
def __init__(self, year, month, day):
self.date = datetime.datetime(year, month, day)
self.updateString()
def getMonthDay(self):
lday = format(self.date.day, '02')
lmonth = format(self.date.month, '02')
return lmonth + lday
def getfilename(self):
lfdate = self.getMonthDay()
lfname = lfdate + "-" + nextfname(lfdate) + ".txt"
return lfname
def updateString(self):
self.datestr = self.date.strftime("%m%d")
def updateDate(self, dt_obj):
self.date = dt_obj
date = myDate(2015, lmonth, lday)
def save(date):
f = open(date.getfilename(), "w")
t = text.get("1.0", END)
f.write(t.encode('utf8'))
f.close()
lfname = date.getfilename()
llabel.configure(text = lfname)
def add_day(date):
dt = datetime.datetime(2015, date.date.month, date.date.day)
dt = dt + datetime.timedelta(days=1)
date.updateDate(dt)
date.updateString()
lfname = date.getfilename()
llabel.configure(text = lfname)
def sub_day(date):
dt = datetime.datetime(2015, date.date.month, date.date.day)
dt = dt - datetime.timedelta(days=1)
date.updateDate(dt)
date.updateString()
lfname = date.getfilename()
llabel.configure(text = lfname)
def select_all(event):
text.tag_add(SEL, "1.0", END)
text.mark_set(INSERT, "1.0")
text.see(INSERT)
return 'break'
def nextfname(prefix):
first = 1
fstr = format(first, '02')
while os.path.exists(prefix + "-" + fstr + ".txt"):<|fim▁hole|>root = Tk()
text = Text(root)
text.insert(INSERT, "")
text.bind("<Control-Key-a>", select_all)
text.grid()
bsave = Button(root, text="Save", command=lambda: save(date))
bsave.grid(columnspan=2, column=1, row=0)
dplus = Button(root, text="d+", command=lambda: add_day(date))
dplus.grid(column=1, row=1)
dminus = Button(root, text="d-", command=lambda: sub_day(date))
dminus.grid(column=2, row=1)
lfname = date.getfilename()
llabel = Label(root, text=lfname)
llabel.grid(columnspan=2, column=1, row=2)
root.mainloop()<|fim▁end|> | first = first + 1
fstr = format(first, '02')
return fstr
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from ajenti.api import *
from ajenti.plugins import *
info = PluginInfo(
title='Hosts',
icon='sitemap',
dependencies=[
PluginDependency('main'),
],
)
def init():
import main<|fim▁end|> | |
<|file_name|>getargs_dict.py<|end_file_name|><|fim▁begin|>def task_compute():<|fim▁hole|> def comp():
return {'x':5,'y':10, 'z': 20}
return {'actions': [(comp,)]}
def show_getargs(values):
print(values)
def task_args_dict():
return {'actions': [show_getargs],
'getargs': {'values': ('compute', None)},
'verbosity': 2,
}<|fim▁end|> | |
<|file_name|>valorchat.server.socket.config.js<|end_file_name|><|fim▁begin|>'use strict';
// Create the valorchat configuration
module.exports = function (io, socket) {
// Emit the status event when a new socket client is connected
io.emit('ValorchatMessage', {
type: 'status',
text: 'Is now connected',
created: Date.now(),
profileImageURL: socket.request.user.profileImageURL,
username: socket.request.user.username
});
// Send a valorchat messages to all connected sockets when a message is received
socket.on('ValorchatMessage', function (message) {
message.type = 'message';
message.created = Date.now();
message.profileImageURL = socket.request.user.profileImageURL;<|fim▁hole|> io.emit('ValorchatMessage', message);
});
// Emit the status event when a socket client is disconnected
socket.on('disconnect', function () {
io.emit('ValorchatMessage', {
type: 'status',
text: 'disconnected',
created: Date.now(),
profileImageURL: socket.request.user.profileImageURL,
username: socket.request.user.username
});
});
};<|fim▁end|> | message.username = socket.request.user.username;
// Emit the 'ValorchatMessage' event |
<|file_name|>CModuleNode.java<|end_file_name|><|fim▁begin|>/*
Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Module;
import com.google.common.base.Preconditions;
import com.google.security.zynamics.binnavi.CMain;
import com.google.security.zynamics.binnavi.Database.Interfaces.IDatabase;
import com.google.security.zynamics.binnavi.Gui.MainWindow.Implementations.CModuleFunctions;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractLazyComponent;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CAbstractNodeComponent;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.CProjectTreeNode;
import com.google.security.zynamics.binnavi.Gui.MainWindow.ProjectTree.Nodes.Module.Component.CModuleNodeComponent;
import com.google.security.zynamics.binnavi.disassembly.CProjectContainer;
import com.google.security.zynamics.binnavi.disassembly.INaviAddressSpace;
import com.google.security.zynamics.binnavi.disassembly.INaviModule;
import com.google.security.zynamics.binnavi.disassembly.Modules.CModuleContainer;
import com.google.security.zynamics.binnavi.disassembly.Modules.CModuleListenerAdapter;
import com.google.security.zynamics.binnavi.disassembly.views.INaviView;
import com.google.security.zynamics.binnavi.disassembly.views.IViewContainer;
import com.google.security.zynamics.zylib.gui.SwingInvoker;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* Represents module nodes in the project tree.
*/
public final class CModuleNode extends CProjectTreeNode<INaviModule> {<|fim▁hole|> /**
* Used for serialization.
*/
private static final long serialVersionUID = -5643276356053733957L;
/**
* Icon used for loaded modules in the project tree.
*/
private static final ImageIcon ICON_MODULE =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module.png"));
/**
* Icon used for unloaded modules in the project tree.
*/
private static final ImageIcon ICON_MODULE_GRAY =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_gray.png"));
/**
* Icon used for incomplete modules in the project tree.
*/
private static final ImageIcon ICON_MODULE_BROKEN =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_broken.png"));
/**
* Icon used for not yet converted modules in the project tree.
*/
private static final ImageIcon ICON_MODULE_UNCONVERTED =
new ImageIcon(CMain.class.getResource("data/projecttreeicons/project_module_light_gray.png"));
/**
* The module described by the node.
*/
private final INaviModule m_module;
/**
* Context in which views of the represented module are opened.
*/
private final IViewContainer m_contextContainer;
/**
* Updates the node on important changes in the represented module.
*/
private final InternalModuleListener m_listener;
/**
* Constructor for modules inside projects.
*
* @param projectTree Project tree of the main window.
* @param parentNode Parent node of this node.
* @param database Database the module belongs to.
* @param addressSpace The address space the module belongs to.
* @param module Module represented by this node.
* @param contextContainer The container in whose context the views are opened.
*/
public CModuleNode(final JTree projectTree,
final DefaultMutableTreeNode parentNode,
final IDatabase database,
final INaviAddressSpace addressSpace,
final INaviModule module,
final CProjectContainer contextContainer) {
super(projectTree, new CAbstractLazyComponent() {
@Override
protected CAbstractNodeComponent createComponent() {
return new CModuleNodeComponent(projectTree, database, addressSpace, module,
contextContainer);
}
}, new CModuleNodeMenuBuilder(projectTree,
parentNode,
database,
addressSpace,
new INaviModule[] {module},
null), module);
Preconditions.checkNotNull(database, "IE01972: Database argument can't be null");
Preconditions.checkNotNull(addressSpace, "IE01973: Address space can't be null");
m_module = Preconditions.checkNotNull(module, "IE01974: Module can't be null");
m_contextContainer = contextContainer;
createChildren();
m_listener = new InternalModuleListener();
m_module.addListener(m_listener);
}
/**
* Constructor for modules outside projects.
*
* @param projectTree Project tree of the main window.
* @param parentNode Parent node of this node.
* @param database Database the module belongs to.
* @param module Module represented by this node.
* @param contextContainer The container in whose context the views are opened.
*/
public CModuleNode(final JTree projectTree, final DefaultMutableTreeNode parentNode,
final IDatabase database, final INaviModule module, final CModuleContainer contextContainer) {
super(projectTree, new CAbstractLazyComponent() {
@Override
protected CAbstractNodeComponent createComponent() {
return new CModuleNodeComponent(projectTree, database, null, module, contextContainer);
}
}, new CModuleNodeMenuBuilder(projectTree,
parentNode,
database,
null,
new INaviModule[] {module},
null), module);
Preconditions.checkNotNull(database, "IE01970: Database can't be null");
m_module = Preconditions.checkNotNull(module, "IE01971: Module can't be null");
m_contextContainer = contextContainer;
createChildren();
m_listener = new InternalModuleListener();
m_module.addListener(m_listener);
}
/**
* Creates the child nodes of the module node. One node is added for the native Call graph of the
* module, another node is added that contains all native Flow graph views of the module.
*/
@Override
protected void createChildren() {}
@Override
public void dispose() {
super.dispose();
m_contextContainer.dispose();
m_module.removeListener(m_listener);
deleteChildren();
}
@Override
public void doubleClicked() {
if (m_module.getConfiguration().getRawModule().isComplete() && !m_module.isLoaded()) {
CModuleFunctions.loadModules(getProjectTree(), new INaviModule[] {m_module});
}
}
@Override
public CModuleNodeComponent getComponent() {
return (CModuleNodeComponent) super.getComponent();
}
@Override
public Icon getIcon() {
if (m_module.getConfiguration().getRawModule().isComplete() && m_module.isInitialized()) {
return m_module.isLoaded() ? ICON_MODULE : ICON_MODULE_GRAY;
} else if (m_module.getConfiguration().getRawModule().isComplete()
&& !m_module.isInitialized()) {
return ICON_MODULE_UNCONVERTED;
} else {
return ICON_MODULE_BROKEN;
}
}
@Override
public String toString() {
return m_module.getConfiguration().getName() + " (" + m_module.getFunctionCount() + "/"
+ m_module.getCustomViewCount() + ")";
}
/**
* Updates the node on important changes in the represented module.
*/
private class InternalModuleListener extends CModuleListenerAdapter {
@Override
public void addedView(final INaviModule module, final INaviView view) {
getTreeModel().nodeChanged(CModuleNode.this);
}
@Override
public void changedName(final INaviModule module, final String name) {
getTreeModel().nodeChanged(CModuleNode.this);
}
@Override
public void deletedView(final INaviModule module, final INaviView view) {
getTreeModel().nodeChanged(CModuleNode.this);
}
/**
* When the module is loaded, create the child nodes.
*/
@Override
public void loadedModule(final INaviModule module) {
new SwingInvoker() {
@Override
protected void operation() {
createChildren();
getTreeModel().nodeStructureChanged(CModuleNode.this);
}
}.invokeAndWait();
}
}
}<|fim▁end|> | |
<|file_name|>migration.py<|end_file_name|><|fim▁begin|># coding: utf-8
#
# Copyright (c) 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# Base on code in migrate/changeset/databases/sqlite.py which is under
# the following license:
#
# The MIT License
#
# Copyright (c) 2009 Evan Rosson, Jan Dittberner, Domen Kožar
#
# 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.
import os
import re
from migrate.changeset import ansisql
from migrate.changeset.databases import sqlite
from migrate import exceptions as versioning_exceptions
from migrate.versioning import api as versioning_api
from migrate.versioning.repository import Repository
import sqlalchemy
from sqlalchemy.schema import UniqueConstraint
from essential.db import exception
from essential.gettextutils import _
def _get_unique_constraints(self, table):
"""Retrieve information about existing unique constraints of the table
This feature is needed for _recreate_table() to work properly.
Unfortunately, it's not available in sqlalchemy 0.7.x/0.8.x.
"""
data = table.metadata.bind.execute(
"""SELECT sql
FROM sqlite_master
WHERE
type='table' AND
name=:table_name""",
table_name=table.name
).fetchone()[0]
UNIQUE_PATTERN = "CONSTRAINT (\w+) UNIQUE \(([^\)]+)\)"
return [
UniqueConstraint(
*[getattr(table.columns, c.strip(' "')) for c in cols.split(",")],
name=name
)
for name, cols in re.findall(UNIQUE_PATTERN, data)
]
def _recreate_table(self, table, column=None, delta=None, omit_uniques=None):
"""Recreate the table properly
Unlike the corresponding original method of sqlalchemy-migrate this one
doesn't drop existing unique constraints when creating a new one.
"""
table_name = self.preparer.format_table(table)
# we remove all indexes so as not to have
# problems during copy and re-create
for index in table.indexes:
index.drop()
# reflect existing unique constraints
for uc in self._get_unique_constraints(table):
table.append_constraint(uc)
# omit given unique constraints when creating a new table if required
table.constraints = set([
cons for cons in table.constraints
if omit_uniques is None or cons.name not in omit_uniques
])
self.append('ALTER TABLE %s RENAME TO migration_tmp' % table_name)
self.execute()
insertion_string = self._modify_table(table, column, delta)
table.create(bind=self.connection)
self.append(insertion_string % {'table_name': table_name})
self.execute()
self.append('DROP TABLE migration_tmp')
self.execute()
def _visit_migrate_unique_constraint(self, *p, **k):
"""Drop the given unique constraint
The corresponding original method of sqlalchemy-migrate just
raises NotImplemented error
"""
self.recreate_table(p[0].table, omit_uniques=[p[0].name])
def patch_migrate():
"""A workaround for SQLite's inability to alter things
SQLite abilities to alter tables are very limited (please read
http://www.sqlite.org/lang_altertable.html for more details).
E. g. one can't drop a column or a constraint in SQLite. The
workaround for this is to recreate the original table omitting
the corresponding constraint (or column).
sqlalchemy-migrate library has recreate_table() method that
implements this workaround, but it does it wrong:
- information about unique constraints of a table
is not retrieved. So if you have a table with one
unique constraint and a migration adding another one
you will end up with a table that has only the
latter unique constraint, and the former will be lost
- dropping of unique constraints is not supported at all
The proper way to fix this is to provide a pull-request to
sqlalchemy-migrate, but the project seems to be dead. So we
can go on with monkey-patching of the lib at least for now.
"""
# this patch is needed to ensure that recreate_table() doesn't drop
# existing unique constraints of the table when creating a new one
helper_cls = sqlite.SQLiteHelper
helper_cls.recreate_table = _recreate_table
helper_cls._get_unique_constraints = _get_unique_constraints
# this patch is needed to be able to drop existing unique constraints
constraint_cls = sqlite.SQLiteConstraintDropper
constraint_cls.visit_migrate_unique_constraint = \
_visit_migrate_unique_constraint
constraint_cls.__bases__ = (ansisql.ANSIColumnDropper,
sqlite.SQLiteConstraintGenerator)
def db_sync(engine, abs_path, version=None, init_version=0, sanity_check=True):
"""Upgrade or downgrade a database.
Function runs the upgrade() or downgrade() functions in change scripts.
:param engine: SQLAlchemy engine instance for a given database
:param abs_path: Absolute path to migrate repository.
:param version: Database will upgrade/downgrade until this version.<|fim▁hole|> :param init_version: Initial database version
:param sanity_check: Require schema sanity checking for all tables
"""
if version is not None:
try:
version = int(version)
except ValueError:
raise exception.DbMigrationError(
message=_("version should be an integer"))
current_version = db_version(engine, abs_path, init_version)
repository = _find_migrate_repo(abs_path)
if sanity_check:
_db_schema_sanity_check(engine)
if version is None or version > current_version:
return versioning_api.upgrade(engine, repository, version)
else:
return versioning_api.downgrade(engine, repository,
version)
def _db_schema_sanity_check(engine):
"""Ensure all database tables were created with required parameters.
:param engine: SQLAlchemy engine instance for a given database
"""
if engine.name == 'mysql':
onlyutf8_sql = ('SELECT TABLE_NAME,TABLE_COLLATION '
'from information_schema.TABLES '
'where TABLE_SCHEMA=%s and '
'TABLE_COLLATION NOT LIKE "%%utf8%%"')
table_names = [res[0] for res in engine.execute(onlyutf8_sql,
engine.url.database)]
if len(table_names) > 0:
raise ValueError(_('Tables "%s" have non utf8 collation, '
'please make sure all tables are CHARSET=utf8'
) % ','.join(table_names))
def db_version(engine, abs_path, init_version):
"""Show the current version of the repository.
:param engine: SQLAlchemy engine instance for a given database
:param abs_path: Absolute path to migrate repository
:param version: Initial database version
"""
repository = _find_migrate_repo(abs_path)
try:
return versioning_api.db_version(engine, repository)
except versioning_exceptions.DatabaseNotControlledError:
meta = sqlalchemy.MetaData()
meta.reflect(bind=engine)
tables = meta.tables
if len(tables) == 0 or 'alembic_version' in tables:
db_version_control(engine, abs_path, version=init_version)
return versioning_api.db_version(engine, repository)
else:
raise exception.DbMigrationError(
message=_(
"The database is not under version control, but has "
"tables. Please stamp the current version of the schema "
"manually."))
def db_version_control(engine, abs_path, version=None):
"""Mark a database as under this repository's version control.
Once a database is under version control, schema changes should
only be done via change scripts in this repository.
:param engine: SQLAlchemy engine instance for a given database
:param abs_path: Absolute path to migrate repository
:param version: Initial database version
"""
repository = _find_migrate_repo(abs_path)
versioning_api.version_control(engine, repository, version)
return version
def _find_migrate_repo(abs_path):
"""Get the project's change script repository
:param abs_path: Absolute path to migrate repository
"""
if not os.path.exists(abs_path):
raise exception.DbMigrationError("Path %s not found" % abs_path)
return Repository(abs_path)<|fim▁end|> | If None - database will update to the latest
available version. |
<|file_name|>position_history_update.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
# !/usr/bin/env python
#import easytrader
import easyhistory
import pdSql_common as pds
from pdSql import StockSQL
import sys
import datetime
from pytrade_api import *
from multiprocessing import Pool
import os, time
import file_config as fc
import code
stock_sql_obj=StockSQL(sqlite_file='pytrader.db',sqltype='sqlite',is_today_update=True)
CHINESE_DICT = stock_sql_obj.get_code_to_name()
def seprate_list(all_codes,seprate_num=4):
"""
分割股票池
"""
#all_codes = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
c = len(all_codes)
sub_c = int(c/seprate_num)
code_list_dict = {}
for j in range(seprate_num-1):
code_list_dict[j] = all_codes[j*sub_c:(j+1)*sub_c]
code_list_dict[j+1] = all_codes[(j+1)*sub_c:]
return code_list_dict
def update_yh_hist_data(all_codes,process_id,latest_date_str):
"""
更新历史数据,单个CPU
"""
all_count = len(all_codes)
print('processor %s: all_count=%s '% (process_id,all_count))
if all_count<=0:
print('processor %s: empty list'% process_id)
return
else:
print('processor %s start'%process_id)
latest_count = 0
count = 0
pc0=0
#print('all_codes=',all_codes)
for code in all_codes:
#print('code=',code)
df,has_tdx_last_string = pds.get_yh_raw_hist_df(code,latest_count=None)
pc = round(round(count,2)/all_count,2)*100
if pc>pc0:
#print('count=',count)
print('processor %s 完成数据更新百分之%s' % (process_id,pc))
pc0 = pc
if len(df)>=1:
last_code_trade_date = df.tail(1).iloc[0].date
if last_code_trade_date==latest_date_str:
latest_count = latest_count + 1
#time.sleep(0.2)
count = count + 1
latest_update_rate =round(round(latest_count,2)/all_count,2)
print('latest_update_rate_processor_%s=%s'%(process_id,latest_update_rate))
return
def update_one_stock_k_data(code):
df,has_tdx_last_string = pds.get_yh_raw_hist_df(code,latest_count=None)
return
def multiprocess_update_k_data0(code_list_dict,update_type='yh'):
"""
多进程更新历史数据,apply_async方法
存在问题:数据分片丢失
"""
#code_list_dict = seprate_list(all_codes,4)
#print('code_list_dict=',code_list_dict)
print('Parent process %s.' % os.getpid())
processor_num=len(code_list_dict)
#update_yh_hist_data(codes_list=[],process_id=0)
p = Pool()
for i in range(processor_num):
p.apply_async(update_yh_hist_data, args=(code_list_dict[i],i,last_date_str,))
print('Waiting for all subprocesses done...')
p.close()
p.join()
print('All subprocesses done.')
return
def multiprocess_update_k_data(allcodes,update_type='yh',pool_num=10):
"""
多进程更新历史数据,map方法
"""
#code_list_dict = seprate_list(all_codes,4)
#print('code_list_dict=',code_list_dict)
print('Parent process %s, multiprocess_num=%s.' % (os.getpid(),pool_num))
processor_num=len(allcodes)
#update_yh_hist_data(codes_list=[],process_id=0)
p = Pool(pool_num)
p.map(update_one_stock_k_data,allcodes)
print('Waiting for all subprocesses done...')
p.close()
p.join()
print('All subprocesses done.')
return
def update_k_data(update_type='yh'):
stock_sql = StockSQL()
hold_df,hold_stocks,available_sells = stock_sql.get_hold_stocks(accounts = ['36005', '38736'])
print('hold_stocks=',hold_stocks)
print('available_sells=',available_sells)
#pds.get_exit_price(hold_codes=['002521'],data_path='C:/中国银河证券海王星/T0002/export/' )
#print(hold_df)
"""从新浪 qq网页更新股票"""
#easyhistory.init(path="C:/hist",stock_codes=hold_stocks)
#easyhistory.update(path="C:/hist",stock_codes=hold_stocks)
"""从银河更新股票"""
#for stock in hold_stocks:
#pds.update_one_stock(symbol=stock,realtime_update=False,dest_dir='C:/hist/day/data/', force_update_from_YH=False)
# pass
#stock_sql.update_sql_position(users={'account':'36005','broker':'yh','json':'yh.json'})
#stock_sql.update_sql_position(users={'account':'38736','broker':'yh','json':'yh1.json'})
#hold_df,hold_stocks,available_sells = stock_sql.get_hold_stocks(accounts = ['36005', '38736'])
#print('hold_stocks=',hold_stocks)
#print(hold_df)
#pds.update_one_stock(symbol='sh',force_update=False)
#pds.update_codes_from_YH(realtime_update=False)
"""从银河更新指数"""
#pds.update_codes_from_YH(realtime_update=False,dest_dir='C:/hist/day/data/', force_update_from_YH=True)
#pds.update_codes_from_YH(realtime_update=False,dest_dir='C:/hist/day/data/', force_update_from_YH=True)
#indexs = ['zxb', 'sh50', 'hs300', 'sz300', 'cyb', 'sz', 'zx300', 'sh']
"""
potential_df = stock_sql.query_data(table='potential',fields='category_id,code,valid,name',condition='valid>=1')
print(potential_df)
lanchou_df = potential_df[potential_df['category_id']==1]
print(lanchou_df['code'].values.tolist())
"""
#"""
last_date_str = pds.tt.get_last_trade_date(date_format='%Y/%m/%d')
latest_date_str = pds.tt.get_latest_trade_date(date_format='%Y/%m/%d')
next_date_str = pds.tt.get_next_trade_date(date_format='%Y/%m/%d')
print('last_date = ',last_date_str)
print('latest_date_str=',latest_date_str)
print('next_date_str=',next_date_str)
indexs,funds,b_stock,all_stocks = pds.get_different_symbols()
if update_type == 'index':
#从银河更新指数
#stock_sql.update_sql_index(index_list=['sh','sz','zxb','cyb','hs300','sh50'],force_update=False)
#stock_sql.download_hist_as_csv(indexs = ['sh','sz','zxb','cyb','hs300','sh50'],dir='C:/hist/day/data/')
pds.update_codes_from_YH(indexs,realtime_update=False,dest_dir='C:/hist/day/data/', force_update_from_YH=True)
elif update_type == 'fund':
#从银河更新基金
all_codes = pds.get_all_code(hist_dir='C:/中国银河证券海王星/T0002/export/')
funds =[]
for code in all_codes:
if code.startswith('1') or code.startswith('5'):
funds.append(code)
pds.update_codes_from_YH(funds,realtime_update=False,dest_dir='C:/hist/day/data/', force_update_from_YH=True)
elif update_type == 'position':
#更新仓位
#stock_sql.update_sql_position(users={'36005':{'broker':'yh','json':'yh.json'},'38736':{'broker':'yh','json':'yh1.json'}})
stock_sql.update_sql_position(users={'account':'36005','broker':'yh','json':'yh.json'})
stock_sql.update_sql_position(users={'account':'38736','broker':'yh','json':'yh1.json'})
hold_df,hold_stocks,available_sells = stock_sql.get_hold_stocks(accounts = ['36005', '38736'])
print('hold_stocks=',hold_stocks)
print(hold_df)
elif update_type == 'stock':
#从新浪 qq网页更新股票
#easyhistory.init(path="C:/hist",stock_codes=hold_stocks)
#easyhistory.update(path="C:/hist",stock_codes=hold_stocks)
#easyhistory.init(path="C:/hist")#,stock_codes=all_codes)
easyhistory.update(path="C:/hist",stock_codes=all_stocks)#+b_stock)
elif update_type == 'YH' or update_type == 'yh':
all_codes = pds.get_all_code(hist_dir='C:/中国银河证券海王星/T0002/export/')
#all_codes = ['999999', '000016', '399007', '399008', '399006', '000300', '399005', '399001',
# '399004','399106','000009','000010','000903','000905']
#all_codes=['300162']
"""
code_list_dict = seprate_list(all_codes,4)
print('code_list_dict=',code_list_dict)
print('Parent process %s.' % os.getpid())
#update_yh_hist_data(codes_list=[],process_id=0)
p = Pool()
for i in range(4):
p.apply_async(update_yh_hist_data, args=(code_list_dict[i],i))
print('Waiting for all subprocesses done...')
p.close()
p.join()
print('All subprocesses done.')
"""
all_count = len(all_codes)
latest_count = 0
count = 0
pc0=0
for code in all_codes:
df,has_tdx_last_string = pds.get_yh_raw_hist_df(code,latest_count=None)
count = count + 1
pc = round(round(count,2)/all_count,2)* 100
if pc>pc0:
print('count=',count)
print('完成数据更新百分之%s' % pc)
pc0 = pc
if len(df)>=1:
last_code_trade_date = df.tail(1).iloc[0].date
if last_code_trade_date==latest_date_str:
latest_count = latest_count + 1
latest_update_rate =round(round(latest_count,2)/all_count,2)
print('latest_update_rate=',latest_update_rate)
#"""
else:
pass
def get_stock_last_trade_date_yh():
last_date_str=''
is_need_del_tdx_last_string=False
df,has_tdx_last_string = pds.get_yh_raw_hist_df(test_code,latest_count=None)
if has_tdx_last_string:
is_need_del_tdx_last_string =True
if not df.empty:
last_date_str_stock = df.tail(1).iloc[0].date
if last_date_str_stock>=target_last_date_str:
last_date_str = last_date_str_stock
else:
if last_date_str_stock>last_date_str:
last_date_str = last_date_str_stock
else:
pass
else:
pass
return last_date_str,is_need_del_tdx_last_string
def get_last_trade_date_yh_hist(target_last_date_str,default_codes=['601398','000002','002001','300059','601857','600028','000333','300251','601766','002027']):
last_date_str=''
is_need_del_tdx_last_string = False
for test_code in default_codes:
df,has_tdx_last_string = pds.get_yh_raw_hist_df(test_code,latest_count=None)
if has_tdx_last_string:
is_need_del_tdx_last_string =True
if not df.empty:
last_date_str_stock = df.tail(1).iloc[0].date
if last_date_str_stock>=target_last_date_str:
last_date_str = last_date_str_stock
break
else:
if last_date_str_stock>last_date_str:
last_date_str = last_date_str_stock
else:
pass
return last_date_str,is_need_del_tdx_last_string
def update_hist_k_datas(update_type='yh'):
target_last_date_str = pds.tt.get_last_trade_date(date_format='%Y/%m/%d')
last_date_str,is_need_del_tdx_last_string = get_last_trade_date_yh_hist(target_last_date_str)
is_need_update = pds.tt.is_need_update_histdata(last_date_str)
update_state = 0
if is_need_update or is_need_del_tdx_last_string:
start = time.time()
all_codes = pds.get_all_code(hist_dir='C:/中国银河证券海王星/T0002/export/')
#multiprocess_update_k_data(code_list_dict) #apply,非阻塞,传不同参数,支持回调函数
multiprocess_update_k_data(all_codes,update_type) #map,阻塞,一个参数
end = time.time()
print('Task update yh hist data runs %0.2f seconds.' % (end - start))
"""Post-check"""
last_date_str,is_need_del_tdx_last_string = get_last_trade_date_yh_hist(target_last_date_str)
is_need_update = pds.tt.is_need_update_histdata(last_date_str)
if is_need_update and not is_need_del_tdx_last_string:
print('尝试更新历史数据,但是更新失败;请全部盘后数据已下载...')
update_state = -1
else:
update_state = 1
else:
print('No need to update history data')
return update_state
def append_to_csv(value,column_name='code',file_name='C:/work/temp/stop_stocks.csv',empty_first=False):
"""
追加单列的CSV文件
"""
stop_codes = []
if empty_first:
pd.DataFrame({column_name:[]}).to_csv(file_name,encoding='utf-8')
try:
stop_trade_df = df=pd.read_csv(file_name)
stop_codes = stop_trade_df[column_name].values.tolist()
except:
pd.DataFrame({column_name:[]}).to_csv(file_name,encoding='utf-8')
stop_codes.append(value)
new_df = pd.DataFrame({column_name:stop_codes})
new_df.to_csv(file_name,encoding='utf-8')
return new_df
def combine_file(tail_num=1,dest_dir='C:/work/temp/',keyword='',prefile_slip_num=0,columns=None,file_list=[],chinese_dict={}):
"""
合并指定目录的最后几行
"""
all_files = os.listdir(dest_dir)
df = pd.DataFrame({})
if not all_files:
return df
file_names = []
if not keyword:
file_names = all_files
else:#根据keywo过滤文件
for file in all_files:
if keyword in file:
file_names.append(file)
else:
continue
#file_names=['bs_000001.csv', 'bs_000002.csv']
#file_names=['000001.csv', '000002.csv']
if file_list:
file_names = list(set(file_names).intersection(set(file_list)))
for file_name in file_names:
tail_df = pd.read_csv(dest_dir+file_name,usecols=None).tail(tail_num)
#columns = tail_df.columns.values.tolist()
#print('columns',columns)
prefile_name = file_name.split('.')[0]
if prefile_slip_num:
prefile_name = prefile_name[prefile_slip_num:]
tail_df['code'] = prefile_name
#tail_df['name'] = tail_df['code'].apply(lambda x: pds.format_name_by_code(x,CHINESE_DICT))
"""
if CHINESE_DICT:#添加中文代码
try:
tail_df['name'] = CHINESE_DICT[prefile_name]
except:
tail_df['name'] = '某指数'
"""
df=df.append(tail_df)
return df
#df = combine_file(tail_num=1,dest_dir='d:/work/temp2/')
def get_latest_yh_k_stocks(write_file_name=fc.ALL_YH_KDATA_FILE,data_dir=fc.YH_SOURCE_DATA_DIR):
"""
获取所有银河最后一个K线的数据:特定目录下
"""
columns = ['date', 'open', 'high', 'low', 'close', 'volume', 'amount']
columns = pds.get_data_columns(dest_dir=data_dir)
df = combine_file(tail_num=1,dest_dir=data_dir,keyword='',prefile_slip_num=0,columns=columns)
if df.empty:
return df
df['counts']=df.index
df = df[['date', 'open', 'high', 'low', 'close', 'volume', 'amount']+['counts','code']]
<|fim▁hole|> if CHINESE_DICT:#添加中文代码
try:
tail_df['name'] = CHINESE_DICT[prefile_name]
except:
tail_df['name'] = '某指数'
"""
if write_file_name:
try:
df.to_csv(write_file_name,encoding='utf-8')
except Exception as e:
print('get_latest_yh_k_stocks: ',e)
return df
#get_latest_yh_k_stocks()
def get_latest_yh_k_stocks_from_csv(file_name=fc.ALL_YH_KDATA_FILE):
"""
获取股票K线数据,数据来源银河证券
"""
#file_name = 'C:/work/result/all_yh_stocks.csv'
#columns = ['date', 'open', 'high', 'low', 'close', 'volume', 'amount']+['counts','code']
columns = pds.get_data_columns(dest_dir=fc.YH_SOURCE_DATA_DIR) + ['counts','code']
#try:
if True:
df = pd.read_csv(file_name)#,usecols=columns)
#print(df)
#print(type(df['code']))
df['code'] = df['name'].apply(lambda x:pds.format_code(x))
df['name'] = df['code'].apply(lambda x: pds.format_name_by_code(x,CHINESE_DICT))
df = df.set_index('code')
return df
#except:
# return get_latest_yh_k_stocks(write_file_name=file_name)
#print(get_latest_yh_k_stocks_from_csv())
def get_stop_stock(last_date_str,source='from_yh'):
"""
获取停牌股票,数据来源银河证券
"""
df = get_latest_yh_k_stocks_from_csv(write_file_name=fc.ALL_YH_KDATA_FILE)
if df.empty:
return pd.DataFrame({})
stop_df = df[df.date<last_date_str]
return stop_df
def update_history_postion():
#freeze_support()
#update_type = ''
update_type = 'index'
#update_type = 'position'
#update_type = 'stock'
update_type = 'yh'
#update_type = 'aa'
now_time =datetime.datetime.now()
now_time_str = now_time.strftime('%Y/%m/%d %X')
last_date_str = pds.tt.get_last_trade_date(date_format='%Y/%m/%d')
print('now_time = ',now_time_str)
print('last_trade_date = ',last_date_str)
if len(sys.argv)>=2:
if sys.argv[1] and isinstance(sys.argv[1], str):
update_type = sys.argv[1] #start date string
"""
#update_type = 'index'
#update_type = 'position'
#update_type = 'aa'
#update_k_data(update_type)
all_codes = pds.get_all_code(hist_dir='C:/中国银河证券海王星/T0002/export/')
#all_codes = ['999999', '000016', '399007', '399008', '399006', '000300', '399005', '399001',
# '399004','399106','000009','000010','000903','000905']
#all_codes=['300162']
code_list_dict = seprate_list(all_codes,4)
#print('code_list_dict=',code_list_dict)
#multiprocess_update_k_data(code_list_dict) #apply,非阻塞,传不同参数,支持回调函数
multiprocess_update_k_data(all_codes,update_type='yh') #map,阻塞,一个参数
"""
stock_sql = StockSQL()
pre_is_tdx_uptodate,pre_is_pos_uptodate,pre_is_backtest_uptodate,systime_dict = stock_sql.is_histdata_uptodate()
print(pre_is_tdx_uptodate,pre_is_pos_uptodate,pre_is_backtest_uptodate,systime_dict)
#pre_is_tdx_uptodate,pre_is_pos_uptodate=True,False
pre_is_tdx_uptodate = False
if not pre_is_tdx_uptodate:#更新历史数据
update_state = update_hist_k_datas(update_type)
if update_state:
"""写入数据库:标识已经更新通达信历史数据 """
#stock_sql.write_tdx_histdata_update_time(now_time_str)
stock_sql.update_system_time(update_field='tdx_update_time')
"""更新all-in-one历史数据文件"""
get_latest_yh_k_stocks(fc.ALL_YH_KDATA_FILE)
else:
print('历史数据已经更新,无需更新;上一次更新时间:%s' % systime_dict['tdx_update_time'])
#stock_sql.update_data(table='systime',fields='tdx_update_time',values=now_time_str,condition='id=0')
#stock_sql.update_data(table='systime',fields='tdx_update_time',values=now_time_str,condition='id=0')
if not pre_is_pos_uptodate:
"""更新持仓数据"""
trader_api='shuangzixing'
op_tdx = trader(trade_api='shuangzixing',acc='331600036005',bebug=False)
if not op_tdx:
print('Error')
"""
op_tdx =trader(trade_api,bebug=True)
op_tdx.enable_debug(debug=True)
"""
#pre_position = op_tdx.getPositionDict()
position = op_tdx.get_all_position()
#position,avl_sell_datas,monitor_stocks = op_tdx.get_all_positions()
print('position=',position)
pos_df = pds.position_datafrom_from_dict(position)
if not pos_df.empty:
"""写入数据库:标识已经更新持仓数据 """
stock_sql.update_all_position(pos_df,table_name='allpositions')
#stock_sql.write_position_update_time(now_time_str)
stock_sql.update_system_time(update_field='pos_update_time')
"""持仓数据写入CSV文件"""
try:
pos_df.to_csv(fc.POSITION_FILE,encoding='gb2312')#encoding='utf-8')
except:
pass
df_dict = stock_sql.get_systime()
print(df_dict)
else:
print('持仓数据已经更新,无需更新;上一次更新时间:%s' % systime_dict['pos_update_time'])
is_tdx_uptodate,is_pos_uptodate,is_backtest_uptodate,systime_dict = stock_sql.is_histdata_uptodate()
if pre_is_tdx_uptodate!=is_tdx_uptodate:
print('完成历史数据更新!')
if pre_is_pos_uptodate!=is_pos_uptodate:
print('完成持仓数据更新!')
#print( 'is_tdx_uptodate=%s, is_pos_uptodate=%s'% (is_tdx_uptodate,is_pos_uptodate))
"""
print('Parent process %s.' % os.getpid())
#update_yh_hist_data(codes_list=[],process_id=0)
p = Pool()
for i in range(4):
p.apply_async(update_yh_hist_data, args=(code_list_dict[i],i,last_date_str,))
print('Waiting for all subprocesses done...')
p.close()
p.join()
print('All subprocesses done.')
update_data = stock_sql.get_table_update_time()
print('last_position_update_time=',update_data['hold'])
print('last_index_update_time=',update_data['sh'])
print(stock_sql.hold)
"""
#"""
"""
print(update_data)
broker = 'yh'
need_data = 'yh.json'
user = easytrader.use('yh')
user.prepare('yh.json')
holding_stocks_df = user.position#['证券代码'] #['code']
print(holding_stocks_df)
"""
"""
当前持仓 股份可用 参考市值 参考市价 股份余额 参考盈亏 交易市场 参考成本价 盈亏比例(%) 股东代码 \
0 6300 6300 24885.0 3.95 6300 343.00 深A 3.896 1.39% 0130010635
1 400 400 9900.0 24.75 400 163.00 深A 24.343 1.67% 0130010635
2 600 600 15060.0 25.10 600 115.00 深A 24.908 0.77% 0130010635
3 1260 0 13041.0 10.35 1260 906.06 沪A 9.631 7.47% A732980330
证券代码 证券名称 买入冻结 卖出冻结
0 000932 华菱钢铁 0 0
1 000977 浪潮信息 0 0
2 300326 凯利泰 0 0
3 601009 南京银行 0 0
"""
#stock_sql.drop_table(table_name='myholding')
#stock_sql.insert_table(data_frame=holding_stocks_df,table_name='myholding')<|fim▁end|> | df['code'] = df['code'].apply(lambda x: pds.format_code(x))
df['name'] = df['code'].apply(lambda x: pds.format_name_by_code(x,CHINESE_DICT))
df = df.set_index('code')
"""
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Code for finding content."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import abc
import collections
import os
<|fim▁hole|>from ... import types as t
from ...util import (
ANSIBLE_SOURCE_ROOT,
)
from .. import (
PathProvider,
)
class Layout:
"""Description of content locations and helper methods to access content."""
def __init__(self,
root, # type: str
paths, # type: t.List[str]
): # type: (...) -> None
self.root = root
self.__paths = paths # contains both file paths and symlinked directory paths (ending with os.path.sep)
self.__files = [path for path in paths if not path.endswith(os.path.sep)] # contains only file paths
self.__paths_tree = paths_to_tree(self.__paths)
self.__files_tree = paths_to_tree(self.__files)
def all_files(self, include_symlinked_directories=False): # type: (bool) -> t.List[str]
"""Return a list of all file paths."""
if include_symlinked_directories:
return self.__paths
return self.__files
def walk_files(self, directory, include_symlinked_directories=False): # type: (str, bool) -> t.List[str]
"""Return a list of file paths found recursively under the given directory."""
if include_symlinked_directories:
tree = self.__paths_tree
else:
tree = self.__files_tree
parts = directory.rstrip(os.sep).split(os.sep)
item = get_tree_item(tree, parts)
if not item:
return []
directories = collections.deque(item[0].values())
files = list(item[1])
while directories:
item = directories.pop()
directories.extend(item[0].values())
files.extend(item[1])
return files
def get_dirs(self, directory): # type: (str) -> t.List[str]
"""Return a list directory paths found directly under the given directory."""
parts = directory.rstrip(os.sep).split(os.sep)
item = get_tree_item(self.__files_tree, parts)
return [os.path.join(directory, key) for key in item[0].keys()] if item else []
def get_files(self, directory): # type: (str) -> t.List[str]
"""Return a list of file paths found directly under the given directory."""
parts = directory.rstrip(os.sep).split(os.sep)
item = get_tree_item(self.__files_tree, parts)
return item[1] if item else []
class ContentLayout(Layout):
"""Information about the current Ansible content being tested."""
def __init__(self,
root, # type: str
paths, # type: t.List[str]
plugin_paths, # type: t.Dict[str, str]
collection=None, # type: t.Optional[CollectionDetail]
integration_path=None, # type: t.Optional[str]
unit_path=None, # type: t.Optional[str]
unit_module_path=None, # type: t.Optional[str]
unit_module_utils_path=None, # type: t.Optional[str]
): # type: (...) -> None
super(ContentLayout, self).__init__(root, paths)
self.plugin_paths = plugin_paths
self.collection = collection
self.integration_path = integration_path
self.integration_targets_path = os.path.join(integration_path, 'targets')
self.integration_vars_path = os.path.join(integration_path, 'integration_config.yml')
self.unit_path = unit_path
self.unit_module_path = unit_module_path
self.unit_module_utils_path = unit_module_utils_path
self.is_ansible = root == ANSIBLE_SOURCE_ROOT
@property
def prefix(self): # type: () -> str
"""Return the collection prefix or an empty string if not a collection."""
if self.collection:
return self.collection.prefix
return ''
@property
def module_path(self): # type: () -> t.Optional[str]
"""Return the path where modules are found, if any."""
return self.plugin_paths.get('modules')
@property
def module_utils_path(self): # type: () -> t.Optional[str]
"""Return the path where module_utils are found, if any."""
return self.plugin_paths.get('module_utils')
@property
def module_utils_powershell_path(self): # type: () -> t.Optional[str]
"""Return the path where powershell module_utils are found, if any."""
if self.is_ansible:
return os.path.join(self.plugin_paths['module_utils'], 'powershell')
return self.plugin_paths.get('module_utils')
@property
def module_utils_csharp_path(self): # type: () -> t.Optional[str]
"""Return the path where csharp module_utils are found, if any."""
if self.is_ansible:
return os.path.join(self.plugin_paths['module_utils'], 'csharp')
return self.plugin_paths.get('module_utils')
class CollectionDetail:
"""Details about the layout of the current collection."""
def __init__(self,
name, # type: str
namespace, # type: str
root, # type: str
): # type: (...) -> None
self.name = name
self.namespace = namespace
self.root = root
self.full_name = '%s.%s' % (namespace, name)
self.prefix = '%s.' % self.full_name
self.directory = os.path.join('ansible_collections', namespace, name)
class LayoutProvider(PathProvider):
"""Base class for layout providers."""
PLUGIN_TYPES = (
'action',
'become',
'cache',
'callback',
'cliconf',
'connection',
'doc_fragments',
'filter',
'httpapi',
'inventory',
'lookup',
'module_utils',
'modules',
'netconf',
'shell',
'strategy',
'terminal',
'test',
'vars',
)
@abc.abstractmethod
def create(self, root, paths): # type: (str, t.List[str]) -> ContentLayout
"""Create a layout using the given root and paths."""
def paths_to_tree(paths): # type: (t.List[str]) -> t.Tuple(t.Dict[str, t.Any], t.List[str])
"""Return a filesystem tree from the given list of paths."""
tree = {}, []
for path in paths:
parts = path.split(os.sep)
root = tree
for part in parts[:-1]:
if part not in root[0]:
root[0][part] = {}, []
root = root[0][part]
root[1].append(path)
return tree
def get_tree_item(tree, parts): # type: (t.Tuple(t.Dict[str, t.Any], t.List[str]), t.List[str]) -> t.Optional[t.Tuple(t.Dict[str, t.Any], t.List[str])]
"""Return the portion of the tree found under the path given by parts, or None if it does not exist."""
root = tree
for part in parts:
root = root[0].get(part)
if not root:
return None
return root<|fim▁end|> | |
<|file_name|>studentnew.js<|end_file_name|><|fim▁begin|>define([
'jquery',
'underscore',
'backbone',
'collections/users/students',
'collections/users/classes',
'collections/users/streams',
'text!templates/students/studentnew.html',
'text!templates/students/classes.html',
'text!templates/students/streams.html',
'jqueryui',
'bootstrap'
], function($, _, Backbone, Students, Classes, Streams, StudentTpl, classesTpl, streamsTpl){
var NewStudent = Backbone.View.extend({
tagName: 'div',
title: "New Student - Student Information System",
events: {
'submit form#new-student' : 'addStudent',
'change #class_id' : 'getStreams'
},
template: _.template(StudentTpl),<|fim▁hole|>
initialize: function(){
$("title").html(this.title);
//fetch list of all classes for this class from the database
var self = this;
Classes.fetch({
data: $.param({
token: tokenString
}),
success: function(data){
self.setClasses();
}
});
//fetch list of all streams for this client from the database
Streams.fetch({
data: $.param({
token: tokenString
})
});
},
render: function(){
this.$el.html(this.template());
this.$classes = this.$("#classes-list");
this.$streams = this.$("#streams-list");
return this;
},
addStudent: function(evt){
evt.preventDefault();
var student = {
reg_number: $("#reg_number").val(),
first_name: $("#first_name").val(),
middle_name: $("#middle_name").val(),
last_name: $("#last_name").val(),
dob: $("#dob").val(),
pob: $("#pob").val(),
bcn: $("#bcn").val(),
sex: $("#sex").val(),
nationality: $("#nationality").val(),
doa: $("#doa").val(),
class_id: $("#class_id").val(),
stream_id: ($("#stream_id").val()) ? $("#stream_id").val() : '',
address: $("#address").val(),
code: $("#code").val(),
town: $("#town").val(),
pg_f_name: $("#pg_f_name").val(),
pg_l_name: $("#pg_l_name").val(),
pg_email: $("#pg_email").val(),
pg_phone: $("#pg_phone").val()
};
$(".submit-button").html("Please wait...");
$(".error-message").hide(200);
$(".success-message").hide(200);
Students.create(student, {
url: baseURL + 'students/students?token=' + tokenString,
success: function(){
$(".success-message").html("Student added successfully!").show(400);
$(".submit-button").html('<i class="fa fa-fw fa-check"></i>Save');
//empty the form
$("#reg_number").val(''),
$("#first_name").val(''),
$("#middle_name").val(''),
$("#last_name").val(''),
$("#dob").val(''),
$("#pob").val(''),
$("#bcn").val(''),
$("#sex").val(''),
$("#nationality").val(''),
$("#doa").val(''),
$("#class_id").val(''),
$("#stream_id").val(''),
$("#address").val(''),
$("#code").val(''),
$("#town").val(''),
$("#pg_f_name").val(''),
$("#pg_l_name").val(''),
$("#pg_email").val(''),
$("#pg_phone").val('')
},
error : function(jqXHR, textStatus, errorThrown) {
if(textStatus.status != 401 && textStatus.status != 403) {
$(".error-message").html("Please check the errors below!").show(400);
$(".submit-button").html('<i class="fa fa-fw fa-check"></i>Save');
}
}
});
},
setClasses: function(){
this.$classes.empty();
var regClasses = [];
Classes.each(function(oneClass){
regClasses.push(oneClass.toJSON());
}, this);
this.$classes.html(this.classesTpl({
regClasses: regClasses
}));
},
getStreams: function(){
var classID = $("#class_id").val();
var regStreams = [];
var streams = Streams.where({
class_id: classID
});
$.each(streams, function(key, oneStream){
regStreams.push(oneStream.toJSON());
});
this.$streams.html(this.streamsTpl({
regStreams: regStreams
}));
}
});
return NewStudent;
});<|fim▁end|> |
classesTpl: _.template(classesTpl),
streamsTpl: _.template(streamsTpl), |
<|file_name|>multi_loader.go<|end_file_name|><|fim▁begin|>package url
import (
"github.com/dpb587/metalink"<|fim▁hole|> "github.com/dpb587/metalink/file"
)
type MultiLoader struct {
loaders []Loader
}
var _ Loader = &MultiLoader{}
func NewMultiLoader(loaders ...Loader) *MultiLoader {
return &MultiLoader{
loaders: loaders,
}
}
func (l *MultiLoader) SupportsURL(source metalink.URL) bool {
for _, loader := range l.loaders {
if loader.SupportsURL(source) {
return true
}
}
return false
}
func (l *MultiLoader) LoadURL(source metalink.URL) (file.Reference, error) {
for _, loader := range l.loaders {
if !loader.SupportsURL(source) {
continue
}
ref, err := loader.LoadURL(source)
if err == UnsupportedURLError {
continue
}
return ref, err
}
return nil, UnsupportedURLError
}
func (l *MultiLoader) Add(add Loader) {
l.loaders = append(l.loaders, add)
}<|fim▁end|> | |
<|file_name|>TestTemporalColorTracker.py<|end_file_name|><|fim▁begin|>from SimpleCV import Camera, Image, Color, TemporalColorTracker, ROI, Display
import matplotlib.pyplot as plt
cam = Camera(1)
tct = TemporalColorTracker()
img = cam.getImage()
roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img)
tct.train(cam,roi=roi,maxFrames=250,pkWndw=20)
# Matplot Lib example plotting
plotc = {'r':'r','g':'g','b':'b','i':'m','h':'y'}
for key in tct.data.keys():
plt.plot(tct.data[key],plotc[key])
for pt in tct.peaks[key]:
plt.plot(pt[0],pt[1],'r*')
for pt in tct.valleys[key]:
plt.plot(pt[0],pt[1],'b*')
plt.grid()
plt.show()
disp = Display((800,600))
while disp.isNotDone():
img = cam.getImage()
result = tct.recognize(img)<|fim▁hole|> plotImg = Image('temp.png')
roi = ROI(img.width*0.45,img.height*0.45,img.width*0.1,img.height*0.1,img)
roi.draw(width=3)
img.drawText(str(result),20,20,color=Color.RED,fontsize=32)
img = img.applyLayers()
img = img.blit(plotImg.resize(w=img.width,h=img.height),pos=(0,0),alpha=0.5)
img.save(disp)<|fim▁end|> | plt.plot(tct._rtData,'r-')
plt.grid()
plt.savefig('temp.png')
plt.clf() |
<|file_name|>extern-crate-used.rs<|end_file_name|><|fim▁begin|>// Extern crate items are marked as used if they are used
// through extern prelude entries introduced by them.
// edition:2018
#![deny(unused_extern_crates)]
// Shouldn't suggest changing to `use`, as new name
// would no longer be added to the prelude which could cause
// compilation errors for imports that use the new name in
// other modules. See #57672.
extern crate core as iso1;
extern crate core as iso2;
extern crate core as iso3;
extern crate core as iso4;
// Doesn't introduce its extern prelude entry, so it's still considered unused.
extern crate core; //~ ERROR unused extern crate
mod m {
use iso1::any as are_you_okay1;
use ::iso2::any as are_you_okay2;
type AreYouOkay1 = dyn iso3::any::Any;
type AreYouOkay2 = dyn (::iso4::any::Any);<|fim▁hole|> type AreYouOkay3 = dyn core::any::Any;
type AreYouOkay4 = dyn (::core::any::Any);
}
fn main() {}<|fim▁end|> |
use core::any as are_you_okay3;
use ::core::any as are_you_okay4; |
<|file_name|>test_insert.py<|end_file_name|><|fim▁begin|>import time
import psycopg2
import os
import sys
if __name__ == "__main__":
try:
conn = psycopg2.connect("dbname='master' user='postgres' host='localhost' password='postgres'")
except Exception, e:
print "unable to connect"
sys.exit()
cur = conn.cursor()
for x in xrange(1,1000):<|fim▁hole|>
cur.close()
conn.close()<|fim▁end|> | print x
cur.execute("INSERT INTO reptable166 (name) VALUES(%s)", ("test" + str(x),))
conn.commit()
time.sleep(1) |
<|file_name|>qaudiooutput_mac_p.cpp<|end_file_name|><|fim▁begin|>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtMultimedia module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
** $QT_END_LICENSE$
**
****************************************************************************/
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists for the convenience
// of other Qt classes. This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//
#include <CoreServices/CoreServices.h>
#include <CoreAudio/CoreAudio.h>
#include <AudioUnit/AudioUnit.h>
#include <AudioToolbox/AudioToolbox.h>
#include <QtCore/qendian.h>
#include <QtCore/qbuffer.h>
#include <QtCore/qtimer.h>
#include <QtCore/qdebug.h>
#include <QtMultimedia/qaudiodeviceinfo.h>
#include <QtMultimedia/qaudiooutput.h>
#include "qaudio_mac_p.h"
#include "qaudiooutput_mac_p.h"
QT_BEGIN_NAMESPACE
namespace
{
static const int default_buffer_size = 8 * 1024;
class QAudioOutputBuffer : public QObject
{
Q_OBJECT
public:
QAudioOutputBuffer(int bufferSize, int maxPeriodSize, QAudioFormat const& audioFormat):
m_deviceError(false),
m_maxPeriodSize(maxPeriodSize),
m_device(0)
{
m_buffer = new QAudioRingBuffer(bufferSize + (bufferSize % maxPeriodSize == 0 ? 0 : maxPeriodSize - (bufferSize % maxPeriodSize)));
m_bytesPerFrame = (audioFormat.sampleSize() / 8) * audioFormat.channels();
m_periodTime = m_maxPeriodSize / m_bytesPerFrame * 1000 / audioFormat.frequency();
m_fillTimer = new QTimer(this);
connect(m_fillTimer, SIGNAL(timeout()), SLOT(fillBuffer()));
}
~QAudioOutputBuffer()
{
delete m_buffer;
}
qint64 readFrames(char* data, qint64 maxFrames)
{
bool wecan = true;
qint64 framesRead = 0;
while (wecan && framesRead < maxFrames) {
QAudioRingBuffer::Region region = m_buffer->acquireReadRegion((maxFrames - framesRead) * m_bytesPerFrame);
if (region.second > 0) {
region.second -= region.second % m_bytesPerFrame;
memcpy(data + (framesRead * m_bytesPerFrame), region.first, region.second);
framesRead += region.second / m_bytesPerFrame;
}
else
wecan = false;
m_buffer->releaseReadRegion(region);
}
if (framesRead == 0 && m_deviceError)
framesRead = -1;
return framesRead;
}
qint64 writeBytes(const char* data, qint64 maxSize)
{
bool wecan = true;
qint64 bytesWritten = 0;
maxSize -= maxSize % m_bytesPerFrame;
while (wecan && bytesWritten < maxSize) {
QAudioRingBuffer::Region region = m_buffer->acquireWriteRegion(maxSize - bytesWritten);
if (region.second > 0) {
memcpy(region.first, data + bytesWritten, region.second);
bytesWritten += region.second;
}
else
wecan = false;
m_buffer->releaseWriteRegion(region);
}
if (bytesWritten > 0)
emit readyRead();
return bytesWritten;
}
int available() const
{
return m_buffer->free();
}
void reset()
{
m_buffer->reset();
m_deviceError = false;
}
void setPrefetchDevice(QIODevice* device)
{
if (m_device != device) {
m_device = device;
if (m_device != 0)
fillBuffer();
}
}
void startFillTimer()
{
if (m_device != 0)
m_fillTimer->start(m_buffer->size() / 2 / m_maxPeriodSize * m_periodTime);
}
void stopFillTimer()
{
m_fillTimer->stop();
}
signals:
void readyRead();
private slots:
void fillBuffer()
{
const int free = m_buffer->free();
const int writeSize = free - (free % m_maxPeriodSize);
if (writeSize > 0) {
bool wecan = true;
int filled = 0;
while (!m_deviceError && wecan && filled < writeSize) {
QAudioRingBuffer::Region region = m_buffer->acquireWriteRegion(writeSize - filled);
if (region.second > 0) {
region.second = m_device->read(region.first, region.second);
if (region.second > 0)
filled += region.second;
else if (region.second == 0)
wecan = false;
else if (region.second < 0) {
m_fillTimer->stop();
region.second = 0;
m_deviceError = true;
}
}
else
wecan = false;
m_buffer->releaseWriteRegion(region);
}
if (filled > 0)
emit readyRead();
}
}
private:
bool m_deviceError;
int m_maxPeriodSize;
int m_bytesPerFrame;
int m_periodTime;
QIODevice* m_device;
QTimer* m_fillTimer;
QAudioRingBuffer* m_buffer;
};
}
class MacOutputDevice : public QIODevice
{
Q_OBJECT
public:
MacOutputDevice(QAudioOutputBuffer* audioBuffer, QObject* parent):
QIODevice(parent),
m_audioBuffer(audioBuffer)
{
open(QIODevice::WriteOnly | QIODevice::Unbuffered);
}
qint64 readData(char* data, qint64 len)
{
Q_UNUSED(data);
Q_UNUSED(len);
return 0;
}
qint64 writeData(const char* data, qint64 len)
{
return m_audioBuffer->writeBytes(data, len);
}
bool isSequential() const
{
return true;
}
private:
QAudioOutputBuffer* m_audioBuffer;
};
QAudioOutputPrivate::QAudioOutputPrivate(const QByteArray& device, const QAudioFormat& format):
audioFormat(format)
{
QDataStream ds(device);
quint32 did, mode;
ds >> did >> mode;
if (QAudio::Mode(mode) == QAudio::AudioInput)
errorCode = QAudio::OpenError;
else {
isOpen = false;
audioDeviceId = AudioDeviceID(did);
audioUnit = 0;
audioIO = 0;
startTime = 0;
totalFrames = 0;
audioBuffer = 0;
internalBufferSize = default_buffer_size;
clockFrequency = AudioGetHostClockFrequency() / 1000;
errorCode = QAudio::NoError;
stateCode = QAudio::StoppedState;
audioThreadState = Stopped;
intervalTimer = new QTimer(this);
intervalTimer->setInterval(1000);
connect(intervalTimer, SIGNAL(timeout()), SIGNAL(notify()));
}
}
QAudioOutputPrivate::~QAudioOutputPrivate()
{
close();
}
bool QAudioOutputPrivate::open()
{
if (errorCode != QAudio::NoError)
return false;
if (isOpen)
return true;
ComponentDescription cd;
cd.componentType = kAudioUnitType_Output;
cd.componentSubType = kAudioUnitSubType_HALOutput;
cd.componentManufacturer = kAudioUnitManufacturer_Apple;
cd.componentFlags = 0;
cd.componentFlagsMask = 0;
// Open
Component cp = FindNextComponent(NULL, &cd);
if (cp == 0) {
qWarning() << "QAudioOutput: Failed to find HAL Output component";
return false;
}
if (OpenAComponent(cp, &audioUnit) != noErr) {
qWarning() << "QAudioOutput: Unable to Open Output Component";
return false;
}
// register callback
AURenderCallbackStruct cb;
cb.inputProc = renderCallback;
cb.inputProcRefCon = this;
if (AudioUnitSetProperty(audioUnit,
kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Global,
0,
&cb,
sizeof(cb)) != noErr) {
qWarning() << "QAudioOutput: Failed to set AudioUnit callback";
return false;
}
// Set Audio Device
if (AudioUnitSetProperty(audioUnit,
kAudioOutputUnitProperty_CurrentDevice,
kAudioUnitScope_Global,
0,
&audioDeviceId,
sizeof(audioDeviceId)) != noErr) {
qWarning() << "QAudioOutput: Unable to use configured device";
return false;
}
// Set stream format
streamFormat = toAudioStreamBasicDescription(audioFormat);
UInt32 size = sizeof(deviceFormat);
if (AudioUnitGetProperty(audioUnit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
0,
&deviceFormat,
&size) != noErr) {
qWarning() << "QAudioOutput: Unable to retrieve device format";
return false;
}
if (AudioUnitSetProperty(audioUnit,
kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input,
0,
&streamFormat,
sizeof(streamFormat)) != noErr) {
qWarning() << "QAudioOutput: Unable to Set Stream information";
return false;
}
// Allocate buffer
UInt32 numberOfFrames = 0;
size = sizeof(UInt32);
if (AudioUnitGetProperty(audioUnit,
kAudioDevicePropertyBufferFrameSize,
kAudioUnitScope_Global,
0,
&numberOfFrames,
&size) != noErr) {
qWarning() << "QAudioInput: Failed to get audio period size";
return false;
}
periodSizeBytes = (numberOfFrames * streamFormat.mSampleRate / deviceFormat.mSampleRate) *
streamFormat.mBytesPerFrame;
if (internalBufferSize < periodSizeBytes * 2)
internalBufferSize = periodSizeBytes * 2;
else
internalBufferSize -= internalBufferSize % streamFormat.mBytesPerFrame;
audioBuffer = new QAudioOutputBuffer(internalBufferSize, periodSizeBytes, audioFormat);
connect(audioBuffer, SIGNAL(readyRead()), SLOT(inputReady())); // Pull
audioIO = new MacOutputDevice(audioBuffer, this);
// Init
if (AudioUnitInitialize(audioUnit)) {
qWarning() << "QAudioOutput: Failed to initialize AudioUnit";
return false;
}
isOpen = true;
return true;
}
void QAudioOutputPrivate::close()
{
if (audioUnit != 0) {
AudioOutputUnitStop(audioUnit);
AudioUnitUninitialize(audioUnit);
CloseComponent(audioUnit);
}
delete audioBuffer;
}
QAudioFormat QAudioOutputPrivate::format() const
{
return audioFormat;
}
QIODevice* QAudioOutputPrivate::start(QIODevice* device)
{
QIODevice* op = device;
if (!open()) {
stateCode = QAudio::StoppedState;
errorCode = QAudio::OpenError;
return audioIO;
}
reset();
audioBuffer->reset();
audioBuffer->setPrefetchDevice(op);
if (op == 0) {
op = audioIO;
stateCode = QAudio::IdleState;
}
else
stateCode = QAudio::ActiveState;
// Start
errorCode = QAudio::NoError;
totalFrames = 0;
startTime = AudioGetCurrentHostTime();
if (stateCode == QAudio::ActiveState)
audioThreadStart();
emit stateChanged(stateCode);
return op;
}
void QAudioOutputPrivate::stop()
{
QMutexLocker lock(&mutex);
if (stateCode != QAudio::StoppedState) {
audioThreadDrain();
stateCode = QAudio::StoppedState;
errorCode = QAudio::NoError;
QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
}
}
void QAudioOutputPrivate::reset()
{
QMutexLocker lock(&mutex);
if (stateCode != QAudio::StoppedState) {
audioThreadStop();
stateCode = QAudio::StoppedState;
errorCode = QAudio::NoError;
QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
}
}
void QAudioOutputPrivate::suspend()
{
QMutexLocker lock(&mutex);
if (stateCode == QAudio::ActiveState || stateCode == QAudio::IdleState) {
audioThreadStop();
stateCode = QAudio::SuspendedState;
errorCode = QAudio::NoError;
QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
}
}
void QAudioOutputPrivate::resume()
{
QMutexLocker lock(&mutex);
if (stateCode == QAudio::SuspendedState) {
audioThreadStart();
stateCode = QAudio::ActiveState;
errorCode = QAudio::NoError;
QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
}
}
int QAudioOutputPrivate::bytesFree() const
{
return audioBuffer->available();
}
int QAudioOutputPrivate::periodSize() const
{
return periodSizeBytes;
}
void QAudioOutputPrivate::setBufferSize(int bs)
{
if (stateCode == QAudio::StoppedState)
internalBufferSize = bs;
}
int QAudioOutputPrivate::bufferSize() const
{
return internalBufferSize;
}
void QAudioOutputPrivate::setNotifyInterval(int milliSeconds)
{
intervalTimer->setInterval(milliSeconds);
}
int QAudioOutputPrivate::notifyInterval() const
{
return intervalTimer->interval();
}
qint64 QAudioOutputPrivate::processedUSecs() const
{
return totalFrames * 1000000 / audioFormat.frequency();
}
qint64 QAudioOutputPrivate::elapsedUSecs() const
{
if (stateCode == QAudio::StoppedState)
return 0;
return (AudioGetCurrentHostTime() - startTime) / (clockFrequency / 1000);
}
QAudio::Error QAudioOutputPrivate::error() const
{
return errorCode;
}
QAudio::State QAudioOutputPrivate::state() const
{
return stateCode;
}
void QAudioOutputPrivate::audioThreadStart()
{
startTimers();
audioThreadState = Running;
AudioOutputUnitStart(audioUnit);
}
void QAudioOutputPrivate::audioThreadStop()
{
stopTimers();
if (audioThreadState.testAndSetAcquire(Running, Stopped))
threadFinished.wait(&mutex);
}
void QAudioOutputPrivate::audioThreadDrain()
{
stopTimers();
if (audioThreadState.testAndSetAcquire(Running, Draining))
threadFinished.wait(&mutex);
}
<|fim▁hole|>void QAudioOutputPrivate::audioDeviceStop()
{
AudioOutputUnitStop(audioUnit);
audioThreadState = Stopped;
threadFinished.wakeOne();
}
void QAudioOutputPrivate::audioDeviceIdle()
{
QMutexLocker lock(&mutex);
if (stateCode == QAudio::ActiveState) {
audioDeviceStop();
errorCode = QAudio::UnderrunError;
stateCode = QAudio::IdleState;
QMetaObject::invokeMethod(this, "deviceStopped", Qt::QueuedConnection);
}
}
void QAudioOutputPrivate::audioDeviceError()
{
QMutexLocker lock(&mutex);
if (stateCode == QAudio::ActiveState) {
audioDeviceStop();
errorCode = QAudio::IOError;
stateCode = QAudio::StoppedState;
QMetaObject::invokeMethod(this, "deviceStopped", Qt::QueuedConnection);
}
}
void QAudioOutputPrivate::startTimers()
{
audioBuffer->startFillTimer();
intervalTimer->start();
}
void QAudioOutputPrivate::stopTimers()
{
audioBuffer->stopFillTimer();
intervalTimer->stop();
}
void QAudioOutputPrivate::deviceStopped()
{
intervalTimer->stop();
emit stateChanged(stateCode);
}
void QAudioOutputPrivate::inputReady()
{
QMutexLocker lock(&mutex);
if (stateCode == QAudio::IdleState) {
audioThreadStart();
stateCode = QAudio::ActiveState;
errorCode = QAudio::NoError;
QMetaObject::invokeMethod(this, "stateChanged", Qt::QueuedConnection, Q_ARG(QAudio::State, stateCode));
}
}
OSStatus QAudioOutputPrivate::renderCallback(void* inRefCon,
AudioUnitRenderActionFlags* ioActionFlags,
const AudioTimeStamp* inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList* ioData)
{
Q_UNUSED(ioActionFlags)
Q_UNUSED(inTimeStamp)
Q_UNUSED(inBusNumber)
Q_UNUSED(inNumberFrames)
QAudioOutputPrivate* d = static_cast<QAudioOutputPrivate*>(inRefCon);
const int threadState = d->audioThreadState.fetchAndAddAcquire(0);
if (threadState == Stopped) {
ioData->mBuffers[0].mDataByteSize = 0;
d->audioDeviceStop();
}
else {
const UInt32 bytesPerFrame = d->streamFormat.mBytesPerFrame;
qint64 framesRead;
framesRead = d->audioBuffer->readFrames((char*)ioData->mBuffers[0].mData,
ioData->mBuffers[0].mDataByteSize / bytesPerFrame);
if (framesRead > 0) {
ioData->mBuffers[0].mDataByteSize = framesRead * bytesPerFrame;
d->totalFrames += framesRead;
}
else {
ioData->mBuffers[0].mDataByteSize = 0;
if (framesRead == 0) {
if (threadState == Draining)
d->audioDeviceStop();
else
d->audioDeviceIdle();
}
else
d->audioDeviceError();
}
}
return noErr;
}
QT_END_NAMESPACE
#include "qaudiooutput_mac_p.moc"<|fim▁end|> | |
<|file_name|>model_control_one_enabled_Fisher_Lag1Trend_Seasonal_Hour_LSTM.py<|end_file_name|><|fim▁begin|><|fim▁hole|>import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Fisher'] , ['Lag1Trend'] , ['Seasonal_Hour'] , ['LSTM'] );<|fim▁end|> | |
<|file_name|>package.py<|end_file_name|><|fim▁begin|>##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.<|fim▁hole|># LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class PyAsn1crypto(PythonPackage):
"""Python ASN.1 library with a focus on performance and a pythonic API """
homepage = "https://github.com/wbond/asn1crypto"
url = "https://pypi.io/packages/source/a/asn1crypto/asn1crypto-0.22.0.tar.gz"
version('0.22.0', '74a8b9402625b38ef19cf3fa69ef8470')
depends_on('py-setuptools', type='build')<|fim▁end|> | |
<|file_name|>resolve-type-param-in-item-in-trait.rs<|end_file_name|><|fim▁begin|>// Issue #14603: Check for references to type parameters from the
// outer scope (in this case, the trait) used on items in an inner
// scope (in this case, the enum).
trait TraitA<A> {
fn outer(&self) {
enum Foo<B> {
Variance(A)
//~^ ERROR can't use generic parameters from outer function
}
}
}
<|fim▁hole|> struct Foo<B>(A);
//~^ ERROR can't use generic parameters from outer function
}
}
trait TraitC<A> {
fn outer(&self) {
struct Foo<B> { a: A }
//~^ ERROR can't use generic parameters from outer function
}
}
trait TraitD<A> {
fn outer(&self) {
fn foo<B>(a: A) { }
//~^ ERROR can't use generic parameters from outer function
}
}
fn main() { }<|fim▁end|> | trait TraitB<A> {
fn outer(&self) { |
<|file_name|>EvaLayout.java<|end_file_name|><|fim▁begin|>/*
package de.elxala.langutil
(c) Copyright 2006 Alejandro Xalabarder Aulet
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
//(o) WelcomeGastona_source_javaj_layout EVALAYOUT
========================================================================================
================ documentation for WelcomeGastona.gast =================================
========================================================================================
#gastonaDoc#
<docType> javaj_layout
<name> EVALAYOUT
<groupInfo>
<javaClass> de.elxala.Eva.layout.EvaLayout
<importance> 10
<desc> //A fexible grid layout
<help>
//
// Eva layout is the most powerful layout used by Javaj. The components are laid out in a grid
// and it is possible to define very accurately which cells of the grid occupy each one, which
// size has to have and if they are expandable or not.
//
// Syntax:
//
// <layout of NAME>
// EVALAYOUT, marginX, marginY, gapX, gapY
//
// --grid-- , header col1, ... , header colN
// header row1, cell 1 1 , ... , cell 1 N
// ... , ... , ... , ...
// header rowM, cell M 1 , ... , cell M N
//
// The first row starts with "EVALAYOUT" or simply "EVA", then optionally the following values
// in pixels for the whole grid
//
// marginX : horizontal margins for both left and right sides
// marginY : vertical margins for both top and bottom areas
// gapX : horizontal space between columns
// gapY : vertical space between rows
//
// The rest of rows defines a grid with arbitrary N columns and M rows, the minimum for both M
// and N is 1. To define a grid M x N we will need M+1 rows and a maximum of N+1 columns, this
// is because the header types given in rows and columns. These header values may be one of:
//
// header
// value meaning
// ------- --------
// A Adapt (default). The row or column will adapt its size to the bigest default
// size of all components that start in this row or column.
// X Expand. The row or column is expandable, when the the frame is resized all
// expandable row or columns will share the remaining space equally.
// a number A fix size in pixels for the row or column
//
// Note that the very first header ("--grid--") acctually does not correspond with a row or a
// column of the grid and therefore it is ignored by EvaLayout.
//
// Finally the cells are used to place and expand the components. If we want the component to
// ocupy just one cell then we place it in that cell. If we want the component to ocupy more
// cells then we place the component on the left-top cell of the rectangle of cells to be
// ocupped, we fill the rest of top cells with "-" to the right and the rest of left cells with
// the symbol "+" to the bottom, the rest of cells (neither top or left cells) might be left in
// blank.
//
// Example:
//
// let's say we want to lay-out the following form
//
// ----------------------------------------------
// | label1 | field -------> | button1 |
// ----------------------------------------------
// | label2 | text -------> | button2 |
// ------------| | |----------
// | | | button3 |
// | V |----------
// | |
// ------------------------
//
// representing this as grid of cells can be done at least in these two ways
//
//
// Adapt Adapt Expand Adapt Adapt Expand Adapt
// ------------------------------------- -----------------------------
// Adapt | label1 | field | - | button1 | Adapt | label1 | field | button1 |
// |---------|-------|-------|---------| |---------|-------|---------|
// Adapt | label2 | text | - | button2 | Adapt | label2 | text | button2 |
// |---------|------ |-------|---------| |---------|------ |---------|
// Adapt | | + | | button3 | Adapt | | + | button3 |
// |---------|------ |-------|---------| |---------|------ |---------|
// Expand | | + | | | Expand | | + | |
// ------------------------------------- -----------------------------
//
// the implementation of the second one as Evalayout would be
//
// <layout of myFirstLayout>
//
// EVALAYOUT
//
// grid, A , X , A
// A, label1 , field , button1
// A, label2 , text , button2
// A, , + , button3
// X, , + ,
//
// NOTE: While columns and rows of type expandable or fixed size might be empty of components,
// this does not make sense for columns and rows of type adaptable (A), since in this
// case there is nothing to adapt. These columns or rows has to be avoided because
// might produce undefined results.
//
<...>
// NOTE: EvaLayout is also available for C++ development with Windows Api and MFC,
// see as reference the article http://www.codeproject.com/KB/dialog/EvaLayout.aspx
//
<examples>
gastSample
eva layout example1
eva layout example2
eva layout example3
eva layout complet
eva layout centering
eva layout percenting
<eva layout example1>
//#gastona#
//
// <!PAINT LAYOUT>
//
//#javaj#
//
// <frames>
// F, "example layout EVALAYOUT"
//
// <layout of F>
//
// EVALAYOUT, 10, 10, 5, 5
//
// grid, , X ,
// , lLabel1 , eField1 , bButton1
// , lLabel2 , xText1 , bButton2
// , , + , bButton3
// X , , + ,
<eva layout example2>
//#gastona#
//
// <!PAINT LAYOUT>
//
//#javaj#
//
// <frames>
// F, "example 2 layout EVALAYOUT"
//
// <layout of F>
//
// EVA, 10, 10, 5, 5
//
// --- , 75 , X , A ,
// , bButton , xMemo , - ,
// , bBoton , + , ,
// , bKnopf , + , ,
// X , , + , ,
// , eCamp , - , bBotó maco ,
<eva layout example3>
//#gastona#
//
// <!PAINT LAYOUT>
//
//#javaj#
//
// <frames>
// F, "example 2 bis layout EVALAYOUT"
//
// <layout of F>
// EVALAYOUT, 15, 15, 5, 5
//
// , , X ,
// 50, bBoton1 , - , -
// , bBoton4 , eField , bBoton2
// X , + , xText , +
// 50, bBoton3 , - , +
<eva layout complet>
//#gastona#
//
// <!PAINT LAYOUT>
//
//#javaj#
//
// <frames>
// F, "example complex layout"
//
// <layout of F>
// EVALAYOUT, 15, 15, 5, 5
//
// ---, 80 , X , 110
// , lLabel1 , eEdit1 , -
// , lLabel2 , cCombo , lLabel3
// , lLabel4 , xMemo , iLista
// , bBoton1 , + , +
// , bBoton2 , + , +
// X , , + , +
// , layOwner , - , +
// , , , bBoton4
//
// <layout of layOwner>
// PANEL, Y, Owner Info
//
// LayFields
//
// <layout of LayFields>
// EVALAYOUT, 5, 5, 5, 5
//
// ---, , X
// , lName , eName
// , lPhone , ePhone
//
<eva layout centering>
//#gastona#
//
// <PAINT LAYOUT>
//
//#javaj#
//
// <frames>
// Fmain, Centering with EvaLayout demo
//
// <layout of Fmain>
// EVA
//
// , X, A , X
// X ,
// A , , bCentered
// X ,
<eva layout percenting>
//#gastona#
//
// <!PAINT LAYOUT>
//
//#javaj#
//
// <frames>
// Fmain, Percenting with EvaLayout demo, 300, 300
//
// <layout of Fmain>
// EVA, 10, 10, 7, 7
//
// , X , X , X , X
// X , b11 , b13 , - , -
// X , b22 , - , b23 , -
// X , + , , + ,
// X , b12 , - , + ,
//
//#data#
//
// <b11> 25% x 25%
// <b13> 75% horizontally 25% vertically
// <b22> fifty-fifty
// <b12> 50% x 25% y
// <b23> half and 3/4
#**FIN_EVA#
*/
package de.elxala.Eva.layout;
import java.util.Vector;
import java.util.Hashtable;
import java.util.Enumeration; // to traverse the HashTable ...
import java.awt.*;
import de.elxala.Eva.*;
import de.elxala.langutil.*;
import de.elxala.zServices.*;
/**
@author Alejandro Xalabarder
@date 11.04.2006 22:32
Example:
<pre>
import java.awt.*;
import javax.swing.*;
import de.elxala.Eva.*;
import de.elxala.Eva.layout.*;
public class sampleEvaLayout
{
public static void main (String [] aa)
{
JFrame frame = new JFrame ("sampleEvaLayout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = frame.getContentPane ();
Eva lay = new Eva();
// set margins
lay.addLine (new EvaLine ("EvaLayout, 15, 15, 5, 5"));
// set grid
lay.addLine (new EvaLine ("RxC, , 100 , X ,"));
lay.addLine (new EvaLine (" , lname , eName , ,"));
lay.addLine (new EvaLine (" , lobserv, xObs , - ,"));
lay.addLine (new EvaLine (" X, , + , ,"));
pane.setLayout (new EvaLayout(lay));
pane.add ("lname", new JLabel("Name"));
pane.add ("lobserv", new JLabel("Notes"));
pane.add ("eName", new JTextField());
pane.add ("xObs", new JTextPane());
frame.pack();
frame.setSize (new Dimension (300, 200));
frame.show();
}
}
</pre>
*/
public class EvaLayout implements LayoutManager2
{
private static logger log = new logger (null, "de.elxala.Eva.EvaLayout", null);
//19.10.2010 20:31
// Note : Limits introduced in change (bildID) 11088 on 2010-09-20 01:47:25
// named "FIX problema en layout (LOW LEVEL BUG 2!)"
// But today the problem (without limits) cannot be reproduced! (?)
// Limits set as aproximation, these can be reviewed and changed
//
private static int MAX_SIZE_DX = 10000;
private static int MAX_SIZE_DY = 10000;
protected static final int HEADER_EXPAND = 10;
protected static final int HEADER_ORIGINAL = 11;
protected static final int HEADER_NUMERIC = 12;
protected static final String EXPAND_HORIZONTAL = "-";
protected static final String EXPAND_VERTICAL = "+";
// variables for pre-calculated layout
//
private boolean isPrecalculated = false;
protected int Hmargin;
protected int Vmargin;
protected int Hgap;
protected int Vgap;
private int mnCols = -1; // note : this is a cached value and might be call before precalculation!
private int mnRows = -1; // note : this is a cached value and might be call before precalculation!
private int fijoH = 0;
private int fijoV = 0;
public int [] HdimMin = new int [0];
public int [] HdimPref = new int [0]; // for preferred instead of minimum
public int [] Hpos = new int [0];
public int [] VdimMin = new int [0];
public int [] VdimPref = new int [0]; // for preferred instead of minimum
public int [] Vpos = new int [0];
private Eva lay = null;
private Hashtable componentHTable = new Hashtable();
protected class widgetInfo
{
public widgetInfo (String nam, Component com)
{
name = nam;
comp = com;
}
public String name; // name of the component in the layout array
public Component comp; // component info
public boolean isLaidOut; // if the component has been found in the layout array
// and therefore if indxPos is a valid calculated field
// place in the layout array mesured in array indices
public int posCol0; // first column that the widget occupies
public int posRow0; // first row
public int posCol1; // last column
public int posRow1; // last row
}
Vector columnsReparto = new Vector ();
Vector rowsReparto = new Vector ();
public EvaLayout()
{
this(new Eva());
}
public EvaLayout(Eva layarray)
{
log.dbg (2, "EvaLayout", "create EvaLayout " + layarray.getName ());
lay = layarray;
}
/**
Switches to another layout : note that the components used in this new layout
has to exists (added to the layout using add method)
*/
public void switchLayout(Eva layarray)
{
log.dbg (2, "switchLayout", "switch new layout info " + layarray.getName ());
lay = layarray;
invalidatePreCalc ();
}
private int headType (String str)
{
if (str.length () == 0 ||
str.equalsIgnoreCase ("a")) return HEADER_ORIGINAL;
if (str.equalsIgnoreCase ("x")) return HEADER_EXPAND;
return HEADER_NUMERIC; // it should
}
private void precalculateAll ()
{
if (isPrecalculated) return;
log.dbg (2, "precalculateAll", "layout " + lay.getName () + " perform precalculation.");
Hmargin = Math.max (0, stdlib.atoi (lay.getValue (0,1)));
Vmargin = Math.max (0, stdlib.atoi (lay.getValue (0,2)));
Hgap = Math.max (0, stdlib.atoi (lay.getValue (0,3)));
Vgap = Math.max (0, stdlib.atoi (lay.getValue (0,4)));
log.dbg (4, "precalculateAll", nColumns() + " columns x " + nRows() + " rows");
log.dbg (4, "precalculateAll", "margins xm=" + Hmargin + ", ym=" + Vmargin + ", yg=" + Hgap + ", yg=" + Vgap);
mnCols = -1; // reset cached number of cols
mnRows = -1; // reset cached number of rows
HdimMin = new int [nColumns()];
HdimPref = new int [nColumns()];
Hpos = new int [nColumns()];
VdimMin = new int [nRows()];
VdimPref = new int [nRows()];
Vpos = new int [nRows()];
columnsReparto = new Vector ();
rowsReparto = new Vector ();
// for all components ...
Enumeration enu = componentHTable.keys();
while (enu.hasMoreElements())
{
String key = (String) enu.nextElement();
((widgetInfo) componentHTable.get(key)).isLaidOut = false;
}
// compute Vdim (Note: it might be precalculated if needed)
fijoV = Vmargin;
for (int rr = 0; rr < nRows(); rr ++)
{
String heaRow = rowHeader(rr);
int typ = headType(heaRow);
int gap = (rr == 0) ? 0: Vgap;
if (typ == HEADER_ORIGINAL)
{
// maximum-minimum of the row
VdimPref[rr] = minHeightOfRow(rr, true);
VdimMin[rr] = minHeightOfRow(rr, false);
log.dbg (2, "precalculateAll", "Adaption... VdimPref[rr] = " + VdimPref[rr]);
}
else if (typ == HEADER_EXPAND)
{
rowsReparto.add (new int [] { rr }); // compute later
log.dbg (2, "precalculateAll", "Expand... VdimPref[rr] = " + VdimPref[rr]);
}
else
{
// indicated size
VdimPref[rr] = VdimMin[rr] = stdlib.atoi(heaRow);
log.dbg (2, "precalculateAll", "Explicit... VdimPref[rr] = " + VdimPref[rr]);
}
Vpos[rr] = fijoV + gap;
fijoV += VdimPref[rr];
fijoV += gap;
}
fijoV += Vmargin;
log.dbg (2, "precalculateAll", "fijoV = " + fijoV + " Vmargin = " + Vmargin + " Vgap = " + Vgap);
//DEBUG ....
if (log.isDebugging (2))
{
String vertical = "Vertical array (posY/prefHeight/minHeight)";
for (int rr = 0; rr < Vpos.length; rr++)
vertical += " " + rr + ") " + Vpos[rr] + "/" + VdimPref[rr] + "/" + VdimMin[rr];
log.dbg (2, "precalculateAll", vertical);
}
// compute Hdim (Note: it might be precalculated if needed)
fijoH = Hmargin;
for (int cc = 0; cc < nColumns(); cc ++)
{
String heaCol = columnHeader(cc);
int typ = headType(heaCol);
int gap = (cc == 0) ? 0: Hgap;
if (typ == HEADER_ORIGINAL)
{
// maximum-minimum of the column
HdimPref[cc] = minWidthOfColumn(cc, true);
HdimMin[cc] = minWidthOfColumn(cc, false);
}
else if (typ == HEADER_EXPAND)
columnsReparto.add (new int [] { cc }); // compute later
else
HdimPref[cc] = HdimMin[cc] = stdlib.atoi(heaCol); // indicated size
Hpos[cc] = fijoH + gap;
fijoH += HdimPref[cc];
fijoH += gap;
}
fijoH += Hmargin;
log.dbg (2, "precalculateAll", "fijoH = " + fijoH);
//DEBUG ....
if (log.isDebugging (2))
{
String horizontal = "Horizontal array (posX/prefWidth/minWidth)";
for (int cc = 0; cc < Hpos.length; cc++)
horizontal += " " + cc + ") " + Hpos[cc] + "/" + HdimPref[cc] + "/" + HdimMin[cc];
log.dbg (2, "precalculateAll", horizontal);
}
// finding all components in the layout array
for (int cc = 0; cc < nColumns(); cc ++)
{
for (int rr = 0; rr < nRows(); rr ++)
{
String name = widgetAt(rr, cc);
widgetInfo wid = theComponent (name);
if (wid == null) continue;
// set position x,y
wid.posCol0 = cc;
wid.posRow0 = rr;
// set position x2,y2
int ava = cc;
while (ava+1 < nColumns() && widgetAt(rr, ava+1).equals (EXPAND_HORIZONTAL)) ava ++;
wid.posCol1 = ava;
ava = rr;
while (ava+1 < nRows() && widgetAt(ava+1, cc).equals (EXPAND_VERTICAL)) ava ++;
wid.posRow1 = ava;
wid.isLaidOut = true;
//DEBUG ....
if (log.isDebugging (2))
{
log.dbg (2, "precalculateAll", wid.name + " leftTop (" + wid.posCol0 + ", " + wid.posRow0 + ") rightBottom (" + wid.posCol1 + ", " + wid.posRow1 + ")");
}
}
}
isPrecalculated = true;
}
protected int nColumns ()
{
// OLD
// return Math.max(0, lay.cols(1) - 1);
if (mnCols != -1) return mnCols;
// has to be calculated,
// the maximum n of cols of header or rows
//
for (int ii = 1; ii < lay.rows (); ii ++)
if (mnCols < Math.max(0, lay.cols(ii) - 1))
mnCols = Math.max(0, lay.cols(ii) - 1);
mnCols = Math.max(0, mnCols);
return mnCols;
}
protected int nRows ()
{
// OLD
// return Math.max(0, lay.rows() - 2);
if (mnRows != -1) return mnRows;
mnRows = Math.max(0, lay.rows() - 2);
return mnRows;
}
public Eva getEva ()
{
return lay;
}
public String [] getWidgets ()
{
java.util.Vector vecWidg = new java.util.Vector ();
for (int rr = 0; rr < nRows(); rr ++)
for (int cc = 0; cc < nColumns(); cc ++)
{
String name = widgetAt (rr, cc);
if (name.length() > 0 && !name.equals(EXPAND_HORIZONTAL) && !name.equals(EXPAND_VERTICAL))
vecWidg.add (name);
}
// pasarlo a array
String [] arrWidg = new String [vecWidg.size ()];
for (int ii = 0; ii < arrWidg.length; ii ++)
arrWidg[ii] = (String) vecWidg.get (ii);
return arrWidg;
}
/**
* Adds the specified component with the specified name
*/
public void addLayoutComponent(String name, Component comp)
{
log.dbg (2, "addLayoutComponent", name + " compName (" + comp.getName () + ")");
componentHTable.put(name, new widgetInfo (name, comp));
isPrecalculated = false;
}
/**
* Removes the specified component from the layout.
* @param comp the component to be removed
*/
public void removeLayoutComponent(Component comp)
{
// componentHTable.remove(comp);
}
/**
* Calculates the preferred size dimensions for the specified
* panel given the components in the specified parent container.
* @param parent the component to be laid out
*/
public Dimension preferredLayoutSize(Container parent)
{
///*EXPERIMENT!!!*/invalidatePreCalc ();
Dimension di = getLayoutSize(parent, true);
log.dbg (2, "preferredLayoutSize", lay.getName() + " preferredLayoutSize (" + di.width + ", " + di.height + ")");
//(o) TODO_javaj_layingOut Problem: preferredLayoutSize
//19.04.2009 19:50 Problem: preferredLayoutSize is called when pack and after that no more
// layouts data dependent like slider (don't know if horizontal or vertical) have problems
// Note: this is not just a problem of EvaLayout but of all layout managers
//log.severe ("SEVERINIO!");
return di;
}
/**
* Calculates the minimum size dimensions for the specified
* panel given the components in the specified parent container.<|fim▁hole|> {
Dimension di = getLayoutSize(parent, false);
log.dbg (2, "minimumLayoutSize", lay.getName() + " minimumLayoutSize (" + di.width + ", " + di.height + ")");
return di;
}
/**
*calculating layout size (minimum or preferred).
*/
protected Dimension getLayoutSize(Container parent, boolean isPreferred)
{
log.dbg (2, "getLayoutSize", lay.getName());
precalculateAll ();
// In precalculateAll the methods minWidthOfColumn and minHeightOfRow
// does not evaluate expandable components since these might use other columns.
// But in order to calculate the minimum or preferred total size we need this information.
// In these cases we have to calculate following : if the sum of the sizes of the
// columns that the component occupies is less that the minimum/preferred size of
// the component then we add the difference to the total width
// We evaluate this ONLY for those components that could be expanded!
// for example
//
// NO COMPONENT HAS TO COMPONENTS comp1 and comp3
// BE RECALCULED HAS TO BE RECALCULED
// --------------------- ------------------------
// grid, 160 , A grid, 160 , X
// A , comp1 , - A , comp1 , -
// A , comp2 , comp3 X , comp2 , comp3
//
int [] extraCol = new int [nColumns ()];
int [] extraRow = new int [nRows ()];
int [] Hdim = isPreferred ? HdimPref: HdimMin;
int [] Vdim = isPreferred ? VdimPref: VdimMin;
//System.err.println ("PARLANT DE " + lay.getName () + " !!!");
// for all components ...
Enumeration enu = componentHTable.keys();
while (enu.hasMoreElements())
{
boolean someExpan = false;
String key = (String) enu.nextElement();
widgetInfo wi = (widgetInfo) componentHTable.get(key);
if (! wi.isLaidOut) continue;
Dimension csiz = (isPreferred) ? wi.comp.getPreferredSize(): wi.comp.getMinimumSize();
log.dbg (2, "getLayoutSize", wi.name + " dim (" + csiz.width + ", " + csiz.height + ")");
// some column expandable ?
//
someExpan = false;
for (int cc = wi.posCol0; cc <= wi.posCol1; cc ++)
if (headType(columnHeader(cc)) == HEADER_EXPAND)
{
someExpan = true;
break;
}
if (someExpan)
{
// sum of all columns that this component occupy
int sum = 0;
for (int cc = wi.posCol0; cc <= wi.posCol1; cc ++)
sum += (Hdim[cc] + extraCol[cc]);
// distribute it in all columns to be salomonic
int resto = csiz.width - sum;
if (resto > 0)
{
if (wi.posCol0 == wi.posCol1)
{
// System.err.println ("Resto X " + resto + " de " + wi.name + " en la " + wi.posCol0 + " veniendo de csiz.width " + csiz.width + " y sum " + sum + " que repahartimos en " + (1 + wi.posCol1 - wi.posCol0) + " parates tenahamos una estra de " + extraCol[wi.posCol0]);
}
for (int cc = wi.posCol0; cc <= wi.posCol1; cc ++)
extraCol[cc] = resto / (1 + wi.posCol1 - wi.posCol0);
}
}
// some row expandable ?
//
someExpan = false;
for (int rr = wi.posRow0; rr <= wi.posRow1; rr ++)
if (headType(rowHeader(rr)) == HEADER_EXPAND)
{
someExpan = true;
break;
}
if (someExpan)
{
// sum of all height (rows) that this component occupy
int sum = 0;
for (int rr = wi.posRow0; rr <= wi.posRow1; rr ++)
sum += (Vdim[rr] + extraRow[rr]);
// distribute it in all columns to be salomonic
int resto = csiz.height - sum;
if (resto > 0)
{
for (int rr = wi.posRow0; rr <= wi.posRow1; rr ++)
extraRow[rr] = resto / (1 + wi.posRow1 - wi.posRow0);
}
}
}
int tot_width = 0;
for (int cc = 0; cc < nColumns(); cc ++)
{
tot_width += (Hdim[cc] + extraCol[cc]);
}
int tot_height = 0;
for (int rr = 0; rr < nRows(); rr ++)
{
tot_height += Vdim[rr] + extraRow[rr];
}
Insets insets = (parent != null) ? parent.getInsets(): new Insets(0,0,0,0);
tot_width += Hgap * (nColumns() - 1) + insets.left + insets.right + 2 * Hmargin;
tot_height += Vgap * (nRows() - 1) + insets.top + insets.bottom + 2 * Vmargin;
log.dbg (2, "getLayoutSize", "returning tot_width " + tot_width + ", tot_height " + tot_height);
// System.out.println ("getLayoutSize pref=" + isPreferred + " nos sale (" + tot_width + ", " + tot_height + ")");
return new Dimension (tot_width, tot_height);
}
private String columnHeader(int ncol)
{
return lay.getValue(1, ncol + 1).toUpperCase ();
}
private String rowHeader(int nrow)
{
return lay.getValue(2 + nrow, 0).toUpperCase ();
}
private String widgetAt(int nrow, int ncol)
{
return lay.getValue (nrow + 2, ncol + 1);
}
private widgetInfo theComponent(String cellName)
{
if (cellName.length() == 0 || cellName.equals(EXPAND_HORIZONTAL) || cellName.equals(EXPAND_VERTICAL)) return null;
widgetInfo wi = (widgetInfo) componentHTable.get(cellName);
if (wi == null)
log.severe ("theComponent", "Component " + cellName + " not found in the container laying out " + lay.getName () + "!");
return wi;
}
private int minWidthOfColumn (int ncol, boolean preferred)
{
// el componente ma's ancho de la columna
int maxwidth = 0;
for (int rr = 0; rr < nRows(); rr ++)
{
String name = widgetAt (rr, ncol);
widgetInfo wi = theComponent (name);
if (wi != null)
{
if (widgetAt (rr, ncol+1).equals(EXPAND_HORIZONTAL)) continue; // widget occupies more columns so do not compute it
Dimension csiz = (preferred) ? wi.comp.getPreferredSize(): wi.comp.getMinimumSize();
maxwidth = Math.max (maxwidth, csiz.width);
}
}
//19.09.2010 Workaround
//in some cases, specially preferred size, can be too high (8000 etc) which make calculations fail!
return maxwidth > MAX_SIZE_DX ? MAX_SIZE_DX : maxwidth;
}
private int minHeightOfRow (int nrow, boolean preferred)
{
// el componente ma's alto de la columna
int maxheight = 0;
for (int cc = 0; cc < nColumns(); cc ++)
{
String name = widgetAt (nrow, cc);
widgetInfo wi = theComponent (name);
if (wi != null)
{
if (widgetAt (nrow+1, cc).equals(EXPAND_VERTICAL)) continue; // widget occupies more rows so do not compute it
Dimension csiz = (preferred) ? wi.comp.getPreferredSize(): wi.comp.getMinimumSize();
maxheight = Math.max (maxheight, csiz.height);
}
}
//19.09.2010 Workaround
//in some cases, specially preferred size, can be too high (8000 etc) which make calculations fail!
return maxheight > MAX_SIZE_DY ? MAX_SIZE_DY : maxheight;
}
/**
* Lays out the container in the specified container.
* @param parent the component which needs to be laid out
*/
public void layoutContainer(Container parent)
{
//isPrecalculated = false;
if (log.isDebugging(4))
log.dbg (4, "layoutContainer", lay.getName ());
precalculateAll ();
synchronized (parent.getTreeLock())
{
Insets insets = parent.getInsets();
//if (log.isDebugging(4))
// log.dbg (4, "layoutContainer", "insets left right =" + insets.left + ", " + insets.right + " top bottom " + insets.top + ", " + insets.bottom);
// Total parent dimensions
Dimension size = parent.getSize();
if (log.isDebugging(4))
log.dbg (4, "layoutContainer", "parent size =" + size.width + ", " + size.height);
int repartH = size.width - (insets.left + insets.right) - fijoH;
int repartV = size.height - (insets.top + insets.bottom) - fijoV;
int [] HextraPos = new int [HdimPref.length];
int [] VextraPos = new int [VdimPref.length];
if (log.isDebugging(4))
log.dbg (4, "layoutContainer", "repartH=" + repartH + " repartV=" + repartV);
// repartir H
if (columnsReparto.size() > 0)
{
repartH /= columnsReparto.size();
for (int ii = 0; ii < columnsReparto.size(); ii ++)
{
int indx = ((int []) columnsReparto.get (ii))[0];
HdimPref[indx] = repartH;
for (int res = indx+1; res < nColumns(); res ++)
HextraPos[res] += repartH;
}
}
// repartir V
if (rowsReparto.size() > 0)
{
repartV /= rowsReparto.size();
for (int ii = 0; ii < rowsReparto.size(); ii ++)
{
int indx = ((int []) rowsReparto.get (ii))[0];
VdimPref[indx] = repartV;
for (int res = indx+1; res < nRows(); res ++)
VextraPos[res] += repartV;
}
}
//
// for all components ... for (int ii = 0; ii < componentArray.size(); ii ++)
//
java.util.Enumeration enu = componentHTable.keys();
while (enu.hasMoreElements())
{
String key = (String) enu.nextElement();
widgetInfo wi = (widgetInfo) componentHTable.get(key);
if (log.isDebugging(4))
log.dbg (4, "layoutContainer", "element [" + key + "]");
// System.out.println ("componente " + wi.name);
if (! wi.isLaidOut) continue;
// System.out.println (" indices " + wi.posCol0 + " (" + Hpos[wi.posCol0] + " extras " + HextraPos[wi.posCol0] + ")");
int x = Hpos[wi.posCol0] + HextraPos[wi.posCol0];
int y = Vpos[wi.posRow0] + VextraPos[wi.posRow0];
int dx = 0;
int dy = 0;
//if (log.isDebugging(4))
// log.dbg (4, "SIGUEY", "1) y = " + y + " Vpos[wi.posRow0] = " + Vpos[wi.posRow0] + " VextraPos[wi.posRow0] = " + VextraPos[wi.posRow0]);
for (int mm = wi.posCol0; mm <= wi.posCol1; mm ++)
{
if (mm != wi.posCol0) dx += Hgap;
dx += HdimPref[mm];
}
for (int mm = wi.posRow0; mm <= wi.posRow1; mm ++)
{
if (mm != wi.posRow0) dy += Vgap;
dy += VdimPref[mm];
}
if (x < 0 || y < 0 || dx < 0 || dy < 0)
{
//Disable this warning because it happens very often when minimizing the window etc
//log.warn ("layoutContainer", "component not laid out! [" + wi.name + "] (" + x + ", " + y + ") (" + dx + ", " + dy + ")");
continue;
}
wi.comp.setBounds(x, y, dx, dy);
if (log.isDebugging(4))
log.dbg (4, "layoutContainer", "vi.name [" + wi.name + "] (" + x + ", " + y + ") (" + dx + ", " + dy + ")");
}
} // end synchronized
}
// LayoutManager2 /////////////////////////////////////////////////////////
/**
* This method make no sense in this layout, the constraints are not per component
* but per column and rows. Since this method is called when adding components through
* the method add(String, Component) we implement it as if constraints were the name
*/
public void addLayoutComponent(Component comp, Object constraints)
{
addLayoutComponent((String) constraints, comp);
}
/**
* Returns the maximum size of this component.
*/
public Dimension maximumLayoutSize(Container target)
{
return new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE);
}
/**
* Returns the alignment along the x axis. This specifies how
* the component would like to be aligned relative to other
* components. The value should be a number between 0 and 1
* where 0 represents alignment along the origin, 1 is aligned
* the furthest away from the origin, 0.5 is centered, etc.
*/
public float getLayoutAlignmentX(Container target)
{
return 0.5f;
}
/**
* Returns the alignment along the y axis. This specifies how
* the component would like to be aligned relative to other
* components. The value should be a number between 0 and 1
* where 0 represents alignment along the origin, 1 is aligned
* the furthest away from the origin, 0.5 is centered, etc.
*/
public float getLayoutAlignmentY(Container target)
{
return 0.5f;
}
/**
* Invalidates the layout, indicating that if the layout manager
* has cached information it should be discarded.
*/
public void invalidateLayout(Container target)
{
invalidatePreCalc();
}
public void invalidatePreCalc()
{
isPrecalculated = false;
}
}<|fim▁end|> | * @param parent the component to be laid out
*/
public Dimension minimumLayoutSize(Container parent) |
<|file_name|>haptic.rs<|end_file_name|><|fim▁begin|>use joystick::SDL_Joystick;
#[cfg(feature = "no_std")]
use core::prelude::*;
use libc::{c_int, c_uint, c_char, c_float, c_void, int16_t, int32_t, uint8_t, uint16_t, uint32_t};
pub const SDL_HAPTIC_CONSTANT: uint16_t = 1 << 0;
pub const SDL_HAPTIC_SINE: uint16_t = 1 << 1;
pub const SDL_HAPTIC_LEFTRIGHT: uint16_t = 1 << 2;
pub const SDL_HAPTIC_TRIANGLE: uint16_t = 1 << 3;
pub const SDL_HAPTIC_SAWTOOTHUP: uint16_t = 1 << 4;
pub const SDL_HAPTIC_SAWTOOTHDOWN: uint16_t = 1 << 5;
pub const SDL_HAPTIC_RAMP: uint16_t = 1 << 6;
pub const SDL_HAPTIC_SPRING: uint16_t = 1 << 7;
pub const SDL_HAPTIC_DAMPER: uint16_t = 1 << 8;
pub const SDL_HAPTIC_INERTIA: uint16_t = 1 << 9;<|fim▁hole|>pub const SDL_HAPTIC_STATUS: uint16_t = 1 << 14;
pub const SDL_HAPTIC_PAUSE: uint16_t = 1 << 15;
pub type SDL_Haptic = c_void;
#[derive(Copy, Clone)]
#[repr(C)]
pub struct SDL_HapticDirection {
pub type_: uint8_t,
pub dir: [int32_t; 3],
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct SDL_HapticConstant {
pub type_: uint16_t,
pub direction: SDL_HapticDirection,
pub length: uint32_t,
pub delay: uint16_t,
pub button: uint16_t,
pub interval: uint16_t,
pub level: int16_t,
pub attack_length: uint16_t,
pub attack_level: uint16_t,
pub fade_length: uint16_t,
pub fade_level: uint16_t,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct SDL_HapticPeriodic {
pub type_: uint16_t,
pub direction: SDL_HapticDirection,
pub length: uint32_t,
pub delay: uint16_t,
pub button: uint16_t,
pub interval: uint16_t,
pub period: uint16_t,
pub magnitude: int16_t,
pub offset: int16_t,
pub phase: uint16_t,
pub attack_length: uint16_t,
pub attack_level: uint16_t,
pub fade_length: uint16_t,
pub fade_level: uint16_t,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct SDL_HapticCondition {
pub type_: uint16_t,
pub direction: SDL_HapticDirection,
pub length: uint32_t,
pub delay: uint16_t,
pub button: uint16_t,
pub interval: uint16_t,
pub right_sat: [uint16_t; 3],
pub left_sat: [uint16_t; 3],
pub right_coeff: [int16_t; 3],
pub left_coeff: [int16_t; 3],
pub deadband: [uint16_t; 3],
pub center: [int16_t; 3],
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct SDL_HapticRamp {
pub type_: uint16_t,
pub length: uint32_t,
pub delay: uint16_t,
pub button: uint16_t,
pub interval: uint16_t,
pub start: int16_t,
pub end: int16_t,
pub attack_length: uint16_t,
pub attack_level: uint16_t,
pub fade_length: uint16_t,
pub fade_level: uint16_t,
}
#[derive(Copy, Clone)]
#[repr(C)]
pub struct SDL_HapticLeftRight {
pub type_: uint16_t,
pub length: uint32_t,
pub large_magnitude: uint16_t,
pub small_magnitude: uint16_t,
}
#[allow(missing_copy_implementations)]
#[repr(C)]
pub struct SDL_HapticCustom {
pub type_: uint16_t,
pub direction: SDL_HapticDirection,
pub length: uint32_t,
pub delay: uint16_t,
pub button: uint16_t,
pub interval: uint16_t,
pub channels: uint8_t,
pub period: uint16_t,
pub samples: uint16_t,
pub data: *const uint16_t,
pub attack_length: uint16_t,
pub attack_level: uint16_t,
pub fade_length: uint16_t,
pub fade_level: uint16_t,
}
#[allow(missing_copy_implementations)]
#[repr(C)]
pub struct SDL_HapticEffect {
pub data: [uint8_t; 72],
}
impl SDL_HapticEffect {
pub fn type_(&mut self) -> *mut uint16_t {
self.data.as_mut_ptr() as *mut _
}
pub fn constant(&mut self) -> *mut SDL_HapticConstant {
self.data.as_mut_ptr() as *mut _
}
pub fn periodic(&mut self) -> *mut SDL_HapticPeriodic {
self.data.as_mut_ptr() as *mut _
}
pub fn condition(&mut self) -> *mut SDL_HapticCondition {
self.data.as_mut_ptr() as *mut _
}
pub fn ramp(&mut self) -> *mut SDL_HapticRamp {
self.data.as_mut_ptr() as *mut _
}
pub fn left_right(&mut self) -> *mut SDL_HapticLeftRight {
self.data.as_mut_ptr() as *mut _
}
pub fn custom(&mut self) -> *mut SDL_HapticCustom {
self.data.as_mut_ptr() as *mut _
}
}
extern "C" {
pub fn SDL_NumHaptics() -> c_int;
pub fn SDL_HapticName(device_index: c_int) -> *const c_char;
pub fn SDL_HapticOpen(device_index: c_int) -> *mut SDL_Haptic;
pub fn SDL_HapticOpened(device_index: c_int) -> c_int;
pub fn SDL_HapticIndex(haptic: *mut SDL_Haptic) -> c_int;
pub fn SDL_MouseIsHaptic() -> c_int;
pub fn SDL_HapticOpenFromMouse() -> *mut SDL_Haptic;
pub fn SDL_JoystickIsHaptic(joystick: *mut SDL_Joystick) -> c_int;
pub fn SDL_HapticOpenFromJoystick(joystick: *mut SDL_Joystick) -> *mut SDL_Haptic;
pub fn SDL_HapticClose(haptic: *mut SDL_Haptic);
pub fn SDL_HapticNumEffects(haptic: *mut SDL_Haptic) -> c_int;
pub fn SDL_HapticNumEffectsPlaying(haptic: *mut SDL_Haptic) -> c_int;
pub fn SDL_HapticQuery(haptic: *mut SDL_Haptic) -> c_uint;
pub fn SDL_HapticNumAxes(haptic: *mut SDL_Haptic) -> c_int;
pub fn SDL_HapticEffectSupported(haptic: *mut SDL_Haptic, effect: *mut SDL_HapticEffect) -> c_int;
pub fn SDL_HapticNewEffect(haptic: *mut SDL_Haptic, effect: *mut SDL_HapticEffect) -> c_int;
pub fn SDL_HapticUpdateEffect(haptic: *mut SDL_Haptic, effect: *mut SDL_HapticEffect) -> c_int;
pub fn SDL_HapticRunEffect(haptic: *mut SDL_Haptic, effect: c_int, iterations: uint32_t) -> c_int;
pub fn SDL_HapticStopEffect(haptic: *mut SDL_Haptic, effect: c_int) -> c_int;
pub fn SDL_HapticDestroyEffect(haptic: *mut SDL_Haptic, effect: c_int);
pub fn SDL_HapticGetEffectStatus(haptic: *mut SDL_Haptic, effect: c_int) -> c_int;
pub fn SDL_HapticSetGain(haptic: *mut SDL_Haptic, gain: c_int) -> c_int;
pub fn SDL_HapticSetAutocenter(haptic: *mut SDL_Haptic, autocenter: c_int) -> c_int;
pub fn SDL_HapticPause(haptic: *mut SDL_Haptic) -> c_int;
pub fn SDL_HapticUnpause(haptic: *mut SDL_Haptic) -> c_int;
pub fn SDL_HapticStopAll(haptic: *mut SDL_Haptic) -> c_int;
pub fn SDL_HapticRumbleSupported(haptic: *mut SDL_Haptic) -> c_int;
pub fn SDL_HapticRumbleInit(haptic: *mut SDL_Haptic) -> c_int;
pub fn SDL_HapticRumblePlay(haptic: *mut SDL_Haptic, strength: c_float, length: uint32_t) -> c_int;
pub fn SDL_HapticRumbleStop(haptic: *mut SDL_Haptic) -> c_int;
}<|fim▁end|> | pub const SDL_HAPTIC_FRICTION: uint16_t = 1 << 10;
pub const SDL_HAPTIC_CUSTOM: uint16_t = 1 << 11;
pub const SDL_HAPTIC_GAIN: uint16_t = 1 << 12;
pub const SDL_HAPTIC_AUTOCENTER: uint16_t = 1 << 13; |