repo_name
stringlengths
6
100
path
stringlengths
4
294
copies
stringlengths
1
5
size
stringlengths
4
6
content
stringlengths
606
896k
license
stringclasses
15 values
lancezlin/ml_template_py
lib/python2.7/site-packages/numpy/lib/scimath.py
221
14085
""" Wrapper functions to more user-friendly calling of certain math functions whose output data-type is different than the input data-type in certain domains of the input. For example, for functions like `log` with branch cuts, the versions in this module provide the mathematically valid answers in the complex plane:: >>> import math >>> from numpy.lib import scimath >>> scimath.log(-math.exp(1)) == (1+1j*math.pi) True Similarly, `sqrt`, other base logarithms, `power` and trig functions are correctly handled. See their respective docstrings for specific examples. """ from __future__ import division, absolute_import, print_function import numpy.core.numeric as nx import numpy.core.numerictypes as nt from numpy.core.numeric import asarray, any from numpy.lib.type_check import isreal __all__ = [ 'sqrt', 'log', 'log2', 'logn', 'log10', 'power', 'arccos', 'arcsin', 'arctanh' ] _ln2 = nx.log(2.0) def _tocomplex(arr): """Convert its input `arr` to a complex array. The input is returned as a complex array of the smallest type that will fit the original data: types like single, byte, short, etc. become csingle, while others become cdouble. A copy of the input is always made. Parameters ---------- arr : array Returns ------- array An array with the same input data as the input but in complex form. Examples -------- First, consider an input of type short: >>> a = np.array([1,2,3],np.short) >>> ac = np.lib.scimath._tocomplex(a); ac array([ 1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) >>> ac.dtype dtype('complex64') If the input is of type double, the output is correspondingly of the complex double type as well: >>> b = np.array([1,2,3],np.double) >>> bc = np.lib.scimath._tocomplex(b); bc array([ 1.+0.j, 2.+0.j, 3.+0.j]) >>> bc.dtype dtype('complex128') Note that even if the input was complex to begin with, a copy is still made, since the astype() method always copies: >>> c = np.array([1,2,3],np.csingle) >>> cc = np.lib.scimath._tocomplex(c); cc array([ 1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) >>> c *= 2; c array([ 2.+0.j, 4.+0.j, 6.+0.j], dtype=complex64) >>> cc array([ 1.+0.j, 2.+0.j, 3.+0.j], dtype=complex64) """ if issubclass(arr.dtype.type, (nt.single, nt.byte, nt.short, nt.ubyte, nt.ushort, nt.csingle)): return arr.astype(nt.csingle) else: return arr.astype(nt.cdouble) def _fix_real_lt_zero(x): """Convert `x` to complex if it has real, negative components. Otherwise, output is just the array version of the input (via asarray). Parameters ---------- x : array_like Returns ------- array Examples -------- >>> np.lib.scimath._fix_real_lt_zero([1,2]) array([1, 2]) >>> np.lib.scimath._fix_real_lt_zero([-1,2]) array([-1.+0.j, 2.+0.j]) """ x = asarray(x) if any(isreal(x) & (x < 0)): x = _tocomplex(x) return x def _fix_int_lt_zero(x): """Convert `x` to double if it has real, negative components. Otherwise, output is just the array version of the input (via asarray). Parameters ---------- x : array_like Returns ------- array Examples -------- >>> np.lib.scimath._fix_int_lt_zero([1,2]) array([1, 2]) >>> np.lib.scimath._fix_int_lt_zero([-1,2]) array([-1., 2.]) """ x = asarray(x) if any(isreal(x) & (x < 0)): x = x * 1.0 return x def _fix_real_abs_gt_1(x): """Convert `x` to complex if it has real components x_i with abs(x_i)>1. Otherwise, output is just the array version of the input (via asarray). Parameters ---------- x : array_like Returns ------- array Examples -------- >>> np.lib.scimath._fix_real_abs_gt_1([0,1]) array([0, 1]) >>> np.lib.scimath._fix_real_abs_gt_1([0,2]) array([ 0.+0.j, 2.+0.j]) """ x = asarray(x) if any(isreal(x) & (abs(x) > 1)): x = _tocomplex(x) return x def sqrt(x): """ Compute the square root of x. For negative input elements, a complex value is returned (unlike `numpy.sqrt` which returns NaN). Parameters ---------- x : array_like The input value(s). Returns ------- out : ndarray or scalar The square root of `x`. If `x` was a scalar, so is `out`, otherwise an array is returned. See Also -------- numpy.sqrt Examples -------- For real, non-negative inputs this works just like `numpy.sqrt`: >>> np.lib.scimath.sqrt(1) 1.0 >>> np.lib.scimath.sqrt([1, 4]) array([ 1., 2.]) But it automatically handles negative inputs: >>> np.lib.scimath.sqrt(-1) (0.0+1.0j) >>> np.lib.scimath.sqrt([-1,4]) array([ 0.+1.j, 2.+0.j]) """ x = _fix_real_lt_zero(x) return nx.sqrt(x) def log(x): """ Compute the natural logarithm of `x`. Return the "principal value" (for a description of this, see `numpy.log`) of :math:`log_e(x)`. For real `x > 0`, this is a real number (``log(0)`` returns ``-inf`` and ``log(np.inf)`` returns ``inf``). Otherwise, the complex principle value is returned. Parameters ---------- x : array_like The value(s) whose log is (are) required. Returns ------- out : ndarray or scalar The log of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array is returned. See Also -------- numpy.log Notes ----- For a log() that returns ``NAN`` when real `x < 0`, use `numpy.log` (note, however, that otherwise `numpy.log` and this `log` are identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`, and, notably, the complex principle value if ``x.imag != 0``). Examples -------- >>> np.emath.log(np.exp(1)) 1.0 Negative arguments are handled "correctly" (recall that ``exp(log(x)) == x`` does *not* hold for real ``x < 0``): >>> np.emath.log(-np.exp(1)) == (1 + np.pi * 1j) True """ x = _fix_real_lt_zero(x) return nx.log(x) def log10(x): """ Compute the logarithm base 10 of `x`. Return the "principal value" (for a description of this, see `numpy.log10`) of :math:`log_{10}(x)`. For real `x > 0`, this is a real number (``log10(0)`` returns ``-inf`` and ``log10(np.inf)`` returns ``inf``). Otherwise, the complex principle value is returned. Parameters ---------- x : array_like or scalar The value(s) whose log base 10 is (are) required. Returns ------- out : ndarray or scalar The log base 10 of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array object is returned. See Also -------- numpy.log10 Notes ----- For a log10() that returns ``NAN`` when real `x < 0`, use `numpy.log10` (note, however, that otherwise `numpy.log10` and this `log10` are identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`, and, notably, the complex principle value if ``x.imag != 0``). Examples -------- (We set the printing precision so the example can be auto-tested) >>> np.set_printoptions(precision=4) >>> np.emath.log10(10**1) 1.0 >>> np.emath.log10([-10**1, -10**2, 10**2]) array([ 1.+1.3644j, 2.+1.3644j, 2.+0.j ]) """ x = _fix_real_lt_zero(x) return nx.log10(x) def logn(n, x): """ Take log base n of x. If `x` contains negative inputs, the answer is computed and returned in the complex domain. Parameters ---------- n : int The base in which the log is taken. x : array_like The value(s) whose log base `n` is (are) required. Returns ------- out : ndarray or scalar The log base `n` of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array is returned. Examples -------- >>> np.set_printoptions(precision=4) >>> np.lib.scimath.logn(2, [4, 8]) array([ 2., 3.]) >>> np.lib.scimath.logn(2, [-4, -8, 8]) array([ 2.+4.5324j, 3.+4.5324j, 3.+0.j ]) """ x = _fix_real_lt_zero(x) n = _fix_real_lt_zero(n) return nx.log(x)/nx.log(n) def log2(x): """ Compute the logarithm base 2 of `x`. Return the "principal value" (for a description of this, see `numpy.log2`) of :math:`log_2(x)`. For real `x > 0`, this is a real number (``log2(0)`` returns ``-inf`` and ``log2(np.inf)`` returns ``inf``). Otherwise, the complex principle value is returned. Parameters ---------- x : array_like The value(s) whose log base 2 is (are) required. Returns ------- out : ndarray or scalar The log base 2 of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array is returned. See Also -------- numpy.log2 Notes ----- For a log2() that returns ``NAN`` when real `x < 0`, use `numpy.log2` (note, however, that otherwise `numpy.log2` and this `log2` are identical, i.e., both return ``-inf`` for `x = 0`, ``inf`` for `x = inf`, and, notably, the complex principle value if ``x.imag != 0``). Examples -------- We set the printing precision so the example can be auto-tested: >>> np.set_printoptions(precision=4) >>> np.emath.log2(8) 3.0 >>> np.emath.log2([-4, -8, 8]) array([ 2.+4.5324j, 3.+4.5324j, 3.+0.j ]) """ x = _fix_real_lt_zero(x) return nx.log2(x) def power(x, p): """ Return x to the power p, (x**p). If `x` contains negative values, the output is converted to the complex domain. Parameters ---------- x : array_like The input value(s). p : array_like of ints The power(s) to which `x` is raised. If `x` contains multiple values, `p` has to either be a scalar, or contain the same number of values as `x`. In the latter case, the result is ``x[0]**p[0], x[1]**p[1], ...``. Returns ------- out : ndarray or scalar The result of ``x**p``. If `x` and `p` are scalars, so is `out`, otherwise an array is returned. See Also -------- numpy.power Examples -------- >>> np.set_printoptions(precision=4) >>> np.lib.scimath.power([2, 4], 2) array([ 4, 16]) >>> np.lib.scimath.power([2, 4], -2) array([ 0.25 , 0.0625]) >>> np.lib.scimath.power([-2, 4], 2) array([ 4.+0.j, 16.+0.j]) """ x = _fix_real_lt_zero(x) p = _fix_int_lt_zero(p) return nx.power(x, p) def arccos(x): """ Compute the inverse cosine of x. Return the "principal value" (for a description of this, see `numpy.arccos`) of the inverse cosine of `x`. For real `x` such that `abs(x) <= 1`, this is a real number in the closed interval :math:`[0, \\pi]`. Otherwise, the complex principle value is returned. Parameters ---------- x : array_like or scalar The value(s) whose arccos is (are) required. Returns ------- out : ndarray or scalar The inverse cosine(s) of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array object is returned. See Also -------- numpy.arccos Notes ----- For an arccos() that returns ``NAN`` when real `x` is not in the interval ``[-1,1]``, use `numpy.arccos`. Examples -------- >>> np.set_printoptions(precision=4) >>> np.emath.arccos(1) # a scalar is returned 0.0 >>> np.emath.arccos([1,2]) array([ 0.-0.j , 0.+1.317j]) """ x = _fix_real_abs_gt_1(x) return nx.arccos(x) def arcsin(x): """ Compute the inverse sine of x. Return the "principal value" (for a description of this, see `numpy.arcsin`) of the inverse sine of `x`. For real `x` such that `abs(x) <= 1`, this is a real number in the closed interval :math:`[-\\pi/2, \\pi/2]`. Otherwise, the complex principle value is returned. Parameters ---------- x : array_like or scalar The value(s) whose arcsin is (are) required. Returns ------- out : ndarray or scalar The inverse sine(s) of the `x` value(s). If `x` was a scalar, so is `out`, otherwise an array object is returned. See Also -------- numpy.arcsin Notes ----- For an arcsin() that returns ``NAN`` when real `x` is not in the interval ``[-1,1]``, use `numpy.arcsin`. Examples -------- >>> np.set_printoptions(precision=4) >>> np.emath.arcsin(0) 0.0 >>> np.emath.arcsin([0,1]) array([ 0. , 1.5708]) """ x = _fix_real_abs_gt_1(x) return nx.arcsin(x) def arctanh(x): """ Compute the inverse hyperbolic tangent of `x`. Return the "principal value" (for a description of this, see `numpy.arctanh`) of `arctanh(x)`. For real `x` such that `abs(x) < 1`, this is a real number. If `abs(x) > 1`, or if `x` is complex, the result is complex. Finally, `x = 1` returns``inf`` and `x=-1` returns ``-inf``. Parameters ---------- x : array_like The value(s) whose arctanh is (are) required. Returns ------- out : ndarray or scalar The inverse hyperbolic tangent(s) of the `x` value(s). If `x` was a scalar so is `out`, otherwise an array is returned. See Also -------- numpy.arctanh Notes ----- For an arctanh() that returns ``NAN`` when real `x` is not in the interval ``(-1,1)``, use `numpy.arctanh` (this latter, however, does return +/-inf for `x = +/-1`). Examples -------- >>> np.set_printoptions(precision=4) >>> np.emath.arctanh(np.matrix(np.eye(2))) array([[ Inf, 0.], [ 0., Inf]]) >>> np.emath.arctanh([1j]) array([ 0.+0.7854j]) """ x = _fix_real_abs_gt_1(x) return nx.arctanh(x)
mit
okfn/opd-brand-manager
manager/apps/brand/notifications.py
2
1306
from django.core.mail import send_mail from django.core.urlresolvers import reverse class EmailNotification: msg_from = 'OKFN team <noreply@okfn.org>' def __init__(self, msg_to, msg_from=None): self.msg_to = msg_to if msg_from: self.msg_from = msg_from def send_mail(self, subject, message): send_mail(subject, message, self.msg_from, [self.msg_to], fail_silently=True) def create_notification(self, brand_nm, bsin): brand_url = reverse('brand', args=(bsin,)) subject = "%s added to the OKFN brand repository" % brand_nm message = """Dear contributor, Your brand %s was added to the OKFN brand respository under BSIN %s. More details at http://product.okfn.org%s . Thank you for your contribution. Regards, OKFN brand manager team""" % (brand_nm, bsin, brand_url) self.send_mail(subject, message) def delete_notification(self, brand_nm, comment): subject = "%s rejected from OKFN brand repository" % brand_nm message = """Dear contributor, Your brand proposal for %s was rejected from the OKFN brand respository. Moderator comment : %s Thank you for your contribution. Regards, OKFN brand manager team""" % (brand_nm, comment) self.send_mail(subject, message)
mit
0jpq0/kbengine
kbe/src/lib/python/Lib/lib2to3/tests/test_fixers.py
89
123507
""" Test suite for the fixer modules """ # Python imports import os import unittest from itertools import chain from operator import itemgetter # Local imports from lib2to3 import pygram, pytree, refactor, fixer_util from lib2to3.tests import support class FixerTestCase(support.TestCase): # Other test cases can subclass this class and replace "fixer_pkg" with # their own. def setUp(self, fix_list=None, fixer_pkg="lib2to3", options=None): if fix_list is None: fix_list = [self.fixer] self.refactor = support.get_refactorer(fixer_pkg, fix_list, options) self.fixer_log = [] self.filename = "<string>" for fixer in chain(self.refactor.pre_order, self.refactor.post_order): fixer.log = self.fixer_log def _check(self, before, after): before = support.reformat(before) after = support.reformat(after) tree = self.refactor.refactor_string(before, self.filename) self.assertEqual(after, str(tree)) return tree def check(self, before, after, ignore_warnings=False): tree = self._check(before, after) self.assertTrue(tree.was_changed) if not ignore_warnings: self.assertEqual(self.fixer_log, []) def warns(self, before, after, message, unchanged=False): tree = self._check(before, after) self.assertIn(message, "".join(self.fixer_log)) if not unchanged: self.assertTrue(tree.was_changed) def warns_unchanged(self, before, message): self.warns(before, before, message, unchanged=True) def unchanged(self, before, ignore_warnings=False): self._check(before, before) if not ignore_warnings: self.assertEqual(self.fixer_log, []) def assert_runs_after(self, *names): fixes = [self.fixer] fixes.extend(names) r = support.get_refactorer("lib2to3", fixes) (pre, post) = r.get_fixers() n = "fix_" + self.fixer if post and post[-1].__class__.__module__.endswith(n): # We're the last fixer to run return if pre and pre[-1].__class__.__module__.endswith(n) and not post: # We're the last in pre and post is empty return self.fail("Fixer run order (%s) is incorrect; %s should be last."\ %(", ".join([x.__class__.__module__ for x in (pre+post)]), n)) class Test_ne(FixerTestCase): fixer = "ne" def test_basic(self): b = """if x <> y: pass""" a = """if x != y: pass""" self.check(b, a) def test_no_spaces(self): b = """if x<>y: pass""" a = """if x!=y: pass""" self.check(b, a) def test_chained(self): b = """if x<>y<>z: pass""" a = """if x!=y!=z: pass""" self.check(b, a) class Test_has_key(FixerTestCase): fixer = "has_key" def test_1(self): b = """x = d.has_key("x") or d.has_key("y")""" a = """x = "x" in d or "y" in d""" self.check(b, a) def test_2(self): b = """x = a.b.c.d.has_key("x") ** 3""" a = """x = ("x" in a.b.c.d) ** 3""" self.check(b, a) def test_3(self): b = """x = a.b.has_key(1 + 2).__repr__()""" a = """x = (1 + 2 in a.b).__repr__()""" self.check(b, a) def test_4(self): b = """x = a.b.has_key(1 + 2).__repr__() ** -3 ** 4""" a = """x = (1 + 2 in a.b).__repr__() ** -3 ** 4""" self.check(b, a) def test_5(self): b = """x = a.has_key(f or g)""" a = """x = (f or g) in a""" self.check(b, a) def test_6(self): b = """x = a + b.has_key(c)""" a = """x = a + (c in b)""" self.check(b, a) def test_7(self): b = """x = a.has_key(lambda: 12)""" a = """x = (lambda: 12) in a""" self.check(b, a) def test_8(self): b = """x = a.has_key(a for a in b)""" a = """x = (a for a in b) in a""" self.check(b, a) def test_9(self): b = """if not a.has_key(b): pass""" a = """if b not in a: pass""" self.check(b, a) def test_10(self): b = """if not a.has_key(b).__repr__(): pass""" a = """if not (b in a).__repr__(): pass""" self.check(b, a) def test_11(self): b = """if not a.has_key(b) ** 2: pass""" a = """if not (b in a) ** 2: pass""" self.check(b, a) class Test_apply(FixerTestCase): fixer = "apply" def test_1(self): b = """x = apply(f, g + h)""" a = """x = f(*g + h)""" self.check(b, a) def test_2(self): b = """y = apply(f, g, h)""" a = """y = f(*g, **h)""" self.check(b, a) def test_3(self): b = """z = apply(fs[0], g or h, h or g)""" a = """z = fs[0](*g or h, **h or g)""" self.check(b, a) def test_4(self): b = """apply(f, (x, y) + t)""" a = """f(*(x, y) + t)""" self.check(b, a) def test_5(self): b = """apply(f, args,)""" a = """f(*args)""" self.check(b, a) def test_6(self): b = """apply(f, args, kwds,)""" a = """f(*args, **kwds)""" self.check(b, a) # Test that complex functions are parenthesized def test_complex_1(self): b = """x = apply(f+g, args)""" a = """x = (f+g)(*args)""" self.check(b, a) def test_complex_2(self): b = """x = apply(f*g, args)""" a = """x = (f*g)(*args)""" self.check(b, a) def test_complex_3(self): b = """x = apply(f**g, args)""" a = """x = (f**g)(*args)""" self.check(b, a) # But dotted names etc. not def test_dotted_name(self): b = """x = apply(f.g, args)""" a = """x = f.g(*args)""" self.check(b, a) def test_subscript(self): b = """x = apply(f[x], args)""" a = """x = f[x](*args)""" self.check(b, a) def test_call(self): b = """x = apply(f(), args)""" a = """x = f()(*args)""" self.check(b, a) # Extreme case def test_extreme(self): b = """x = apply(a.b.c.d.e.f, args, kwds)""" a = """x = a.b.c.d.e.f(*args, **kwds)""" self.check(b, a) # XXX Comments in weird places still get lost def test_weird_comments(self): b = """apply( # foo f, # bar args)""" a = """f(*args)""" self.check(b, a) # These should *not* be touched def test_unchanged_1(self): s = """apply()""" self.unchanged(s) def test_unchanged_2(self): s = """apply(f)""" self.unchanged(s) def test_unchanged_3(self): s = """apply(f,)""" self.unchanged(s) def test_unchanged_4(self): s = """apply(f, args, kwds, extras)""" self.unchanged(s) def test_unchanged_5(self): s = """apply(f, *args, **kwds)""" self.unchanged(s) def test_unchanged_6(self): s = """apply(f, *args)""" self.unchanged(s) def test_unchanged_7(self): s = """apply(func=f, args=args, kwds=kwds)""" self.unchanged(s) def test_unchanged_8(self): s = """apply(f, args=args, kwds=kwds)""" self.unchanged(s) def test_unchanged_9(self): s = """apply(f, args, kwds=kwds)""" self.unchanged(s) def test_space_1(self): a = """apply( f, args, kwds)""" b = """f(*args, **kwds)""" self.check(a, b) def test_space_2(self): a = """apply( f ,args,kwds )""" b = """f(*args, **kwds)""" self.check(a, b) class Test_reload(FixerTestCase): fixer = "reload" def test(self): b = """reload(a)""" a = """import imp\nimp.reload(a)""" self.check(b, a) def test_comment(self): b = """reload( a ) # comment""" a = """import imp\nimp.reload( a ) # comment""" self.check(b, a) # PEP 8 comments b = """reload( a ) # comment""" a = """import imp\nimp.reload( a ) # comment""" self.check(b, a) def test_space(self): b = """reload( a )""" a = """import imp\nimp.reload( a )""" self.check(b, a) b = """reload( a)""" a = """import imp\nimp.reload( a)""" self.check(b, a) b = """reload(a )""" a = """import imp\nimp.reload(a )""" self.check(b, a) def test_unchanged(self): s = """reload(a=1)""" self.unchanged(s) s = """reload(f, g)""" self.unchanged(s) s = """reload(f, *h)""" self.unchanged(s) s = """reload(f, *h, **i)""" self.unchanged(s) s = """reload(f, **i)""" self.unchanged(s) s = """reload(*h, **i)""" self.unchanged(s) s = """reload(*h)""" self.unchanged(s) s = """reload(**i)""" self.unchanged(s) s = """reload()""" self.unchanged(s) class Test_intern(FixerTestCase): fixer = "intern" def test_prefix_preservation(self): b = """x = intern( a )""" a = """import sys\nx = sys.intern( a )""" self.check(b, a) b = """y = intern("b" # test )""" a = """import sys\ny = sys.intern("b" # test )""" self.check(b, a) b = """z = intern(a+b+c.d, )""" a = """import sys\nz = sys.intern(a+b+c.d, )""" self.check(b, a) def test(self): b = """x = intern(a)""" a = """import sys\nx = sys.intern(a)""" self.check(b, a) b = """z = intern(a+b+c.d,)""" a = """import sys\nz = sys.intern(a+b+c.d,)""" self.check(b, a) b = """intern("y%s" % 5).replace("y", "")""" a = """import sys\nsys.intern("y%s" % 5).replace("y", "")""" self.check(b, a) # These should not be refactored def test_unchanged(self): s = """intern(a=1)""" self.unchanged(s) s = """intern(f, g)""" self.unchanged(s) s = """intern(*h)""" self.unchanged(s) s = """intern(**i)""" self.unchanged(s) s = """intern()""" self.unchanged(s) class Test_reduce(FixerTestCase): fixer = "reduce" def test_simple_call(self): b = "reduce(a, b, c)" a = "from functools import reduce\nreduce(a, b, c)" self.check(b, a) def test_bug_7253(self): # fix_tuple_params was being bad and orphaning nodes in the tree. b = "def x(arg): reduce(sum, [])" a = "from functools import reduce\ndef x(arg): reduce(sum, [])" self.check(b, a) def test_call_with_lambda(self): b = "reduce(lambda x, y: x + y, seq)" a = "from functools import reduce\nreduce(lambda x, y: x + y, seq)" self.check(b, a) def test_unchanged(self): s = "reduce(a)" self.unchanged(s) s = "reduce(a, b=42)" self.unchanged(s) s = "reduce(a, b, c, d)" self.unchanged(s) s = "reduce(**c)" self.unchanged(s) s = "reduce()" self.unchanged(s) class Test_print(FixerTestCase): fixer = "print" def test_prefix_preservation(self): b = """print 1, 1+1, 1+1+1""" a = """print(1, 1+1, 1+1+1)""" self.check(b, a) def test_idempotency(self): s = """print()""" self.unchanged(s) s = """print('')""" self.unchanged(s) def test_idempotency_print_as_function(self): self.refactor.driver.grammar = pygram.python_grammar_no_print_statement s = """print(1, 1+1, 1+1+1)""" self.unchanged(s) s = """print()""" self.unchanged(s) s = """print('')""" self.unchanged(s) def test_1(self): b = """print 1, 1+1, 1+1+1""" a = """print(1, 1+1, 1+1+1)""" self.check(b, a) def test_2(self): b = """print 1, 2""" a = """print(1, 2)""" self.check(b, a) def test_3(self): b = """print""" a = """print()""" self.check(b, a) def test_4(self): # from bug 3000 b = """print whatever; print""" a = """print(whatever); print()""" self.check(b, a) def test_5(self): b = """print; print whatever;""" a = """print(); print(whatever);""" self.check(b, a) def test_tuple(self): b = """print (a, b, c)""" a = """print((a, b, c))""" self.check(b, a) # trailing commas def test_trailing_comma_1(self): b = """print 1, 2, 3,""" a = """print(1, 2, 3, end=' ')""" self.check(b, a) def test_trailing_comma_2(self): b = """print 1, 2,""" a = """print(1, 2, end=' ')""" self.check(b, a) def test_trailing_comma_3(self): b = """print 1,""" a = """print(1, end=' ')""" self.check(b, a) # >> stuff def test_vargs_without_trailing_comma(self): b = """print >>sys.stderr, 1, 2, 3""" a = """print(1, 2, 3, file=sys.stderr)""" self.check(b, a) def test_with_trailing_comma(self): b = """print >>sys.stderr, 1, 2,""" a = """print(1, 2, end=' ', file=sys.stderr)""" self.check(b, a) def test_no_trailing_comma(self): b = """print >>sys.stderr, 1+1""" a = """print(1+1, file=sys.stderr)""" self.check(b, a) def test_spaces_before_file(self): b = """print >> sys.stderr""" a = """print(file=sys.stderr)""" self.check(b, a) def test_with_future_print_function(self): s = "from __future__ import print_function\n" \ "print('Hai!', end=' ')" self.unchanged(s) b = "print 'Hello, world!'" a = "print('Hello, world!')" self.check(b, a) class Test_exec(FixerTestCase): fixer = "exec" def test_prefix_preservation(self): b = """ exec code in ns1, ns2""" a = """ exec(code, ns1, ns2)""" self.check(b, a) def test_basic(self): b = """exec code""" a = """exec(code)""" self.check(b, a) def test_with_globals(self): b = """exec code in ns""" a = """exec(code, ns)""" self.check(b, a) def test_with_globals_locals(self): b = """exec code in ns1, ns2""" a = """exec(code, ns1, ns2)""" self.check(b, a) def test_complex_1(self): b = """exec (a.b()) in ns""" a = """exec((a.b()), ns)""" self.check(b, a) def test_complex_2(self): b = """exec a.b() + c in ns""" a = """exec(a.b() + c, ns)""" self.check(b, a) # These should not be touched def test_unchanged_1(self): s = """exec(code)""" self.unchanged(s) def test_unchanged_2(self): s = """exec (code)""" self.unchanged(s) def test_unchanged_3(self): s = """exec(code, ns)""" self.unchanged(s) def test_unchanged_4(self): s = """exec(code, ns1, ns2)""" self.unchanged(s) class Test_repr(FixerTestCase): fixer = "repr" def test_prefix_preservation(self): b = """x = `1 + 2`""" a = """x = repr(1 + 2)""" self.check(b, a) def test_simple_1(self): b = """x = `1 + 2`""" a = """x = repr(1 + 2)""" self.check(b, a) def test_simple_2(self): b = """y = `x`""" a = """y = repr(x)""" self.check(b, a) def test_complex(self): b = """z = `y`.__repr__()""" a = """z = repr(y).__repr__()""" self.check(b, a) def test_tuple(self): b = """x = `1, 2, 3`""" a = """x = repr((1, 2, 3))""" self.check(b, a) def test_nested(self): b = """x = `1 + `2``""" a = """x = repr(1 + repr(2))""" self.check(b, a) def test_nested_tuples(self): b = """x = `1, 2 + `3, 4``""" a = """x = repr((1, 2 + repr((3, 4))))""" self.check(b, a) class Test_except(FixerTestCase): fixer = "except" def test_prefix_preservation(self): b = """ try: pass except (RuntimeError, ImportError), e: pass""" a = """ try: pass except (RuntimeError, ImportError) as e: pass""" self.check(b, a) def test_simple(self): b = """ try: pass except Foo, e: pass""" a = """ try: pass except Foo as e: pass""" self.check(b, a) def test_simple_no_space_before_target(self): b = """ try: pass except Foo,e: pass""" a = """ try: pass except Foo as e: pass""" self.check(b, a) def test_tuple_unpack(self): b = """ def foo(): try: pass except Exception, (f, e): pass except ImportError, e: pass""" a = """ def foo(): try: pass except Exception as xxx_todo_changeme: (f, e) = xxx_todo_changeme.args pass except ImportError as e: pass""" self.check(b, a) def test_multi_class(self): b = """ try: pass except (RuntimeError, ImportError), e: pass""" a = """ try: pass except (RuntimeError, ImportError) as e: pass""" self.check(b, a) def test_list_unpack(self): b = """ try: pass except Exception, [a, b]: pass""" a = """ try: pass except Exception as xxx_todo_changeme: [a, b] = xxx_todo_changeme.args pass""" self.check(b, a) def test_weird_target_1(self): b = """ try: pass except Exception, d[5]: pass""" a = """ try: pass except Exception as xxx_todo_changeme: d[5] = xxx_todo_changeme pass""" self.check(b, a) def test_weird_target_2(self): b = """ try: pass except Exception, a.foo: pass""" a = """ try: pass except Exception as xxx_todo_changeme: a.foo = xxx_todo_changeme pass""" self.check(b, a) def test_weird_target_3(self): b = """ try: pass except Exception, a().foo: pass""" a = """ try: pass except Exception as xxx_todo_changeme: a().foo = xxx_todo_changeme pass""" self.check(b, a) def test_bare_except(self): b = """ try: pass except Exception, a: pass except: pass""" a = """ try: pass except Exception as a: pass except: pass""" self.check(b, a) def test_bare_except_and_else_finally(self): b = """ try: pass except Exception, a: pass except: pass else: pass finally: pass""" a = """ try: pass except Exception as a: pass except: pass else: pass finally: pass""" self.check(b, a) def test_multi_fixed_excepts_before_bare_except(self): b = """ try: pass except TypeError, b: pass except Exception, a: pass except: pass""" a = """ try: pass except TypeError as b: pass except Exception as a: pass except: pass""" self.check(b, a) def test_one_line_suites(self): b = """ try: raise TypeError except TypeError, e: pass """ a = """ try: raise TypeError except TypeError as e: pass """ self.check(b, a) b = """ try: raise TypeError except TypeError, e: pass """ a = """ try: raise TypeError except TypeError as e: pass """ self.check(b, a) b = """ try: raise TypeError except TypeError, e: pass """ a = """ try: raise TypeError except TypeError as e: pass """ self.check(b, a) b = """ try: raise TypeError except TypeError, e: pass else: function() finally: done() """ a = """ try: raise TypeError except TypeError as e: pass else: function() finally: done() """ self.check(b, a) # These should not be touched: def test_unchanged_1(self): s = """ try: pass except: pass""" self.unchanged(s) def test_unchanged_2(self): s = """ try: pass except Exception: pass""" self.unchanged(s) def test_unchanged_3(self): s = """ try: pass except (Exception, SystemExit): pass""" self.unchanged(s) class Test_raise(FixerTestCase): fixer = "raise" def test_basic(self): b = """raise Exception, 5""" a = """raise Exception(5)""" self.check(b, a) def test_prefix_preservation(self): b = """raise Exception,5""" a = """raise Exception(5)""" self.check(b, a) b = """raise Exception, 5""" a = """raise Exception(5)""" self.check(b, a) def test_with_comments(self): b = """raise Exception, 5 # foo""" a = """raise Exception(5) # foo""" self.check(b, a) b = """raise E, (5, 6) % (a, b) # foo""" a = """raise E((5, 6) % (a, b)) # foo""" self.check(b, a) b = """def foo(): raise Exception, 5, 6 # foo""" a = """def foo(): raise Exception(5).with_traceback(6) # foo""" self.check(b, a) def test_None_value(self): b = """raise Exception(5), None, tb""" a = """raise Exception(5).with_traceback(tb)""" self.check(b, a) def test_tuple_value(self): b = """raise Exception, (5, 6, 7)""" a = """raise Exception(5, 6, 7)""" self.check(b, a) def test_tuple_detection(self): b = """raise E, (5, 6) % (a, b)""" a = """raise E((5, 6) % (a, b))""" self.check(b, a) def test_tuple_exc_1(self): b = """raise (((E1, E2), E3), E4), V""" a = """raise E1(V)""" self.check(b, a) def test_tuple_exc_2(self): b = """raise (E1, (E2, E3), E4), V""" a = """raise E1(V)""" self.check(b, a) # These should produce a warning def test_string_exc(self): s = """raise 'foo'""" self.warns_unchanged(s, "Python 3 does not support string exceptions") def test_string_exc_val(self): s = """raise "foo", 5""" self.warns_unchanged(s, "Python 3 does not support string exceptions") def test_string_exc_val_tb(self): s = """raise "foo", 5, 6""" self.warns_unchanged(s, "Python 3 does not support string exceptions") # These should result in traceback-assignment def test_tb_1(self): b = """def foo(): raise Exception, 5, 6""" a = """def foo(): raise Exception(5).with_traceback(6)""" self.check(b, a) def test_tb_2(self): b = """def foo(): a = 5 raise Exception, 5, 6 b = 6""" a = """def foo(): a = 5 raise Exception(5).with_traceback(6) b = 6""" self.check(b, a) def test_tb_3(self): b = """def foo(): raise Exception,5,6""" a = """def foo(): raise Exception(5).with_traceback(6)""" self.check(b, a) def test_tb_4(self): b = """def foo(): a = 5 raise Exception,5,6 b = 6""" a = """def foo(): a = 5 raise Exception(5).with_traceback(6) b = 6""" self.check(b, a) def test_tb_5(self): b = """def foo(): raise Exception, (5, 6, 7), 6""" a = """def foo(): raise Exception(5, 6, 7).with_traceback(6)""" self.check(b, a) def test_tb_6(self): b = """def foo(): a = 5 raise Exception, (5, 6, 7), 6 b = 6""" a = """def foo(): a = 5 raise Exception(5, 6, 7).with_traceback(6) b = 6""" self.check(b, a) class Test_throw(FixerTestCase): fixer = "throw" def test_1(self): b = """g.throw(Exception, 5)""" a = """g.throw(Exception(5))""" self.check(b, a) def test_2(self): b = """g.throw(Exception,5)""" a = """g.throw(Exception(5))""" self.check(b, a) def test_3(self): b = """g.throw(Exception, (5, 6, 7))""" a = """g.throw(Exception(5, 6, 7))""" self.check(b, a) def test_4(self): b = """5 + g.throw(Exception, 5)""" a = """5 + g.throw(Exception(5))""" self.check(b, a) # These should produce warnings def test_warn_1(self): s = """g.throw("foo")""" self.warns_unchanged(s, "Python 3 does not support string exceptions") def test_warn_2(self): s = """g.throw("foo", 5)""" self.warns_unchanged(s, "Python 3 does not support string exceptions") def test_warn_3(self): s = """g.throw("foo", 5, 6)""" self.warns_unchanged(s, "Python 3 does not support string exceptions") # These should not be touched def test_untouched_1(self): s = """g.throw(Exception)""" self.unchanged(s) def test_untouched_2(self): s = """g.throw(Exception(5, 6))""" self.unchanged(s) def test_untouched_3(self): s = """5 + g.throw(Exception(5, 6))""" self.unchanged(s) # These should result in traceback-assignment def test_tb_1(self): b = """def foo(): g.throw(Exception, 5, 6)""" a = """def foo(): g.throw(Exception(5).with_traceback(6))""" self.check(b, a) def test_tb_2(self): b = """def foo(): a = 5 g.throw(Exception, 5, 6) b = 6""" a = """def foo(): a = 5 g.throw(Exception(5).with_traceback(6)) b = 6""" self.check(b, a) def test_tb_3(self): b = """def foo(): g.throw(Exception,5,6)""" a = """def foo(): g.throw(Exception(5).with_traceback(6))""" self.check(b, a) def test_tb_4(self): b = """def foo(): a = 5 g.throw(Exception,5,6) b = 6""" a = """def foo(): a = 5 g.throw(Exception(5).with_traceback(6)) b = 6""" self.check(b, a) def test_tb_5(self): b = """def foo(): g.throw(Exception, (5, 6, 7), 6)""" a = """def foo(): g.throw(Exception(5, 6, 7).with_traceback(6))""" self.check(b, a) def test_tb_6(self): b = """def foo(): a = 5 g.throw(Exception, (5, 6, 7), 6) b = 6""" a = """def foo(): a = 5 g.throw(Exception(5, 6, 7).with_traceback(6)) b = 6""" self.check(b, a) def test_tb_7(self): b = """def foo(): a + g.throw(Exception, 5, 6)""" a = """def foo(): a + g.throw(Exception(5).with_traceback(6))""" self.check(b, a) def test_tb_8(self): b = """def foo(): a = 5 a + g.throw(Exception, 5, 6) b = 6""" a = """def foo(): a = 5 a + g.throw(Exception(5).with_traceback(6)) b = 6""" self.check(b, a) class Test_long(FixerTestCase): fixer = "long" def test_1(self): b = """x = long(x)""" a = """x = int(x)""" self.check(b, a) def test_2(self): b = """y = isinstance(x, long)""" a = """y = isinstance(x, int)""" self.check(b, a) def test_3(self): b = """z = type(x) in (int, long)""" a = """z = type(x) in (int, int)""" self.check(b, a) def test_unchanged(self): s = """long = True""" self.unchanged(s) s = """s.long = True""" self.unchanged(s) s = """def long(): pass""" self.unchanged(s) s = """class long(): pass""" self.unchanged(s) s = """def f(long): pass""" self.unchanged(s) s = """def f(g, long): pass""" self.unchanged(s) s = """def f(x, long=True): pass""" self.unchanged(s) def test_prefix_preservation(self): b = """x = long( x )""" a = """x = int( x )""" self.check(b, a) class Test_execfile(FixerTestCase): fixer = "execfile" def test_conversion(self): b = """execfile("fn")""" a = """exec(compile(open("fn").read(), "fn", 'exec'))""" self.check(b, a) b = """execfile("fn", glob)""" a = """exec(compile(open("fn").read(), "fn", 'exec'), glob)""" self.check(b, a) b = """execfile("fn", glob, loc)""" a = """exec(compile(open("fn").read(), "fn", 'exec'), glob, loc)""" self.check(b, a) b = """execfile("fn", globals=glob)""" a = """exec(compile(open("fn").read(), "fn", 'exec'), globals=glob)""" self.check(b, a) b = """execfile("fn", locals=loc)""" a = """exec(compile(open("fn").read(), "fn", 'exec'), locals=loc)""" self.check(b, a) b = """execfile("fn", globals=glob, locals=loc)""" a = """exec(compile(open("fn").read(), "fn", 'exec'), globals=glob, locals=loc)""" self.check(b, a) def test_spacing(self): b = """execfile( "fn" )""" a = """exec(compile(open( "fn" ).read(), "fn", 'exec'))""" self.check(b, a) b = """execfile("fn", globals = glob)""" a = """exec(compile(open("fn").read(), "fn", 'exec'), globals = glob)""" self.check(b, a) class Test_isinstance(FixerTestCase): fixer = "isinstance" def test_remove_multiple_items(self): b = """isinstance(x, (int, int, int))""" a = """isinstance(x, int)""" self.check(b, a) b = """isinstance(x, (int, float, int, int, float))""" a = """isinstance(x, (int, float))""" self.check(b, a) b = """isinstance(x, (int, float, int, int, float, str))""" a = """isinstance(x, (int, float, str))""" self.check(b, a) b = """isinstance(foo() + bar(), (x(), y(), x(), int, int))""" a = """isinstance(foo() + bar(), (x(), y(), x(), int))""" self.check(b, a) def test_prefix_preservation(self): b = """if isinstance( foo(), ( bar, bar, baz )) : pass""" a = """if isinstance( foo(), ( bar, baz )) : pass""" self.check(b, a) def test_unchanged(self): self.unchanged("isinstance(x, (str, int))") class Test_dict(FixerTestCase): fixer = "dict" def test_prefix_preservation(self): b = "if d. keys ( ) : pass" a = "if list(d. keys ( )) : pass" self.check(b, a) b = "if d. items ( ) : pass" a = "if list(d. items ( )) : pass" self.check(b, a) b = "if d. iterkeys ( ) : pass" a = "if iter(d. keys ( )) : pass" self.check(b, a) b = "[i for i in d. iterkeys( ) ]" a = "[i for i in d. keys( ) ]" self.check(b, a) b = "if d. viewkeys ( ) : pass" a = "if d. keys ( ) : pass" self.check(b, a) b = "[i for i in d. viewkeys( ) ]" a = "[i for i in d. keys( ) ]" self.check(b, a) def test_trailing_comment(self): b = "d.keys() # foo" a = "list(d.keys()) # foo" self.check(b, a) b = "d.items() # foo" a = "list(d.items()) # foo" self.check(b, a) b = "d.iterkeys() # foo" a = "iter(d.keys()) # foo" self.check(b, a) b = """[i for i in d.iterkeys() # foo ]""" a = """[i for i in d.keys() # foo ]""" self.check(b, a) b = """[i for i in d.iterkeys() # foo ]""" a = """[i for i in d.keys() # foo ]""" self.check(b, a) b = "d.viewitems() # foo" a = "d.items() # foo" self.check(b, a) def test_unchanged(self): for wrapper in fixer_util.consuming_calls: s = "s = %s(d.keys())" % wrapper self.unchanged(s) s = "s = %s(d.values())" % wrapper self.unchanged(s) s = "s = %s(d.items())" % wrapper self.unchanged(s) def test_01(self): b = "d.keys()" a = "list(d.keys())" self.check(b, a) b = "a[0].foo().keys()" a = "list(a[0].foo().keys())" self.check(b, a) def test_02(self): b = "d.items()" a = "list(d.items())" self.check(b, a) def test_03(self): b = "d.values()" a = "list(d.values())" self.check(b, a) def test_04(self): b = "d.iterkeys()" a = "iter(d.keys())" self.check(b, a) def test_05(self): b = "d.iteritems()" a = "iter(d.items())" self.check(b, a) def test_06(self): b = "d.itervalues()" a = "iter(d.values())" self.check(b, a) def test_07(self): s = "list(d.keys())" self.unchanged(s) def test_08(self): s = "sorted(d.keys())" self.unchanged(s) def test_09(self): b = "iter(d.keys())" a = "iter(list(d.keys()))" self.check(b, a) def test_10(self): b = "foo(d.keys())" a = "foo(list(d.keys()))" self.check(b, a) def test_11(self): b = "for i in d.keys(): print i" a = "for i in list(d.keys()): print i" self.check(b, a) def test_12(self): b = "for i in d.iterkeys(): print i" a = "for i in d.keys(): print i" self.check(b, a) def test_13(self): b = "[i for i in d.keys()]" a = "[i for i in list(d.keys())]" self.check(b, a) def test_14(self): b = "[i for i in d.iterkeys()]" a = "[i for i in d.keys()]" self.check(b, a) def test_15(self): b = "(i for i in d.keys())" a = "(i for i in list(d.keys()))" self.check(b, a) def test_16(self): b = "(i for i in d.iterkeys())" a = "(i for i in d.keys())" self.check(b, a) def test_17(self): b = "iter(d.iterkeys())" a = "iter(d.keys())" self.check(b, a) def test_18(self): b = "list(d.iterkeys())" a = "list(d.keys())" self.check(b, a) def test_19(self): b = "sorted(d.iterkeys())" a = "sorted(d.keys())" self.check(b, a) def test_20(self): b = "foo(d.iterkeys())" a = "foo(iter(d.keys()))" self.check(b, a) def test_21(self): b = "print h.iterkeys().next()" a = "print iter(h.keys()).next()" self.check(b, a) def test_22(self): b = "print h.keys()[0]" a = "print list(h.keys())[0]" self.check(b, a) def test_23(self): b = "print list(h.iterkeys().next())" a = "print list(iter(h.keys()).next())" self.check(b, a) def test_24(self): b = "for x in h.keys()[0]: print x" a = "for x in list(h.keys())[0]: print x" self.check(b, a) def test_25(self): b = "d.viewkeys()" a = "d.keys()" self.check(b, a) def test_26(self): b = "d.viewitems()" a = "d.items()" self.check(b, a) def test_27(self): b = "d.viewvalues()" a = "d.values()" self.check(b, a) def test_28(self): b = "[i for i in d.viewkeys()]" a = "[i for i in d.keys()]" self.check(b, a) def test_29(self): b = "(i for i in d.viewkeys())" a = "(i for i in d.keys())" self.check(b, a) def test_30(self): b = "iter(d.viewkeys())" a = "iter(d.keys())" self.check(b, a) def test_31(self): b = "list(d.viewkeys())" a = "list(d.keys())" self.check(b, a) def test_32(self): b = "sorted(d.viewkeys())" a = "sorted(d.keys())" self.check(b, a) class Test_xrange(FixerTestCase): fixer = "xrange" def test_prefix_preservation(self): b = """x = xrange( 10 )""" a = """x = range( 10 )""" self.check(b, a) b = """x = xrange( 1 , 10 )""" a = """x = range( 1 , 10 )""" self.check(b, a) b = """x = xrange( 0 , 10 , 2 )""" a = """x = range( 0 , 10 , 2 )""" self.check(b, a) def test_single_arg(self): b = """x = xrange(10)""" a = """x = range(10)""" self.check(b, a) def test_two_args(self): b = """x = xrange(1, 10)""" a = """x = range(1, 10)""" self.check(b, a) def test_three_args(self): b = """x = xrange(0, 10, 2)""" a = """x = range(0, 10, 2)""" self.check(b, a) def test_wrap_in_list(self): b = """x = range(10, 3, 9)""" a = """x = list(range(10, 3, 9))""" self.check(b, a) b = """x = foo(range(10, 3, 9))""" a = """x = foo(list(range(10, 3, 9)))""" self.check(b, a) b = """x = range(10, 3, 9) + [4]""" a = """x = list(range(10, 3, 9)) + [4]""" self.check(b, a) b = """x = range(10)[::-1]""" a = """x = list(range(10))[::-1]""" self.check(b, a) b = """x = range(10) [3]""" a = """x = list(range(10)) [3]""" self.check(b, a) def test_xrange_in_for(self): b = """for i in xrange(10):\n j=i""" a = """for i in range(10):\n j=i""" self.check(b, a) b = """[i for i in xrange(10)]""" a = """[i for i in range(10)]""" self.check(b, a) def test_range_in_for(self): self.unchanged("for i in range(10): pass") self.unchanged("[i for i in range(10)]") def test_in_contains_test(self): self.unchanged("x in range(10, 3, 9)") def test_in_consuming_context(self): for call in fixer_util.consuming_calls: self.unchanged("a = %s(range(10))" % call) class Test_xrange_with_reduce(FixerTestCase): def setUp(self): super(Test_xrange_with_reduce, self).setUp(["xrange", "reduce"]) def test_double_transform(self): b = """reduce(x, xrange(5))""" a = """from functools import reduce reduce(x, range(5))""" self.check(b, a) class Test_raw_input(FixerTestCase): fixer = "raw_input" def test_prefix_preservation(self): b = """x = raw_input( )""" a = """x = input( )""" self.check(b, a) b = """x = raw_input( '' )""" a = """x = input( '' )""" self.check(b, a) def test_1(self): b = """x = raw_input()""" a = """x = input()""" self.check(b, a) def test_2(self): b = """x = raw_input('')""" a = """x = input('')""" self.check(b, a) def test_3(self): b = """x = raw_input('prompt')""" a = """x = input('prompt')""" self.check(b, a) def test_4(self): b = """x = raw_input(foo(a) + 6)""" a = """x = input(foo(a) + 6)""" self.check(b, a) def test_5(self): b = """x = raw_input(invite).split()""" a = """x = input(invite).split()""" self.check(b, a) def test_6(self): b = """x = raw_input(invite) . split ()""" a = """x = input(invite) . split ()""" self.check(b, a) def test_8(self): b = "x = int(raw_input())" a = "x = int(input())" self.check(b, a) class Test_funcattrs(FixerTestCase): fixer = "funcattrs" attrs = ["closure", "doc", "name", "defaults", "code", "globals", "dict"] def test(self): for attr in self.attrs: b = "a.func_%s" % attr a = "a.__%s__" % attr self.check(b, a) b = "self.foo.func_%s.foo_bar" % attr a = "self.foo.__%s__.foo_bar" % attr self.check(b, a) def test_unchanged(self): for attr in self.attrs: s = "foo(func_%s + 5)" % attr self.unchanged(s) s = "f(foo.__%s__)" % attr self.unchanged(s) s = "f(foo.__%s__.foo)" % attr self.unchanged(s) class Test_xreadlines(FixerTestCase): fixer = "xreadlines" def test_call(self): b = "for x in f.xreadlines(): pass" a = "for x in f: pass" self.check(b, a) b = "for x in foo().xreadlines(): pass" a = "for x in foo(): pass" self.check(b, a) b = "for x in (5 + foo()).xreadlines(): pass" a = "for x in (5 + foo()): pass" self.check(b, a) def test_attr_ref(self): b = "foo(f.xreadlines + 5)" a = "foo(f.__iter__ + 5)" self.check(b, a) b = "foo(f().xreadlines + 5)" a = "foo(f().__iter__ + 5)" self.check(b, a) b = "foo((5 + f()).xreadlines + 5)" a = "foo((5 + f()).__iter__ + 5)" self.check(b, a) def test_unchanged(self): s = "for x in f.xreadlines(5): pass" self.unchanged(s) s = "for x in f.xreadlines(k=5): pass" self.unchanged(s) s = "for x in f.xreadlines(*k, **v): pass" self.unchanged(s) s = "foo(xreadlines)" self.unchanged(s) class ImportsFixerTests: def test_import_module(self): for old, new in self.modules.items(): b = "import %s" % old a = "import %s" % new self.check(b, a) b = "import foo, %s, bar" % old a = "import foo, %s, bar" % new self.check(b, a) def test_import_from(self): for old, new in self.modules.items(): b = "from %s import foo" % old a = "from %s import foo" % new self.check(b, a) b = "from %s import foo, bar" % old a = "from %s import foo, bar" % new self.check(b, a) b = "from %s import (yes, no)" % old a = "from %s import (yes, no)" % new self.check(b, a) def test_import_module_as(self): for old, new in self.modules.items(): b = "import %s as foo_bar" % old a = "import %s as foo_bar" % new self.check(b, a) b = "import %s as foo_bar" % old a = "import %s as foo_bar" % new self.check(b, a) def test_import_from_as(self): for old, new in self.modules.items(): b = "from %s import foo as bar" % old a = "from %s import foo as bar" % new self.check(b, a) def test_star(self): for old, new in self.modules.items(): b = "from %s import *" % old a = "from %s import *" % new self.check(b, a) def test_import_module_usage(self): for old, new in self.modules.items(): b = """ import %s foo(%s.bar) """ % (old, old) a = """ import %s foo(%s.bar) """ % (new, new) self.check(b, a) b = """ from %s import x %s = 23 """ % (old, old) a = """ from %s import x %s = 23 """ % (new, old) self.check(b, a) s = """ def f(): %s.method() """ % (old,) self.unchanged(s) # test nested usage b = """ import %s %s.bar(%s.foo) """ % (old, old, old) a = """ import %s %s.bar(%s.foo) """ % (new, new, new) self.check(b, a) b = """ import %s x.%s """ % (old, old) a = """ import %s x.%s """ % (new, old) self.check(b, a) class Test_imports(FixerTestCase, ImportsFixerTests): fixer = "imports" from ..fixes.fix_imports import MAPPING as modules def test_multiple_imports(self): b = """import urlparse, cStringIO""" a = """import urllib.parse, io""" self.check(b, a) def test_multiple_imports_as(self): b = """ import copy_reg as bar, HTMLParser as foo, urlparse s = urlparse.spam(bar.foo()) """ a = """ import copyreg as bar, html.parser as foo, urllib.parse s = urllib.parse.spam(bar.foo()) """ self.check(b, a) class Test_imports2(FixerTestCase, ImportsFixerTests): fixer = "imports2" from ..fixes.fix_imports2 import MAPPING as modules class Test_imports_fixer_order(FixerTestCase, ImportsFixerTests): def setUp(self): super(Test_imports_fixer_order, self).setUp(['imports', 'imports2']) from ..fixes.fix_imports2 import MAPPING as mapping2 self.modules = mapping2.copy() from ..fixes.fix_imports import MAPPING as mapping1 for key in ('dbhash', 'dumbdbm', 'dbm', 'gdbm'): self.modules[key] = mapping1[key] def test_after_local_imports_refactoring(self): for fix in ("imports", "imports2"): self.fixer = fix self.assert_runs_after("import") class Test_urllib(FixerTestCase): fixer = "urllib" from ..fixes.fix_urllib import MAPPING as modules def test_import_module(self): for old, changes in self.modules.items(): b = "import %s" % old a = "import %s" % ", ".join(map(itemgetter(0), changes)) self.check(b, a) def test_import_from(self): for old, changes in self.modules.items(): all_members = [] for new, members in changes: for member in members: all_members.append(member) b = "from %s import %s" % (old, member) a = "from %s import %s" % (new, member) self.check(b, a) s = "from foo import %s" % member self.unchanged(s) b = "from %s import %s" % (old, ", ".join(members)) a = "from %s import %s" % (new, ", ".join(members)) self.check(b, a) s = "from foo import %s" % ", ".join(members) self.unchanged(s) # test the breaking of a module into multiple replacements b = "from %s import %s" % (old, ", ".join(all_members)) a = "\n".join(["from %s import %s" % (new, ", ".join(members)) for (new, members) in changes]) self.check(b, a) def test_import_module_as(self): for old in self.modules: s = "import %s as foo" % old self.warns_unchanged(s, "This module is now multiple modules") def test_import_from_as(self): for old, changes in self.modules.items(): for new, members in changes: for member in members: b = "from %s import %s as foo_bar" % (old, member) a = "from %s import %s as foo_bar" % (new, member) self.check(b, a) b = "from %s import %s as blah, %s" % (old, member, member) a = "from %s import %s as blah, %s" % (new, member, member) self.check(b, a) def test_star(self): for old in self.modules: s = "from %s import *" % old self.warns_unchanged(s, "Cannot handle star imports") def test_indented(self): b = """ def foo(): from urllib import urlencode, urlopen """ a = """ def foo(): from urllib.parse import urlencode from urllib.request import urlopen """ self.check(b, a) b = """ def foo(): other() from urllib import urlencode, urlopen """ a = """ def foo(): other() from urllib.parse import urlencode from urllib.request import urlopen """ self.check(b, a) def test_import_module_usage(self): for old, changes in self.modules.items(): for new, members in changes: for member in members: new_import = ", ".join([n for (n, mems) in self.modules[old]]) b = """ import %s foo(%s.%s) """ % (old, old, member) a = """ import %s foo(%s.%s) """ % (new_import, new, member) self.check(b, a) b = """ import %s %s.%s(%s.%s) """ % (old, old, member, old, member) a = """ import %s %s.%s(%s.%s) """ % (new_import, new, member, new, member) self.check(b, a) class Test_input(FixerTestCase): fixer = "input" def test_prefix_preservation(self): b = """x = input( )""" a = """x = eval(input( ))""" self.check(b, a) b = """x = input( '' )""" a = """x = eval(input( '' ))""" self.check(b, a) def test_trailing_comment(self): b = """x = input() # foo""" a = """x = eval(input()) # foo""" self.check(b, a) def test_idempotency(self): s = """x = eval(input())""" self.unchanged(s) s = """x = eval(input(''))""" self.unchanged(s) s = """x = eval(input(foo(5) + 9))""" self.unchanged(s) def test_1(self): b = """x = input()""" a = """x = eval(input())""" self.check(b, a) def test_2(self): b = """x = input('')""" a = """x = eval(input(''))""" self.check(b, a) def test_3(self): b = """x = input('prompt')""" a = """x = eval(input('prompt'))""" self.check(b, a) def test_4(self): b = """x = input(foo(5) + 9)""" a = """x = eval(input(foo(5) + 9))""" self.check(b, a) class Test_tuple_params(FixerTestCase): fixer = "tuple_params" def test_unchanged_1(self): s = """def foo(): pass""" self.unchanged(s) def test_unchanged_2(self): s = """def foo(a, b, c): pass""" self.unchanged(s) def test_unchanged_3(self): s = """def foo(a=3, b=4, c=5): pass""" self.unchanged(s) def test_1(self): b = """ def foo(((a, b), c)): x = 5""" a = """ def foo(xxx_todo_changeme): ((a, b), c) = xxx_todo_changeme x = 5""" self.check(b, a) def test_2(self): b = """ def foo(((a, b), c), d): x = 5""" a = """ def foo(xxx_todo_changeme, d): ((a, b), c) = xxx_todo_changeme x = 5""" self.check(b, a) def test_3(self): b = """ def foo(((a, b), c), d) -> e: x = 5""" a = """ def foo(xxx_todo_changeme, d) -> e: ((a, b), c) = xxx_todo_changeme x = 5""" self.check(b, a) def test_semicolon(self): b = """ def foo(((a, b), c)): x = 5; y = 7""" a = """ def foo(xxx_todo_changeme): ((a, b), c) = xxx_todo_changeme; x = 5; y = 7""" self.check(b, a) def test_keywords(self): b = """ def foo(((a, b), c), d, e=5) -> z: x = 5""" a = """ def foo(xxx_todo_changeme, d, e=5) -> z: ((a, b), c) = xxx_todo_changeme x = 5""" self.check(b, a) def test_varargs(self): b = """ def foo(((a, b), c), d, *vargs, **kwargs) -> z: x = 5""" a = """ def foo(xxx_todo_changeme, d, *vargs, **kwargs) -> z: ((a, b), c) = xxx_todo_changeme x = 5""" self.check(b, a) def test_multi_1(self): b = """ def foo(((a, b), c), (d, e, f)) -> z: x = 5""" a = """ def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z: ((a, b), c) = xxx_todo_changeme (d, e, f) = xxx_todo_changeme1 x = 5""" self.check(b, a) def test_multi_2(self): b = """ def foo(x, ((a, b), c), d, (e, f, g), y) -> z: x = 5""" a = """ def foo(x, xxx_todo_changeme, d, xxx_todo_changeme1, y) -> z: ((a, b), c) = xxx_todo_changeme (e, f, g) = xxx_todo_changeme1 x = 5""" self.check(b, a) def test_docstring(self): b = """ def foo(((a, b), c), (d, e, f)) -> z: "foo foo foo foo" x = 5""" a = """ def foo(xxx_todo_changeme, xxx_todo_changeme1) -> z: "foo foo foo foo" ((a, b), c) = xxx_todo_changeme (d, e, f) = xxx_todo_changeme1 x = 5""" self.check(b, a) def test_lambda_no_change(self): s = """lambda x: x + 5""" self.unchanged(s) def test_lambda_parens_single_arg(self): b = """lambda (x): x + 5""" a = """lambda x: x + 5""" self.check(b, a) b = """lambda(x): x + 5""" a = """lambda x: x + 5""" self.check(b, a) b = """lambda ((((x)))): x + 5""" a = """lambda x: x + 5""" self.check(b, a) b = """lambda((((x)))): x + 5""" a = """lambda x: x + 5""" self.check(b, a) def test_lambda_simple(self): b = """lambda (x, y): x + f(y)""" a = """lambda x_y: x_y[0] + f(x_y[1])""" self.check(b, a) b = """lambda(x, y): x + f(y)""" a = """lambda x_y: x_y[0] + f(x_y[1])""" self.check(b, a) b = """lambda (((x, y))): x + f(y)""" a = """lambda x_y: x_y[0] + f(x_y[1])""" self.check(b, a) b = """lambda(((x, y))): x + f(y)""" a = """lambda x_y: x_y[0] + f(x_y[1])""" self.check(b, a) def test_lambda_one_tuple(self): b = """lambda (x,): x + f(x)""" a = """lambda x1: x1[0] + f(x1[0])""" self.check(b, a) b = """lambda (((x,))): x + f(x)""" a = """lambda x1: x1[0] + f(x1[0])""" self.check(b, a) def test_lambda_simple_multi_use(self): b = """lambda (x, y): x + x + f(x) + x""" a = """lambda x_y: x_y[0] + x_y[0] + f(x_y[0]) + x_y[0]""" self.check(b, a) def test_lambda_simple_reverse(self): b = """lambda (x, y): y + x""" a = """lambda x_y: x_y[1] + x_y[0]""" self.check(b, a) def test_lambda_nested(self): b = """lambda (x, (y, z)): x + y + z""" a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]""" self.check(b, a) b = """lambda (((x, (y, z)))): x + y + z""" a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + x_y_z[1][1]""" self.check(b, a) def test_lambda_nested_multi_use(self): b = """lambda (x, (y, z)): x + y + f(y)""" a = """lambda x_y_z: x_y_z[0] + x_y_z[1][0] + f(x_y_z[1][0])""" self.check(b, a) class Test_methodattrs(FixerTestCase): fixer = "methodattrs" attrs = ["func", "self", "class"] def test(self): for attr in self.attrs: b = "a.im_%s" % attr if attr == "class": a = "a.__self__.__class__" else: a = "a.__%s__" % attr self.check(b, a) b = "self.foo.im_%s.foo_bar" % attr if attr == "class": a = "self.foo.__self__.__class__.foo_bar" else: a = "self.foo.__%s__.foo_bar" % attr self.check(b, a) def test_unchanged(self): for attr in self.attrs: s = "foo(im_%s + 5)" % attr self.unchanged(s) s = "f(foo.__%s__)" % attr self.unchanged(s) s = "f(foo.__%s__.foo)" % attr self.unchanged(s) class Test_next(FixerTestCase): fixer = "next" def test_1(self): b = """it.next()""" a = """next(it)""" self.check(b, a) def test_2(self): b = """a.b.c.d.next()""" a = """next(a.b.c.d)""" self.check(b, a) def test_3(self): b = """(a + b).next()""" a = """next((a + b))""" self.check(b, a) def test_4(self): b = """a().next()""" a = """next(a())""" self.check(b, a) def test_5(self): b = """a().next() + b""" a = """next(a()) + b""" self.check(b, a) def test_6(self): b = """c( a().next() + b)""" a = """c( next(a()) + b)""" self.check(b, a) def test_prefix_preservation_1(self): b = """ for a in b: foo(a) a.next() """ a = """ for a in b: foo(a) next(a) """ self.check(b, a) def test_prefix_preservation_2(self): b = """ for a in b: foo(a) # abc # def a.next() """ a = """ for a in b: foo(a) # abc # def next(a) """ self.check(b, a) def test_prefix_preservation_3(self): b = """ next = 5 for a in b: foo(a) a.next() """ a = """ next = 5 for a in b: foo(a) a.__next__() """ self.check(b, a, ignore_warnings=True) def test_prefix_preservation_4(self): b = """ next = 5 for a in b: foo(a) # abc # def a.next() """ a = """ next = 5 for a in b: foo(a) # abc # def a.__next__() """ self.check(b, a, ignore_warnings=True) def test_prefix_preservation_5(self): b = """ next = 5 for a in b: foo(foo(a), # abc a.next()) """ a = """ next = 5 for a in b: foo(foo(a), # abc a.__next__()) """ self.check(b, a, ignore_warnings=True) def test_prefix_preservation_6(self): b = """ for a in b: foo(foo(a), # abc a.next()) """ a = """ for a in b: foo(foo(a), # abc next(a)) """ self.check(b, a) def test_method_1(self): b = """ class A: def next(self): pass """ a = """ class A: def __next__(self): pass """ self.check(b, a) def test_method_2(self): b = """ class A(object): def next(self): pass """ a = """ class A(object): def __next__(self): pass """ self.check(b, a) def test_method_3(self): b = """ class A: def next(x): pass """ a = """ class A: def __next__(x): pass """ self.check(b, a) def test_method_4(self): b = """ class A: def __init__(self, foo): self.foo = foo def next(self): pass def __iter__(self): return self """ a = """ class A: def __init__(self, foo): self.foo = foo def __next__(self): pass def __iter__(self): return self """ self.check(b, a) def test_method_unchanged(self): s = """ class A: def next(self, a, b): pass """ self.unchanged(s) def test_shadowing_assign_simple(self): s = """ next = foo class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_assign_tuple_1(self): s = """ (next, a) = foo class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_assign_tuple_2(self): s = """ (a, (b, (next, c)), a) = foo class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_assign_list_1(self): s = """ [next, a] = foo class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_assign_list_2(self): s = """ [a, [b, [next, c]], a] = foo class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_builtin_assign(self): s = """ def foo(): __builtin__.next = foo class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_builtin_assign_in_tuple(self): s = """ def foo(): (a, __builtin__.next) = foo class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_builtin_assign_in_list(self): s = """ def foo(): [a, __builtin__.next] = foo class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_assign_to_next(self): s = """ def foo(): A.next = foo class A: def next(self, a, b): pass """ self.unchanged(s) def test_assign_to_next_in_tuple(self): s = """ def foo(): (a, A.next) = foo class A: def next(self, a, b): pass """ self.unchanged(s) def test_assign_to_next_in_list(self): s = """ def foo(): [a, A.next] = foo class A: def next(self, a, b): pass """ self.unchanged(s) def test_shadowing_import_1(self): s = """ import foo.bar as next class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_import_2(self): s = """ import bar, bar.foo as next class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_import_3(self): s = """ import bar, bar.foo as next, baz class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_import_from_1(self): s = """ from x import next class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_import_from_2(self): s = """ from x.a import next class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_import_from_3(self): s = """ from x import a, next, b class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_import_from_4(self): s = """ from x.a import a, next, b class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_funcdef_1(self): s = """ def next(a): pass class A: def next(self, a, b): pass """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_funcdef_2(self): b = """ def next(a): pass class A: def next(self): pass it.next() """ a = """ def next(a): pass class A: def __next__(self): pass it.__next__() """ self.warns(b, a, "Calls to builtin next() possibly shadowed") def test_shadowing_global_1(self): s = """ def f(): global next next = 5 """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_global_2(self): s = """ def f(): global a, next, b next = 5 """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_for_simple(self): s = """ for next in it(): pass b = 5 c = 6 """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_for_tuple_1(self): s = """ for next, b in it(): pass b = 5 c = 6 """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_shadowing_for_tuple_2(self): s = """ for a, (next, c), b in it(): pass b = 5 c = 6 """ self.warns_unchanged(s, "Calls to builtin next() possibly shadowed") def test_noncall_access_1(self): b = """gnext = g.next""" a = """gnext = g.__next__""" self.check(b, a) def test_noncall_access_2(self): b = """f(g.next + 5)""" a = """f(g.__next__ + 5)""" self.check(b, a) def test_noncall_access_3(self): b = """f(g().next + 5)""" a = """f(g().__next__ + 5)""" self.check(b, a) class Test_nonzero(FixerTestCase): fixer = "nonzero" def test_1(self): b = """ class A: def __nonzero__(self): pass """ a = """ class A: def __bool__(self): pass """ self.check(b, a) def test_2(self): b = """ class A(object): def __nonzero__(self): pass """ a = """ class A(object): def __bool__(self): pass """ self.check(b, a) def test_unchanged_1(self): s = """ class A(object): def __bool__(self): pass """ self.unchanged(s) def test_unchanged_2(self): s = """ class A(object): def __nonzero__(self, a): pass """ self.unchanged(s) def test_unchanged_func(self): s = """ def __nonzero__(self): pass """ self.unchanged(s) class Test_numliterals(FixerTestCase): fixer = "numliterals" def test_octal_1(self): b = """0755""" a = """0o755""" self.check(b, a) def test_long_int_1(self): b = """a = 12L""" a = """a = 12""" self.check(b, a) def test_long_int_2(self): b = """a = 12l""" a = """a = 12""" self.check(b, a) def test_long_hex(self): b = """b = 0x12l""" a = """b = 0x12""" self.check(b, a) def test_comments_and_spacing(self): b = """b = 0x12L""" a = """b = 0x12""" self.check(b, a) b = """b = 0755 # spam""" a = """b = 0o755 # spam""" self.check(b, a) def test_unchanged_int(self): s = """5""" self.unchanged(s) def test_unchanged_float(self): s = """5.0""" self.unchanged(s) def test_unchanged_octal(self): s = """0o755""" self.unchanged(s) def test_unchanged_hex(self): s = """0xABC""" self.unchanged(s) def test_unchanged_exp(self): s = """5.0e10""" self.unchanged(s) def test_unchanged_complex_int(self): s = """5 + 4j""" self.unchanged(s) def test_unchanged_complex_float(self): s = """5.4 + 4.9j""" self.unchanged(s) def test_unchanged_complex_bare(self): s = """4j""" self.unchanged(s) s = """4.4j""" self.unchanged(s) class Test_renames(FixerTestCase): fixer = "renames" modules = {"sys": ("maxint", "maxsize"), } def test_import_from(self): for mod, (old, new) in list(self.modules.items()): b = "from %s import %s" % (mod, old) a = "from %s import %s" % (mod, new) self.check(b, a) s = "from foo import %s" % old self.unchanged(s) def test_import_from_as(self): for mod, (old, new) in list(self.modules.items()): b = "from %s import %s as foo_bar" % (mod, old) a = "from %s import %s as foo_bar" % (mod, new) self.check(b, a) def test_import_module_usage(self): for mod, (old, new) in list(self.modules.items()): b = """ import %s foo(%s, %s.%s) """ % (mod, mod, mod, old) a = """ import %s foo(%s, %s.%s) """ % (mod, mod, mod, new) self.check(b, a) def XXX_test_from_import_usage(self): # not implemented yet for mod, (old, new) in list(self.modules.items()): b = """ from %s import %s foo(%s, %s) """ % (mod, old, mod, old) a = """ from %s import %s foo(%s, %s) """ % (mod, new, mod, new) self.check(b, a) class Test_unicode(FixerTestCase): fixer = "unicode" def test_whitespace(self): b = """unicode( x)""" a = """str( x)""" self.check(b, a) b = """ unicode(x )""" a = """ str(x )""" self.check(b, a) b = """ u'h'""" a = """ 'h'""" self.check(b, a) def test_unicode_call(self): b = """unicode(x, y, z)""" a = """str(x, y, z)""" self.check(b, a) def test_unichr(self): b = """unichr(u'h')""" a = """chr('h')""" self.check(b, a) def test_unicode_literal_1(self): b = '''u"x"''' a = '''"x"''' self.check(b, a) def test_unicode_literal_2(self): b = """ur'x'""" a = """r'x'""" self.check(b, a) def test_unicode_literal_3(self): b = """UR'''x''' """ a = """R'''x''' """ self.check(b, a) def test_native_literal_escape_u(self): b = r"""'\\\u20ac\U0001d121\\u20ac'""" a = r"""'\\\\u20ac\\U0001d121\\u20ac'""" self.check(b, a) b = r"""r'\\\u20ac\U0001d121\\u20ac'""" a = r"""r'\\\u20ac\U0001d121\\u20ac'""" self.check(b, a) def test_bytes_literal_escape_u(self): b = r"""b'\\\u20ac\U0001d121\\u20ac'""" a = r"""b'\\\u20ac\U0001d121\\u20ac'""" self.check(b, a) b = r"""br'\\\u20ac\U0001d121\\u20ac'""" a = r"""br'\\\u20ac\U0001d121\\u20ac'""" self.check(b, a) def test_unicode_literal_escape_u(self): b = r"""u'\\\u20ac\U0001d121\\u20ac'""" a = r"""'\\\u20ac\U0001d121\\u20ac'""" self.check(b, a) b = r"""ur'\\\u20ac\U0001d121\\u20ac'""" a = r"""r'\\\u20ac\U0001d121\\u20ac'""" self.check(b, a) def test_native_unicode_literal_escape_u(self): f = 'from __future__ import unicode_literals\n' b = f + r"""'\\\u20ac\U0001d121\\u20ac'""" a = f + r"""'\\\u20ac\U0001d121\\u20ac'""" self.check(b, a) b = f + r"""r'\\\u20ac\U0001d121\\u20ac'""" a = f + r"""r'\\\u20ac\U0001d121\\u20ac'""" self.check(b, a) class Test_callable(FixerTestCase): fixer = "callable" def test_prefix_preservation(self): b = """callable( x)""" a = """import collections\nisinstance( x, collections.Callable)""" self.check(b, a) b = """if callable(x): pass""" a = """import collections if isinstance(x, collections.Callable): pass""" self.check(b, a) def test_callable_call(self): b = """callable(x)""" a = """import collections\nisinstance(x, collections.Callable)""" self.check(b, a) def test_global_import(self): b = """ def spam(foo): callable(foo)"""[1:] a = """ import collections def spam(foo): isinstance(foo, collections.Callable)"""[1:] self.check(b, a) b = """ import collections def spam(foo): callable(foo)"""[1:] # same output if it was already imported self.check(b, a) b = """ from collections import * def spam(foo): callable(foo)"""[1:] a = """ from collections import * import collections def spam(foo): isinstance(foo, collections.Callable)"""[1:] self.check(b, a) b = """ do_stuff() do_some_other_stuff() assert callable(do_stuff)"""[1:] a = """ import collections do_stuff() do_some_other_stuff() assert isinstance(do_stuff, collections.Callable)"""[1:] self.check(b, a) b = """ if isinstance(do_stuff, Callable): assert callable(do_stuff) do_stuff(do_stuff) if not callable(do_stuff): exit(1) else: assert callable(do_stuff) else: assert not callable(do_stuff)"""[1:] a = """ import collections if isinstance(do_stuff, Callable): assert isinstance(do_stuff, collections.Callable) do_stuff(do_stuff) if not isinstance(do_stuff, collections.Callable): exit(1) else: assert isinstance(do_stuff, collections.Callable) else: assert not isinstance(do_stuff, collections.Callable)"""[1:] self.check(b, a) def test_callable_should_not_change(self): a = """callable(*x)""" self.unchanged(a) a = """callable(x, y)""" self.unchanged(a) a = """callable(x, kw=y)""" self.unchanged(a) a = """callable()""" self.unchanged(a) class Test_filter(FixerTestCase): fixer = "filter" def test_prefix_preservation(self): b = """x = filter( foo, 'abc' )""" a = """x = list(filter( foo, 'abc' ))""" self.check(b, a) b = """x = filter( None , 'abc' )""" a = """x = [_f for _f in 'abc' if _f]""" self.check(b, a) def test_filter_basic(self): b = """x = filter(None, 'abc')""" a = """x = [_f for _f in 'abc' if _f]""" self.check(b, a) b = """x = len(filter(f, 'abc'))""" a = """x = len(list(filter(f, 'abc')))""" self.check(b, a) b = """x = filter(lambda x: x%2 == 0, range(10))""" a = """x = [x for x in range(10) if x%2 == 0]""" self.check(b, a) # Note the parens around x b = """x = filter(lambda (x): x%2 == 0, range(10))""" a = """x = [x for x in range(10) if x%2 == 0]""" self.check(b, a) # XXX This (rare) case is not supported ## b = """x = filter(f, 'abc')[0]""" ## a = """x = list(filter(f, 'abc'))[0]""" ## self.check(b, a) def test_filter_nochange(self): a = """b.join(filter(f, 'abc'))""" self.unchanged(a) a = """(a + foo(5)).join(filter(f, 'abc'))""" self.unchanged(a) a = """iter(filter(f, 'abc'))""" self.unchanged(a) a = """list(filter(f, 'abc'))""" self.unchanged(a) a = """list(filter(f, 'abc'))[0]""" self.unchanged(a) a = """set(filter(f, 'abc'))""" self.unchanged(a) a = """set(filter(f, 'abc')).pop()""" self.unchanged(a) a = """tuple(filter(f, 'abc'))""" self.unchanged(a) a = """any(filter(f, 'abc'))""" self.unchanged(a) a = """all(filter(f, 'abc'))""" self.unchanged(a) a = """sum(filter(f, 'abc'))""" self.unchanged(a) a = """sorted(filter(f, 'abc'))""" self.unchanged(a) a = """sorted(filter(f, 'abc'), key=blah)""" self.unchanged(a) a = """sorted(filter(f, 'abc'), key=blah)[0]""" self.unchanged(a) a = """enumerate(filter(f, 'abc'))""" self.unchanged(a) a = """enumerate(filter(f, 'abc'), start=1)""" self.unchanged(a) a = """for i in filter(f, 'abc'): pass""" self.unchanged(a) a = """[x for x in filter(f, 'abc')]""" self.unchanged(a) a = """(x for x in filter(f, 'abc'))""" self.unchanged(a) def test_future_builtins(self): a = "from future_builtins import spam, filter; filter(f, 'ham')" self.unchanged(a) b = """from future_builtins import spam; x = filter(f, 'abc')""" a = """from future_builtins import spam; x = list(filter(f, 'abc'))""" self.check(b, a) a = "from future_builtins import *; filter(f, 'ham')" self.unchanged(a) class Test_map(FixerTestCase): fixer = "map" def check(self, b, a): self.unchanged("from future_builtins import map; " + b, a) super(Test_map, self).check(b, a) def test_prefix_preservation(self): b = """x = map( f, 'abc' )""" a = """x = list(map( f, 'abc' ))""" self.check(b, a) def test_trailing_comment(self): b = """x = map(f, 'abc') # foo""" a = """x = list(map(f, 'abc')) # foo""" self.check(b, a) def test_None_with_multiple_arguments(self): s = """x = map(None, a, b, c)""" self.warns_unchanged(s, "cannot convert map(None, ...) with " "multiple arguments") def test_map_basic(self): b = """x = map(f, 'abc')""" a = """x = list(map(f, 'abc'))""" self.check(b, a) b = """x = len(map(f, 'abc', 'def'))""" a = """x = len(list(map(f, 'abc', 'def')))""" self.check(b, a) b = """x = map(None, 'abc')""" a = """x = list('abc')""" self.check(b, a) b = """x = map(lambda x: x+1, range(4))""" a = """x = [x+1 for x in range(4)]""" self.check(b, a) # Note the parens around x b = """x = map(lambda (x): x+1, range(4))""" a = """x = [x+1 for x in range(4)]""" self.check(b, a) b = """ foo() # foo map(f, x) """ a = """ foo() # foo list(map(f, x)) """ self.warns(b, a, "You should use a for loop here") # XXX This (rare) case is not supported ## b = """x = map(f, 'abc')[0]""" ## a = """x = list(map(f, 'abc'))[0]""" ## self.check(b, a) def test_map_nochange(self): a = """b.join(map(f, 'abc'))""" self.unchanged(a) a = """(a + foo(5)).join(map(f, 'abc'))""" self.unchanged(a) a = """iter(map(f, 'abc'))""" self.unchanged(a) a = """list(map(f, 'abc'))""" self.unchanged(a) a = """list(map(f, 'abc'))[0]""" self.unchanged(a) a = """set(map(f, 'abc'))""" self.unchanged(a) a = """set(map(f, 'abc')).pop()""" self.unchanged(a) a = """tuple(map(f, 'abc'))""" self.unchanged(a) a = """any(map(f, 'abc'))""" self.unchanged(a) a = """all(map(f, 'abc'))""" self.unchanged(a) a = """sum(map(f, 'abc'))""" self.unchanged(a) a = """sorted(map(f, 'abc'))""" self.unchanged(a) a = """sorted(map(f, 'abc'), key=blah)""" self.unchanged(a) a = """sorted(map(f, 'abc'), key=blah)[0]""" self.unchanged(a) a = """enumerate(map(f, 'abc'))""" self.unchanged(a) a = """enumerate(map(f, 'abc'), start=1)""" self.unchanged(a) a = """for i in map(f, 'abc'): pass""" self.unchanged(a) a = """[x for x in map(f, 'abc')]""" self.unchanged(a) a = """(x for x in map(f, 'abc'))""" self.unchanged(a) def test_future_builtins(self): a = "from future_builtins import spam, map, eggs; map(f, 'ham')" self.unchanged(a) b = """from future_builtins import spam, eggs; x = map(f, 'abc')""" a = """from future_builtins import spam, eggs; x = list(map(f, 'abc'))""" self.check(b, a) a = "from future_builtins import *; map(f, 'ham')" self.unchanged(a) class Test_zip(FixerTestCase): fixer = "zip" def check(self, b, a): self.unchanged("from future_builtins import zip; " + b, a) super(Test_zip, self).check(b, a) def test_zip_basic(self): b = """x = zip(a, b, c)""" a = """x = list(zip(a, b, c))""" self.check(b, a) b = """x = len(zip(a, b))""" a = """x = len(list(zip(a, b)))""" self.check(b, a) def test_zip_nochange(self): a = """b.join(zip(a, b))""" self.unchanged(a) a = """(a + foo(5)).join(zip(a, b))""" self.unchanged(a) a = """iter(zip(a, b))""" self.unchanged(a) a = """list(zip(a, b))""" self.unchanged(a) a = """list(zip(a, b))[0]""" self.unchanged(a) a = """set(zip(a, b))""" self.unchanged(a) a = """set(zip(a, b)).pop()""" self.unchanged(a) a = """tuple(zip(a, b))""" self.unchanged(a) a = """any(zip(a, b))""" self.unchanged(a) a = """all(zip(a, b))""" self.unchanged(a) a = """sum(zip(a, b))""" self.unchanged(a) a = """sorted(zip(a, b))""" self.unchanged(a) a = """sorted(zip(a, b), key=blah)""" self.unchanged(a) a = """sorted(zip(a, b), key=blah)[0]""" self.unchanged(a) a = """enumerate(zip(a, b))""" self.unchanged(a) a = """enumerate(zip(a, b), start=1)""" self.unchanged(a) a = """for i in zip(a, b): pass""" self.unchanged(a) a = """[x for x in zip(a, b)]""" self.unchanged(a) a = """(x for x in zip(a, b))""" self.unchanged(a) def test_future_builtins(self): a = "from future_builtins import spam, zip, eggs; zip(a, b)" self.unchanged(a) b = """from future_builtins import spam, eggs; x = zip(a, b)""" a = """from future_builtins import spam, eggs; x = list(zip(a, b))""" self.check(b, a) a = "from future_builtins import *; zip(a, b)" self.unchanged(a) class Test_standarderror(FixerTestCase): fixer = "standarderror" def test(self): b = """x = StandardError()""" a = """x = Exception()""" self.check(b, a) b = """x = StandardError(a, b, c)""" a = """x = Exception(a, b, c)""" self.check(b, a) b = """f(2 + StandardError(a, b, c))""" a = """f(2 + Exception(a, b, c))""" self.check(b, a) class Test_types(FixerTestCase): fixer = "types" def test_basic_types_convert(self): b = """types.StringType""" a = """bytes""" self.check(b, a) b = """types.DictType""" a = """dict""" self.check(b, a) b = """types . IntType""" a = """int""" self.check(b, a) b = """types.ListType""" a = """list""" self.check(b, a) b = """types.LongType""" a = """int""" self.check(b, a) b = """types.NoneType""" a = """type(None)""" self.check(b, a) class Test_idioms(FixerTestCase): fixer = "idioms" def test_while(self): b = """while 1: foo()""" a = """while True: foo()""" self.check(b, a) b = """while 1: foo()""" a = """while True: foo()""" self.check(b, a) b = """ while 1: foo() """ a = """ while True: foo() """ self.check(b, a) def test_while_unchanged(self): s = """while 11: foo()""" self.unchanged(s) s = """while 0: foo()""" self.unchanged(s) s = """while foo(): foo()""" self.unchanged(s) s = """while []: foo()""" self.unchanged(s) def test_eq_simple(self): b = """type(x) == T""" a = """isinstance(x, T)""" self.check(b, a) b = """if type(x) == T: pass""" a = """if isinstance(x, T): pass""" self.check(b, a) def test_eq_reverse(self): b = """T == type(x)""" a = """isinstance(x, T)""" self.check(b, a) b = """if T == type(x): pass""" a = """if isinstance(x, T): pass""" self.check(b, a) def test_eq_expression(self): b = """type(x+y) == d.get('T')""" a = """isinstance(x+y, d.get('T'))""" self.check(b, a) b = """type( x + y) == d.get('T')""" a = """isinstance(x + y, d.get('T'))""" self.check(b, a) def test_is_simple(self): b = """type(x) is T""" a = """isinstance(x, T)""" self.check(b, a) b = """if type(x) is T: pass""" a = """if isinstance(x, T): pass""" self.check(b, a) def test_is_reverse(self): b = """T is type(x)""" a = """isinstance(x, T)""" self.check(b, a) b = """if T is type(x): pass""" a = """if isinstance(x, T): pass""" self.check(b, a) def test_is_expression(self): b = """type(x+y) is d.get('T')""" a = """isinstance(x+y, d.get('T'))""" self.check(b, a) b = """type( x + y) is d.get('T')""" a = """isinstance(x + y, d.get('T'))""" self.check(b, a) def test_is_not_simple(self): b = """type(x) is not T""" a = """not isinstance(x, T)""" self.check(b, a) b = """if type(x) is not T: pass""" a = """if not isinstance(x, T): pass""" self.check(b, a) def test_is_not_reverse(self): b = """T is not type(x)""" a = """not isinstance(x, T)""" self.check(b, a) b = """if T is not type(x): pass""" a = """if not isinstance(x, T): pass""" self.check(b, a) def test_is_not_expression(self): b = """type(x+y) is not d.get('T')""" a = """not isinstance(x+y, d.get('T'))""" self.check(b, a) b = """type( x + y) is not d.get('T')""" a = """not isinstance(x + y, d.get('T'))""" self.check(b, a) def test_ne_simple(self): b = """type(x) != T""" a = """not isinstance(x, T)""" self.check(b, a) b = """if type(x) != T: pass""" a = """if not isinstance(x, T): pass""" self.check(b, a) def test_ne_reverse(self): b = """T != type(x)""" a = """not isinstance(x, T)""" self.check(b, a) b = """if T != type(x): pass""" a = """if not isinstance(x, T): pass""" self.check(b, a) def test_ne_expression(self): b = """type(x+y) != d.get('T')""" a = """not isinstance(x+y, d.get('T'))""" self.check(b, a) b = """type( x + y) != d.get('T')""" a = """not isinstance(x + y, d.get('T'))""" self.check(b, a) def test_type_unchanged(self): a = """type(x).__name__""" self.unchanged(a) def test_sort_list_call(self): b = """ v = list(t) v.sort() foo(v) """ a = """ v = sorted(t) foo(v) """ self.check(b, a) b = """ v = list(foo(b) + d) v.sort() foo(v) """ a = """ v = sorted(foo(b) + d) foo(v) """ self.check(b, a) b = """ while x: v = list(t) v.sort() foo(v) """ a = """ while x: v = sorted(t) foo(v) """ self.check(b, a) b = """ v = list(t) # foo v.sort() foo(v) """ a = """ v = sorted(t) # foo foo(v) """ self.check(b, a) b = r""" v = list( t) v.sort() foo(v) """ a = r""" v = sorted( t) foo(v) """ self.check(b, a) b = r""" try: m = list(s) m.sort() except: pass """ a = r""" try: m = sorted(s) except: pass """ self.check(b, a) b = r""" try: m = list(s) # foo m.sort() except: pass """ a = r""" try: m = sorted(s) # foo except: pass """ self.check(b, a) b = r""" m = list(s) # more comments m.sort()""" a = r""" m = sorted(s) # more comments""" self.check(b, a) def test_sort_simple_expr(self): b = """ v = t v.sort() foo(v) """ a = """ v = sorted(t) foo(v) """ self.check(b, a) b = """ v = foo(b) v.sort() foo(v) """ a = """ v = sorted(foo(b)) foo(v) """ self.check(b, a) b = """ v = b.keys() v.sort() foo(v) """ a = """ v = sorted(b.keys()) foo(v) """ self.check(b, a) b = """ v = foo(b) + d v.sort() foo(v) """ a = """ v = sorted(foo(b) + d) foo(v) """ self.check(b, a) b = """ while x: v = t v.sort() foo(v) """ a = """ while x: v = sorted(t) foo(v) """ self.check(b, a) b = """ v = t # foo v.sort() foo(v) """ a = """ v = sorted(t) # foo foo(v) """ self.check(b, a) b = r""" v = t v.sort() foo(v) """ a = r""" v = sorted(t) foo(v) """ self.check(b, a) def test_sort_unchanged(self): s = """ v = list(t) w.sort() foo(w) """ self.unchanged(s) s = """ v = list(t) v.sort(u) foo(v) """ self.unchanged(s) class Test_basestring(FixerTestCase): fixer = "basestring" def test_basestring(self): b = """isinstance(x, basestring)""" a = """isinstance(x, str)""" self.check(b, a) class Test_buffer(FixerTestCase): fixer = "buffer" def test_buffer(self): b = """x = buffer(y)""" a = """x = memoryview(y)""" self.check(b, a) def test_slicing(self): b = """buffer(y)[4:5]""" a = """memoryview(y)[4:5]""" self.check(b, a) class Test_future(FixerTestCase): fixer = "future" def test_future(self): b = """from __future__ import braces""" a = """""" self.check(b, a) b = """# comment\nfrom __future__ import braces""" a = """# comment\n""" self.check(b, a) b = """from __future__ import braces\n# comment""" a = """\n# comment""" self.check(b, a) def test_run_order(self): self.assert_runs_after('print') class Test_itertools(FixerTestCase): fixer = "itertools" def checkall(self, before, after): # Because we need to check with and without the itertools prefix # and on each of the three functions, these loops make it all # much easier for i in ('itertools.', ''): for f in ('map', 'filter', 'zip'): b = before %(i+'i'+f) a = after %(f) self.check(b, a) def test_0(self): # A simple example -- test_1 covers exactly the same thing, # but it's not quite as clear. b = "itertools.izip(a, b)" a = "zip(a, b)" self.check(b, a) def test_1(self): b = """%s(f, a)""" a = """%s(f, a)""" self.checkall(b, a) def test_qualified(self): b = """itertools.ifilterfalse(a, b)""" a = """itertools.filterfalse(a, b)""" self.check(b, a) b = """itertools.izip_longest(a, b)""" a = """itertools.zip_longest(a, b)""" self.check(b, a) def test_2(self): b = """ifilterfalse(a, b)""" a = """filterfalse(a, b)""" self.check(b, a) b = """izip_longest(a, b)""" a = """zip_longest(a, b)""" self.check(b, a) def test_space_1(self): b = """ %s(f, a)""" a = """ %s(f, a)""" self.checkall(b, a) def test_space_2(self): b = """ itertools.ifilterfalse(a, b)""" a = """ itertools.filterfalse(a, b)""" self.check(b, a) b = """ itertools.izip_longest(a, b)""" a = """ itertools.zip_longest(a, b)""" self.check(b, a) def test_run_order(self): self.assert_runs_after('map', 'zip', 'filter') class Test_itertools_imports(FixerTestCase): fixer = 'itertools_imports' def test_reduced(self): b = "from itertools import imap, izip, foo" a = "from itertools import foo" self.check(b, a) b = "from itertools import bar, imap, izip, foo" a = "from itertools import bar, foo" self.check(b, a) b = "from itertools import chain, imap, izip" a = "from itertools import chain" self.check(b, a) def test_comments(self): b = "#foo\nfrom itertools import imap, izip" a = "#foo\n" self.check(b, a) def test_none(self): b = "from itertools import imap, izip" a = "" self.check(b, a) b = "from itertools import izip" a = "" self.check(b, a) def test_import_as(self): b = "from itertools import izip, bar as bang, imap" a = "from itertools import bar as bang" self.check(b, a) b = "from itertools import izip as _zip, imap, bar" a = "from itertools import bar" self.check(b, a) b = "from itertools import imap as _map" a = "" self.check(b, a) b = "from itertools import imap as _map, izip as _zip" a = "" self.check(b, a) s = "from itertools import bar as bang" self.unchanged(s) def test_ifilter_and_zip_longest(self): for name in "filterfalse", "zip_longest": b = "from itertools import i%s" % (name,) a = "from itertools import %s" % (name,) self.check(b, a) b = "from itertools import imap, i%s, foo" % (name,) a = "from itertools import %s, foo" % (name,) self.check(b, a) b = "from itertools import bar, i%s, foo" % (name,) a = "from itertools import bar, %s, foo" % (name,) self.check(b, a) def test_import_star(self): s = "from itertools import *" self.unchanged(s) def test_unchanged(self): s = "from itertools import foo" self.unchanged(s) class Test_import(FixerTestCase): fixer = "import" def setUp(self): super(Test_import, self).setUp() # Need to replace fix_import's exists method # so we can check that it's doing the right thing self.files_checked = [] self.present_files = set() self.always_exists = True def fake_exists(name): self.files_checked.append(name) return self.always_exists or (name in self.present_files) from lib2to3.fixes import fix_import fix_import.exists = fake_exists def tearDown(self): from lib2to3.fixes import fix_import fix_import.exists = os.path.exists def check_both(self, b, a): self.always_exists = True super(Test_import, self).check(b, a) self.always_exists = False super(Test_import, self).unchanged(b) def test_files_checked(self): def p(path): # Takes a unix path and returns a path with correct separators return os.path.pathsep.join(path.split("/")) self.always_exists = False self.present_files = set(['__init__.py']) expected_extensions = ('.py', os.path.sep, '.pyc', '.so', '.sl', '.pyd') names_to_test = (p("/spam/eggs.py"), "ni.py", p("../../shrubbery.py")) for name in names_to_test: self.files_checked = [] self.filename = name self.unchanged("import jam") if os.path.dirname(name): name = os.path.dirname(name) + '/jam' else: name = 'jam' expected_checks = set(name + ext for ext in expected_extensions) expected_checks.add("__init__.py") self.assertEqual(set(self.files_checked), expected_checks) def test_not_in_package(self): s = "import bar" self.always_exists = False self.present_files = set(["bar.py"]) self.unchanged(s) def test_with_absolute_import_enabled(self): s = "from __future__ import absolute_import\nimport bar" self.always_exists = False self.present_files = set(["__init__.py", "bar.py"]) self.unchanged(s) def test_in_package(self): b = "import bar" a = "from . import bar" self.always_exists = False self.present_files = set(["__init__.py", "bar.py"]) self.check(b, a) def test_import_from_package(self): b = "import bar" a = "from . import bar" self.always_exists = False self.present_files = set(["__init__.py", "bar" + os.path.sep]) self.check(b, a) def test_already_relative_import(self): s = "from . import bar" self.unchanged(s) def test_comments_and_indent(self): b = "import bar # Foo" a = "from . import bar # Foo" self.check(b, a) def test_from(self): b = "from foo import bar, baz" a = "from .foo import bar, baz" self.check_both(b, a) b = "from foo import bar" a = "from .foo import bar" self.check_both(b, a) b = "from foo import (bar, baz)" a = "from .foo import (bar, baz)" self.check_both(b, a) def test_dotted_from(self): b = "from green.eggs import ham" a = "from .green.eggs import ham" self.check_both(b, a) def test_from_as(self): b = "from green.eggs import ham as spam" a = "from .green.eggs import ham as spam" self.check_both(b, a) def test_import(self): b = "import foo" a = "from . import foo" self.check_both(b, a) b = "import foo, bar" a = "from . import foo, bar" self.check_both(b, a) b = "import foo, bar, x" a = "from . import foo, bar, x" self.check_both(b, a) b = "import x, y, z" a = "from . import x, y, z" self.check_both(b, a) def test_import_as(self): b = "import foo as x" a = "from . import foo as x" self.check_both(b, a) b = "import a as b, b as c, c as d" a = "from . import a as b, b as c, c as d" self.check_both(b, a) def test_local_and_absolute(self): self.always_exists = False self.present_files = set(["foo.py", "__init__.py"]) s = "import foo, bar" self.warns_unchanged(s, "absolute and local imports together") def test_dotted_import(self): b = "import foo.bar" a = "from . import foo.bar" self.check_both(b, a) def test_dotted_import_as(self): b = "import foo.bar as bang" a = "from . import foo.bar as bang" self.check_both(b, a) def test_prefix(self): b = """ # prefix import foo.bar """ a = """ # prefix from . import foo.bar """ self.check_both(b, a) class Test_set_literal(FixerTestCase): fixer = "set_literal" def test_basic(self): b = """set([1, 2, 3])""" a = """{1, 2, 3}""" self.check(b, a) b = """set((1, 2, 3))""" a = """{1, 2, 3}""" self.check(b, a) b = """set((1,))""" a = """{1}""" self.check(b, a) b = """set([1])""" self.check(b, a) b = """set((a, b))""" a = """{a, b}""" self.check(b, a) b = """set([a, b])""" self.check(b, a) b = """set((a*234, f(args=23)))""" a = """{a*234, f(args=23)}""" self.check(b, a) b = """set([a*23, f(23)])""" a = """{a*23, f(23)}""" self.check(b, a) b = """set([a-234**23])""" a = """{a-234**23}""" self.check(b, a) def test_listcomps(self): b = """set([x for x in y])""" a = """{x for x in y}""" self.check(b, a) b = """set([x for x in y if x == m])""" a = """{x for x in y if x == m}""" self.check(b, a) b = """set([x for x in y for a in b])""" a = """{x for x in y for a in b}""" self.check(b, a) b = """set([f(x) - 23 for x in y])""" a = """{f(x) - 23 for x in y}""" self.check(b, a) def test_whitespace(self): b = """set( [1, 2])""" a = """{1, 2}""" self.check(b, a) b = """set([1 , 2])""" a = """{1 , 2}""" self.check(b, a) b = """set([ 1 ])""" a = """{ 1 }""" self.check(b, a) b = """set( [1] )""" a = """{1}""" self.check(b, a) b = """set([ 1, 2 ])""" a = """{ 1, 2 }""" self.check(b, a) b = """set([x for x in y ])""" a = """{x for x in y }""" self.check(b, a) b = """set( [1, 2] ) """ a = """{1, 2}\n""" self.check(b, a) def test_comments(self): b = """set((1, 2)) # Hi""" a = """{1, 2} # Hi""" self.check(b, a) # This isn't optimal behavior, but the fixer is optional. b = """ # Foo set( # Bar (1, 2) ) """ a = """ # Foo {1, 2} """ self.check(b, a) def test_unchanged(self): s = """set()""" self.unchanged(s) s = """set(a)""" self.unchanged(s) s = """set(a, b, c)""" self.unchanged(s) # Don't transform generators because they might have to be lazy. s = """set(x for x in y)""" self.unchanged(s) s = """set(x for x in y if z)""" self.unchanged(s) s = """set(a*823-23**2 + f(23))""" self.unchanged(s) class Test_sys_exc(FixerTestCase): fixer = "sys_exc" def test_0(self): b = "sys.exc_type" a = "sys.exc_info()[0]" self.check(b, a) def test_1(self): b = "sys.exc_value" a = "sys.exc_info()[1]" self.check(b, a) def test_2(self): b = "sys.exc_traceback" a = "sys.exc_info()[2]" self.check(b, a) def test_3(self): b = "sys.exc_type # Foo" a = "sys.exc_info()[0] # Foo" self.check(b, a) def test_4(self): b = "sys. exc_type" a = "sys. exc_info()[0]" self.check(b, a) def test_5(self): b = "sys .exc_type" a = "sys .exc_info()[0]" self.check(b, a) class Test_paren(FixerTestCase): fixer = "paren" def test_0(self): b = """[i for i in 1, 2 ]""" a = """[i for i in (1, 2) ]""" self.check(b, a) def test_1(self): b = """[i for i in 1, 2, ]""" a = """[i for i in (1, 2,) ]""" self.check(b, a) def test_2(self): b = """[i for i in 1, 2 ]""" a = """[i for i in (1, 2) ]""" self.check(b, a) def test_3(self): b = """[i for i in 1, 2 if i]""" a = """[i for i in (1, 2) if i]""" self.check(b, a) def test_4(self): b = """[i for i in 1, 2 ]""" a = """[i for i in (1, 2) ]""" self.check(b, a) def test_5(self): b = """(i for i in 1, 2)""" a = """(i for i in (1, 2))""" self.check(b, a) def test_6(self): b = """(i for i in 1 ,2 if i)""" a = """(i for i in (1 ,2) if i)""" self.check(b, a) def test_unchanged_0(self): s = """[i for i in (1, 2)]""" self.unchanged(s) def test_unchanged_1(self): s = """[i for i in foo()]""" self.unchanged(s) def test_unchanged_2(self): s = """[i for i in (1, 2) if nothing]""" self.unchanged(s) def test_unchanged_3(self): s = """(i for i in (1, 2))""" self.unchanged(s) def test_unchanged_4(self): s = """[i for i in m]""" self.unchanged(s) class Test_metaclass(FixerTestCase): fixer = 'metaclass' def test_unchanged(self): self.unchanged("class X(): pass") self.unchanged("class X(object): pass") self.unchanged("class X(object1, object2): pass") self.unchanged("class X(object1, object2, object3): pass") self.unchanged("class X(metaclass=Meta): pass") self.unchanged("class X(b, arg=23, metclass=Meta): pass") self.unchanged("class X(b, arg=23, metaclass=Meta, other=42): pass") s = """ class X: def __metaclass__(self): pass """ self.unchanged(s) s = """ class X: a[23] = 74 """ self.unchanged(s) def test_comments(self): b = """ class X: # hi __metaclass__ = AppleMeta """ a = """ class X(metaclass=AppleMeta): # hi pass """ self.check(b, a) b = """ class X: __metaclass__ = Meta # Bedtime! """ a = """ class X(metaclass=Meta): pass # Bedtime! """ self.check(b, a) def test_meta(self): # no-parent class, odd body b = """ class X(): __metaclass__ = Q pass """ a = """ class X(metaclass=Q): pass """ self.check(b, a) # one parent class, no body b = """class X(object): __metaclass__ = Q""" a = """class X(object, metaclass=Q): pass""" self.check(b, a) # one parent, simple body b = """ class X(object): __metaclass__ = Meta bar = 7 """ a = """ class X(object, metaclass=Meta): bar = 7 """ self.check(b, a) b = """ class X: __metaclass__ = Meta; x = 4; g = 23 """ a = """ class X(metaclass=Meta): x = 4; g = 23 """ self.check(b, a) # one parent, simple body, __metaclass__ last b = """ class X(object): bar = 7 __metaclass__ = Meta """ a = """ class X(object, metaclass=Meta): bar = 7 """ self.check(b, a) # redefining __metaclass__ b = """ class X(): __metaclass__ = A __metaclass__ = B bar = 7 """ a = """ class X(metaclass=B): bar = 7 """ self.check(b, a) # multiple inheritance, simple body b = """ class X(clsA, clsB): __metaclass__ = Meta bar = 7 """ a = """ class X(clsA, clsB, metaclass=Meta): bar = 7 """ self.check(b, a) # keywords in the class statement b = """class m(a, arg=23): __metaclass__ = Meta""" a = """class m(a, arg=23, metaclass=Meta): pass""" self.check(b, a) b = """ class X(expression(2 + 4)): __metaclass__ = Meta """ a = """ class X(expression(2 + 4), metaclass=Meta): pass """ self.check(b, a) b = """ class X(expression(2 + 4), x**4): __metaclass__ = Meta """ a = """ class X(expression(2 + 4), x**4, metaclass=Meta): pass """ self.check(b, a) b = """ class X: __metaclass__ = Meta save.py = 23 """ a = """ class X(metaclass=Meta): save.py = 23 """ self.check(b, a) class Test_getcwdu(FixerTestCase): fixer = 'getcwdu' def test_basic(self): b = """os.getcwdu""" a = """os.getcwd""" self.check(b, a) b = """os.getcwdu()""" a = """os.getcwd()""" self.check(b, a) b = """meth = os.getcwdu""" a = """meth = os.getcwd""" self.check(b, a) b = """os.getcwdu(args)""" a = """os.getcwd(args)""" self.check(b, a) def test_comment(self): b = """os.getcwdu() # Foo""" a = """os.getcwd() # Foo""" self.check(b, a) def test_unchanged(self): s = """os.getcwd()""" self.unchanged(s) s = """getcwdu()""" self.unchanged(s) s = """os.getcwdb()""" self.unchanged(s) def test_indentation(self): b = """ if 1: os.getcwdu() """ a = """ if 1: os.getcwd() """ self.check(b, a) def test_multilation(self): b = """os .getcwdu()""" a = """os .getcwd()""" self.check(b, a) b = """os. getcwdu""" a = """os. getcwd""" self.check(b, a) b = """os.getcwdu ( )""" a = """os.getcwd ( )""" self.check(b, a) class Test_operator(FixerTestCase): fixer = "operator" def test_operator_isCallable(self): b = "operator.isCallable(x)" a = "hasattr(x, '__call__')" self.check(b, a) def test_operator_sequenceIncludes(self): b = "operator.sequenceIncludes(x, y)" a = "operator.contains(x, y)" self.check(b, a) b = "operator .sequenceIncludes(x, y)" a = "operator .contains(x, y)" self.check(b, a) b = "operator. sequenceIncludes(x, y)" a = "operator. contains(x, y)" self.check(b, a) def test_operator_isSequenceType(self): b = "operator.isSequenceType(x)" a = "import collections\nisinstance(x, collections.Sequence)" self.check(b, a) def test_operator_isMappingType(self): b = "operator.isMappingType(x)" a = "import collections\nisinstance(x, collections.Mapping)" self.check(b, a) def test_operator_isNumberType(self): b = "operator.isNumberType(x)" a = "import numbers\nisinstance(x, numbers.Number)" self.check(b, a) def test_operator_repeat(self): b = "operator.repeat(x, n)" a = "operator.mul(x, n)" self.check(b, a) b = "operator .repeat(x, n)" a = "operator .mul(x, n)" self.check(b, a) b = "operator. repeat(x, n)" a = "operator. mul(x, n)" self.check(b, a) def test_operator_irepeat(self): b = "operator.irepeat(x, n)" a = "operator.imul(x, n)" self.check(b, a) b = "operator .irepeat(x, n)" a = "operator .imul(x, n)" self.check(b, a) b = "operator. irepeat(x, n)" a = "operator. imul(x, n)" self.check(b, a) def test_bare_isCallable(self): s = "isCallable(x)" t = "You should use 'hasattr(x, '__call__')' here." self.warns_unchanged(s, t) def test_bare_sequenceIncludes(self): s = "sequenceIncludes(x, y)" t = "You should use 'operator.contains(x, y)' here." self.warns_unchanged(s, t) def test_bare_operator_isSequenceType(self): s = "isSequenceType(z)" t = "You should use 'isinstance(z, collections.Sequence)' here." self.warns_unchanged(s, t) def test_bare_operator_isMappingType(self): s = "isMappingType(x)" t = "You should use 'isinstance(x, collections.Mapping)' here." self.warns_unchanged(s, t) def test_bare_operator_isNumberType(self): s = "isNumberType(y)" t = "You should use 'isinstance(y, numbers.Number)' here." self.warns_unchanged(s, t) def test_bare_operator_repeat(self): s = "repeat(x, n)" t = "You should use 'operator.mul(x, n)' here." self.warns_unchanged(s, t) def test_bare_operator_irepeat(self): s = "irepeat(y, 187)" t = "You should use 'operator.imul(y, 187)' here." self.warns_unchanged(s, t) class Test_exitfunc(FixerTestCase): fixer = "exitfunc" def test_simple(self): b = """ import sys sys.exitfunc = my_atexit """ a = """ import sys import atexit atexit.register(my_atexit) """ self.check(b, a) def test_names_import(self): b = """ import sys, crumbs sys.exitfunc = my_func """ a = """ import sys, crumbs, atexit atexit.register(my_func) """ self.check(b, a) def test_complex_expression(self): b = """ import sys sys.exitfunc = do(d)/a()+complex(f=23, g=23)*expression """ a = """ import sys import atexit atexit.register(do(d)/a()+complex(f=23, g=23)*expression) """ self.check(b, a) def test_comments(self): b = """ import sys # Foo sys.exitfunc = f # Blah """ a = """ import sys import atexit # Foo atexit.register(f) # Blah """ self.check(b, a) b = """ import apples, sys, crumbs, larry # Pleasant comments sys.exitfunc = func """ a = """ import apples, sys, crumbs, larry, atexit # Pleasant comments atexit.register(func) """ self.check(b, a) def test_in_a_function(self): b = """ import sys def f(): sys.exitfunc = func """ a = """ import sys import atexit def f(): atexit.register(func) """ self.check(b, a) def test_no_sys_import(self): b = """sys.exitfunc = f""" a = """atexit.register(f)""" msg = ("Can't find sys import; Please add an atexit import at the " "top of your file.") self.warns(b, a, msg) def test_unchanged(self): s = """f(sys.exitfunc)""" self.unchanged(s) class Test_asserts(FixerTestCase): fixer = "asserts" def test_deprecated_names(self): tests = [ ('self.assert_(True)', 'self.assertTrue(True)'), ('self.assertEquals(2, 2)', 'self.assertEqual(2, 2)'), ('self.assertNotEquals(2, 3)', 'self.assertNotEqual(2, 3)'), ('self.assertAlmostEquals(2, 3)', 'self.assertAlmostEqual(2, 3)'), ('self.assertNotAlmostEquals(2, 8)', 'self.assertNotAlmostEqual(2, 8)'), ('self.failUnlessEqual(2, 2)', 'self.assertEqual(2, 2)'), ('self.failIfEqual(2, 3)', 'self.assertNotEqual(2, 3)'), ('self.failUnlessAlmostEqual(2, 3)', 'self.assertAlmostEqual(2, 3)'), ('self.failIfAlmostEqual(2, 8)', 'self.assertNotAlmostEqual(2, 8)'), ('self.failUnless(True)', 'self.assertTrue(True)'), ('self.failUnlessRaises(foo)', 'self.assertRaises(foo)'), ('self.failIf(False)', 'self.assertFalse(False)'), ] for b, a in tests: self.check(b, a) def test_variants(self): b = 'eq = self.assertEquals' a = 'eq = self.assertEqual' self.check(b, a) b = 'self.assertEquals(2, 3, msg="fail")' a = 'self.assertEqual(2, 3, msg="fail")' self.check(b, a) b = 'self.assertEquals(2, 3, msg="fail") # foo' a = 'self.assertEqual(2, 3, msg="fail") # foo' self.check(b, a) b = 'self.assertEquals (2, 3)' a = 'self.assertEqual (2, 3)' self.check(b, a) b = ' self.assertEquals (2, 3)' a = ' self.assertEqual (2, 3)' self.check(b, a) b = 'with self.failUnlessRaises(Explosion): explode()' a = 'with self.assertRaises(Explosion): explode()' self.check(b, a) b = 'with self.failUnlessRaises(Explosion) as cm: explode()' a = 'with self.assertRaises(Explosion) as cm: explode()' self.check(b, a) def test_unchanged(self): self.unchanged('self.assertEqualsOnSaturday') self.unchanged('self.assertEqualsOnSaturday(3, 5)')
lgpl-3.0
energicryptocurrency/energi
qa/rpc-tests/mempool_packages.py
1
11060
#!/usr/bin/env python3 # Copyright (c) 2015-2018 The Energi Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # Copyright (c) 2014-2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # Test descendant package tracking code from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * from test_framework.mininode import COIN MAX_ANCESTORS = 25 MAX_DESCENDANTS = 25 class MempoolPackagesTest(BitcoinTestFramework): def __init__(self): super().__init__() self.num_nodes = 2 self.setup_clean_chain = False def setup_network(self): self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-maxorphantx=1000", "-debug"])) self.nodes.append(start_node(1, self.options.tmpdir, ["-maxorphantx=1000", "-limitancestorcount=5", "-debug"])) connect_nodes(self.nodes[0], 1) self.is_network_split = False self.sync_all() # Build a transaction that spends parent_txid:vout # Return amount sent def chain_transaction(self, node, parent_txid, vout, value, fee, num_outputs): send_value = satoshi_round((value - fee)/num_outputs) inputs = [ {'txid' : parent_txid, 'vout' : vout} ] outputs = {} for i in range(num_outputs): outputs[node.getnewaddress()] = send_value rawtx = node.createrawtransaction(inputs, outputs) signedtx = node.signrawtransaction(rawtx) txid = node.sendrawtransaction(signedtx['hex']) fulltx = node.getrawtransaction(txid, 1) assert(len(fulltx['vout']) == num_outputs) # make sure we didn't generate a change output return (txid, send_value) def run_test(self): ''' Mine some blocks and have them mature. ''' self.nodes[0].generate(101) utxo = self.nodes[0].listunspent(10) txid = utxo[0]['txid'] vout = utxo[0]['vout'] value = utxo[0]['amount'] fee = Decimal("0.0001") # MAX_ANCESTORS transactions off a confirmed tx should be fine chain = [] for i in range(MAX_ANCESTORS): (txid, sent_value) = self.chain_transaction(self.nodes[0], txid, 0, value, fee, 1) value = sent_value chain.append(txid) # Check mempool has MAX_ANCESTORS transactions in it, and descendant # count and fees should look correct mempool = self.nodes[0].getrawmempool(True) assert_equal(len(mempool), MAX_ANCESTORS) descendant_count = 1 descendant_fees = 0 descendant_size = 0 descendants = [] ancestors = list(chain) for x in reversed(chain): # Check that getmempoolentry is consistent with getrawmempool entry = self.nodes[0].getmempoolentry(x) assert_equal(entry, mempool[x]) # Check that the descendant calculations are correct assert_equal(mempool[x]['descendantcount'], descendant_count) descendant_fees += mempool[x]['fee'] assert_equal(mempool[x]['modifiedfee'], mempool[x]['fee']) assert_equal(mempool[x]['descendantfees'], descendant_fees * COIN) descendant_size += mempool[x]['size'] assert_equal(mempool[x]['descendantsize'], descendant_size) descendant_count += 1 # Check that getmempooldescendants is correct assert_equal(sorted(descendants), sorted(self.nodes[0].getmempooldescendants(x))) descendants.append(x) # Check that getmempoolancestors is correct ancestors.remove(x) assert_equal(sorted(ancestors), sorted(self.nodes[0].getmempoolancestors(x))) # Check that getmempoolancestors/getmempooldescendants correctly handle verbose=true v_ancestors = self.nodes[0].getmempoolancestors(chain[-1], True) assert_equal(len(v_ancestors), len(chain)-1) for x in v_ancestors.keys(): assert_equal(mempool[x], v_ancestors[x]) assert(chain[-1] not in v_ancestors.keys()) v_descendants = self.nodes[0].getmempooldescendants(chain[0], True) assert_equal(len(v_descendants), len(chain)-1) for x in v_descendants.keys(): assert_equal(mempool[x], v_descendants[x]) assert(chain[0] not in v_descendants.keys()) # Check that ancestor modified fees includes fee deltas from # prioritisetransaction self.nodes[0].prioritisetransaction(chain[0], 0, 1000) mempool = self.nodes[0].getrawmempool(True) ancestor_fees = 0 for x in chain: ancestor_fees += mempool[x]['fee'] assert_equal(mempool[x]['ancestorfees'], ancestor_fees * COIN + 1000) # Undo the prioritisetransaction for later tests self.nodes[0].prioritisetransaction(chain[0], 0, -1000) # Check that descendant modified fees includes fee deltas from # prioritisetransaction self.nodes[0].prioritisetransaction(chain[-1], 0, 1000) mempool = self.nodes[0].getrawmempool(True) descendant_fees = 0 for x in reversed(chain): descendant_fees += mempool[x]['fee'] assert_equal(mempool[x]['descendantfees'], descendant_fees * COIN + 1000) # Adding one more transaction on to the chain should fail. try: self.chain_transaction(self.nodes[0], txid, vout, value, fee, 1) except JSONRPCException as e: print("too-long-ancestor-chain successfully rejected") # Check that prioritising a tx before it's added to the mempool works # First clear the mempool by mining a block. self.nodes[0].generate(1) sync_blocks(self.nodes) assert_equal(len(self.nodes[0].getrawmempool()), 0) # Prioritise a transaction that has been mined, then add it back to the # mempool by using invalidateblock. self.nodes[0].prioritisetransaction(chain[-1], 0, 2000) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) # Keep node1's tip synced with node0 self.nodes[1].invalidateblock(self.nodes[1].getbestblockhash()) # Now check that the transaction is in the mempool, with the right modified fee mempool = self.nodes[0].getrawmempool(True) descendant_fees = 0 for x in reversed(chain): descendant_fees += mempool[x]['fee'] if (x == chain[-1]): assert_equal(mempool[x]['modifiedfee'], mempool[x]['fee']+satoshi_round(0.00002)) assert_equal(mempool[x]['descendantfees'], descendant_fees * COIN + 2000) # TODO: check that node1's mempool is as expected # TODO: test ancestor size limits # Now test descendant chain limits txid = utxo[1]['txid'] value = utxo[1]['amount'] vout = utxo[1]['vout'] transaction_package = [] # First create one parent tx with 10 children (txid, sent_value) = self.chain_transaction(self.nodes[0], txid, vout, value, fee, 10) parent_transaction = txid for i in range(10): transaction_package.append({'txid': txid, 'vout': i, 'amount': sent_value}) for i in range(MAX_DESCENDANTS): utxo = transaction_package.pop(0) try: (txid, sent_value) = self.chain_transaction(self.nodes[0], utxo['txid'], utxo['vout'], utxo['amount'], fee, 10) for j in range(10): transaction_package.append({'txid': txid, 'vout': j, 'amount': sent_value}) if i == MAX_DESCENDANTS - 2: mempool = self.nodes[0].getrawmempool(True) assert_equal(mempool[parent_transaction]['descendantcount'], MAX_DESCENDANTS) except JSONRPCException as e: print(e.error['message']) assert_equal(i, MAX_DESCENDANTS - 1) print("tx that would create too large descendant package successfully rejected") # TODO: check that node1's mempool is as expected # TODO: test descendant size limits # Test reorg handling # First, the basics: self.nodes[0].generate(1) sync_blocks(self.nodes) self.nodes[1].invalidateblock(self.nodes[0].getbestblockhash()) self.nodes[1].reconsiderblock(self.nodes[0].getbestblockhash()) # Now test the case where node1 has a transaction T in its mempool that # depends on transactions A and B which are in a mined block, and the # block containing A and B is disconnected, AND B is not accepted back # into node1's mempool because its ancestor count is too high. # Create 8 transactions, like so: # Tx0 -> Tx1 (vout0) # \--> Tx2 (vout1) -> Tx3 -> Tx4 -> Tx5 -> Tx6 -> Tx7 # # Mine them in the next block, then generate a new tx8 that spends # Tx1 and Tx7, and add to node1's mempool, then disconnect the # last block. # Create tx0 with 2 outputs utxo = self.nodes[0].listunspent() txid = utxo[0]['txid'] value = utxo[0]['amount'] vout = utxo[0]['vout'] send_value = satoshi_round((value - fee)/2) inputs = [ {'txid' : txid, 'vout' : vout} ] outputs = {} for i in range(2): outputs[self.nodes[0].getnewaddress()] = send_value rawtx = self.nodes[0].createrawtransaction(inputs, outputs) signedtx = self.nodes[0].signrawtransaction(rawtx) txid = self.nodes[0].sendrawtransaction(signedtx['hex']) tx0_id = txid value = send_value # Create tx1 (tx1_id, tx1_value) = self.chain_transaction(self.nodes[0], tx0_id, 0, value, fee, 1) # Create tx2-7 vout = 1 txid = tx0_id for i in range(6): (txid, sent_value) = self.chain_transaction(self.nodes[0], txid, vout, value, fee, 1) vout = 0 value = sent_value # Mine these in a block self.nodes[0].generate(1) self.sync_all() # Now generate tx8, with a big fee inputs = [ {'txid' : tx1_id, 'vout': 0}, {'txid' : txid, 'vout': 0} ] outputs = { self.nodes[0].getnewaddress() : send_value + value - 4*fee } rawtx = self.nodes[0].createrawtransaction(inputs, outputs) signedtx = self.nodes[0].signrawtransaction(rawtx) txid = self.nodes[0].sendrawtransaction(signedtx['hex']) sync_mempools(self.nodes) # Now try to disconnect the tip on each node... self.nodes[1].invalidateblock(self.nodes[1].getbestblockhash()) self.nodes[0].invalidateblock(self.nodes[0].getbestblockhash()) sync_blocks(self.nodes) if __name__ == '__main__': MempoolPackagesTest().main()
mit
hgl888/chromium-crosswalk-efl
remoting/tools/build/remoting_localize.py
56
26845
#!/usr/bin/env python # Copyright 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ localize.py -- Generates an output file from the given template replacing variables and localizing strings. The script uses Jinja2 template processing library (src/third_party/jinja2). Variables available to the templates: - |languages| - the list of languages passed on the command line. ('-l'). - Each NAME=VALUE define ('-d') can be accesses as {{ NAME }}. - |official_build| is set to '1' when CHROME_BUILD_TYPE environment variable is set to "_official". Filters: - GetCodepage - returns the code page for the given language. - GetCodepageDecimal same as GetCodepage, but returns a decimal value. - GetLangId - returns Win32 LANGID. - GetPrimaryLanguage - returns a named Win32 constant specifing the primary language ID. - GetSublanguage - returns a named Win32 constant specifing the sublanguage ID. Globals: - IsRtlLanguage(language) - returns True if the language is right-to-left. - SelectLanguage(language) - allows to select the language to the used by {% trans %}{% endtrans %} statements. """ import io import json from optparse import OptionParser import os import sys from string import Template # Win32 primary languages IDs. _LANGUAGE_PRIMARY = { 'LANG_NEUTRAL' : 0x00, 'LANG_INVARIANT' : 0x7f, 'LANG_AFRIKAANS' : 0x36, 'LANG_ALBANIAN' : 0x1c, 'LANG_ALSATIAN' : 0x84, 'LANG_AMHARIC' : 0x5e, 'LANG_ARABIC' : 0x01, 'LANG_ARMENIAN' : 0x2b, 'LANG_ASSAMESE' : 0x4d, 'LANG_AZERI' : 0x2c, 'LANG_BASHKIR' : 0x6d, 'LANG_BASQUE' : 0x2d, 'LANG_BELARUSIAN' : 0x23, 'LANG_BENGALI' : 0x45, 'LANG_BRETON' : 0x7e, 'LANG_BOSNIAN' : 0x1a, 'LANG_BULGARIAN' : 0x02, 'LANG_CATALAN' : 0x03, 'LANG_CHINESE' : 0x04, 'LANG_CORSICAN' : 0x83, 'LANG_CROATIAN' : 0x1a, 'LANG_CZECH' : 0x05, 'LANG_DANISH' : 0x06, 'LANG_DARI' : 0x8c, 'LANG_DIVEHI' : 0x65, 'LANG_DUTCH' : 0x13, 'LANG_ENGLISH' : 0x09, 'LANG_ESTONIAN' : 0x25, 'LANG_FAEROESE' : 0x38, 'LANG_FILIPINO' : 0x64, 'LANG_FINNISH' : 0x0b, 'LANG_FRENCH' : 0x0c, 'LANG_FRISIAN' : 0x62, 'LANG_GALICIAN' : 0x56, 'LANG_GEORGIAN' : 0x37, 'LANG_GERMAN' : 0x07, 'LANG_GREEK' : 0x08, 'LANG_GREENLANDIC' : 0x6f, 'LANG_GUJARATI' : 0x47, 'LANG_HAUSA' : 0x68, 'LANG_HEBREW' : 0x0d, 'LANG_HINDI' : 0x39, 'LANG_HUNGARIAN' : 0x0e, 'LANG_ICELANDIC' : 0x0f, 'LANG_IGBO' : 0x70, 'LANG_INDONESIAN' : 0x21, 'LANG_INUKTITUT' : 0x5d, 'LANG_IRISH' : 0x3c, 'LANG_ITALIAN' : 0x10, 'LANG_JAPANESE' : 0x11, 'LANG_KANNADA' : 0x4b, 'LANG_KASHMIRI' : 0x60, 'LANG_KAZAK' : 0x3f, 'LANG_KHMER' : 0x53, 'LANG_KICHE' : 0x86, 'LANG_KINYARWANDA' : 0x87, 'LANG_KONKANI' : 0x57, 'LANG_KOREAN' : 0x12, 'LANG_KYRGYZ' : 0x40, 'LANG_LAO' : 0x54, 'LANG_LATVIAN' : 0x26, 'LANG_LITHUANIAN' : 0x27, 'LANG_LOWER_SORBIAN' : 0x2e, 'LANG_LUXEMBOURGISH' : 0x6e, 'LANG_MACEDONIAN' : 0x2f, 'LANG_MALAY' : 0x3e, 'LANG_MALAYALAM' : 0x4c, 'LANG_MALTESE' : 0x3a, 'LANG_MANIPURI' : 0x58, 'LANG_MAORI' : 0x81, 'LANG_MAPUDUNGUN' : 0x7a, 'LANG_MARATHI' : 0x4e, 'LANG_MOHAWK' : 0x7c, 'LANG_MONGOLIAN' : 0x50, 'LANG_NEPALI' : 0x61, 'LANG_NORWEGIAN' : 0x14, 'LANG_OCCITAN' : 0x82, 'LANG_ORIYA' : 0x48, 'LANG_PASHTO' : 0x63, 'LANG_PERSIAN' : 0x29, 'LANG_POLISH' : 0x15, 'LANG_PORTUGUESE' : 0x16, 'LANG_PUNJABI' : 0x46, 'LANG_QUECHUA' : 0x6b, 'LANG_ROMANIAN' : 0x18, 'LANG_ROMANSH' : 0x17, 'LANG_RUSSIAN' : 0x19, 'LANG_SAMI' : 0x3b, 'LANG_SANSKRIT' : 0x4f, 'LANG_SCOTTISH_GAELIC' : 0x91, 'LANG_SERBIAN' : 0x1a, 'LANG_SINDHI' : 0x59, 'LANG_SINHALESE' : 0x5b, 'LANG_SLOVAK' : 0x1b, 'LANG_SLOVENIAN' : 0x24, 'LANG_SOTHO' : 0x6c, 'LANG_SPANISH' : 0x0a, 'LANG_SWAHILI' : 0x41, 'LANG_SWEDISH' : 0x1d, 'LANG_SYRIAC' : 0x5a, 'LANG_TAJIK' : 0x28, 'LANG_TAMAZIGHT' : 0x5f, 'LANG_TAMIL' : 0x49, 'LANG_TATAR' : 0x44, 'LANG_TELUGU' : 0x4a, 'LANG_THAI' : 0x1e, 'LANG_TIBETAN' : 0x51, 'LANG_TIGRIGNA' : 0x73, 'LANG_TSWANA' : 0x32, 'LANG_TURKISH' : 0x1f, 'LANG_TURKMEN' : 0x42, 'LANG_UIGHUR' : 0x80, 'LANG_UKRAINIAN' : 0x22, 'LANG_UPPER_SORBIAN' : 0x2e, 'LANG_URDU' : 0x20, 'LANG_UZBEK' : 0x43, 'LANG_VIETNAMESE' : 0x2a, 'LANG_WELSH' : 0x52, 'LANG_WOLOF' : 0x88, 'LANG_XHOSA' : 0x34, 'LANG_YAKUT' : 0x85, 'LANG_YI' : 0x78, 'LANG_YORUBA' : 0x6a, 'LANG_ZULU' : 0x35, } # Win32 sublanguage IDs. _LANGUAGE_SUB = { 'SUBLANG_NEUTRAL' : 0x00, 'SUBLANG_DEFAULT' : 0x01, 'SUBLANG_SYS_DEFAULT' : 0x02, 'SUBLANG_CUSTOM_DEFAULT' : 0x03, 'SUBLANG_CUSTOM_UNSPECIFIED' : 0x04, 'SUBLANG_UI_CUSTOM_DEFAULT' : 0x05, 'SUBLANG_AFRIKAANS_SOUTH_AFRICA' : 0x01, 'SUBLANG_ALBANIAN_ALBANIA' : 0x01, 'SUBLANG_ALSATIAN_FRANCE' : 0x01, 'SUBLANG_AMHARIC_ETHIOPIA' : 0x01, 'SUBLANG_ARABIC_SAUDI_ARABIA' : 0x01, 'SUBLANG_ARABIC_IRAQ' : 0x02, 'SUBLANG_ARABIC_EGYPT' : 0x03, 'SUBLANG_ARABIC_LIBYA' : 0x04, 'SUBLANG_ARABIC_ALGERIA' : 0x05, 'SUBLANG_ARABIC_MOROCCO' : 0x06, 'SUBLANG_ARABIC_TUNISIA' : 0x07, 'SUBLANG_ARABIC_OMAN' : 0x08, 'SUBLANG_ARABIC_YEMEN' : 0x09, 'SUBLANG_ARABIC_SYRIA' : 0x0a, 'SUBLANG_ARABIC_JORDAN' : 0x0b, 'SUBLANG_ARABIC_LEBANON' : 0x0c, 'SUBLANG_ARABIC_KUWAIT' : 0x0d, 'SUBLANG_ARABIC_UAE' : 0x0e, 'SUBLANG_ARABIC_BAHRAIN' : 0x0f, 'SUBLANG_ARABIC_QATAR' : 0x10, 'SUBLANG_ARMENIAN_ARMENIA' : 0x01, 'SUBLANG_ASSAMESE_INDIA' : 0x01, 'SUBLANG_AZERI_LATIN' : 0x01, 'SUBLANG_AZERI_CYRILLIC' : 0x02, 'SUBLANG_BASHKIR_RUSSIA' : 0x01, 'SUBLANG_BASQUE_BASQUE' : 0x01, 'SUBLANG_BELARUSIAN_BELARUS' : 0x01, 'SUBLANG_BENGALI_INDIA' : 0x01, 'SUBLANG_BENGALI_BANGLADESH' : 0x02, 'SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_LATIN' : 0x05, 'SUBLANG_BOSNIAN_BOSNIA_HERZEGOVINA_CYRILLIC' : 0x08, 'SUBLANG_BRETON_FRANCE' : 0x01, 'SUBLANG_BULGARIAN_BULGARIA' : 0x01, 'SUBLANG_CATALAN_CATALAN' : 0x01, 'SUBLANG_CHINESE_TRADITIONAL' : 0x01, 'SUBLANG_CHINESE_SIMPLIFIED' : 0x02, 'SUBLANG_CHINESE_HONGKONG' : 0x03, 'SUBLANG_CHINESE_SINGAPORE' : 0x04, 'SUBLANG_CHINESE_MACAU' : 0x05, 'SUBLANG_CORSICAN_FRANCE' : 0x01, 'SUBLANG_CZECH_CZECH_REPUBLIC' : 0x01, 'SUBLANG_CROATIAN_CROATIA' : 0x01, 'SUBLANG_CROATIAN_BOSNIA_HERZEGOVINA_LATIN' : 0x04, 'SUBLANG_DANISH_DENMARK' : 0x01, 'SUBLANG_DARI_AFGHANISTAN' : 0x01, 'SUBLANG_DIVEHI_MALDIVES' : 0x01, 'SUBLANG_DUTCH' : 0x01, 'SUBLANG_DUTCH_BELGIAN' : 0x02, 'SUBLANG_ENGLISH_US' : 0x01, 'SUBLANG_ENGLISH_UK' : 0x02, 'SUBLANG_ENGLISH_AUS' : 0x03, 'SUBLANG_ENGLISH_CAN' : 0x04, 'SUBLANG_ENGLISH_NZ' : 0x05, 'SUBLANG_ENGLISH_EIRE' : 0x06, 'SUBLANG_ENGLISH_SOUTH_AFRICA' : 0x07, 'SUBLANG_ENGLISH_JAMAICA' : 0x08, 'SUBLANG_ENGLISH_CARIBBEAN' : 0x09, 'SUBLANG_ENGLISH_BELIZE' : 0x0a, 'SUBLANG_ENGLISH_TRINIDAD' : 0x0b, 'SUBLANG_ENGLISH_ZIMBABWE' : 0x0c, 'SUBLANG_ENGLISH_PHILIPPINES' : 0x0d, 'SUBLANG_ENGLISH_INDIA' : 0x10, 'SUBLANG_ENGLISH_MALAYSIA' : 0x11, 'SUBLANG_ENGLISH_SINGAPORE' : 0x12, 'SUBLANG_ESTONIAN_ESTONIA' : 0x01, 'SUBLANG_FAEROESE_FAROE_ISLANDS' : 0x01, 'SUBLANG_FILIPINO_PHILIPPINES' : 0x01, 'SUBLANG_FINNISH_FINLAND' : 0x01, 'SUBLANG_FRENCH' : 0x01, 'SUBLANG_FRENCH_BELGIAN' : 0x02, 'SUBLANG_FRENCH_CANADIAN' : 0x03, 'SUBLANG_FRENCH_SWISS' : 0x04, 'SUBLANG_FRENCH_LUXEMBOURG' : 0x05, 'SUBLANG_FRENCH_MONACO' : 0x06, 'SUBLANG_FRISIAN_NETHERLANDS' : 0x01, 'SUBLANG_GALICIAN_GALICIAN' : 0x01, 'SUBLANG_GEORGIAN_GEORGIA' : 0x01, 'SUBLANG_GERMAN' : 0x01, 'SUBLANG_GERMAN_SWISS' : 0x02, 'SUBLANG_GERMAN_AUSTRIAN' : 0x03, 'SUBLANG_GERMAN_LUXEMBOURG' : 0x04, 'SUBLANG_GERMAN_LIECHTENSTEIN' : 0x05, 'SUBLANG_GREEK_GREECE' : 0x01, 'SUBLANG_GREENLANDIC_GREENLAND' : 0x01, 'SUBLANG_GUJARATI_INDIA' : 0x01, 'SUBLANG_HAUSA_NIGERIA_LATIN' : 0x01, 'SUBLANG_HEBREW_ISRAEL' : 0x01, 'SUBLANG_HINDI_INDIA' : 0x01, 'SUBLANG_HUNGARIAN_HUNGARY' : 0x01, 'SUBLANG_ICELANDIC_ICELAND' : 0x01, 'SUBLANG_IGBO_NIGERIA' : 0x01, 'SUBLANG_INDONESIAN_INDONESIA' : 0x01, 'SUBLANG_INUKTITUT_CANADA' : 0x01, 'SUBLANG_INUKTITUT_CANADA_LATIN' : 0x02, 'SUBLANG_IRISH_IRELAND' : 0x02, 'SUBLANG_ITALIAN' : 0x01, 'SUBLANG_ITALIAN_SWISS' : 0x02, 'SUBLANG_JAPANESE_JAPAN' : 0x01, 'SUBLANG_KANNADA_INDIA' : 0x01, 'SUBLANG_KASHMIRI_SASIA' : 0x02, 'SUBLANG_KASHMIRI_INDIA' : 0x02, 'SUBLANG_KAZAK_KAZAKHSTAN' : 0x01, 'SUBLANG_KHMER_CAMBODIA' : 0x01, 'SUBLANG_KICHE_GUATEMALA' : 0x01, 'SUBLANG_KINYARWANDA_RWANDA' : 0x01, 'SUBLANG_KONKANI_INDIA' : 0x01, 'SUBLANG_KOREAN' : 0x01, 'SUBLANG_KYRGYZ_KYRGYZSTAN' : 0x01, 'SUBLANG_LAO_LAO' : 0x01, 'SUBLANG_LATVIAN_LATVIA' : 0x01, 'SUBLANG_LITHUANIAN' : 0x01, 'SUBLANG_LOWER_SORBIAN_GERMANY' : 0x02, 'SUBLANG_LUXEMBOURGISH_LUXEMBOURG' : 0x01, 'SUBLANG_MACEDONIAN_MACEDONIA' : 0x01, 'SUBLANG_MALAY_MALAYSIA' : 0x01, 'SUBLANG_MALAY_BRUNEI_DARUSSALAM' : 0x02, 'SUBLANG_MALAYALAM_INDIA' : 0x01, 'SUBLANG_MALTESE_MALTA' : 0x01, 'SUBLANG_MAORI_NEW_ZEALAND' : 0x01, 'SUBLANG_MAPUDUNGUN_CHILE' : 0x01, 'SUBLANG_MARATHI_INDIA' : 0x01, 'SUBLANG_MOHAWK_MOHAWK' : 0x01, 'SUBLANG_MONGOLIAN_CYRILLIC_MONGOLIA' : 0x01, 'SUBLANG_MONGOLIAN_PRC' : 0x02, 'SUBLANG_NEPALI_INDIA' : 0x02, 'SUBLANG_NEPALI_NEPAL' : 0x01, 'SUBLANG_NORWEGIAN_BOKMAL' : 0x01, 'SUBLANG_NORWEGIAN_NYNORSK' : 0x02, 'SUBLANG_OCCITAN_FRANCE' : 0x01, 'SUBLANG_ORIYA_INDIA' : 0x01, 'SUBLANG_PASHTO_AFGHANISTAN' : 0x01, 'SUBLANG_PERSIAN_IRAN' : 0x01, 'SUBLANG_POLISH_POLAND' : 0x01, 'SUBLANG_PORTUGUESE' : 0x02, 'SUBLANG_PORTUGUESE_BRAZILIAN' : 0x01, 'SUBLANG_PUNJABI_INDIA' : 0x01, 'SUBLANG_QUECHUA_BOLIVIA' : 0x01, 'SUBLANG_QUECHUA_ECUADOR' : 0x02, 'SUBLANG_QUECHUA_PERU' : 0x03, 'SUBLANG_ROMANIAN_ROMANIA' : 0x01, 'SUBLANG_ROMANSH_SWITZERLAND' : 0x01, 'SUBLANG_RUSSIAN_RUSSIA' : 0x01, 'SUBLANG_SAMI_NORTHERN_NORWAY' : 0x01, 'SUBLANG_SAMI_NORTHERN_SWEDEN' : 0x02, 'SUBLANG_SAMI_NORTHERN_FINLAND' : 0x03, 'SUBLANG_SAMI_LULE_NORWAY' : 0x04, 'SUBLANG_SAMI_LULE_SWEDEN' : 0x05, 'SUBLANG_SAMI_SOUTHERN_NORWAY' : 0x06, 'SUBLANG_SAMI_SOUTHERN_SWEDEN' : 0x07, 'SUBLANG_SAMI_SKOLT_FINLAND' : 0x08, 'SUBLANG_SAMI_INARI_FINLAND' : 0x09, 'SUBLANG_SANSKRIT_INDIA' : 0x01, 'SUBLANG_SCOTTISH_GAELIC' : 0x01, 'SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_LATIN' : 0x06, 'SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC' : 0x07, 'SUBLANG_SERBIAN_MONTENEGRO_LATIN' : 0x0b, 'SUBLANG_SERBIAN_MONTENEGRO_CYRILLIC' : 0x0c, 'SUBLANG_SERBIAN_SERBIA_LATIN' : 0x09, 'SUBLANG_SERBIAN_SERBIA_CYRILLIC' : 0x0a, 'SUBLANG_SERBIAN_CROATIA' : 0x01, 'SUBLANG_SERBIAN_LATIN' : 0x02, 'SUBLANG_SERBIAN_CYRILLIC' : 0x03, 'SUBLANG_SINDHI_INDIA' : 0x01, 'SUBLANG_SINDHI_PAKISTAN' : 0x02, 'SUBLANG_SINDHI_AFGHANISTAN' : 0x02, 'SUBLANG_SINHALESE_SRI_LANKA' : 0x01, 'SUBLANG_SOTHO_NORTHERN_SOUTH_AFRICA' : 0x01, 'SUBLANG_SLOVAK_SLOVAKIA' : 0x01, 'SUBLANG_SLOVENIAN_SLOVENIA' : 0x01, 'SUBLANG_SPANISH' : 0x01, 'SUBLANG_SPANISH_MEXICAN' : 0x02, 'SUBLANG_SPANISH_MODERN' : 0x03, 'SUBLANG_SPANISH_GUATEMALA' : 0x04, 'SUBLANG_SPANISH_COSTA_RICA' : 0x05, 'SUBLANG_SPANISH_PANAMA' : 0x06, 'SUBLANG_SPANISH_DOMINICAN_REPUBLIC' : 0x07, 'SUBLANG_SPANISH_VENEZUELA' : 0x08, 'SUBLANG_SPANISH_COLOMBIA' : 0x09, 'SUBLANG_SPANISH_PERU' : 0x0a, 'SUBLANG_SPANISH_ARGENTINA' : 0x0b, 'SUBLANG_SPANISH_ECUADOR' : 0x0c, 'SUBLANG_SPANISH_CHILE' : 0x0d, 'SUBLANG_SPANISH_URUGUAY' : 0x0e, 'SUBLANG_SPANISH_PARAGUAY' : 0x0f, 'SUBLANG_SPANISH_BOLIVIA' : 0x10, 'SUBLANG_SPANISH_EL_SALVADOR' : 0x11, 'SUBLANG_SPANISH_HONDURAS' : 0x12, 'SUBLANG_SPANISH_NICARAGUA' : 0x13, 'SUBLANG_SPANISH_PUERTO_RICO' : 0x14, 'SUBLANG_SPANISH_US' : 0x15, 'SUBLANG_SWAHILI_KENYA' : 0x01, 'SUBLANG_SWEDISH' : 0x01, 'SUBLANG_SWEDISH_FINLAND' : 0x02, 'SUBLANG_SYRIAC_SYRIA' : 0x01, 'SUBLANG_TAJIK_TAJIKISTAN' : 0x01, 'SUBLANG_TAMAZIGHT_ALGERIA_LATIN' : 0x02, 'SUBLANG_TAMIL_INDIA' : 0x01, 'SUBLANG_TATAR_RUSSIA' : 0x01, 'SUBLANG_TELUGU_INDIA' : 0x01, 'SUBLANG_THAI_THAILAND' : 0x01, 'SUBLANG_TIBETAN_PRC' : 0x01, 'SUBLANG_TIGRIGNA_ERITREA' : 0x02, 'SUBLANG_TSWANA_SOUTH_AFRICA' : 0x01, 'SUBLANG_TURKISH_TURKEY' : 0x01, 'SUBLANG_TURKMEN_TURKMENISTAN' : 0x01, 'SUBLANG_UIGHUR_PRC' : 0x01, 'SUBLANG_UKRAINIAN_UKRAINE' : 0x01, 'SUBLANG_UPPER_SORBIAN_GERMANY' : 0x01, 'SUBLANG_URDU_PAKISTAN' : 0x01, 'SUBLANG_URDU_INDIA' : 0x02, 'SUBLANG_UZBEK_LATIN' : 0x01, 'SUBLANG_UZBEK_CYRILLIC' : 0x02, 'SUBLANG_VIETNAMESE_VIETNAM' : 0x01, 'SUBLANG_WELSH_UNITED_KINGDOM' : 0x01, 'SUBLANG_WOLOF_SENEGAL' : 0x01, 'SUBLANG_XHOSA_SOUTH_AFRICA' : 0x01, 'SUBLANG_YAKUT_RUSSIA' : 0x01, 'SUBLANG_YI_PRC' : 0x01, 'SUBLANG_YORUBA_NIGERIA' : 0x01, 'SUBLANG_ZULU_SOUTH_AFRICA' : 0x01, } ''' This dictionary defines the language lookup table. The key is the language ISO country code, and the value specifies the corresponding code page, primary language and sublanguage. LCID resource: http://msdn.microsoft.com/en-us/library/ms776294.aspx Codepage resource: http://www.science.co.il/language/locale-codes.asp Language ID resource: http://msdn.microsoft.com/en-us/library/ms776294.aspx There is no appropriate sublang for Spanish (Latin America) [es-419], so we use Mexico. SUBLANG_DEFAULT would incorrectly map to Spain. Unlike other Latin American countries, Mexican Spanish is supported by VERSIONINFO: http://msdn.microsoft.com/en-us/library/aa381058.aspx ''' _LANGUAGE_MAP = { # Language neutral LCID, unicode(1200) code page. 'neutral' : [ 1200, 'LANG_NEUTRAL', 'SUBLANG_NEUTRAL' ], # LANG_USER_DEFAULT LCID, unicode(1200) code page. 'userdefault' : [ 1200, 'LANG_NEUTRAL', 'SUBLANG_DEFAULT' ], 'fake-bidi' : [ 1255, 'LANG_HEBREW', 'SUBLANG_DEFAULT' ], 'af' : [ 1252, 'LANG_AFRIKAANS', 'SUBLANG_DEFAULT' ], 'am' : [ 1200, 'LANG_AMHARIC', 'SUBLANG_DEFAULT' ], 'ar' : [ 1256, 'LANG_ARABIC', 'SUBLANG_DEFAULT' ], 'bg' : [ 1251, 'LANG_BULGARIAN', 'SUBLANG_DEFAULT' ], 'bn' : [ 1200, 'LANG_BENGALI', 'SUBLANG_DEFAULT' ], 'ca' : [ 1252, 'LANG_CATALAN', 'SUBLANG_DEFAULT' ], 'cs' : [ 1250, 'LANG_CZECH', 'SUBLANG_DEFAULT' ], 'da' : [ 1252, 'LANG_DANISH', 'SUBLANG_DEFAULT' ], 'de' : [ 1252, 'LANG_GERMAN', 'SUBLANG_GERMAN' ], 'el' : [ 1253, 'LANG_GREEK', 'SUBLANG_DEFAULT' ], 'en' : [ 1200, 'LANG_ENGLISH', 'SUBLANG_ENGLISH_US' ], 'en-GB' : [ 1038, 'LANG_ENGLISH', 'SUBLANG_ENGLISH_UK' ], 'es' : [ 1252, 'LANG_SPANISH', 'SUBLANG_SPANISH_MODERN' ], # LCID for Mexico; Windows does not support L.A. LCID. 'es-419' : [ 1252, 'LANG_SPANISH', 'SUBLANG_SPANISH_MEXICAN' ], 'et' : [ 1257, 'LANG_ESTONIAN', 'SUBLANG_DEFAULT' ], 'eu' : [ 1252, 'LANG_BASQUE', 'SUBLANG_DEFAULT' ], 'fa' : [ 1256, 'LANG_PERSIAN', 'SUBLANG_DEFAULT' ], 'fi' : [ 1252, 'LANG_FINNISH', 'SUBLANG_DEFAULT' ], 'fil' : [ 1252, 'LANG_FILIPINO', 'SUBLANG_DEFAULT' ], 'fr' : [ 1252, 'LANG_FRENCH', 'SUBLANG_FRENCH' ], 'fr-CA' : [ 1252, 'LANG_FRENCH', 'SUBLANG_FRENCH_CANADIAN' ], 'gl' : [ 1252, 'LANG_GALICIAN', 'SUBLANG_DEFAULT' ], 'gu' : [ 1200, 'LANG_GUJARATI', 'SUBLANG_DEFAULT' ], 'he' : [ 1255, 'LANG_HEBREW', 'SUBLANG_DEFAULT' ], 'hi' : [ 1200, 'LANG_HINDI', 'SUBLANG_DEFAULT' ], 'hr' : [ 1252, 'LANG_CROATIAN', 'SUBLANG_DEFAULT' ], 'hu' : [ 1250, 'LANG_HUNGARIAN', 'SUBLANG_DEFAULT' ], 'id' : [ 1252, 'LANG_INDONESIAN', 'SUBLANG_DEFAULT' ], 'is' : [ 1252, 'LANG_ICELANDIC', 'SUBLANG_DEFAULT' ], 'it' : [ 1252, 'LANG_ITALIAN', 'SUBLANG_DEFAULT' ], 'iw' : [ 1255, 'LANG_HEBREW', 'SUBLANG_DEFAULT' ], 'ja' : [ 932, 'LANG_JAPANESE', 'SUBLANG_DEFAULT' ], 'kn' : [ 1200, 'LANG_KANNADA', 'SUBLANG_DEFAULT' ], 'ko' : [ 949, 'LANG_KOREAN', 'SUBLANG_KOREAN' ], 'lt' : [ 1257, 'LANG_LITHUANIAN', 'SUBLANG_LITHUANIAN' ], 'lv' : [ 1257, 'LANG_LATVIAN', 'SUBLANG_DEFAULT' ], 'ml' : [ 1200, 'LANG_MALAYALAM', 'SUBLANG_DEFAULT' ], 'mr' : [ 1200, 'LANG_MARATHI', 'SUBLANG_DEFAULT' ], # Malay (Malaysia) [ms-MY] 'ms' : [ 1252, 'LANG_MALAY', 'SUBLANG_DEFAULT' ], 'nb' : [ 1252, 'LANG_NORWEGIAN', 'SUBLANG_NORWEGIAN_BOKMAL' ], 'ne' : [ 1200, 'LANG_NEPALI', 'SUBLANG_NEPALI_NEPAL' ], 'nl' : [ 1252, 'LANG_DUTCH', 'SUBLANG_DEFAULT' ], 'nn' : [ 1252, 'LANG_NORWEGIAN', 'SUBLANG_NORWEGIAN_NYNORSK' ], 'no' : [ 1252, 'LANG_NORWEGIAN', 'SUBLANG_DEFAULT' ], 'or' : [ 1200, 'LANG_ORIYA', 'SUBLANG_DEFAULT' ], 'pa' : [ 1200, 'LANG_PUNJABI', 'SUBLANG_PUNJABI_INDIA' ], 'pl' : [ 1250, 'LANG_POLISH', 'SUBLANG_DEFAULT' ], 'pt-BR' : [ 1252, 'LANG_PORTUGUESE', 'SUBLANG_DEFAULT' ], 'pt-PT' : [ 1252, 'LANG_PORTUGUESE', 'SUBLANG_PORTUGUESE' ], 'ro' : [ 1250, 'LANG_ROMANIAN', 'SUBLANG_DEFAULT' ], 'ru' : [ 1251, 'LANG_RUSSIAN', 'SUBLANG_DEFAULT' ], 'sa' : [ 1200, 'LANG_SANSKRIT', 'SUBLANG_SANSKRIT_INDIA' ], 'si' : [ 1200, 'LANG_SINHALESE', 'SUBLANG_SINHALESE_SRI_LANKA' ], 'sk' : [ 1250, 'LANG_SLOVAK', 'SUBLANG_DEFAULT' ], 'sl' : [ 1250, 'LANG_SLOVENIAN', 'SUBLANG_DEFAULT' ], 'sr' : [ 1250, 'LANG_SERBIAN', 'SUBLANG_SERBIAN_LATIN' ], 'sv' : [ 1252, 'LANG_SWEDISH', 'SUBLANG_SWEDISH' ], 'sw' : [ 1252, 'LANG_SWAHILI', 'SUBLANG_DEFAULT' ], 'ta' : [ 1200, 'LANG_TAMIL', 'SUBLANG_DEFAULT' ], 'te' : [ 1200, 'LANG_TELUGU', 'SUBLANG_DEFAULT' ], 'th' : [ 874, 'LANG_THAI', 'SUBLANG_DEFAULT' ], 'ti' : [ 1200, 'LANG_TIGRIGNA', 'SUBLANG_TIGRIGNA_ERITREA' ], 'tr' : [ 1254, 'LANG_TURKISH', 'SUBLANG_DEFAULT' ], 'uk' : [ 1251, 'LANG_UKRAINIAN', 'SUBLANG_DEFAULT' ], 'ur' : [ 1200, 'LANG_URDU', 'SUBLANG_DEFAULT' ], 'vi' : [ 1258, 'LANG_VIETNAMESE', 'SUBLANG_DEFAULT' ], 'zh-CN' : [ 936, 'LANG_CHINESE', 'SUBLANG_CHINESE_SIMPLIFIED' ], 'zh-HK' : [ 950, 'LANG_CHINESE', 'SUBLANG_CHINESE_HONGKONG' ], 'zh-TW' : [ 950, 'LANG_CHINESE', 'SUBLANG_CHINESE_TRADITIONAL' ], 'zu' : [ 1200, 'LANG_ZULU', 'SUBLANG_DEFAULT' ], } # Right-To-Left languages _RTL_LANGUAGES = ( 'ar', # Arabic 'fa', # Farsi 'iw', # Hebrew 'ks', # Kashmiri 'ku', # Kurdish 'ps', # Pashto 'ur', # Urdu 'yi', # Yiddish ) def GetCodepage(language): """ Returns the codepage for the given |language|. """ lang = _LANGUAGE_MAP[language] return "%04x" % lang[0] def GetCodepageDecimal(language): """ Returns the codepage for the given |language| as a decimal value. """ lang = _LANGUAGE_MAP[language] return "%d" % lang[0] def GetLangId(language): """ Returns the language id for the given |language|. """ lang = _LANGUAGE_MAP[language] return "%04x" % (_LANGUAGE_PRIMARY[lang[1]] | (_LANGUAGE_SUB[lang[2]] << 10)) def GetPrimaryLanguage(language): """ Returns the primary language ID for the given |language|. """ lang = _LANGUAGE_MAP[language] return _LANGUAGE_PRIMARY[lang[1]] def GetSublanguage(language): """ Returns the sublanguage ID for the given |language|. """ lang = _LANGUAGE_MAP[language] return _LANGUAGE_SUB[lang[2]] def IsRtlLanguage(language): return language in _RTL_LANGUAGES; def NormalizeLanguageCode(language): lang = language.replace('_', '-', 1) if lang == 'en-US': lang = 'en' return lang def GetDataPackageSuffix(language): lang = NormalizeLanguageCode(language) if lang == 'en': lang = 'en-US' return lang def GetJsonSuffix(language): return language.replace('-', '_', 1) def ReadValuesFromFile(values_dict, file_name): """ Reads NAME=VALUE settings from the specified file. Everything to the left of the first '=' is the keyword, everything to the right is the value. No stripping of white space, so beware. The file must exist, otherwise you get the Python exception from open(). """ for line in open(file_name, 'r').readlines(): key, val = line.rstrip('\r\n').split('=', 1) values_dict[key] = val def ReadMessagesFromFile(file_name): """ Reads messages from a 'chrome_messages_json' file. The file must exist, otherwise you get the Python exception from open(). """ messages_file = io.open(file_name, encoding='utf-8-sig') messages = json.load(messages_file) messages_file.close() values = {} for key in messages.keys(): values[key] = unicode(messages[key]['message']); return values def WriteIfChanged(file_name, contents, encoding): """ Writes the specified contents to the specified file_name iff the contents are different than the current contents. """ try: target = io.open(file_name, 'r') old_contents = target.read() except EnvironmentError: pass except UnicodeDecodeError: target.close() os.unlink(file_name) else: if contents == old_contents: return target.close() os.unlink(file_name) io.open(file_name, 'w', encoding=encoding).write(contents) class MessageMap: """ Provides a dictionary of localized messages for each language.""" def __init__(self, languages, locale_dir): self.language = None self.message_map = {} # Populate the message map if locale_dir: for language in languages: file_name = os.path.join(locale_dir, GetJsonSuffix(language), 'messages.json') self.message_map[language] = ReadMessagesFromFile(file_name) def GetText(self, message): """ Returns a localized message for the current language. """ return self.message_map[self.language][message] def SelectLanguage(self, language): """ Selects the language to be used when retrieving localized messages. """ self.language = language def MakeSelectLanguage(self): """ Returns a function that can be used to select the current language. """ return lambda language: self.SelectLanguage(language) def MakeGetText(self): """ Returns a function that can be used to retrieve a localized message. """ return lambda message: self.GetText(message) # Use '@' as a delimiter for string templates instead of '$' to avoid unintended # expansion when passing the string from GYP. class GypTemplate(Template): delimiter = '@' def Localize(source, locales, options): # Set the list of languages to use. languages = map(NormalizeLanguageCode, locales) context = { 'languages' : languages } # Load the localized messages. message_map = MessageMap(languages, options.locale_dir) # Add OFFICIAL_BUILD variable the same way build/util/version.py # does. if os.environ.get('CHROME_BUILD_TYPE') == '_official': context['official_build'] = '1' else: context['official_build'] = '0' # Add all variables defined in the command line. if options.define: for define in options.define: context.update(dict([define.split('=', 1)])); # Read NAME=VALUE variables from file. if options.variables: for file_name in options.variables: ReadValuesFromFile(context, file_name) env = None template = None if source: # Load jinja2 library. if options.jinja2: jinja2_path = os.path.normpath(options.jinja2) else: jinja2_path = os.path.normpath( os.path.join(os.path.abspath(__file__), '../../../../third_party/jinja2')) sys.path.append(os.path.split(jinja2_path)[0]) from jinja2 import Environment, FileSystemLoader # Create jinja2 environment. (template_path, template_name) = os.path.split(source) env = Environment(loader=FileSystemLoader(template_path), extensions=['jinja2.ext.do', 'jinja2.ext.i18n']) # Register custom filters. env.filters['GetCodepage'] = GetCodepage env.filters['GetCodepageDecimal'] = GetCodepageDecimal env.filters['GetLangId'] = GetLangId env.filters['GetPrimaryLanguage'] = GetPrimaryLanguage env.filters['GetSublanguage'] = GetSublanguage # Register the message map with jinja2.i18n extension. env.globals['IsRtlLanguage'] = IsRtlLanguage env.globals['SelectLanguage'] = message_map.MakeSelectLanguage() env.install_gettext_callables(message_map.MakeGetText(), message_map.MakeGetText()); template = env.get_template(template_name) # Generate a separate file per each locale if requested. outputs = [] if options.locale_output: target = GypTemplate(options.locale_output) for lang in languages: context['languages'] = [ lang ] context['language'] = lang context['pak_suffix'] = GetDataPackageSuffix(lang) context['json_suffix'] = GetJsonSuffix(lang) message_map.SelectLanguage(lang) template_file_name = target.safe_substitute(context) outputs.append(template_file_name) if not options.print_only: WriteIfChanged(template_file_name, template.render(context), options.encoding) else: outputs.append(options.output) if not options.print_only: WriteIfChanged(options.output, template.render(context), options.encoding) if options.print_only: # Quote each element so filename spaces don't mess up gyp's attempt to parse # it into a list. return " ".join(['"%s"' % x for x in outputs]) return def DoMain(argv): usage = "Usage: localize [options] locales" parser = OptionParser(usage=usage) parser.add_option( '-d', '--define', dest='define', action='append', type='string', help='define a variable (NAME=VALUE).') parser.add_option( '--encoding', dest='encoding', type='string', default='utf-8', help="set the encoding of <output>. 'utf-8' is the default.") parser.add_option( '--jinja2', dest='jinja2', type='string', help="specifies path to the jinja2 library.") parser.add_option( '--locale_dir', dest='locale_dir', type='string', help="set path to localized message files.") parser.add_option( '--locale_output', dest='locale_output', type='string', help='specify the per-locale output file name.') parser.add_option( '-o', '--output', dest='output', type='string', help="specify the output file name.") parser.add_option( '--print_only', dest='print_only', action='store_true', default=False, help='print the output file names only.') parser.add_option( '-t', '--template', dest='template', type='string', help="specify the template file name.") parser.add_option( '--variables', dest='variables', action='append', type='string', help='read variables (NAME=VALUE) from file.') options, locales = parser.parse_args(argv) if not locales: parser.error('At least one locale must be specified') if bool(options.output) == bool(options.locale_output): parser.error( 'Either --output or --locale_output must be specified but not both') if not options.template and not options.print_only: parser.error('The template name is required unless --print_only is used') return Localize(options.template, locales, options) if __name__ == '__main__': sys.exit(DoMain(sys.argv[1:]))
bsd-3-clause
diegocortassa/TACTIC
src/tactic/ui/panel/custom_layout_wdg.py
1
51769
########################################################### # # Copyright (c) 2005, Southpaw Technology # All Rights Reserved # # PROPRIETARY INFORMATION. This software is proprietary to # Southpaw Technology, and is not to be reproduced, transmitted, # or disclosed in any way without written permission. # # # from __future__ import print_function __all__ = ["CustomLayoutWdg", "SObjectHeaderWdg"] import os, types, re import cStringIO from pyasm.common import Xml, XmlException, Common, TacticException, Environment, Container, jsonloads, jsondumps from pyasm.biz import Schema, ExpressionParser, Project from pyasm.search import Search, SearchKey, WidgetDbConfig, SObject from pyasm.web import DivWdg, SpanWdg, HtmlElement, Table, Widget, Html, WebContainer from pyasm.widget import WidgetConfig, WidgetConfigView, IconWdg from tactic.ui.common import BaseRefreshWdg from tactic.ui.container import SmartMenu from tactic.ui.container import Menu, MenuItem, SmartMenu from tactic_client_lib import TacticServerStub class CustomLayoutWdg(BaseRefreshWdg): ARGS_KEYS = { 'search_key': 'search key of the sobject to be displayed', # or 'search_type': 'search type of the sobject to be displayed', 'code': 'code of the sobject to be displayed', 'id': { 'description': 'id of the sobject to be displayed', 'category': '_internal', }, 'sobjects_expr': 'expression to populate the sobjects for this widget', 'category': { 'description': 'category of the config to search for', }, 'search_type': { 'description': 'search type of the sobject to be displayed', 'type': 'TextWdg', 'order': 1, }, 'view': { 'description': 'The view defined in the widget config/Custom Layout Editor that contains the custom html', 'type': 'TextWdg', 'order': 2, 'category': 'Options' }, 'state': { 'description': 'State surrounding the widget', 'category': '_deprecated' }, 'html': { 'description': 'Explicitly define the html layout inline', 'type': 'TextAreaWdg', }, 'include_mako': { 'description': 'Boolean to turn on mako', 'type': 'SelectWdg', 'values': 'false|true', }, 'include': { 'description': 'Include any other config files', 'type': 'TextWdg', #'order': '1', } } def __init__(self, **kwargs): super(CustomLayoutWdg, self).__init__(**kwargs) def init(self): self.server = TacticServerStub.get(protocol='local') sobjects_expr = self.kwargs.get("sobjects_expr") if sobjects_expr: self.sobjects = Search.eval(sobjects_expr) self.data = {} # NOTE: this is is for the FilterElement Functionality self.show_title = True self.layout_wdg = None self.config = None self.def_config = None self.sobject_dicts = None self.is_table_element = False self.sequence_data = [] def preprocess(self): code = self.kwargs.get('data') if not code: self.data = {} return # preprocess using mako #include_mako = self.kwargs.get("include_mako") #if not include_mako: # include_mako = self.view_attrs.get("include_mako") from tactic.command import PythonCmd python_cmd = PythonCmd(code=code) self.data = python_cmd.execute() # NOTE: this is so that a custom layout can be used as a filter .... # however, this is not ideal because a filter requires a number of # methods that should not be present in this class def alter_search(self, search): script_path = self.get_option("alter_search_script_path") script_code = self.get_option("alter_search_script_code") from tactic.command import PythonCmd if script_path: cmd = PythonCmd(script_path=script_path, values=self.values, search=search, show_title=self.show_title) elif script_code: cmd = PythonCmd(script_code=script_code, values=self.values, search=search, show_title=self.show_title) cmd.execute() def set_values(self, values): self.values = values def set_show_title(self, flag): self.show_title = flag def get_display(self): self.sobject = self.get_current_sobject() if not self.sobject: self.sobject = self.get_sobject_from_kwargs() if self.sobject and self.sobject.is_insert(): return DivWdg() if self.sobject: self.search_key = SearchKey.get_by_sobject(self.sobject) self.kwargs['search_key'] = self.search_key else: self.search_key = self.kwargs.get('search_key') html = self.kwargs.get('html') if not html: html = "" # DEPRECATED self.state = self.kwargs.get("state") self.state = BaseRefreshWdg.process_state(self.state) if not self.state: self.state = self.kwargs self.state['search_key'] = self.search_key self.view = self.kwargs.get('view') self.view = self.view.replace("/", ".") self.view_folder = "" if self.view.startswith("."): self.view_folder = self.kwargs.get("__view_folder__") if self.view_folder: self.view = "%s%s" % (self.view_folder, self.view) parts = self.view.split(".") self.view_folder = ".".join(parts[:-1]) if not self.view and not html: raise TacticException("No view defined in custom layout") # If html is not a string, then convert it? if not isinstance(html, basestring): html = str(html) self.view_attrs = {} self.category = self.kwargs.get("category") self.search_type = self.kwargs.get("search_type") self.encoding = self.kwargs.get("encoding") if not self.encoding: self.encoding = 'utf-8' self.plugin = None xml = None # if html is not provided, then get it from the config config = None if not html: if self.config != None: config = self.config else: config = self.kwargs.get("config") if not config: config = self.get_config() if not config: #div = DivWdg() #div.add("No config defined for view [%s] for custom layout" % self.view) #return div raise TacticException("No config defined for view [%s] for custom layout" % self.view) if isinstance(config, WidgetDbConfig): config_str = config.get_value("config") else: config_str = '' if config_str.startswith("<html>"): html = config_str self.def_config = None else: xml = config.get_xml() if self.def_config == None: self.def_config = self.get_def_config(xml) # get the view attributes if isinstance(config, WidgetConfigView): top_config = config.get_configs()[0] else: top_config = config view_node = top_config.get_view_node() if view_node is None: div = DivWdg("No view node found in xml. Invalid XML entry found") return div self.view_attrs = xml.get_attributes(view_node) nodes = xml.get_nodes("config/%s/html/*" % self.view) if not nodes: div = DivWdg("No definition found") return div # convert html tag to a div html = cStringIO.StringIO() for node in nodes: # unfortunately, html does not recognize <textarea/> # so we have to make sure it becomes <textarea></textarea> text = xml.to_string(node) text = text.encode('utf-8') keys = ['textarea','input'] for key in keys: p = re.compile("(<%s.*?/>)" % key) m = p.search(text) if m: for group in m.groups(): xx = group.replace("/", "") xx = "%s</%s>" % (xx, key) text = text.replace(group, xx) text = text.replace("<%s/>" % key, "<%s></%s>" % (key, key)) # add linebreaks to element tag key = 'element' # reg full tag <element><display...></element> p = re.compile(r"(<%s\b[^>]*>(?:.*?)</%s>)" % (key, key)) # short-hand tag <element/> p1 = re.compile("(</%s>|<%s.*?/>)" %(key, key)) m = p.search(text) m1 = p1.search(text) if m: for group in m.groups(): if group: text = text.replace(group, '\n%s\n'%group) if m1: for group in m1.groups(): if group: text = text.replace(group, '\n%s\n'%group) html.write(text) html = html.getvalue() self.config = config #self.def_config = config # This is unnessary? # try to get the sobject if this is in a table element widget if self.search_key: try: # this will raise an exception if it is not in a table element sobject = self.get_current_sobject() except: sobject = SearchKey.get_by_search_key(self.search_key) sobjects = [sobject] else: try: # this will raise an exception if it is not in a table element sobject = self.get_current_sobject() if sobject: sobjects = [sobject] else: sobjects = [] except: sobject = self.sobjects self.layout = self.get_layout_wdg() # preprocess using mako include_mako = self.kwargs.get("include_mako") if not include_mako: include_mako = self.view_attrs.get("include_mako") if xml: mako_node = xml.get_node("config/%s/mako" % self.view) if mako_node is not None: mako_str = xml.get_node_value(mako_node) html = "<%%\n%s\n%%>\n%s" % (mako_str, html) from pyasm.web import Palette num_palettes = Palette.num_palettes() #if include_mako in ['true', True]: if include_mako not in ['false', False]: html = html.replace("&lt;", "<") html = html.replace("&gt;", ">") html = self.process_mako(html) # preparse out expressions # use relative expressions - [expr]xxx[/expr] p = re.compile('\[expr\](.*?)\[\/expr\]') parser = ExpressionParser() matches = p.finditer(html) for m in matches: full_expr = m.group() expr = m.groups()[0] result = parser.eval(expr, sobjects, single=True, state=self.state) if isinstance(result, basestring): result = Common.process_unicode_string(result) else: result = str(result) html = html.replace(full_expr, result ) # use absolute expressions - [expr]xxx[/expr] p = re.compile('\[abs_expr\](.*?)\[\/abs_expr\]') parser = ExpressionParser() matches = p.finditer(html) for m in matches: full_expr = m.group() expr = m.groups()[0] result = parser.eval(expr, single=True) if isinstance(result, basestring): result = Common.process_unicode_string(result) else: result = str(result) html = html.replace(full_expr, result ) # need a top widget that can be used to refresh top = self.top self.set_as_panel(top) top.add_class("spt_custom_top") top.add_class("spt_panel") ignore_events = self.kwargs.get("ignore_events") in ['true', True] if ignore_events: top.add_style("pointer-events: none") # create the content div content = DivWdg() content.add_class("spt_custom_content") content.add_style("position: relative") if ignore_events: content.add_style("pointer-events: none") top.add(content) self.content = content is_test = Container.get("CustomLayout::is_test") if not is_test: is_test = self.kwargs.get("is_test") in [True, 'true'] if is_test: Container.put("CustomLayout::is_test", True) self.top.add_style("margin: 0px 5px") self.handle_is_test(content) html = self.replace_elements(html) content.add(html) if xml: self.add_behaviors(content, xml) # remove all the extra palettes created while True: extra_palettes = Palette.num_palettes() - num_palettes if extra_palettes > 0: Palette.pop_palette() else: break if self.kwargs.get("is_top") in ['true', True]: return html elif self.kwargs.get("is_refresh"): return content else: return top def handle_is_test(self, content): content.add_behavior( { 'type': 'mouseover', 'cbjs_action': ''' //bvr.src_el.setStyle("border", "solid 1px blue"); bvr.src_el.setStyle("box-shadow", "0px 0px 5px rgba(0, 0, 0, 0.5)"); //bvr.src_el.setStyle("margin", "-1px"); var els = bvr.src_el.getElements(".spt_test"); for (var i = 0; i < els.length; i++) { els[i].setStyle("display", ""); break; } ''' } ) content.add_behavior( { 'type': 'mouseleave', 'cbjs_action': ''' bvr.src_el.setStyle("box-shadow", ""); //bvr.src_el.setStyle("margin", "0px"); var els = bvr.src_el.getElements(".spt_test"); for (var i = 0; i < els.length; i++) { els[i].setStyle("display", "none"); break; } ''' } ) div = DivWdg() content.add(div) div.add_style("position: absolute") div.add("View: %s" % self.view) div.add_class("spt_test") div.add_border() #div.set_box_shadow("1px 1px 1px 1px") div.add_style("display: none") div.add_style("padding: 3px") div.add_style("margin-left: 3px") div.add_style("left: 0px") div.add_style("top: -15px") #div.add_style("opacity: 0.5") div.add_style("inherit: false") div.add_style("z-index: 1000") div.add_style("background-color: white") div.add_class("hand") div.add_behavior( { 'type': 'click_up', 'cbjs_action': ''' var top = bvr.src_el.getParent(".spt_custom_top"); top.setAttribute("spt_is_test", "true"); var size = top.getSize(); top.innerHTML = "<div style='width: "+size.x+";height: "+size.y+";padding: 10px; font-weight: bold'>Loading ...</div>"; spt.panel.refresh(top); ''' } ) # add in a context menu menu = self.get_test_context_menu() menus = [menu.get_data()] menus_in = { 'TEST_CTX': menus, } SmartMenu.attach_smart_context_menu( div, menus_in, False ) SmartMenu.assign_as_local_activator( div, 'TEST_CTX' ) def get_test_context_menu(self): menu = Menu(width=180) menu.set_allow_icons(False) menu_item = MenuItem(type='title', label='Actions') menu.add(menu_item) menu_item = MenuItem(type='action', label='Refresh') menu.add(menu_item) menu_item.add_behavior( { 'type': 'click_up', 'view': self.view, 'cbjs_action': ''' var activator = spt.smenu.get_activator(bvr); var top = activator.getParent(".spt_custom_top"); top.setAttribute("spt_is_test", "true"); var size = top.getSize(); top.innerHTML = "<div style='width: "+size.x+";height: "+size.y+";padding: 10px; font-weight: bold'>Loading ...</div>"; spt.panel.refresh(top); ''' } ) menu_item = MenuItem(type='action', label='Edit') menu.add(menu_item) menu_item.add_behavior( { 'type': 'click_up', 'view': self.view, 'cbjs_action': ''' var activator = spt.smenu.get_activator(bvr); var popup_top = activator.getParent(".spt_popup"); var top = popup_top.top; if (top) { top.setAttribute("spt_view", bvr.view); spt.app_busy.show("Loading view: " + bvr.view); spt.panel.refresh(top); spt.app_busy.hide(); } ''' } ) menu_item = MenuItem(type='action', label='Open in Main Tab') menu.add(menu_item) menu_item.add_behavior( { 'type': 'click_up', 'view': self.view, 'cbjs_action': ''' var activator = spt.smenu.get_activator(bvr); var popup_top = activator.getParent(".spt_popup"); spt.popup.close(popup_top); var top = activator.getParent(".spt_custom_top"); var class_name = top.getAttribute("spt_class_name"); var kwargs = spt.panel.get_element_options(top); //kwargs['is_test'] = true; var title = "Test: " + bvr.view; spt.tab.set_main_body_tab(); spt.tab.add_new(title, title, class_name, kwargs); ''' } ) return menu HEADER = '''<%def name='expr(expr)'><% result = server.eval(expr) %>${result}</%def>''' def process_mako(self, html): from mako.template import Template from mako import exceptions html = '%s%s' % (CustomLayoutWdg.HEADER, html) # remove CDATA tags html = html.replace("<![CDATA[", "") html = html.replace("]]>", "") #html = html.decode('utf-8') if self.encoding == 'ascii': template = Template(html) else: template = Template(html, output_encoding=self.encoding, input_encoding=self.encoding) # get the api version of the sobject if not self.is_table_element: if self.sobject_dicts == None: self.sobject_dicts = [] for sobject in self.sobjects: sobject_dict = sobject.get_sobject_dict() self.sobject_dicts.append(sobject_dict) if self.sobject: sobject = self.sobject.get_sobject_dict() else: sobject = {} # find out if there is a plugin associated with this plugin = self.kwargs.get("plugin") if not plugin or plugin == '{}': plugin = {} """ if not plugin and isinstance(self.config, SObject): plugin = Search.eval("@SOBJECT(config/plugin_content.config/plugin)", self.config, single=True) """ if plugin: if isinstance(plugin, dict): pass else: plugin = plugin.get_sobject_dict() plugin_code = plugin.get("code") plugin_dir = self.server.get_plugin_dir(plugin) else: plugin_code = "" plugin_dir = "" plugin = {} self.kwargs['plugin_dir'] = plugin_dir self.kwargs['plugin_code'] = plugin_code try: html = template.render(server=self.server, search=Search, sobject=sobject, sobjects=self.sobject_dicts, data=self.data, plugin=plugin, kwargs=self.kwargs) # we have to replace all & signs to &amp; for it be proper html html = html.replace("&", "&amp;") return html except Exception as e: if str(e) == """'str' object has no attribute 'caller_stack'""": raise TacticException("Mako variable 'context' has been redefined. Please use another variable name") else: print("Error in view [%s]: " % self.view, exceptions.text_error_template().render()) #html = exceptions.html_error_template().render(css=False) html = exceptions.html_error_template().render() html = html.replace("body { font-family:verdana; margin:10px 30px 10px 30px;}", "") return html def handle_layout_behaviors(self, layout): '''required for BaseTableElementWdg used by fast table''' pass def add_test(self, xml): # add a test env in text_node = xml.get_nodes("config/%s/test" % self.view) def add_kwargs(self, widget, xml): """ ARGS_KEYS = { 'category': { 'description': 'category of the config to search for', }, 'view': { 'description': 'The view defined in the widget config/Custom Layout Editor that contains the custom html', 'type': 'TextWdg', 'order': 2, 'category': 'Options' }, } <kwargs> <kwarg name="category"> <description>category of the config to search for</description> </kwarg> <kwarg name="view"> <description>The view defined in the widget config/Custom Layout Editor that contains the custom html</description> <type>TextWdg</type> <order>2</order> <category>Options</category> </kwarg> </kwargs> """ kwargs_nodes = xml.get_nodes("config/%s/kwargs/kwarg" % self.view) for kwarg_node in kwargs_node: pass def add_behaviors(self, widget, xml): behavior_nodes = xml.get_nodes("config/%s/behavior" % self.view) if behavior_nodes: hidden_div = DivWdg() hidden_div.add_styles("display: none"); hidden_div.add_class("spt_customlayoutwdg_handoffs") widget.add( hidden_div ) widget.add_behavior({ 'type': 'load', 'cbjs_action': ''' // handle embedded load behaviors! var el_load_list = bvr.src_el.getElements(".SPT_BVR_LOAD_PENDING"); spt.behavior.process_load_behaviors( el_load_list ); ''' }) # remove objects that cannot be json marshalled view_kwargs = self.kwargs.copy() for key, value in view_kwargs.items(): try: test = jsondumps(value) except Exception as e: del(view_kwargs[key]) for behavior_node in behavior_nodes: bvr_div = DivWdg() hidden_div.add( bvr_div ) css_class = Xml.get_attribute(behavior_node, 'class') behavior_str = Xml.get_node_value(behavior_node) behavior_str = behavior_str.strip() # if the event is specified in the xml, then use that event = Xml.get_attribute(behavior_node, 'event') modkeys = Xml.get_attribute(behavior_node, 'modkeys') relay_class = Xml.get_attribute(behavior_node, 'relay_class') if not behavior_str: continue try: try: bvr = eval(behavior_str) except: # try it as a string bvr_str = eval("'''\n%s\n'''" % behavior_str) if bvr_str: bvr = {} bvr['cbjs_action'] = bvr_str if event: bvr['type'] = event if modkeys: bvr['modkeys'] = modkeys # add the kwargs to this so behaviors have access bvr['kwargs'] = view_kwargs bvr['class_name'] = Common.get_full_class_name(self) if relay_class: bvr['bvr_match_class'] = relay_class if not bvr.get("type"): bvr['type'] = 'mouseup' self.content.add_relay_behavior( bvr ) elif bvr.get("type") == "smart_drag": bvr['bvr_match_class'] = css_class self.content.add_behavior(bvr) elif bvr.get("type") == "listen": bvr['bvr_match_class'] = css_class bvr['event_name'] = Xml.get_attribute(behavior_node,'event_name') self.content.add_behavior(bvr) else: bvr['_handoff_'] = '@.getParent(".spt_custom_content").getElements(".%s")' % css_class if not bvr.get("type"): bvr['type'] = 'click_up' bvr_div.add_behavior( bvr ) except Exception as e: print("Error: ", e) raise TacticException("Error parsing behavior [%s]" % behavior_str) def get_config(self): config = None config_xml = self.kwargs.get('config_xml') if config_xml: config = WidgetConfig.get(xml=config_xml, view=self.view) return config # this is the new preferred way of defining CustomLayoutWdg search = Search("config/widget_config") if self.category: search.add_filter("category", self.category) else: search.add_filter("category", 'CustomLayoutWdg') if self.search_type: search.add_filter("search_type", self.search_type) search.add_filter("view", self.view) configs = search.get_sobjects() # annoyingly NULL is always higher than any number, so we have # put them at the end if configs and configs[0].column_exists("priority"): configs = sorted(configs, key=lambda x: x.get("priority")) configs.reverse() if configs: config = configs[0] return config # if it is not defined in the database, look at a config file includes = self.kwargs.get("include") if includes: includes = includes.split("|") for include in includes: if include.find('/') != -1: file_path = include else: tmp_path = __file__ dir_name = os.path.dirname(tmp_path) file_path ="%s/../config/%s" % (dir_name, include) config = WidgetConfig.get(file_path=file_path, view=self.view) if config and config.has_view(self.view): return config # deprecated approach, assuming a "CustomLayoutWdg" as search_type, # is deprecated if not config: search = Search("config/widget_config") if self.category: search.add_filter("category", self.category) if self.search_type: search.add_filter("search_type", "CustomLayoutWdg") search.add_filter("view", self.view) config = search.get_sobject() #if not config and self.search_type and self.view: # config = WidgetConfigView.get_by_search_type(self.search_type, self.view) # this is the new preferred way of defining CustomLayoutWdg # NOTE: this finds a definition where search type is not explicitly # given> if not config: search = Search("config/widget_config") search.add_filter("view", self.view) search.add_filter("search_type", None) config = search.get_sobject() return config def get_def_config(self, def_xml=None): def_confg = None self.def_view = self.kwargs.get('definition') if self.def_view: #raise TacticException("No definition view defined in custom layout with view [%s]" % self.view) self.search_type = "CustomLayoutWdg" search = Search("config/widget_config") search.add_filter("search_type", self.search_type) search.add_filter("view", self.def_view) def_db_config = search.get_sobject() if not def_db_config: raise TacticException("Definition config [%s] not defined" % self.def_view) def_xml = def_db_config.get_xml() def_config = WidgetConfig.get("definition", xml=def_xml) # also look inline to see if there are any definitions if def_xml: # just use the passed in xml for a definition def_config = WidgetConfig.get(self.view, xml=def_xml) return def_config def replace_elements(self, html_str): """ # NOTE: this likely is a better way to extract elements, but still # need to find a way to inject html back into the xml xml = Xml() xml.read_string("<div>%s</div>" % html_str) elements = xml.get_nodes("//element") for element in elements: # create a complete config full_line_str = xml.to_string(element) tmp_config = '''<config><tmp>%s</tmp></config>''' % full_line_str try: element_wdg = self.get_element_wdg(xml, self.def_config) element_html = element_wdg.get_buffer_display() except Exception as e: from pyasm.widget import ExceptionWdg element_html = ExceptionWdg(e).get_buffer_display() xml = Xml() try: xml.read_string(element_html) except Exception as e: print("Error: ", e) xml.read_string("<h1>%s</h1>" % str(e) ) root = xml.get_root_node() parent = xml.get_parent(element) xml.replace_child(parent, element, root) return xml.to_string() """ # a simple readline interpreter html = Html() full_line = [] parse_context = None for line in html_str.split("\n"): line2 = line.strip() #if not parse_context and not line2.startswith('<element '): index = line2.find('<element>') if index == -1: index = line2.find('<element ') if not parse_context and index == -1: #line = Common.process_unicode_string(line) html.writeln(line) continue if index != -1: part1 = line2[:index] html.write(part1) line2 = line2[index:] full_line.append(line2) xml = Xml() # determine if this is valid xml try: # create a complete config full_line_str = "".join(full_line) tmp_config = '''<config><tmp>%s</tmp></config>''' % full_line_str xml.read_string(tmp_config, print_error=False) full_line = [] parse_context = '' except XmlException as e: parse_context = 'element' #raise e continue try: if Xml.get_value(xml, "config/tmp/element/@enabled") == "false": continue element_wdg = self.get_element_wdg(xml, self.def_config) if element_wdg: element_html = element_wdg.get_buffer_display() else: element_html = '' except Exception as e: from pyasm.widget import ExceptionWdg element_html = ExceptionWdg(e).get_buffer_display() # Test to ensure that the html produced is "xml" conforming """ try: new_xml = Xml() new_xml.read_string(element_html) except Exception as e: f = open("/tmp/error", 'w') f.write(element_html) f.close() #print(element_html) print("Error: ", e) """ if element_html: html.writeln(element_html) sequence_wdg = self.get_sequence_wdg() html.writeln(sequence_wdg.get_buffer_display() ) return html.to_string() # FIXME: this is all necessary because CustomLayoutWdg is not derived from # BaseTableElementWdg ... CustomLayoutWdg should probably not be used # as a table elementj # NOTE: Use tactic.ui.table.CustomLayoutElementWdg for adding custom layouts # to layouts def set_parent_wdg(self, name): pass def is_in_column(self): return True def is_groupable(self): return False def set_layout_wdg(self, widget): self.layout_wdg = widget def get_layout_wdg(self): return self.layout_wdg def get_title(self): '''Returns a widget containing the title to be displayed for this column''' if self.title: title = self.title return title title = self.name if not title: title = "" return title title = Common.get_display_title(title) return title def get_value(self): return None def get_text_value(self): '''for csv export''' sobject = self.get_current_sobject() text_expr = self.kwargs.get("text_value") text_expr = "@GET(.id)" if not text_expr: return '' value = Search.eval(text_expr, sobject, single=True) return value def is_sortable(self): return False def is_searchable(self): return False def handle_th(self, th, xx=None): pass def handle_td(self, td): pass def handle_tr(self, tr): pass def is_editable(self): return False def get_bottom_wdg(self): return None def get_group_bottom_wdg(self, sobjects=None): return None def get_header_option_wdg(self): return None def get_generator(self): return self.generator_element def set_generator(self, element_name): self.generator_element = element_name ## END TableElementWdg methods def get_sequence_wdg(self): funcs = [] div = DivWdg() if not self.sequence_data: return div div.add_behavior( { 'type': 'load', 'data': self.sequence_data, 'cbjs_action': ''' var count = -1; var func = function() { if (count == bvr.data.length-1) { return; } count += 1; var item = bvr.data[count]; var unique_id = item.unique_id; var class_name = item.class_name; var kwargs = item.kwargs; var options = { async: true, callback: func } spt.panel.load($(unique_id), class_name, kwargs, {}, options); } func(); ''' } ) return div def get_async_element_wdg(self, xml, element_name, load): tmp_config = WidgetConfig.get('tmp', xml=xml) display_handler = tmp_config.get_display_handler(element_name) display_options = tmp_config.get_display_options(element_name) div = DivWdg() unique_id = div.set_unique_id() div.add_class("spt_manual_load") show_loading = self.kwargs.get("show_loading") if load == "sequence": self.sequence_data.append( { 'class_name': display_handler, 'kwargs': display_options, 'unique_id': unique_id } ) elif load == "manual": show_loading = False div.add_behavior( { 'type': 'load', 'class_name': display_handler, 'kwargs': display_options, 'cbjs_action': ''' bvr.src_el.load = function() { spt.panel.async_load(bvr.src_el, bvr.class_name, bvr.kwargs); } ''' } ) msg = DivWdg() div.add(msg) msg.add_style("padding", "20px") msg.add_style("margin", "10px auto") msg.add_style("width", "150px") msg.add_style("border", "solid 1px #DDD") msg.add_style("text-align", "center") msg.add("Loading ...") else: div.add_behavior( { 'type': 'load', 'class_name': display_handler, 'kwargs': display_options, 'cbjs_action': ''' spt.panel.async_load(bvr.src_el, bvr.class_name, bvr.kwargs); ''' } ) if show_loading not in ["False", False, "false"]: loading_div = DivWdg() loading_div.add_style("margin: auto auto") loading_div.add_style("width: 150px") loading_div.add_style("text-align: center") loading_div.add_style("padding: 20px") div.add(loading_div) loading_div.add('''<img src="/context/icons/common/indicator_snake.gif" border="0"/> <b>Loading ...</b>''') return div def get_element_wdg(self, xml, def_config): element_node = xml.get_node("config/tmp/element") attrs = Xml.get_attributes(element_node) element_name = attrs.get("name") widget = self.get_widget(element_name) if widget: return widget if not element_name: import random num = random.randint(0, 1000000) element_name = "element%s" % num xml.set_attribute(element_node, "name", element_name) # enable an ability to have a widget only loaded once in a request if attrs.get('load_once') in ['true', True]: widgets = Container.get("CustomLayoutWdg:widgets") if widgets == None: widgets = {} Container.put("CustomLayoutWdg:widgets", widgets) else: if widgets[element_name] == True: return None widgets[element_name] = True # provide the ability to have shorthand format # ie: <element display_class="tactic.ui..." /> display_node = xml.get_node("config/tmp/element/display") if display_node is None: view = attrs.get("view") type = attrs.get("type") if type == "reference": search_type = attrs.get("search_type") self.config = WidgetConfigView.get_by_search_type(search_type, view) # check if definition has no name. Don't use element_name if not attrs.get("name"): return element_wdg = self.config.get_display_widget(element_name, extra_options=attrs) container = DivWdg() container.add(element_wdg) return container class_name = attrs.get("display_class") # if no class name is defined and not view is defined look # at predefined elements if not view and not class_name: element_wdg = self.config.get_display_widget(element_name, extra_options=attrs) container = DivWdg() container.add(element_wdg) return container # look at the attributes if not class_name: class_name = "tactic.ui.panel.CustomLayoutWdg" display_node = xml.create_element("display") xml.set_attribute(display_node, "class", class_name) xml.append_child(element_node, display_node) for name, value in attrs.items(): # replace the spt_ in the name. # NOTE: should this be restricted to only spt_ attributes? name = name.replace("spt_", "") attr_node = xml.create_element(name) xml.set_node_value(attr_node, value) xml.append_child(display_node, attr_node) load = attrs.get("load") if load in ["none"]: return None elif load in ["async", "sequence","manual"]: return self.get_async_element_wdg(xml, element_name, load) # add the content try: view_node = xml.get_node("config/tmp/element/display/view") if view_node is not None: view = xml.get_node_value(view_node) if view.startswith("."): if self.view_folder: xml.set_node_value(view_node, "%s%s" %(self.view_folder,view)) tmp_config = WidgetConfig.get('tmp', xml=xml) configs = [] configs.append(tmp_config) # add the def_config if it exists if def_config: configs.append(def_config) config = WidgetConfigView('CustomLayoutWdg', 'tmp', configs, state=self.state) # NOTE: this doesn't work too well when we go to an abasolute # view. parent_view = self.kwargs.get("parent_view") if parent_view: parent_view = parent_view.replace(".", "/") parent_view = "%s/%s" % (parent_view, self.view) else: parent_view = self.view # NOTE: need some protection code for infinite loops includes = self.kwargs.get("include") extra_options = {"parent_view": parent_view} if includes: extra_options['include'] = includes element_wdg = config.get_display_widget(element_name, extra_options=extra_options) element_top = element_wdg.get_top() for name, value in attrs.items(): if name == 'class': for item in value.split(" "): element_top.add_class(item) elif name == 'style': for item in re.split(";\ ?", value): element_top.add_style(item) else: element_top.set_attr(name, value) # make a provision if this custom widget is in a table if self.layout: sobject = self.get_current_sobject() element_wdg.set_sobject(sobject) except Exception as e: from pyasm.widget import ExceptionWdg log = ExceptionWdg(e) element_wdg = log return element_wdg container.add(element_wdg) return container def get_smart_header_context_menu_data(self): from pyasm.widget import IconWdg menu_data = { 'menu_tag_suffix': 'MAIN', 'width': 200 } opt_spec_list = [] opt_spec_list.append( { "type": "action", "label": "Edit Definition", "icon": IconWdg.EDIT, "bvr_cb": { 'cbjs_action': 'alert("Edit Definition")' } }) opt_spec_list.append( { "type": "separator" } ) opt_spec_list.append( { "type": "action", "label": "Split Horizontal", "icon": IconWdg.TABLE_ROW_INSERT, "bvr_cb": { 'cbjs_action': 'spt.custom_project.split_horizontal(evt, bvr)' } }) opt_spec_list.append( { "type": "action", "label": "Split Vertical", "bvr_cb": {'cbjs_action': "spt.js_log.show();"} }) opt_spec_list.append( { "type": "action", "label": "Remove Panel", "icon": IconWdg.TABLE_ROW_DELETE, "bvr_cb": { 'cbjs_action': 'spt.custom_project.remove_panel(evt, bvr)' } }) opt_spec_list.append( { "type": "separator" } ) opt_spec_list.append( { "type": "action", "label": "Save Layout", "icon": IconWdg.SAVE, "bvr_cb": { 'cbjs_action': 'spt.custom_project.save_layout(evt, bvr)' } }) menu_data['opt_spec_list'] = opt_spec_list return menu_data __all__.append("TestStateWdg") class TestStateWdg(BaseRefreshWdg): def get_display(self): self.top.add(self.kwargs) self.top.add("<hr/>") if self.sobjects: self.top.add(self.sobjects[0].get_code()) else: self.top.add("No sobjects") return self.top # DEPRECATED """ class ContainerWdg(BaseRefreshWdg): def get_args_keys(self): return { 'inner_width': 'Inner width, sans rounded corner wrapper ... numeric value only', 'inner_height': 'Inner height, sans rounded corner wrapper ... numeric value only', 'show_resize_scroll': 'true|false: determines whether to show scroll bars or not' } def init(self): self.top = DivWdg() self.content_wdg = DivWdg() is_IE = WebContainer.get_web().is_IE() # get the width and height of the contents (the inner part of the container) ... self.inner_width = self.kwargs.get('inner_width') self.inner_height = self.kwargs.get('inner_height') if self.inner_width: self.inner_width = int(self.inner_width) if is_IE: self.inner_width -= 20 # adjust for rounded corner wrapper else: self.inner_width = 600 if self.inner_height: self.inner_height = int(self.inner_height) if is_IE: self.inner_height -= 20 # adjust for rounded corner wrapper else: self.inner_height = 200 # Now place a ResizeScrollWdg within a RoundedCornerDivWdg ... the ResizeScrollWdg will contain # the actual contents of this container, so that the contents can be scrolled and resized ... # from tactic.ui.container import RoundedCornerDivWdg color = self.top.get_color("background") self.rc_wdg = RoundedCornerDivWdg(hex_color_code=color,corner_size=10) #show_scrollbars = self.kwargs.get("show_resize_scroll") #if show_scrollbars in ['', 'false']: # self.inner_wdg = DivWdg() #else: # from tactic.ui.container import ResizeScrollWdg # self.inner_wdg = ResizeScrollWdg( width=self.inner_width, height=self.inner_height, scroll_bar_size_str='medium', scroll_expansion='inside' ) self.inner_wdg = DivWdg() self.inner_wdg.add_style("width: %s" % self.inner_width) self.inner_wdg.add_style("height: %s" % self.inner_height) self.inner_wdg.add_style("overflow-y: auto") self.inner_wdg.add_style("overflow-x: hidden") self.rc_wdg.add( self.inner_wdg ) self.content_wdg.add(self.rc_wdg) self.table = Table(css="minimal") self.table.add_row() self.content_td = self.table.add_cell() self.content_td.add_class("spt_content") self.content_td.add_style('padding: 2px') def add_style(self, name, value=None): if name.startswith("height"): self.content_td.add_style(name, value) elif name.startswith("width"): self.content_td.add_style(name, value) else: self.top.add_style(name, value) def get_display(self): # fill in the content widget for widget in self.widgets: self.inner_wdg.add(widget) self.top.add_class("spt_container") self.content_wdg.add_style("float: left") # -- DO NOT SET THE WIDTH AND HEIGHT of the content_wdg! Commenting out these lines ... # self.content_wdg.add_style("width: 100%") # self.content_wdg.add_style("height: 100%") # add the content self.content_td.add_style("vertical-align: top") self.content_td.add(self.content_wdg) self.top.add(self.table) return self.top def get_divider_wdg(self, activator, mode='vertical'): divider_div = DivWdg() divider_div.add_style("border-style", "dashed") divider_div.add_style("border-color", "#999") if mode == 'vertical': divider_div.add_style("margin-left", "3px") divider_div.add_style("height", "100%") divider_div.add_style("width", "1px") divider_div.add_style("border-width", "0 0 0 1px") else: divider_div.add_style("margin-top", "3px") divider_div.add_style("width", "100%") divider_div.add_style("height", "1px") divider_div.add_style("border-width", "1px 0 0 0") divider_div.add_class("hand") divider_div.add_class("content") divider_div.add_style("display", "none") activator.add_event("onmouseover", "$(this).getElement('.content').setStyle('display', '');") activator.add_event("onmouseout", "$(this).getElement('.content').setStyle('display', 'none');") return divider_div """ class SObjectHeaderWdg(BaseRefreshWdg): def get_args_keys(self): return { "parent_key": "the search key of the sobject that the header will display" } def get_display(self): search_key = self.kwargs.get('parent_key') div = DivWdg() if not search_key: div.add("Search Key for SObjectHeaderHdg is empty") return div sobject = Search.get_by_search_key( search_key ) if not sobject: div.add("SObject with Search Key [%s] does not exist" % search_key) return div search_type_obj = sobject.get_search_type_obj() title = search_type_obj.get_title() title_wdg = DivWdg() title_wdg.add_style("font-size: 1.8em") name = sobject.get_display_value() title_wdg.add("%s: %s" % (title, name )) div.add(title_wdg) div.add(HtmlElement.hr()) return div
epl-1.0
scikit-learn-contrib/categorical-encoding
category_encoders/__init__.py
1
1448
""" .. module:: category_encoders :synopsis: :platform: """ from category_encoders.backward_difference import BackwardDifferenceEncoder from category_encoders.binary import BinaryEncoder from category_encoders.count import CountEncoder from category_encoders.hashing import HashingEncoder from category_encoders.helmert import HelmertEncoder from category_encoders.one_hot import OneHotEncoder from category_encoders.ordinal import OrdinalEncoder from category_encoders.sum_coding import SumEncoder from category_encoders.polynomial import PolynomialEncoder from category_encoders.basen import BaseNEncoder from category_encoders.leave_one_out import LeaveOneOutEncoder from category_encoders.target_encoder import TargetEncoder from category_encoders.woe import WOEEncoder from category_encoders.m_estimate import MEstimateEncoder from category_encoders.james_stein import JamesSteinEncoder from category_encoders.cat_boost import CatBoostEncoder from category_encoders.glmm import GLMMEncoder __version__ = '2.2.2' __author__ = 'willmcginnis' __all__ = [ 'BackwardDifferenceEncoder', 'BinaryEncoder', 'CountEncoder', 'HashingEncoder', 'HelmertEncoder', 'OneHotEncoder', 'OrdinalEncoder', 'SumEncoder', 'PolynomialEncoder', 'BaseNEncoder', 'LeaveOneOutEncoder', 'TargetEncoder', 'WOEEncoder', 'MEstimateEncoder', 'JamesSteinEncoder', 'CatBoostEncoder', 'GLMMEncoder' ]
bsd-3-clause
ibm-research-ireland/sparkoscope
examples/src/main/python/mllib/fpgrowth_example.py
158
1280
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # $example on$ from pyspark.mllib.fpm import FPGrowth # $example off$ from pyspark import SparkContext if __name__ == "__main__": sc = SparkContext(appName="FPGrowth") # $example on$ data = sc.textFile("data/mllib/sample_fpgrowth.txt") transactions = data.map(lambda line: line.strip().split(' ')) model = FPGrowth.train(transactions, minSupport=0.2, numPartitions=10) result = model.freqItemsets().collect() for fi in result: print(fi) # $example off$
apache-2.0
parkera/swift
utils/gyb_syntax_support/__init__.py
7
6049
import textwrap from AttributeNodes import ATTRIBUTE_NODES # noqa: I201 from AvailabilityNodes import AVAILABILITY_NODES # noqa: I201 import Classification # noqa: I201 from CommonNodes import COMMON_NODES # noqa: I201 from DeclNodes import DECL_NODES # noqa: I201 from ExprNodes import EXPR_NODES # noqa: I201 from GenericNodes import GENERIC_NODES # noqa: I201 from NodeSerializationCodes import SYNTAX_NODE_SERIALIZATION_CODES, \ get_serialization_code, \ verify_syntax_node_serialization_codes from PatternNodes import PATTERN_NODES # noqa: I201 from StmtNodes import STMT_NODES # noqa: I201 import Token from TypeNodes import TYPE_NODES # noqa: I201 # Re-export global constants SYNTAX_NODES = COMMON_NODES + EXPR_NODES + DECL_NODES + ATTRIBUTE_NODES + \ STMT_NODES + GENERIC_NODES + TYPE_NODES + PATTERN_NODES + \ AVAILABILITY_NODES SYNTAX_TOKENS = Token.SYNTAX_TOKENS SYNTAX_TOKEN_MAP = Token.SYNTAX_TOKEN_MAP SYNTAX_CLASSIFICATIONS = Classification.SYNTAX_CLASSIFICATIONS verify_syntax_node_serialization_codes(SYNTAX_NODES, SYNTAX_NODE_SERIALIZATION_CODES) def make_missing_child(child): """ Generates a C++ call to make the raw syntax for a given Child object. """ if child.is_token(): token = child.main_token() tok_kind = token.kind if token else "unknown" tok_text = token.text if token else "" return \ 'RawSyntax::missing(tok::%s, OwnedString::makeUnowned("%s"))' % \ (tok_kind, tok_text) else: missing_kind = "Unknown" if child.syntax_kind == "Syntax" \ else child.syntax_kind if child.node_choices: return make_missing_child(child.node_choices[0]) return 'RawSyntax::missing(SyntaxKind::%s)' % missing_kind def check_child_condition_raw(child): """ Generates a C++ closure to check whether a given raw syntax node can satisfy the requirements of child. """ result = '[](const RC<RawSyntax> &Raw) {\n' result += ' // check %s\n' % child.name if child.token_choices: result += 'if (!Raw->isToken()) return false;\n' result += 'auto TokKind = Raw->getTokenKind();\n' tok_checks = [] for choice in child.token_choices: tok_checks.append("TokKind == tok::%s" % choice.kind) result += 'return %s;\n' % (' || '.join(tok_checks)) elif child.text_choices: result += 'if (!Raw->isToken()) return false;\n' result += 'auto Text = Raw->getTokenText();\n' tok_checks = [] for choice in child.text_choices: tok_checks.append('Text == "%s"' % choice) result += 'return %s;\n' % (' || '.join(tok_checks)) elif child.node_choices: node_checks = [] for choice in child.node_choices: node_checks.append(check_child_condition_raw(choice) + '(Raw)') result += 'return %s;\n' % ((' || ').join(node_checks)) else: result += 'return %s::kindof(Raw->getKind());' % child.type_name result += '}' return result def check_parsed_child_condition_raw(child): """ Generates a C++ closure to check whether a given raw syntax node can satisfy the requirements of child. """ result = '[](const ParsedRawSyntaxNode &Raw) {\n' result += ' // check %s\n' % child.name if child.token_choices: result += 'if (!Raw.isToken()) return false;\n' result += 'auto TokKind = Raw.getTokenKind();\n' tok_checks = [] for choice in child.token_choices: tok_checks.append("TokKind == tok::%s" % choice.kind) result += 'return %s;\n' % (' || '.join(tok_checks)) elif child.text_choices: result += 'return Raw.isToken();\n' elif child.node_choices: node_checks = [] for choice in child.node_choices: node_checks.append( check_parsed_child_condition_raw(choice) + '(Raw)') result += 'return %s;\n' % ((' || ').join(node_checks)) else: result += 'return Parsed%s::kindof(Raw.getKind());' % child.type_name result += '}' return result def make_missing_swift_child(child): """ Generates a Swift call to make the raw syntax for a given Child object. """ if child.is_token(): token = child.main_token() tok_kind = token.swift_kind() if token else "unknown" if not token or not token.text: tok_kind += '("")' return 'RawSyntax.missingToken(TokenKind.%s)' % tok_kind else: missing_kind = "unknown" if child.syntax_kind == "Syntax" \ else child.swift_syntax_kind return 'RawSyntax.missing(SyntaxKind.%s)' % missing_kind def create_node_map(): """ Creates a lookup table to find nodes by their kind. """ return {node.syntax_kind: node for node in SYNTAX_NODES} def is_visitable(node): return not node.is_base() def dedented_lines(description): """ Each line of the provided string with leading whitespace stripped. """ if not description: return [] return textwrap.dedent(description).split('\n') def hash_syntax_node(node): # Hash into the syntax name and serialization code result = hash((node.name, get_serialization_code(node.syntax_kind))) for child in node.children: # Hash into the expected child syntax result = hash((result, child.syntax_kind)) # Hash into the child name result = hash((result, child.name)) # Hash into whether the child is optional result = hash((result, child.is_optional)) return result def hash_token_syntax(token): # Hash into the token name and serialization code return hash((token.name, token.serialization_code)) def calculate_node_hash(): result = 0 for node in SYNTAX_NODES: result = hash((result, hash_syntax_node(node))) for token in SYNTAX_TOKENS: result = hash((result, hash_token_syntax(token))) return result
apache-2.0
mouton5000/DiscreteEventApplicationEditor
game/Registeries/SpriteRegistery.py
1
2662
from pygame.rect import Rect __author__ = 'mouton' from pygame.sprite import Sprite import pygame from collections import defaultdict from copy import copy _rootDir = None _spritesList = defaultdict(pygame.sprite.OrderedUpdates) _rectsToUpdate = [] def init(rootDir): global _rootDir _rootDir = rootDir reinit() def reinit(): _spritesList.clear() del _rectsToUpdate[:] def getLayers(): return iter(_spritesList.keys()) def draw(z, scene): _spritesList[z].draw(scene) def addRectToUpdate(rectToUpdate): _rectsToUpdate.append(rectToUpdate) def getRectsToUpdate(): return _rectsToUpdate def clearRectsToUpdate(): del _rectsToUpdate[:] class SpriteReg(Sprite): def __init__(self, fileName, x, y, z, rotate, scale): Sprite.__init__(self) self.fileName = None self.z = None self.rect = None self.reload(fileName, x, y, z, rotate, scale) def reload(self, fileName, x, y, z, rotate, scale): filePath = _rootDir + '/' + fileName import game.gameWindow as gameWindow scene = gameWindow.getScene() prevRect = copy(self.rect) if self.fileName is None or self.fileName != fileName or rotate != 0 or scale != 1: self.fileName = fileName self.image = pygame.image.load(filePath).convert_alpha(scene) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y if rotate != 0 or scale != 1: self.image = pygame.transform.rotozoom(self.image, rotate, scale) transformedRect = self.image.get_rect() transformedRect.center = self.rect.center self.rect = transformedRect if prevRect is not None: rectToUpdate = Rect(prevRect.x - 1, prevRect.y - 1, prevRect.width + 2, prevRect.height + 2) r2 = Rect(self.rect.x - 1, self.rect.y - 1, self.rect.width + 2, self.rect.height + 2) rectToUpdate.union_ip(r2) addRectToUpdate(rectToUpdate) else: rectToUpdate = Rect(self.rect.x - 1, self.rect.y - 1, self.rect.width + 2, self.rect.height + 2) addRectToUpdate(rectToUpdate) if self.z is not None: self.remove() _spritesList[z].add(self) self.z = z def __str__(self): return str((self.fileName, self.rect)) def __repr__(self): return str((self.fileName, self.rect)) def remove(self): _spritesList[self.z].remove(self) rectToUpdate = Rect(self.rect.x - 1, self.rect.y - 1, self.rect.width + 2, self.rect.height + 2) addRectToUpdate(rectToUpdate)
mit
kwilliams-mo/iris
lib/iris/tests/test_peak.py
3
11420
# (C) British Crown Copyright 2013, Met Office # # This file is part of Iris. # # Iris 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, either version 3 of the License, or # (at your option) any later version. # # Iris is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Iris. If not, see <http://www.gnu.org/licenses/>. import iris.tests as tests import iris.tests.stock import numpy as np import numpy.ma as ma class TestPeakAggregator(tests.IrisTest): def test_peak_coord_length_1(self): # Coordinate contains a single point. latitude = iris.coords.DimCoord(np.array([0]), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([1]), standard_name='air_temperature', units='kelvin') cube.add_dim_coord(latitude, 0) collapsed_cube = cube.collapsed('latitude', iris.analysis.PEAK) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([1], dtype=np.float32)) def test_peak_coord_length_2(self): # Coordinate contains 2 points. latitude = iris.coords.DimCoord(range(0, 2, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([1, 2]), standard_name='air_temperature', units='kelvin') cube.add_dim_coord(latitude, 0) collapsed_cube = cube.collapsed('latitude', iris.analysis.PEAK) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([2], dtype=np.float32)) def test_peak_coord_length_3(self): # Coordinate contains 3 points. latitude = iris.coords.DimCoord(range(0, 3, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([1, 2, 1]), standard_name='air_temperature', units='kelvin') cube.add_dim_coord(latitude, 0) collapsed_cube = cube.collapsed('latitude', iris.analysis.PEAK) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([2], dtype=np.float32)) def test_peak_1d(self): # Collapse a 1d cube. latitude = iris.coords.DimCoord(range(0, 11, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([1, 2, 3, 4, 5, 6, 5, 4, 3, 2, 1]), standard_name='air_temperature', units='kelvin') cube.add_dim_coord(latitude, 0) collapsed_cube = cube.collapsed('latitude', iris.analysis.PEAK) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([6], dtype=np.float32)) def test_peak_duplicate_coords(self): # Collapse cube along 2 coordinates (both the same). latitude = iris.coords.DimCoord(range(0, 4, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([1, 2, 3, 1]), standard_name='air_temperature', units='kelvin') cube.add_dim_coord(latitude, 0) collapsed_cube = cube.collapsed('latitude', iris.analysis.PEAK) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([3], dtype=np.float32)) collapsed_cube = cube.collapsed(('latitude', 'latitude'), iris.analysis.PEAK) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([3], dtype=np.float32)) def test_peak_2d(self): # Collapse a 2d cube. longitude = iris.coords.DimCoord(range(0, 4, 1), standard_name='longitude', units='degrees') latitude = iris.coords.DimCoord(range(0, 3, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([[1, 2, 3, 1], [4, 5, 7, 4], [2, 3, 4, 2]]), standard_name='air_temperature', units='kelvin') cube.add_dim_coord(latitude, 0) cube.add_dim_coord(longitude, 1) collapsed_cube = cube.collapsed('longitude', iris.analysis.PEAK) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([3, 7.024054, 4], dtype=np.float32)) collapsed_cube = cube.collapsed('latitude', iris.analysis.PEAK) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([4.024977, 5.024977, 7.017852, 4.024977], dtype=np.float32)) collapsed_cube = cube.collapsed(('longitude', 'latitude'), iris.analysis.PEAK) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([7.041787], dtype=np.float32)) collapsed_cube = cube.collapsed(('latitude', 'longitude'), iris.analysis.PEAK) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([7.041629], dtype=np.float32)) def test_peak_without_peak_value(self): # No peak in column (values equal). latitude = iris.coords.DimCoord(range(0, 4, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([1, 1, 1, 1]), standard_name='air_temperature', units='kelvin') cube.add_dim_coord(latitude, 0) collapsed_cube = cube.collapsed('latitude', iris.analysis.PEAK) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([1], dtype=np.float32)) def test_peak_with_nan(self): # Single nan in column. latitude = iris.coords.DimCoord(range(0, 5, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([1, 4, 2, 3, 1], dtype=np.float32), standard_name='air_temperature', units='kelvin') cube.add_dim_coord(latitude, 0) cube.data[3] = np.nan collapsed_cube = cube.collapsed('latitude', iris.analysis.PEAK) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([4.024977], dtype=np.float32)) self.assertEqual(collapsed_cube.data.shape, (1,)) # Only nans in column. cube.data[:] = np.nan collapsed_cube = cube.collapsed('latitude', iris.analysis.PEAK) self.assertTrue(np.isnan(collapsed_cube.data).all()) self.assertEqual(collapsed_cube.data.shape, (1,)) def test_peak_with_mask(self): # Single value in column masked. latitude = iris.coords.DimCoord(range(0, 5, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(ma.array([1, 4, 2, 3, 2], dtype=np.float32), standard_name='air_temperature', units='kelvin') cube.add_dim_coord(latitude, 0) cube.data[3] = ma.masked collapsed_cube = cube.collapsed('latitude', iris.analysis.PEAK) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([4.024977], dtype=np.float32)) self.assertTrue(ma.isMaskedArray(collapsed_cube.data)) self.assertEqual(collapsed_cube.data.shape, (1,)) # Whole column masked. cube.data[:] = ma.masked collapsed_cube = cube.collapsed('latitude', iris.analysis.PEAK) masked_array = ma.array(ma.masked) self.assertTrue(ma.allequal(collapsed_cube.data, masked_array)) self.assertTrue(ma.isMaskedArray(collapsed_cube.data)) self.assertEqual(collapsed_cube.data.shape, (1,)) def test_peak_with_nan_and_mask(self): # Single nan in column with single value masked. latitude = iris.coords.DimCoord(range(0, 5, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(ma.array([1, 4, 2, 3, 1], dtype=np.float32), standard_name='air_temperature', units='kelvin') cube.add_dim_coord(latitude, 0) cube.data[3] = np.nan cube.data[4] = ma.masked collapsed_cube = cube.collapsed('latitude', iris.analysis.PEAK) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([4.024977], dtype=np.float32)) self.assertTrue(ma.isMaskedArray(collapsed_cube.data)) self.assertEqual(collapsed_cube.data.shape, (1,)) # Only nans in column where values not masked. cube.data[0:3] = np.nan collapsed_cube = cube.collapsed('latitude', iris.analysis.PEAK) self.assertTrue(np.isnan(collapsed_cube.data).all()) self.assertTrue(ma.isMaskedArray(collapsed_cube.data)) self.assertEqual(collapsed_cube.data.shape, (1,)) def test_peak_against_max(self): # Cube with data that infers a peak value greater than the column max. latitude = iris.coords.DimCoord(range(0, 7, 1), standard_name='latitude', units='degrees') cube = iris.cube.Cube(np.array([0, 1, 3, 7, 7, 4, 2], dtype=np.float32), standard_name='air_temperature', units='kelvin') cube.add_dim_coord(latitude, 0) collapsed_cube = cube.collapsed('latitude', iris.analysis.PEAK) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([7.630991], dtype=np.float32)) collapsed_cube = cube.collapsed('latitude', iris.analysis.MAX) self.assertArrayAlmostEqual(collapsed_cube.data, np.array([7], dtype=np.float32)) if __name__ == "__main__": tests.main()
gpl-3.0
CVSoft/UTQuery
Demo_GSQuery.py
1
3672
from time import sleep import GSQuery # Let's pick a server. We'll use TeamRectifier as they're usually populated. gs = GSQuery.GSServer('31.186.250.42') # Let's get the basic server details with the GameSpy query protocol. # The query methods return dictionary types, so we can store them for later use # instead of having to ask the server every time we want to know something. try: gs_bsd = gs.parse_query() # Sometimes, our packets get lost, or the server is restarting. In that case, # we can just wait a few seconds, try again, and hope our query is returned. except: sleep(5) gs_bsd = gs.parse_query() # and find out the server's name print "Server Name :", gs_bsd["hostname"] # Now let's see what map they're on print "Map Name :", gs_bsd["mapname"] # But what are they playing? (Assume the server name didn't make this obvious.) # Let's see what game type is active. print "Gametype :", gs_bsd["gametype"] # What game version do they use? print "Game Version:", gs_bsd["gamever"] #a little cleanup for what follows... print "\n====\n" # Why do all of these methods start with parse? This is because they take a # `query` argument, which is a raw query returned by UTServer.query(). # Specifying the `query` argument is optional, and the method will send the # necessary type of query needed if one is not provided. ################################################################################ # Unlike the query method used above, the player query method does not return a # dictionary of key-value pairs, but rather a list of UTPlayer objects. # # UTPlayer objects have six attributes: # - Name, which is the colored name shown in-game, if colored names are used. # - Score # - Ping, in milliseconds. This ping value is the one shown in-game. # - Team, which for team games is (red=0, blue=1). For DeathMatch, all players # have a team value of 0. Unlike UTQuery, spectators are not shown at all. # - Player ID, which is simply the player's index in the GameSpy query response. # - Stats ID, which the GameSpy protocol doesn't implement and is set to None. # # We can access these values through their values: # name, score, ping, team, pid, sid # respectively. # # Let's start with getting the online player list. gs_players = gs.parse_players() # If we get an empty list, one of two things happened: either no players are # online, or our query was not returned. The server will return data if our # query was lost, but I haven't bothered to implement that check in my code # yet. # Now let's display their information. We really only care about name, score, # team, and ping. Since we are requesting information from a TeamArenaMaster # server, we are going to assume teams are present. For a DeathMatch server, # all players have a team value of 0, since there are no teams. # First, we should check if players are online. if len(gs_players) > 0: #If there are, let's display some information about them. print "Online Players:" for p in gs_players: # Skip anything with a ping of 0, as they're probably not real players. # Team scores appear as players with a ping of 0. if p.ping == 0: continue # Translate the team number to English. The rest are just numbers. team = ["red", "blue"][p.team] # Show their name, score, and ping. print p.name + " is on " + team + " with a score of " + str(p.score) + \ " and a ping of " + str(p.ping) + "ms." # If we didn't find anyone online, we go here. else: print "No online players!"
gpl-3.0
atuljain/odoo
addons/mass_mailing/models/mail_thread.py
65
4900
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2013-Today OpenERP SA (<http://www.openerp.com>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/> # ############################################################################## import logging from openerp import tools from openerp.addons.mail.mail_message import decode from openerp.addons.mail.mail_thread import decode_header from openerp.osv import osv _logger = logging.getLogger(__name__) class MailThread(osv.AbstractModel): """ Update MailThread to add the feature of bounced emails and replied emails in message_process. """ _name = 'mail.thread' _inherit = ['mail.thread'] def message_route_check_bounce(self, cr, uid, message, context=None): """ Override to verify that the email_to is the bounce alias. If it is the case, log the bounce, set the parent and related document as bounced and return False to end the routing process. """ bounce_alias = self.pool['ir.config_parameter'].get_param(cr, uid, "mail.bounce.alias", context=context) message_id = message.get('Message-Id') email_from = decode_header(message, 'From') email_to = decode_header(message, 'To') # 0. Verify whether this is a bounced email (wrong destination,...) -> use it to collect data, such as dead leads if bounce_alias in email_to: bounce_match = tools.bounce_re.search(email_to) if bounce_match: bounced_model, bounced_thread_id = None, False bounced_mail_id = bounce_match.group(1) stat_ids = self.pool['mail.mail.statistics'].set_bounced(cr, uid, mail_mail_ids=[bounced_mail_id], context=context) for stat in self.pool['mail.mail.statistics'].browse(cr, uid, stat_ids, context=context): bounced_model = stat.model bounced_thread_id = stat.res_id _logger.info('Routing mail from %s to %s with Message-Id %s: bounced mail from mail %s, model: %s, thread_id: %s', email_from, email_to, message_id, bounced_mail_id, bounced_model, bounced_thread_id) if bounced_model and bounced_model in self.pool and hasattr(self.pool[bounced_model], 'message_receive_bounce') and bounced_thread_id: self.pool[bounced_model].message_receive_bounce(cr, uid, [bounced_thread_id], mail_id=bounced_mail_id, context=context) return False return True def message_route(self, cr, uid, message, message_dict, model=None, thread_id=None, custom_values=None, context=None): if not self.message_route_check_bounce(cr, uid, message, context=context): return [] return super(MailThread, self).message_route(cr, uid, message, message_dict, model, thread_id, custom_values, context) def message_receive_bounce(self, cr, uid, ids, mail_id=None, context=None): """Called by ``message_process`` when a bounce email (such as Undelivered Mail Returned to Sender) is received for an existing thread. The default behavior is to check is an integer ``message_bounce`` column exists. If it is the case, its content is incremented. """ if self._all_columns.get('message_bounce'): for obj in self.browse(cr, uid, ids, context=context): self.write(cr, uid, [obj.id], {'message_bounce': obj.message_bounce + 1}, context=context) def message_route_process(self, cr, uid, message, message_dict, routes, context=None): """ Override to update the parent mail statistics. The parent is found by using the References header of the incoming message and looking for matching message_id in mail.mail.statistics. """ if message.get('References'): message_ids = [x.strip() for x in decode(message['References']).split()] self.pool['mail.mail.statistics'].set_replied(cr, uid, mail_message_ids=message_ids, context=context) return super(MailThread, self).message_route_process(cr, uid, message, message_dict, routes, context=context)
agpl-3.0
Microvellum/Fluid-Designer
win64-vc/2.78/Python/lib/site-packages/packaging/requirements.py
140
4271
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function import string import re from pyparsing import stringStart, stringEnd, originalTextFor, ParseException from pyparsing import ZeroOrMore, Word, Optional, Regex, Combine from pyparsing import Literal as L # noqa from six.moves.urllib import parse as urlparse from .markers import MARKER_EXPR, Marker from .specifiers import LegacySpecifier, Specifier, SpecifierSet class InvalidRequirement(ValueError): """ An invalid requirement was found, users should refer to PEP 508. """ ALPHANUM = Word(string.ascii_letters + string.digits) LBRACKET = L("[").suppress() RBRACKET = L("]").suppress() LPAREN = L("(").suppress() RPAREN = L(")").suppress() COMMA = L(",").suppress() SEMICOLON = L(";").suppress() AT = L("@").suppress() PUNCTUATION = Word("-_.") IDENTIFIER_END = ALPHANUM | (ZeroOrMore(PUNCTUATION) + ALPHANUM) IDENTIFIER = Combine(ALPHANUM + ZeroOrMore(IDENTIFIER_END)) NAME = IDENTIFIER("name") EXTRA = IDENTIFIER URI = Regex(r'[^ ]+')("url") URL = (AT + URI) EXTRAS_LIST = EXTRA + ZeroOrMore(COMMA + EXTRA) EXTRAS = (LBRACKET + Optional(EXTRAS_LIST) + RBRACKET)("extras") VERSION_PEP440 = Regex(Specifier._regex_str, re.VERBOSE | re.IGNORECASE) VERSION_LEGACY = Regex(LegacySpecifier._regex_str, re.VERBOSE | re.IGNORECASE) VERSION_ONE = VERSION_PEP440 ^ VERSION_LEGACY VERSION_MANY = Combine(VERSION_ONE + ZeroOrMore(COMMA + VERSION_ONE), joinString=",", adjacent=False)("_raw_spec") _VERSION_SPEC = Optional(((LPAREN + VERSION_MANY + RPAREN) | VERSION_MANY)) _VERSION_SPEC.setParseAction(lambda s, l, t: t._raw_spec or '') VERSION_SPEC = originalTextFor(_VERSION_SPEC)("specifier") VERSION_SPEC.setParseAction(lambda s, l, t: t[1]) MARKER_EXPR = originalTextFor(MARKER_EXPR())("marker") MARKER_EXPR.setParseAction( lambda s, l, t: Marker(s[t._original_start:t._original_end]) ) MARKER_SEPERATOR = SEMICOLON MARKER = MARKER_SEPERATOR + MARKER_EXPR VERSION_AND_MARKER = VERSION_SPEC + Optional(MARKER) URL_AND_MARKER = URL + Optional(MARKER) NAMED_REQUIREMENT = \ NAME + Optional(EXTRAS) + (URL_AND_MARKER | VERSION_AND_MARKER) REQUIREMENT = stringStart + NAMED_REQUIREMENT + stringEnd class Requirement(object): """Parse a requirement. Parse a given requirement string into its parts, such as name, specifier, URL, and extras. Raises InvalidRequirement on a badly-formed requirement string. """ # TODO: Can we test whether something is contained within a requirement? # If so how do we do that? Do we need to test against the _name_ of # the thing as well as the version? What about the markers? # TODO: Can we normalize the name and extra name? def __init__(self, requirement_string): try: req = REQUIREMENT.parseString(requirement_string) except ParseException as e: raise InvalidRequirement( "Invalid requirement, parse error at \"{0!r}\"".format( requirement_string[e.loc:e.loc + 8])) self.name = req.name if req.url: parsed_url = urlparse.urlparse(req.url) if not (parsed_url.scheme and parsed_url.netloc) or ( not parsed_url.scheme and not parsed_url.netloc): raise InvalidRequirement("Invalid URL given") self.url = req.url else: self.url = None self.extras = set(req.extras.asList() if req.extras else []) self.specifier = SpecifierSet(req.specifier) self.marker = req.marker if req.marker else None def __str__(self): parts = [self.name] if self.extras: parts.append("[{0}]".format(",".join(sorted(self.extras)))) if self.specifier: parts.append(str(self.specifier)) if self.url: parts.append("@ {0}".format(self.url)) if self.marker: parts.append("; {0}".format(self.marker)) return "".join(parts) def __repr__(self): return "<Requirement({0!r})>".format(str(self))
gpl-3.0
ray-project/ray
python/ray/util/collective/tests/single_node_cpu_tests/test_reducescatter.py
1
5148
"""Test the collective reducescatter API.""" import pytest import ray import numpy as np import torch from ray.util.collective.types import Backend from ray.util.collective.tests.cpu_util import create_collective_workers, \ init_tensors_for_gather_scatter @pytest.mark.parametrize("backend", [Backend.GLOO]) @pytest.mark.parametrize("tensor_backend", ["numpy", "torch"]) @pytest.mark.parametrize("array_size", [2, 2**5, 2**10, 2**15, 2**20, [2, 2], [5, 5, 5]]) def test_reducescatter_different_array_size(ray_start_single_node, array_size, tensor_backend, backend): world_size = 2 actors, _ = create_collective_workers(world_size, backend=backend) init_tensors_for_gather_scatter( actors, array_size=array_size, tensor_backend=tensor_backend) results = ray.get([a.do_reducescatter.remote() for a in actors]) for i in range(world_size): if tensor_backend == "numpy": assert (results[i] == np.ones(array_size, dtype=np.float32) * world_size).all() else: assert (results[i] == torch.ones(array_size, dtype=torch.float32) * world_size).all() @pytest.mark.parametrize("backend", [Backend.GLOO]) @pytest.mark.parametrize("dtype", [np.uint8, np.float16, np.float32, np.float64]) def test_reducescatter_different_dtype(ray_start_single_node, dtype, backend): world_size = 2 actors, _ = create_collective_workers(world_size, backend=backend) init_tensors_for_gather_scatter(actors, dtype=dtype) results = ray.get([a.do_reducescatter.remote() for a in actors]) for i in range(world_size): for j in range(world_size): assert (results[i] == np.ones(10, dtype=dtype) * world_size).all() @pytest.mark.parametrize("backend", [Backend.GLOO]) def test_reducescatter_torch_numpy(ray_start_single_node, backend): world_size = 2 shape = [10, 10] actors, _ = create_collective_workers(world_size, backend=backend) # tensor is pytorch, list is numpy for i, a in enumerate(actors): t = torch.ones(shape, dtype=torch.float32) * (i + 1) ray.wait([a.set_buffer.remote(t)]) list_buffer = [ np.ones(shape, dtype=np.float32) for _ in range(world_size) ] ray.wait([a.set_list_buffer.remote(list_buffer)]) results = ray.get([a.do_reducescatter.remote() for a in actors]) for i in range(world_size): assert (results[i] == torch.ones(shape, dtype=torch.float32) * world_size).all() # tensor is numpy, list is pytorch for i, a in enumerate(actors): t = np.ones(shape, dtype=np.float32) * (i + 1) ray.wait([a.set_buffer.remote(t)]) list_buffer = [ torch.ones(shape, dtype=torch.float32) for _ in range(world_size) ] ray.wait([a.set_list_buffer.remote(list_buffer)]) results = ray.get([a.do_reducescatter.remote() for a in actors]) for i in range(world_size): assert ( results[i] == np.ones(shape, dtype=np.float32) * world_size).all() # some tensors in the list are pytorch, some are numpy for i, a in enumerate(actors): if i % 2 == 0: t = torch.ones(shape, dtype=torch.float32) * (i + 1) else: t = np.ones(shape, dtype=np.float32) * (i + 1) ray.wait([a.set_buffer.remote(t)]) list_buffer = [] for j in range(world_size): if j % 2 == 0: list_buffer.append(torch.ones(shape, dtype=torch.float32)) else: list_buffer.append(np.ones(shape, dtype=np.float32)) ray.wait([a.set_list_buffer.remote(list_buffer)]) results = ray.get([a.do_reducescatter.remote() for a in actors]) for i in range(world_size): if i % 2 == 0: assert (results[i] == torch.ones(shape, dtype=torch.float32) * world_size).all() else: assert (results[i] == np.ones(shape, dtype=np.float32) * world_size).all() # mixed case for i, a in enumerate(actors): if i % 2 == 0: t = torch.ones(shape, dtype=torch.float32) * (i + 1) else: t = np.ones(shape, dtype=np.float32) * (i + 1) ray.wait([a.set_buffer.remote(t)]) list_buffer = [] for j in range(world_size): if j % 2 == 0: list_buffer.append(np.ones(shape, dtype=np.float32)) else: list_buffer.append(torch.ones(shape, dtype=torch.float32)) ray.wait([a.set_list_buffer.remote(list_buffer)]) results = ray.get([a.do_reducescatter.remote() for a in actors]) for i in range(world_size): if i % 2 == 0: assert (results[i] == torch.ones(shape, dtype=torch.float32) * world_size).all() else: assert (results[i] == np.ones(shape, dtype=np.float32) * world_size).all() if __name__ == "__main__": import pytest import sys sys.exit(pytest.main(["-v", "-x", __file__]))
apache-2.0
vhanla/CudaText
app/cudatext.app/Contents/Resources/py/cuda_addonman/__init__.py
2
20035
import os import re import shutil import json import collections import webbrowser import subprocess from cudatext import * from urllib.parse import unquote from .work_local import * from .work_remote import * from .work_dlg_config import * from .work_github import * from .work_cudatext_updates__fosshub import check_cudatext from .work_install_helper import after_install from . import opt dir_for_all = os.path.join(os.path.expanduser('~'), 'CudaText_addons') fn_config = os.path.join(app_path(APP_DIR_SETTINGS), 'cuda_addonman.json') PREINST = 'preinstalled' STD_MODULES = ( 'cuda_addonman', 'cuda_comments', 'cuda_emmet', 'cuda_insert_time', 'cuda_make_plugin', 'cuda_multi_installer', 'cuda_new_file', 'cuda_options_editor', 'cuda_palette', 'cuda_project_man', 'cuda_show_unsaved', 'cuda_snippet_panel', 'cuda_sort', 'cuda_tabs_list', 'cuda_tree_markdown', 'cuda_lexer_detecter', ) STD_LEXERS = ( 'Assembly', 'Bash script', 'Batch files', 'C', 'C++', 'CSS', 'HTML', 'Ini files', 'JavaScript', 'JSDoc', 'JSON', 'Lua', 'Markdown', 'PHP', 'PHP_', 'PowerShell', 'Python', 'RegEx', 'reStructuredText', 'Search results', 'VBScript', 'XML', 'YAML', ) STD_LEXERS_LITE = ( 'JSON', 'Log files', 'SQL', 'XML', ) STD_THEMES = ( 'amy', 'cobalt', 'darkwolf', 'ebony', 'green', 'navy', 'sub', 'white', 'zeus', ) STD_TRANSLATIONS = ( 'ru_RU', 'translation template', ) STD_SNIPPETS = ( 'Std.HtmlTags', 'Std.Php', ) class Command: def __init__(self): if os.path.isfile(fn_config): data = json.loads(open(fn_config).read(), object_pairs_hook=collections.OrderedDict) opt.ch_user = data.get('channels_user', opt.ch_user) opt.suggest_readme = data.get('suggest_readme', True) opt.install_confirm = data.get('install_confirm', True) opt.proxy = data.get('proxy', '') def do_config(self): res = do_config_dialog() if res is None: return data = {} data['channels_user'] = opt.ch_user data['suggest_readme'] = opt.suggest_readme data['install_confirm'] = opt.install_confirm data['proxy'] = opt.proxy with open(fn_config, 'w') as f: f.write(json.dumps(data, indent=4)) def do_show_links(self): msg_status('Downloading list...') items = get_remote_addons_list(opt.ch_def+opt.ch_user) msg_status('') if not items: msg_status('Cannot download list') return res = sorted([item['url'] for item in items]) file_open('') ed.set_text_all('\n'.join(res)+'\n') def do_download_all(self): global dir_for_all res = dlg_input('Folder to save files:', dir_for_all) if not res: return dir_for_all = res if not os.path.isdir(dir_for_all): os.mkdir(dir_for_all) if not os.path.isdir(dir_for_all): msg_box('Cannot create dir: '+dir_for_all, MB_OK+MB_ICONERROR) return msg_status('Downloading list...') items = get_remote_addons_list(opt.ch_def+opt.ch_user) msg_status('') if not items: msg_status('Cannot download list') return self.init_progress() self.stopped = False self.stopped_force = False self.stopped_msg = '' dlg_proc(self.h_pro, DLG_SHOW_NONMODAL) err = 0 for (i, item) in enumerate(items): url = item['url'] if self.stopped: self.stopped_force = True self.stopped_msg = '(got %d of %d files)' % (i+1, len(items)) break percent = (i+1)*100//len(items) text = 'Downloading: %d/%d'%(i+1, len(items)) self.show_progress(percent, text) name = unquote(url.split('/')[-1]) dir = os.path.join(dir_for_all, name.split('.')[0]) if not os.path.isdir(dir): os.mkdir(dir) fn = os.path.join(dir, name) res = get_url(url, fn) if res == False: #abort button break if not os.path.isfile(fn): err += 1 print('Cannot download file: '+url) continue self.hide_progress() text = 'Download complete' if not self.stopped_force else 'Download stopped '+self.stopped_msg if err>0: text += '\nErrors occured, see Python console' msg_box(text, MB_OK+MB_ICONINFO) def do_reinstall_addon(self): self.do_install_addon(True) def do_install_addon(self, reinstall=False): def is_item_installed(item, installed_modules, installed_lexers): if item['kind']=='lexer': return item['name'] in installed_lexers else: return item.get('module', '') in installed_modules caption = 'Re-install' if reinstall else 'Install' msg_status('Downloading list...') items = get_remote_addons_list(opt.ch_def+opt.ch_user) msg_status('') if not items: msg_status('Cannot download list') return items = sorted(items, key=lambda item: (item['kind'], item['name']) ) kinds = sorted(list(set([i['kind'] for i in items]))) installed = get_installed_addons() installed_modules = [i['module'] for i in installed if i['kind']=='plugin'] installed_lexers = [i['name'].replace(' ', '_') for i in installed if i['kind']=='lexer'] if reinstall: items = [i for i in items if is_item_installed(i, installed_modules, installed_lexers)] else: items = [i for i in items if not is_item_installed(i, installed_modules, installed_lexers)] names = ['<Category>'] + [ i['kind']+': '+i['name']+'\t'+i['desc'] for i in items ] res = dlg_menu( MENU_LIST_ALT+MENU_NO_FUZZY+MENU_NO_FULLFILTER, names, caption=caption ) if res is None: return if res==0: res = dlg_menu( MENU_LIST, kinds, caption='Category' ) if res is None: return need_kind = kinds[res] items = [ i for i in items if i['kind']==need_kind ] names = [ i['kind']+': '+i['name']+'\t'+i['desc'] for i in items ] res = dlg_menu( MENU_LIST_ALT+MENU_NO_FUZZY+MENU_NO_FULLFILTER, names, caption=caption+' / Category "'+need_kind+'"' ) if res is None: return name = items[res]['name'] url = items[res]['url'] version = items[res]['v'] kind = items[res]['kind'] req = items[res].get('req', '') else: res -= 1 name = items[res]['name'] url = items[res]['url'] version = items[res]['v'] kind = items[res]['kind'] req = items[res].get('req', '') req_items = [] for req_name in req.split(','): req_items += [i for i in items if req_name+'.zip'==os.path.basename(i['url']) ] if req_items: req_names = ', '.join([i['kind']+': '+i['name'] for i in req_items]) if msg_box('Add-on "%s" requires:\n%s\n\nRequirements will be auto-installed. Proceed?' % (name, req_names), MB_OKCANCEL+MB_ICONQUESTION)!=ID_OK: return for item in req_items: self.do_install_single(item['name'], item['url'], item['v'], item['kind'], True, False) self.do_install_single(name, url, version, kind, not opt.install_confirm, opt.suggest_readme) def do_install_single(self, name, url, version, kind, is_silent, suggest_readme): #check for CudaLint if 'linter.' in url: if not 'cuda_lint' in get_installed_modules(): msg_box('This is linter, it requires CudaLint plugin installed', MB_OK+MB_ICONWARNING) return #check for CudaFormatter if 'formatter.' in url: if not 'cuda_fmt' in get_installed_modules(): msg_box('This is formatter, it requires CudaFormatter plugin installed', MB_OK+MB_ICONWARNING) return #download fn = get_plugin_zip(url) if not os.path.isfile(fn): msg_status('Cannot download file') return s_options = '/silent' if is_silent else '' ok = file_open(fn, options=s_options) msg_status('Addon installed' if ok else 'Installation cancelled') if not ok: os.remove(fn) return #save version props = do_save_version(url, fn, version) os.remove(fn) if props: #suggest readme m = props[2] if m: after_install(m) if m and suggest_readme: names = [] fn = get_readme_of_module(m) if fn: names.append((get_name_of_module(m)+': view readme', fn)) fn = get_history_of_module(m) if fn: names.append((get_name_of_module(m)+': view history', fn)) if names: res = dlg_menu(MENU_LIST, [s[0] for s in names]) if res is None: return file_open(names[res][1]) def do_install_lexer(self): """Not used. For future? Suggest only lexers to install""" items = get_avail_list() items = [l for l in items if l[0].startswith('Lexer:')] res = dlg_menu(MENU_LIST, [l[0] for l in items]) if res is None: return res = items[res] url = get_item_url(res[2]) fn = get_plugin_zip(url) if os.path.isfile(fn): file_open(fn) def do_remove(self): items = get_installed_addons({ 'plugins': STD_MODULES, 'lexers': STD_LEXERS, 'lexers_lite': STD_LEXERS_LITE, 'themes': STD_THEMES, 'lang': STD_TRANSLATIONS, 'snippets': STD_SNIPPETS, }) desc = [i['kind']+': '+i['name'] for i in items] res = dlg_menu(MENU_LIST, desc, caption='Remove add-on') if res is None: return item = items[res] if msg_box('Remove '+item['kind']+': '+item['name'], MB_OKCANCEL+MB_ICONQUESTION)!=ID_OK: return module = item.get('module', '') if module: do_remove_version_of_plugin(module) ok = True for fn in item['files']: if fn.endswith('/'): fn = fn[:-1] ok = do_remove_dir(fn) else: if os.path.isfile(fn): os.remove(fn) if ok: msg_box('Removed, restart program to see changes', MB_OK+MB_ICONINFO) def do_edit(self): m = get_installed_choice('Edit') if m is None: return fn = get_initpy_of_module(m) file_open(fn) msg_status('Opened: '+fn) def do_homepage(self): m = get_installed_choice('Visit homepage') if m is None: return s = get_homepage_of_module(m) if s: webbrowser.open_new_tab(s) msg_status('Opened browser: '+s) else: msg_box('Plugin "%s" doesn\'t have "homepage" field in install.inf' % \ get_name_of_module(m), MB_OK+MB_ICONWARNING) def do_readme(self): m = get_installed_choice('Open readme') if m is None: return s = get_readme_of_module(m) if s: file_open(s) else: msg_status('Plugin "%s" doesn\'t have readme' % get_name_of_module(m)) def do_history(self): m = get_installed_choice('Open history') if m is None: return s = get_history_of_module(m) if s: file_open(s) else: msg_status('Plugin "%s" doesn\'t have history' % get_name_of_module(m)) def do_update(self): def fix_name(s, del_brackets): s = s.replace(' ', '_') # strip additions in name for "gruvbox (Dark) (Medium)" if del_brackets: n = s.find('_(') if n>=0: s = s[:n] return s dir_data = app_path(APP_DIR_DATA) dir_py = app_path(APP_DIR_PY) msg_status('Downloading list...') addons = get_remote_addons_list(opt.ch_def+opt.ch_user) msg_status('') if not addons: msg_status('Cannot download list') return modules = get_installed_modules() modules_git = [m for m in modules if os.path.isdir(os.path.join(dir_py, m, '.git'))] modules = [m for m in modules if not m in modules_git] installed = get_installed_addons() lexers = [fix_name(i['name'], False) for i in installed if i['kind']=='lexer'] langs = [fix_name(i['name'], False) for i in installed if i['kind']=='translation'] themes = [fix_name(i['name'], True) for i in installed if i['kind']=='theme'] addons = [a for a in addons if a['kind'] in ('plugin', 'treehelper', 'linter', 'formatter') and a.get('module', '') in modules] \ + [a for a in addons if a['kind']=='lexer' and a['name'] in lexers] \ + [a for a in addons if a['kind']=='translation' and a['name'] in langs] \ + [a for a in addons if a['kind']=='theme' and a['name'].lower() in themes] modules_web = [a.get('module', '') for a in addons] modules_web = [a for a in modules_web if a] modules_local = [m for m in modules if m not in modules_web] for a in addons: m = a.get('module', '') if a['kind']=='lexer': a['dir'] = 'data/lexlib' elif a['kind']=='translation': a['dir'] = 'data/lang' elif a['kind']=='theme': a['dir'] = 'data/themes' else: a['dir'] = 'py/'+m v_local = '?' if m in STD_MODULES: v_local = PREINST url = a['url'] v_remote = a['v'] v_local = get_addon_version(url) or v_local a['v_local'] = v_local a['check'] = (v_local!=PREINST) and ((v_local=='?') or (v_local<v_remote)) for m in modules_git: d = {} d['module'] = m d['dir'] = 'py/'+m d['kind'] = 'plugin' d['name'] = get_name_of_module(m) d['v_local'] = 'Git' d['v'] = 'Git' d['url'] = '' d['check'] = False addons.append(d) text_headers = '\r'.join(('Name=260', 'Folder=180', 'Local=125', 'Available=125')) text_columns = ['\r'.join(('['+i['kind']+'] '+i['name'], i['dir'], i['v_local'], i['v'])) for i in addons] text_items = '\t'.join([text_headers]+text_columns) text_checks = ['1' if i['check'] else '0' for i in addons] text_val = '0;'+','.join(text_checks) text_val_initial = text_val RES_OK = 0 RES_CANCEL = 1 RES_LIST = 2 RES_SEL_NONE = 3 RES_SEL_NEW = 4 c1 = chr(1) while True: text = '\n'.join([ c1.join(['type=button', 'pos=514,500,614,0', 'cap=Update', 'props=1']), c1.join(['type=button', 'pos=620,500,720,0', 'cap=Cancel']), c1.join(['type=checklistview', 'pos=6,6,720,490', 'items='+text_items, 'val='+text_val, 'props=1']), c1.join(['type=button', 'pos=6,500,100,0', 'cap=Deselect all']), c1.join(['type=button', 'pos=106,500,200,0', 'cap=Select new']), ]) res = dlg_custom('Update add-ons', 726, 532, text) if res is None: return res, text = res if res == RES_SEL_NONE: text_val = '0;' continue if res == RES_SEL_NEW: text_val = text_val_initial continue if res == RES_CANCEL: return if res == RES_OK: break text = text.splitlines()[RES_LIST] text = text.split(';')[1].split(',') addons = [a for (i, a) in enumerate(addons) if 0<=i<len(text) and text[i]=='1'] if not addons: return print('Updating addons:') fail_count = 0 for a in addons: print(' [%s] %s' % (a['kind'], a['name'])) msg_status('Updating: [%s] %s' % (a['kind'], a['name']), True) m = a.get('module', '') if m: # special update for Git repos m_dir = os.path.join(app_path(APP_DIR_PY), m) if os.path.isdir(os.path.join(m_dir, '.git')): msg_status('Running "git pull" in "%s"'%m_dir, True) try: subprocess.call(['git', 'stash', 'save'], cwd=m_dir) subprocess.call(['git', 'pull'], cwd=m_dir) except: msg_status('Error running Git', True) print(' Error running Git') else: # delete old dir do_remove_dir(m_dir) url = a['url'] if not url: continue fn = get_plugin_zip(url) if not fn: continue if os.path.isfile(fn) and file_open(fn, options='/silent'): do_save_version(url, fn, a['v']) else: fail_count += 1 print(' Update failed: [%s] %s' % (a['kind'], a['name']) ) s = 'Done' if fail_count>0: s += ', with %d fail(s)'%fail_count print(s) msg_status(s) def check_cudatext_updates(self): check_cudatext() def install_from_github(self): do_install_from_github() def init_progress(self): self.h_pro = dlg_proc(0, DLG_CREATE) dlg_proc(self.h_pro, DLG_PROP_SET, prop={ 'cap': 'Download add-ons', 'w': 400, 'h': 110, 'topmost': True, 'on_close': self.progress_close, }) n = dlg_proc(self.h_pro, DLG_CTL_ADD, prop='label') dlg_proc(self.h_pro, DLG_CTL_PROP_SET, index=n, prop={ 'name': 'inf', 'cap': 'Downloading...', 'x': 10, 'y': 25, }) n = dlg_proc(self.h_pro, DLG_CTL_ADD, prop='progressbar') dlg_proc(self.h_pro, DLG_CTL_PROP_SET, index=n, prop={ 'name': 'pro', 'x': 10, 'y': 50, 'w': 380, 'h': 15, 'ex1': 0, #min 'ex2': 100, #max 'ex3': True, #smooth }) n = dlg_proc(self.h_pro, DLG_CTL_ADD, prop='button') dlg_proc(self.h_pro, DLG_CTL_PROP_SET, index=n, prop={ 'name': 'btn', 'cap': 'Cancel', 'x': 150, 'w': 100, 'y': 80, 'on_change': self.progress_btn_click, }) def show_progress(self, percent, text): dlg_proc(self.h_pro, DLG_CTL_PROP_SET, name='pro', prop={'val': percent,}) dlg_proc(self.h_pro, DLG_CTL_PROP_SET, name='inf', prop={'cap': text,}) app_idle(False) def hide_progress(self): dlg_proc(self.h_pro, DLG_HIDE) dlg_proc(self.h_pro, DLG_FREE) self.h_pro = None def progress_btn_click(self, id_dlg, id_ctl, data='', info=''): self.stopped = True def progress_close(self, id_dlg, id_ctl, data='', info=''): self.stopped = True
mpl-2.0
40223209/2015cd_midterm
static/Brython3.1.1-20150328-091302/Lib/textwrap.py
745
16488
"""Text wrapping and filling. """ # Copyright (C) 1999-2001 Gregory P. Ward. # Copyright (C) 2002, 2003 Python Software Foundation. # Written by Greg Ward <gward@python.net> import re __all__ = ['TextWrapper', 'wrap', 'fill', 'dedent', 'indent'] # Hardcode the recognized whitespace characters to the US-ASCII # whitespace characters. The main reason for doing this is that in # ISO-8859-1, 0xa0 is non-breaking whitespace, so in certain locales # that character winds up in string.whitespace. Respecting # string.whitespace in those cases would 1) make textwrap treat 0xa0 the # same as any other whitespace char, which is clearly wrong (it's a # *non-breaking* space), 2) possibly cause problems with Unicode, # since 0xa0 is not in range(128). _whitespace = '\t\n\x0b\x0c\r ' class TextWrapper: """ Object for wrapping/filling text. The public interface consists of the wrap() and fill() methods; the other methods are just there for subclasses to override in order to tweak the default behaviour. If you want to completely replace the main wrapping algorithm, you'll probably have to override _wrap_chunks(). Several instance attributes control various aspects of wrapping: width (default: 70) the maximum width of wrapped lines (unless break_long_words is false) initial_indent (default: "") string that will be prepended to the first line of wrapped output. Counts towards the line's width. subsequent_indent (default: "") string that will be prepended to all lines save the first of wrapped output; also counts towards each line's width. expand_tabs (default: true) Expand tabs in input text to spaces before further processing. Each tab will become 0 .. 'tabsize' spaces, depending on its position in its line. If false, each tab is treated as a single character. tabsize (default: 8) Expand tabs in input text to 0 .. 'tabsize' spaces, unless 'expand_tabs' is false. replace_whitespace (default: true) Replace all whitespace characters in the input text by spaces after tab expansion. Note that if expand_tabs is false and replace_whitespace is true, every tab will be converted to a single space! fix_sentence_endings (default: false) Ensure that sentence-ending punctuation is always followed by two spaces. Off by default because the algorithm is (unavoidably) imperfect. break_long_words (default: true) Break words longer than 'width'. If false, those words will not be broken, and some lines might be longer than 'width'. break_on_hyphens (default: true) Allow breaking hyphenated words. If true, wrapping will occur preferably on whitespaces and right after hyphens part of compound words. drop_whitespace (default: true) Drop leading and trailing whitespace from lines. """ unicode_whitespace_trans = {} uspace = ord(' ') for x in _whitespace: unicode_whitespace_trans[ord(x)] = uspace # This funky little regex is just the trick for splitting # text up into word-wrappable chunks. E.g. # "Hello there -- you goof-ball, use the -b option!" # splits into # Hello/ /there/ /--/ /you/ /goof-/ball,/ /use/ /the/ /-b/ /option! # (after stripping out empty strings). wordsep_re = re.compile( r'(\s+|' # any whitespace r'[^\s\w]*\w+[^0-9\W]-(?=\w+[^0-9\W])|' # hyphenated words r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w))') # em-dash # This less funky little regex just split on recognized spaces. E.g. # "Hello there -- you goof-ball, use the -b option!" # splits into # Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/ wordsep_simple_re = re.compile(r'(\s+)') # XXX this is not locale- or charset-aware -- string.lowercase # is US-ASCII only (and therefore English-only) sentence_end_re = re.compile(r'[a-z]' # lowercase letter r'[\.\!\?]' # sentence-ending punct. r'[\"\']?' # optional end-of-quote r'\Z') # end of chunk def __init__(self, width=70, initial_indent="", subsequent_indent="", expand_tabs=True, replace_whitespace=True, fix_sentence_endings=False, break_long_words=True, drop_whitespace=True, break_on_hyphens=True, tabsize=8): self.width = width self.initial_indent = initial_indent self.subsequent_indent = subsequent_indent self.expand_tabs = expand_tabs self.replace_whitespace = replace_whitespace self.fix_sentence_endings = fix_sentence_endings self.break_long_words = break_long_words self.drop_whitespace = drop_whitespace self.break_on_hyphens = break_on_hyphens self.tabsize = tabsize # -- Private methods ----------------------------------------------- # (possibly useful for subclasses to override) def _munge_whitespace(self, text): """_munge_whitespace(text : string) -> string Munge whitespace in text: expand tabs and convert all other whitespace characters to spaces. Eg. " foo\tbar\n\nbaz" becomes " foo bar baz". """ if self.expand_tabs: text = text.expandtabs(self.tabsize) if self.replace_whitespace: text = text.translate(self.unicode_whitespace_trans) return text def _split(self, text): """_split(text : string) -> [string] Split the text to wrap into indivisible chunks. Chunks are not quite the same as words; see _wrap_chunks() for full details. As an example, the text Look, goof-ball -- use the -b option! breaks into the following chunks: 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', 'use', ' ', 'the', ' ', '-b', ' ', 'option!' if break_on_hyphens is True, or in: 'Look,', ' ', 'goof-ball', ' ', '--', ' ', 'use', ' ', 'the', ' ', '-b', ' ', option!' otherwise. """ if self.break_on_hyphens is True: chunks = self.wordsep_re.split(text) else: chunks = self.wordsep_simple_re.split(text) chunks = [c for c in chunks if c] return chunks def _fix_sentence_endings(self, chunks): """_fix_sentence_endings(chunks : [string]) Correct for sentence endings buried in 'chunks'. Eg. when the original text contains "... foo.\nBar ...", munge_whitespace() and split() will convert that to [..., "foo.", " ", "Bar", ...] which has one too few spaces; this method simply changes the one space to two. """ i = 0 patsearch = self.sentence_end_re.search while i < len(chunks)-1: if chunks[i+1] == " " and patsearch(chunks[i]): chunks[i+1] = " " i += 2 else: i += 1 def _handle_long_word(self, reversed_chunks, cur_line, cur_len, width): """_handle_long_word(chunks : [string], cur_line : [string], cur_len : int, width : int) Handle a chunk of text (most likely a word, not whitespace) that is too long to fit in any line. """ # Figure out when indent is larger than the specified width, and make # sure at least one character is stripped off on every pass if width < 1: space_left = 1 else: space_left = width - cur_len # If we're allowed to break long words, then do so: put as much # of the next chunk onto the current line as will fit. if self.break_long_words: cur_line.append(reversed_chunks[-1][:space_left]) reversed_chunks[-1] = reversed_chunks[-1][space_left:] # Otherwise, we have to preserve the long word intact. Only add # it to the current line if there's nothing already there -- # that minimizes how much we violate the width constraint. elif not cur_line: cur_line.append(reversed_chunks.pop()) # If we're not allowed to break long words, and there's already # text on the current line, do nothing. Next time through the # main loop of _wrap_chunks(), we'll wind up here again, but # cur_len will be zero, so the next line will be entirely # devoted to the long word that we can't handle right now. def _wrap_chunks(self, chunks): """_wrap_chunks(chunks : [string]) -> [string] Wrap a sequence of text chunks and return a list of lines of length 'self.width' or less. (If 'break_long_words' is false, some lines may be longer than this.) Chunks correspond roughly to words and the whitespace between them: each chunk is indivisible (modulo 'break_long_words'), but a line break can come between any two chunks. Chunks should not have internal whitespace; ie. a chunk is either all whitespace or a "word". Whitespace chunks will be removed from the beginning and end of lines, but apart from that whitespace is preserved. """ lines = [] if self.width <= 0: raise ValueError("invalid width %r (must be > 0)" % self.width) # Arrange in reverse order so items can be efficiently popped # from a stack of chucks. chunks.reverse() while chunks: # Start the list of chunks that will make up the current line. # cur_len is just the length of all the chunks in cur_line. cur_line = [] cur_len = 0 # Figure out which static string will prefix this line. if lines: indent = self.subsequent_indent else: indent = self.initial_indent # Maximum width for this line. width = self.width - len(indent) # First chunk on line is whitespace -- drop it, unless this # is the very beginning of the text (ie. no lines started yet). if self.drop_whitespace and chunks[-1].strip() == '' and lines: del chunks[-1] while chunks: l = len(chunks[-1]) # Can at least squeeze this chunk onto the current line. if cur_len + l <= width: cur_line.append(chunks.pop()) cur_len += l # Nope, this line is full. else: break # The current line is full, and the next chunk is too big to # fit on *any* line (not just this one). if chunks and len(chunks[-1]) > width: self._handle_long_word(chunks, cur_line, cur_len, width) # If the last chunk on this line is all whitespace, drop it. if self.drop_whitespace and cur_line and cur_line[-1].strip() == '': del cur_line[-1] # Convert current line back to a string and store it in list # of all lines (return value). if cur_line: lines.append(indent + ''.join(cur_line)) return lines # -- Public interface ---------------------------------------------- def wrap(self, text): """wrap(text : string) -> [string] Reformat the single paragraph in 'text' so it fits in lines of no more than 'self.width' columns, and return a list of wrapped lines. Tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. """ text = self._munge_whitespace(text) chunks = self._split(text) if self.fix_sentence_endings: self._fix_sentence_endings(chunks) return self._wrap_chunks(chunks) def fill(self, text): """fill(text : string) -> string Reformat the single paragraph in 'text' to fit in lines of no more than 'self.width' columns, and return a new string containing the entire wrapped paragraph. """ return "\n".join(self.wrap(text)) # -- Convenience interface --------------------------------------------- def wrap(text, width=70, **kwargs): """Wrap a single paragraph of text, returning a list of wrapped lines. Reformat the single paragraph in 'text' so it fits in lines of no more than 'width' columns, and return a list of wrapped lines. By default, tabs in 'text' are expanded with string.expandtabs(), and all other whitespace characters (including newline) are converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ w = TextWrapper(width=width, **kwargs) return w.wrap(text) def fill(text, width=70, **kwargs): """Fill a single paragraph of text, returning a new string. Reformat the single paragraph in 'text' to fit in lines of no more than 'width' columns, and return a new string containing the entire wrapped paragraph. As with wrap(), tabs are expanded and other whitespace characters converted to space. See TextWrapper class for available keyword args to customize wrapping behaviour. """ w = TextWrapper(width=width, **kwargs) return w.fill(text) # -- Loosely related functionality ------------------------------------- _whitespace_only_re = re.compile('^[ \t]+$', re.MULTILINE) _leading_whitespace_re = re.compile('(^[ \t]*)(?:[^ \t\n])', re.MULTILINE) def dedent(text): """Remove any common leading whitespace from every line in `text`. This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form. Note that tabs and spaces are both treated as whitespace, but they are not equal: the lines " hello" and "\thello" are considered to have no common leading whitespace. (This behaviour is new in Python 2.5; older versions of this module incorrectly expanded tabs before searching for common leading whitespace.) """ # Look for the longest leading string of spaces and tabs common to # all lines. margin = None text = _whitespace_only_re.sub('', text) indents = _leading_whitespace_re.findall(text) for indent in indents: if margin is None: margin = indent # Current line more deeply indented than previous winner: # no change (previous winner is still on top). elif indent.startswith(margin): pass # Current line consistent with and no deeper than previous winner: # it's the new winner. elif margin.startswith(indent): margin = indent # Current line and previous winner have no common whitespace: # there is no margin. else: margin = "" break # sanity check (testing/debugging only) if 0 and margin: for line in text.split("\n"): assert not line or line.startswith(margin), \ "line = %r, margin = %r" % (line, margin) if margin: text = re.sub(r'(?m)^' + margin, '', text) return text def indent(text, prefix, predicate=None): """Adds 'prefix' to the beginning of selected lines in 'text'. If 'predicate' is provided, 'prefix' will only be added to the lines where 'predicate(line)' is True. If 'predicate' is not provided, it will default to adding 'prefix' to all non-empty lines that do not consist solely of whitespace characters. """ if predicate is None: def predicate(line): return line.strip() def prefixed_lines(): for line in text.splitlines(True): yield (prefix + line if predicate(line) else line) return ''.join(prefixed_lines()) if __name__ == "__main__": #print dedent("\tfoo\n\tbar") #print dedent(" \thello there\n \t how are you?") print(dedent("Hello there.\n This is indented."))
gpl-3.0
brennie/reviewboard
reviewboard/webapi/tests/test_review_reply_general_comment.py
5
9334
from __future__ import unicode_literals from django.utils import six from reviewboard.reviews.models import GeneralComment from reviewboard.webapi.resources import resources from reviewboard.webapi.tests.base import BaseWebAPITestCase from reviewboard.webapi.tests.mimetypes import ( review_reply_general_comment_item_mimetype, review_reply_general_comment_list_mimetype) from reviewboard.webapi.tests.mixins import ( BasicTestsMetaclass, ReviewRequestChildItemMixin, ReviewRequestChildListMixin) from reviewboard.webapi.tests.mixins_comment import ( CommentReplyItemMixin, CommentReplyListMixin) from reviewboard.webapi.tests.urls import ( get_review_reply_general_comment_item_url, get_review_reply_general_comment_list_url) @six.add_metaclass(BasicTestsMetaclass) class ResourceListTests(CommentReplyListMixin, ReviewRequestChildListMixin, BaseWebAPITestCase): """Testing the ReviewReplyGeneralCommentResource list APIs.""" fixtures = ['test_users'] sample_api_url = \ 'review-requests/<id>/reviews/<id>/replies/<id>/general-comments/' resource = resources.review_reply_general_comment def setup_review_request_child_test(self, review_request): review = self.create_review(review_request, user=self.user, publish=True) self.create_general_comment(review) reply = self.create_reply(review, user=self.user) return (get_review_reply_general_comment_list_url(reply), review_reply_general_comment_list_mimetype) def compare_item(self, item_rsp, comment): self.assertEqual(item_rsp['id'], comment.pk) self.assertEqual(item_rsp['text'], comment.text) if comment.rich_text: self.assertEqual(item_rsp['text_type'], 'markdown') else: self.assertEqual(item_rsp['text_type'], 'plain') # # HTTP GET tests # def setup_basic_get_test(self, user, with_local_site, local_site_name, populate_items): review_request = self.create_review_request( with_local_site=with_local_site, submitter=user, publish=True) review = self.create_review(review_request, user=user) comment = self.create_general_comment(review) reply = self.create_reply(review, user=user) if populate_items: items = [ self.create_general_comment(reply, reply_to=comment), ] else: items = [] return (get_review_reply_general_comment_list_url(reply, local_site_name), review_reply_general_comment_list_mimetype, items) # # HTTP POST tests # def setup_basic_post_test(self, user, with_local_site, local_site_name, post_valid_data): review_request = self.create_review_request( with_local_site=with_local_site, submitter=user, publish=True) review = self.create_review(review_request, user=user, publish=True) comment = self.create_general_comment(review) reply = self.create_reply(review, user=user) return (get_review_reply_general_comment_list_url(reply, local_site_name), review_reply_general_comment_item_mimetype, { 'reply_to_id': comment.pk, 'text': 'Test comment', }, [reply, comment]) def check_post_result(self, user, rsp, reply, comment): reply_comment = \ GeneralComment.objects.get(pk=rsp['general_comment']['id']) self.assertEqual(reply_comment.text, 'Test comment') self.assertEqual(reply_comment.reply_to, comment) self.assertEqual(reply_comment.rich_text, False) self.compare_item(rsp['general_comment'], reply_comment) def test_post_with_http_303(self): """Testing the POST review-requests/<id>/reviews/<id>/replies/<id>/general-comments/ API with second instance of same reply """ comment_text = "My Comment Text" review_request = self.create_review_request(publish=True) review = self.create_review(review_request, user=self.user, publish=True) comment = self.create_general_comment(review) reply = self.create_reply(review, user=self.user) reply_comment = self.create_general_comment(reply, reply_to=comment) # Now post another reply to the same comment in the same review. rsp = self.api_post( get_review_reply_general_comment_list_url(reply), { 'reply_to_id': comment.pk, 'text': comment_text }, expected_status=303, expected_mimetype=review_reply_general_comment_item_mimetype) self.assertEqual(rsp['stat'], 'ok') reply_comment = GeneralComment.objects.get( pk=rsp['general_comment']['id']) self.assertEqual(reply_comment.text, comment_text) @six.add_metaclass(BasicTestsMetaclass) class ResourceItemTests(CommentReplyItemMixin, ReviewRequestChildItemMixin, BaseWebAPITestCase): """Testing the ReviewReplyGeneralCommentResource item APIs.""" fixtures = ['test_users'] sample_api_url = ('review-requests/<id>/reviews/<id>/replies/<id>/' 'general-comments/<id>/') resource = resources.review_reply_general_comment def setup_review_request_child_test(self, review_request): review = self.create_review(review_request, user=self.user, publish=True) comment = self.create_general_comment(review) reply = self.create_reply(review, user=self.user) reply_comment = self.create_general_comment(reply, reply_to=comment) return (get_review_reply_general_comment_item_url(reply, reply_comment.pk), review_reply_general_comment_item_mimetype) def compare_item(self, item_rsp, comment): self.assertEqual(item_rsp['id'], comment.pk) self.assertEqual(item_rsp['text'], comment.text) if comment.rich_text: self.assertEqual(item_rsp['text_type'], 'markdown') else: self.assertEqual(item_rsp['text_type'], 'plain') # # HTTP DELETE tests # def setup_basic_delete_test(self, user, with_local_site, local_site_name): review_request = self.create_review_request( with_local_site=with_local_site, submitter=user, publish=True) review = self.create_review(review_request, user=user, publish=True) comment = self.create_general_comment(review) reply = self.create_reply(review, user=user) reply_comment = self.create_general_comment(reply, reply_to=comment) return ( get_review_reply_general_comment_item_url( reply, reply_comment.pk, local_site_name), [reply_comment, reply] ) def check_delete_result(self, user, reply_comment, reply): self.assertNotIn(reply_comment, reply.general_comments.all()) # # HTTP GET tests # def setup_basic_get_test(self, user, with_local_site, local_site_name): review_request = self.create_review_request( with_local_site=with_local_site, submitter=user, publish=True) review = self.create_review(review_request, user=user, publish=True) comment = self.create_general_comment(review) reply = self.create_reply(review, user=user) reply_comment = self.create_general_comment(reply, reply_to=comment) return ( get_review_reply_general_comment_item_url( reply, reply_comment.pk, local_site_name), review_reply_general_comment_item_mimetype, reply_comment ) # # HTTP PUT tests # def setup_basic_put_test(self, user, with_local_site, local_site_name, put_valid_data): review_request = self.create_review_request( with_local_site=with_local_site, submitter=user, publish=True) review = self.create_review(review_request, user=user, publish=True) comment = self.create_general_comment(review) reply = self.create_reply(review, user=user) reply_comment = self.create_general_comment(reply, reply_to=comment) return ( get_review_reply_general_comment_item_url( reply, reply_comment.pk, local_site_name), review_reply_general_comment_item_mimetype, { 'text': 'Test comment', }, reply_comment, []) def check_put_result(self, user, item_rsp, comment, *args): comment = GeneralComment.objects.get(pk=comment.pk) self.assertEqual(item_rsp['id'], comment.pk) self.assertEqual(item_rsp['text'], 'Test comment') self.assertEqual(comment.text, 'Test comment')
mit
tschneidereit/servo
tests/wpt/web-platform-tests/tools/wptserve/tests/functional/test_cookies.py
299
1996
import os import unittest import urllib2 import json import wptserve from base import TestUsingServer, doc_root class TestResponseSetCookie(TestUsingServer): def test_name_value(self): @wptserve.handlers.handler def handler(request, response): response.set_cookie("name", "value") return "Test" route = ("GET", "/test/name_value", handler) self.server.router.register(*route) resp = self.request(route[1]) self.assertEquals(resp.info()["Set-Cookie"], "name=value; Path=/") def test_unset(self): @wptserve.handlers.handler def handler(request, response): response.set_cookie("name", "value") response.unset_cookie("name") return "Test" route = ("GET", "/test/unset", handler) self.server.router.register(*route) resp = self.request(route[1]) self.assertTrue("Set-Cookie" not in resp.info()) def test_delete(self): @wptserve.handlers.handler def handler(request, response): response.delete_cookie("name") return "Test" route = ("GET", "/test/delete", handler) self.server.router.register(*route) resp = self.request(route[1]) parts = dict(item.split("=") for item in resp.info()["Set-Cookie"].split("; ") if item) self.assertEquals(parts["name"], "") self.assertEquals(parts["Path"], "/") #Should also check that expires is in the past class TestRequestCookies(TestUsingServer): def test_set_cookie(self): @wptserve.handlers.handler def handler(request, response): return request.cookies["name"].value route = ("GET", "/test/set_cookie", handler) self.server.router.register(*route) resp = self.request(route[1], headers={"Cookie": "name=value"}) self.assertEquals(resp.read(), "value") if __name__ == '__main__': unittest.main()
mpl-2.0
ic-hep/DIRAC
Core/scripts/dirac-platform.py
5
4471
#!/usr/bin/env python ######################################################################## # File : dirac-platform # Author : Adria Casajus ######################################################################## __RCSID__ = "$Id$" try: from DIRAC.Core.Utilities.Platform import getPlatformString except: import platform, os, sys, re, subprocess # We need to patch python platform module. It does a string comparison for the libc versions. # it fails when going from 2.9 to 2.10, # the fix converts the version to a tuple and attempts a numeric comparison _libc_search = re.compile( r'(__libc_init)' '|' '(GLIBC_([0-9.]+))' '|' '(libc(_\w+)?\.so(?:\.(\d[0-9.]*))?)' ) def libc_ver( executable = sys.executable, lib = '', version = '', chunksize = 2048 ): """ Tries to determine the libc version that the file executable (which defaults to the Python interpreter) is linked against. Returns a tuple of strings (lib,version) which default to the given parameters in case the lookup fails. Note that the function has intimate knowledge of how different libc versions add symbols to the executable and thus is probably only useable for executables compiled using gcc. The file is read and scanned in chunks of chunksize bytes. """ with open( executable, 'rb' ) as f: binary = f.read( chunksize ) pos = 0 version = [0, 0, 0] while True: m = _libc_search.search( binary, pos ) if not m: binary = f.read( chunksize ) if not binary: break pos = 0 continue libcinit, glibc, glibcversion, so, threads, soversion = m.groups() if libcinit and not lib: lib = 'libc' elif glibc: glibcversion_parts = glibcversion.split( '.' ) for i in xrange( len( glibcversion_parts ) ): try: glibcversion_parts[i] = int( glibcversion_parts[i] ) except ValueError: glibcversion_parts[i] = 0 if libcinit and not lib: lib = 'libc' elif glibc: if lib != 'glibc': lib = 'glibc' version = glibcversion_parts elif glibcversion_parts > version: version = glibcversion_parts elif so: if lib != 'glibc': lib = 'libc' version = max( version, soversion ) if threads and version[-len( threads ):] != threads: version = version + threads pos = m.end() return lib, '.'.join( map( str, version ) ) ### Command line interface def getPlatformString(): # Modified to return our desired platform string, R. Graciani platformTuple = ( platform.system(), platform.machine() ) if platformTuple[0] == 'Linux': sp = subprocess.Popen( [ '/sbin/ldconfig', '--print-cache' ], stdout=subprocess.PIPE ) ldre = re.compile( ".*=> (.*/libc\.so\..*$)" ) libs = [] for line in sp.stdout.readlines(): reM = ldre.match( line ) if reM: libs.append( reM.groups()[0] ) if not libs: # get version of higher libc installed if platform.machine().find( '64' ) != -1: lib = '/lib64' else: lib = '/lib' for libFile in os.listdir( lib ): if libFile.find( 'libc-' ) == 0 or libFile.find( 'libc.so' ) == 0 : libs.append( os.path.join( lib , libFile ) ) newest_lib = [0, 0, 0] for lib in libs: lib_parts = libc_ver( lib )[1].split( '.' ) for i in xrange( len( lib_parts ) ): try: lib_parts[i] = int( lib_parts[i] ) except ValueError: lib_parts[i] = 0 # print "non integer version numbers" if lib_parts > newest_lib: newest_lib = lib_parts platformTuple += ( 'glibc-' + '.'.join( map( str, newest_lib ) ) , ) elif platformTuple[0] == 'Darwin': platformTuple += ( '.'.join( platform.mac_ver()[0].split( "." )[:2] ), ) elif platformTuple[0] == 'Windows': platformTuple += ( platform.win32_ver()[0], ) else: platformTuple += ( platform.release() ) platformString = "%s_%s_%s" % platformTuple return platformString if __name__ == "__main__": print getPlatformString()
gpl-3.0
kinooo/Sick-Beard
sickbeard/notifiers/pushbullet.py
1
4935
# Author: Pedro Correia (http://github.com/pedrocorreia/) # Based on pushalot.py by Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard 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. # # Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>. import base64 from httplib import HTTPSConnection, HTTPException from urllib import urlencode from ssl import SSLError import sickbeard from sickbeard import logger, common class PushbulletNotifier: def test_notify(self, pushbullet_api): return self._sendPushbullet(pushbullet_api, event="Test", message="Testing Pushbullet settings from Sick Beard", method="POST", notificationType="note", force=True) def get_devices(self, pushbullet_api): return self._sendPushbullet(pushbullet_api, method="GET", force=True) def notify_snatch(self, ep_name): if sickbeard.PUSHBULLET_NOTIFY_ONSNATCH: self._sendPushbullet(pushbullet_api=None, event=common.notifyStrings[common.NOTIFY_SNATCH], message=ep_name, notificationType="note", method="POST") def notify_download(self, ep_name): if sickbeard.PUSHBULLET_NOTIFY_ONDOWNLOAD: self._sendPushbullet(pushbullet_api=None, event=common.notifyStrings[common.NOTIFY_DOWNLOAD], message=ep_name, notificationType="note", method="POST") def notify_subtitle_download(self, ep_name, lang): if sickbeard.PUSHBULLET_NOTIFY_ONSUBTITLEDOWNLOAD: self._sendPushbullet(pushbullet_api=None, event=common.notifyStrings[common.NOTIFY_SUBTITLE_DOWNLOAD], message=ep_name + ": " + lang, notificationType="note", method="POST") def _sendPushbullet(self, pushbullet_api=None, pushbullet_device=None, event=None, message=None, notificationType=None, method=None, force=False): if not sickbeard.USE_PUSHBULLET and not force: return False if pushbullet_api == None: pushbullet_api = sickbeard.PUSHBULLET_API if pushbullet_device == None: pushbullet_device = sickbeard.PUSHBULLET_DEVICE if method == 'POST': uri = '/v2/pushes' else: uri = '/api/devices' logger.log(u"Pushbullet event: " + str(event), logger.DEBUG) logger.log(u"Pushbullet message: " + str(message), logger.DEBUG) logger.log(u"Pushbullet api: " + str(pushbullet_api), logger.DEBUG) logger.log(u"Pushbullet devices: " + str(pushbullet_device), logger.DEBUG) logger.log(u"Pushbullet notification type: " + str(notificationType), logger.DEBUG) http_handler = HTTPSConnection("api.pushbullet.com") authString = base64.encodestring('%s:' % (pushbullet_api)).replace('\n', '') if notificationType == None: testMessage = True try: logger.log(u"Testing Pushbullet authentication and retrieving the device list.", logger.DEBUG) http_handler.request(method, uri, None, headers={'Authorization':'Basic %s:' % authString}) except (SSLError, HTTPException): logger.log(u"Pushbullet notification failed.", logger.ERROR) return False else: testMessage = False try: data = { 'title': event.encode('utf-8'), 'body': message.encode('utf-8'), 'device_iden': pushbullet_device, 'type': notificationType} http_handler.request(method, uri, body = urlencode(data), headers={'Authorization':'Basic %s' % authString}) pass except (SSLError, HTTPException): return False response = http_handler.getresponse() request_body = response.read() request_status = response.status if request_status == 200: if testMessage: return request_body else: logger.log(u"Pushbullet notifications sent.", logger.DEBUG) return True elif request_status == 410: logger.log(u"Pushbullet auth failed: %s" % response.reason, logger.ERROR) return False else: logger.log(u"Pushbullet notification failed.", logger.ERROR) return False notifier = PushbulletNotifier
gpl-3.0
BruceDLong/CodeDog
Scons/scons-local-4.1.0.post1/SCons/Scanner/Fortran.py
4
14787
# MIT License # # Copyright The SCons Foundation # # 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. """Dependency scanner for Fortran code.""" import re import SCons.Node import SCons.Node.FS import SCons.Scanner import SCons.Util import SCons.Warnings class F90Scanner(SCons.Scanner.Classic): """ A Classic Scanner subclass for Fortran source files which takes into account both USE and INCLUDE statements. This scanner will work for both F77 and F90 (and beyond) compilers. Currently, this scanner assumes that the include files do not contain USE statements. To enable the ability to deal with USE statements in include files, add logic right after the module names are found to loop over each include file, search for and locate each USE statement, and append each module name to the list of dependencies. Caching the search results in a common dictionary somewhere so that the same include file is not searched multiple times would be a smart thing to do. """ def __init__(self, name, suffixes, path_variable, use_regex, incl_regex, def_regex, *args, **kw): self.cre_use = re.compile(use_regex, re.M) self.cre_incl = re.compile(incl_regex, re.M) self.cre_def = re.compile(def_regex, re.M) def _scan(node, env, path, self=self): node = node.rfile() if not node.exists(): return [] return self.scan(node, env, path) kw['function'] = _scan kw['path_function'] = SCons.Scanner.FindPathDirs(path_variable) kw['recursive'] = 1 kw['skeys'] = suffixes kw['name'] = name SCons.Scanner.Current.__init__(self, *args, **kw) def scan(self, node, env, path=()): # cache the includes list in node so we only scan it once: if node.includes is not None: mods_and_includes = node.includes else: # retrieve all included filenames includes = self.cre_incl.findall(node.get_text_contents()) # retrieve all USE'd module names modules = self.cre_use.findall(node.get_text_contents()) # retrieve all defined module names defmodules = self.cre_def.findall(node.get_text_contents()) # Remove all USE'd module names that are defined in the same file # (case-insensitively) d = {} for m in defmodules: d[m.lower()] = 1 modules = [m for m in modules if m.lower() not in d] # Convert module name to a .mod filename suffix = env.subst('$FORTRANMODSUFFIX') modules = [x.lower() + suffix for x in modules] # Remove unique items from the list mods_and_includes = SCons.Util.unique(includes+modules) node.includes = mods_and_includes # This is a hand-coded DSU (decorate-sort-undecorate, or # Schwartzian transform) pattern. The sort key is the raw name # of the file as specifed on the USE or INCLUDE line, which lets # us keep the sort order constant regardless of whether the file # is actually found in a Repository or locally. nodes = [] source_dir = node.get_dir() if callable(path): path = path() for dep in mods_and_includes: n, i = self.find_include(dep, source_dir, path) if n is None: SCons.Warnings.warn(SCons.Warnings.DependencyWarning, "No dependency generated for file: %s (referenced by: %s) -- file not found" % (i, node)) else: sortkey = self.sort_key(dep) nodes.append((sortkey, n)) return [pair[1] for pair in sorted(nodes)] def FortranScan(path_variable="FORTRANPATH"): """Return a prototype Scanner instance for scanning source files for Fortran USE & INCLUDE statements""" # The USE statement regex matches the following: # # USE module_name # USE :: module_name # USE, INTRINSIC :: module_name # USE, NON_INTRINSIC :: module_name # # Limitations # # -- While the regex can handle multiple USE statements on one line, # it cannot properly handle them if they are commented out. # In either of the following cases: # # ! USE mod_a ; USE mod_b [entire line is commented out] # USE mod_a ! ; USE mod_b [in-line comment of second USE statement] # # the second module name (mod_b) will be picked up as a dependency # even though it should be ignored. The only way I can see # to rectify this would be to modify the scanner to eliminate # the call to re.findall, read in the contents of the file, # treating the comment character as an end-of-line character # in addition to the normal linefeed, loop over each line, # weeding out the comments, and looking for the USE statements. # One advantage to this is that the regex passed to the scanner # would no longer need to match a semicolon. # # -- I question whether or not we need to detect dependencies to # INTRINSIC modules because these are built-in to the compiler. # If we consider them a dependency, will SCons look for them, not # find them, and kill the build? Or will we there be standard # compiler-specific directories we will need to point to so the # compiler and SCons can locate the proper object and mod files? # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # ^ : start of line # (?: : group a collection of regex symbols without saving the match as a "group" # ^|; : matches either the start of the line or a semicolon - semicolon # ) : end the unsaved grouping # \s* : any amount of white space # USE : match the string USE, case insensitive # (?: : group a collection of regex symbols without saving the match as a "group" # \s+| : match one or more whitespace OR .... (the next entire grouped set of regex symbols) # (?: : group a collection of regex symbols without saving the match as a "group" # (?: : establish another unsaved grouping of regex symbols # \s* : any amount of white space # , : match a comma # \s* : any amount of white space # (?:NON_)? : optionally match the prefix NON_, case insensitive # INTRINSIC : match the string INTRINSIC, case insensitive # )? : optionally match the ", INTRINSIC/NON_INTRINSIC" grouped expression # \s* : any amount of white space # :: : match a double colon that must appear after the INTRINSIC/NON_INTRINSIC attribute # ) : end the unsaved grouping # ) : end the unsaved grouping # \s* : match any amount of white space # (\w+) : match the module name that is being USE'd # # use_regex = r"(?i)(?:^|;)\s*USE(?:\s+|(?:(?:\s*,\s*(?:NON_)?INTRINSIC)?\s*::))\s*(\w+)" # The INCLUDE statement regex matches the following: # # INCLUDE 'some_Text' # INCLUDE "some_Text" # INCLUDE "some_Text" ; INCLUDE "some_Text" # INCLUDE kind_"some_Text" # INCLUDE kind_'some_Text" # # where some_Text can include any alphanumeric and/or special character # as defined by the Fortran 2003 standard. # # Limitations: # # -- The Fortran standard dictates that a " or ' in the INCLUDE'd # string must be represented as a "" or '', if the quotes that wrap # the entire string are either a ' or ", respectively. While the # regular expression below can detect the ' or " characters just fine, # the scanning logic, presently is unable to detect them and reduce # them to a single instance. This probably isn't an issue since, # in practice, ' or " are not generally used in filenames. # # -- This regex will not properly deal with multiple INCLUDE statements # when the entire line has been commented out, ala # # ! INCLUDE 'some_file' ; INCLUDE 'some_file' # # In such cases, it will properly ignore the first INCLUDE file, # but will actually still pick up the second. Interestingly enough, # the regex will properly deal with these cases: # # INCLUDE 'some_file' # INCLUDE 'some_file' !; INCLUDE 'some_file' # # To get around the above limitation, the FORTRAN programmer could # simply comment each INCLUDE statement separately, like this # # ! INCLUDE 'some_file' !; INCLUDE 'some_file' # # The way I see it, the only way to get around this limitation would # be to modify the scanning logic to replace the calls to re.findall # with a custom loop that processes each line separately, throwing # away fully commented out lines before attempting to match against # the INCLUDE syntax. # # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # (?: : begin a non-saving group that matches the following: # ^ : either the start of the line # | : or # ['">]\s*; : a semicolon that follows a single quote, # double quote or greater than symbol (with any # amount of whitespace in between). This will # allow the regex to match multiple INCLUDE # statements per line (although it also requires # the positive lookahead assertion that is # used below). It will even properly deal with # (i.e. ignore) cases in which the additional # INCLUDES are part of an in-line comment, ala # " INCLUDE 'someFile' ! ; INCLUDE 'someFile2' " # ) : end of non-saving group # \s* : any amount of white space # INCLUDE : match the string INCLUDE, case insensitive # \s+ : match one or more white space characters # (?\w+_)? : match the optional "kind-param _" prefix allowed by the standard # [<"'] : match the include delimiter - an apostrophe, double quote, or less than symbol # (.+?) : match one or more characters that make up # the included path and file name and save it # in a group. The Fortran standard allows for # any non-control character to be used. The dot # operator will pick up any character, including # control codes, but I can't conceive of anyone # putting control codes in their file names. # The question mark indicates it is non-greedy so # that regex will match only up to the next quote, # double quote, or greater than symbol # (?=["'>]) : positive lookahead assertion to match the include # delimiter - an apostrophe, double quote, or # greater than symbol. This level of complexity # is required so that the include delimiter is # not consumed by the match, thus allowing the # sub-regex discussed above to uniquely match a # set of semicolon-separated INCLUDE statements # (as allowed by the F2003 standard) include_regex = r"""(?i)(?:^|['">]\s*;)\s*INCLUDE\s+(?:\w+_)?[<"'](.+?)(?=["'>])""" # The MODULE statement regex finds module definitions by matching # the following: # # MODULE module_name # # but *not* the following: # # MODULE PROCEDURE procedure_name # MODULE SUBROUTINE subroutine_name # MODULE FUNCTION function_name # MODULE PURE SUBROUTINE|FUNCTION subroutine_name|function_name # MODULE ELEMENTAL SUBROUTINE|FUNCTION subroutine_name|function_name # # Here is a breakdown of the regex: # # (?i) : regex is case insensitive # ^\s* : any amount of white space # MODULE : match the string MODULE, case # insensitive # \s+ : match one or more white space # characters # (?!PROCEDURE|SUBROUTINE|FUNCTION|PURE|ELEMENTAL) # : but *don't* match if the next word # matches PROCEDURE, SUBROUTINE, # FUNCTION, PURE or ELEMENTAL (negative # lookahead assertion), case insensitive # (\w+) : match one or more alphanumeric # characters that make up the defined # module name and save it in a group def_regex = r"""(?i)^\s*MODULE\s+(?!PROCEDURE|SUBROUTINE|FUNCTION|PURE|ELEMENTAL)(\w+)""" scanner = F90Scanner("FortranScan", "$FORTRANSUFFIXES", path_variable, use_regex, include_regex, def_regex) return scanner # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
gpl-2.0
yan12125/youtube-dl
youtube_dl/extractor/newstube.py
16
3123
# coding: utf-8 from __future__ import unicode_literals import base64 import hashlib from .common import InfoExtractor from ..aes import aes_cbc_decrypt from ..utils import ( bytes_to_intlist, int_or_none, intlist_to_bytes, parse_codecs, parse_duration, ) class NewstubeIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?newstube\.ru/media/(?P<id>.+)' _TEST = { 'url': 'http://www.newstube.ru/media/telekanal-cnn-peremestil-gorod-slavyansk-v-krym', 'md5': '9d10320ad473444352f72f746ccb8b8c', 'info_dict': { 'id': '728e0ef2-e187-4012-bac0-5a081fdcb1f6', 'ext': 'mp4', 'title': 'Телеканал CNN переместил город Славянск в Крым', 'description': 'md5:419a8c9f03442bc0b0a794d689360335', 'duration': 31.05, }, } def _real_extract(self, url): video_id = self._match_id(url) page = self._download_webpage(url, video_id) title = self._html_search_meta(['og:title', 'twitter:title'], page, fatal=True) video_guid = self._html_search_regex( r'<meta\s+property="og:video(?::(?:(?:secure_)?url|iframe))?"\s+content="https?://(?:www\.)?newstube\.ru/embed/(?P<guid>[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})', page, 'video GUID') enc_data = base64.b64decode(self._download_webpage( 'https://www.newstube.ru/embed/api/player/getsources2', video_guid, query={ 'guid': video_guid, 'ff': 3, })) key = hashlib.pbkdf2_hmac( 'sha1', video_guid.replace('-', '').encode(), enc_data[:16], 1)[:16] dec_data = aes_cbc_decrypt( bytes_to_intlist(enc_data[32:]), bytes_to_intlist(key), bytes_to_intlist(enc_data[16:32])) sources = self._parse_json(intlist_to_bytes(dec_data[:-dec_data[-1]]), video_guid) formats = [] for source in sources: source_url = source.get('Src') if not source_url: continue height = int_or_none(source.get('Height')) f = { 'format_id': 'http' + ('-%dp' % height if height else ''), 'url': source_url, 'width': int_or_none(source.get('Width')), 'height': height, } source_type = source.get('Type') if source_type: f.update(parse_codecs(self._search_regex( r'codecs="([^"]+)"', source_type, 'codecs', fatal=False))) formats.append(f) self._check_formats(formats, video_guid) self._sort_formats(formats) return { 'id': video_guid, 'title': title, 'description': self._html_search_meta(['description', 'og:description'], page), 'thumbnail': self._html_search_meta(['og:image:secure_url', 'og:image', 'twitter:image'], page), 'duration': parse_duration(self._html_search_meta('duration', page)), 'formats': formats, }
unlicense
jvrsantacruz/XlsxWriter
xlsxwriter/test/comparison/test_chart_scatter14.py
8
1803
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org # from ..excel_comparsion_test import ExcelComparisonTest from ...workbook import Workbook class TestCompareXLSXFiles(ExcelComparisonTest): """ Test file created by XlsxWriter against a file created by Excel. """ def setUp(self): self.maxDiff = None filename = 'chart_scatter14.xlsx' test_dir = 'xlsxwriter/test/comparison/' self.got_filename = test_dir + '_test_' + filename self.exp_filename = test_dir + 'xlsx_files/' + filename self.ignore_files = [] self.ignore_elements = {} def test_create_file(self): """Test the creation of a simple XlsxWriter file.""" workbook = Workbook(self.got_filename) worksheet = workbook.add_worksheet() chart = workbook.add_chart({'type': 'scatter', 'subtype': 'straight'}) chart.axis_ids = [69216512, 69214976] data = [ [1, 2, 3, 4, 5], [2, 4, 6, 8, 10], [3, 6, 9, 12, 15], ] worksheet.write_column('A1', data[0]) worksheet.write_column('B1', data[1]) worksheet.write_column('C1', data[2]) chart.add_series({ 'categories': '=Sheet1!$A$1:$A$5', 'values': '=Sheet1!$B$1:$B$5', 'marker': {'type': 'star', 'size': 5}, }) chart.add_series({ 'categories': '=Sheet1!$A$1:$A$5', 'values': '=Sheet1!$C$1:$C$5', 'marker': {'type': 'plus', 'size': 5}, }) worksheet.insert_chart('E9', chart) workbook.close() self.assertExcelEqual()
bsd-2-clause
otsaloma/gaupol
aeidon/pattern.py
1
1548
# -*- coding: utf-8 -*- # Copyright (C) 2007 Osmo Salomaa # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """Regular expression substitution for subtitle text.""" import aeidon import re __all__ = ("Pattern",) class Pattern(aeidon.MetadataItem): """ Regular expression substitution for subtitle text. :ivar enabled: ``True`` if pattern should be used, ``False`` if not :ivar fields: Dictionary of all data field names and values :ivar local: ``True`` if pattern is defined by user, ``False`` if system """ def __init__(self, fields=None): """Initialize a :class:`Pattern` instance.""" aeidon.MetadataItem.__init__(self, fields) self.enabled = True self.local = False def get_flags(self): """Return the evaluated value of the ``Flags`` field.""" flags = 0 for name in self.get_field_list("Flags"): flags = flags | getattr(re, name) return flags
gpl-3.0
surgebiswas/poker
PokerBots_2017/Johnny/theano/d3viz/tests/test_formatting.py
3
2165
import numpy as np import unittest import theano as th from theano.d3viz.formatting import PyDotFormatter from theano.d3viz.tests import models from nose.plugins.skip import SkipTest from theano.d3viz.formatting import pydot_imported if not pydot_imported: raise SkipTest('Missing requirements') class TestPyDotFormatter(unittest.TestCase): def setUp(self): self.rng = np.random.RandomState(0) def node_counts(self, graph): node_types = [node.get_attributes()['node_type'] for node in graph.get_nodes()] a, b = np.unique(node_types, return_counts=True) nc = dict(zip(a, b)) return nc def test_mlp(self): m = models.Mlp() f = th.function(m.inputs, m.outputs) pdf = PyDotFormatter() graph = pdf(f) expected = 11 if th.config.mode == "FAST_COMPILE": expected = 12 self.assertEqual(len(graph.get_nodes()), expected) nc = self.node_counts(graph) if th.config.mode == "FAST_COMPILE": assert nc['apply'] == 6 else: assert nc['apply'] == 5 assert nc['output'] == 1 def test_ofg(self): m = models.Ofg() f = th.function(m.inputs, m.outputs) pdf = PyDotFormatter() graph = pdf(f) assert len(graph.get_nodes()) == 10 sub_graphs = graph.get_subgraph_list() assert len(sub_graphs) == 2 ofg1, ofg2 = sub_graphs if th.config.mode == "FAST_COMPILE": assert len(ofg1.get_nodes()) == 9 else: assert len(ofg1.get_nodes()) == 5 assert len(ofg1.get_nodes()) == len(ofg2.get_nodes()) def test_ofg_nested(self): m = models.OfgNested() f = th.function(m.inputs, m.outputs) pdf = PyDotFormatter() graph = pdf(f) assert len(graph.get_nodes()) == 7 assert len(graph.get_subgraph_list()) == 1 ofg1 = graph.get_subgraph_list()[0] assert len(ofg1.get_nodes()) == 6 assert len(ofg1.get_subgraph_list()) == 1 ofg2 = ofg1.get_subgraph_list()[0] assert len(ofg2.get_nodes()) == 4
mit
glenn-edgar/local_controller_2
flask_web/werkzeug/testsuite/serving.py
74
2218
# -*- coding: utf-8 -*- """ werkzeug.testsuite.serving ~~~~~~~~~~~~~~~~~~~~~~~~~~ Added serving tests. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import sys import time import urllib import unittest from functools import update_wrapper from StringIO import StringIO from werkzeug.testsuite import WerkzeugTestCase from werkzeug import __version__ as version, serving from werkzeug.testapp import test_app from threading import Thread real_make_server = serving.make_server def silencestderr(f): def new_func(*args, **kwargs): old_stderr = sys.stderr sys.stderr = StringIO() try: return f(*args, **kwargs) finally: sys.stderr = old_stderr return update_wrapper(new_func, f) def run_dev_server(application): servers = [] def tracking_make_server(*args, **kwargs): srv = real_make_server(*args, **kwargs) servers.append(srv) return srv serving.make_server = tracking_make_server try: t = Thread(target=serving.run_simple, args=('localhost', 0, application)) t.setDaemon(True) t.start() time.sleep(0.25) finally: serving.make_server = real_make_server if not servers: return None, None server ,= servers ip, port = server.socket.getsockname()[:2] if ':' in ip: ip = '[%s]' % ip return server, '%s:%d' % (ip, port) class ServingTestCase(WerkzeugTestCase): @silencestderr def test_serving(self): server, addr = run_dev_server(test_app) rv = urllib.urlopen('http://%s/?foo=bar&baz=blah' % addr).read() assert 'WSGI Information' in rv assert 'foo=bar&amp;baz=blah' in rv assert ('Werkzeug/%s' % version) in rv @silencestderr def test_broken_app(self): def broken_app(environ, start_response): 1/0 server, addr = run_dev_server(broken_app) rv = urllib.urlopen('http://%s/?foo=bar&baz=blah' % addr).read() assert 'Internal Server Error' in rv def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(ServingTestCase)) return suite
mit
doheekim/chuizonetest
lib/wtforms/ext/appengine/fields.py
177
7574
from __future__ import unicode_literals import decimal import operator from wtforms import fields, widgets from wtforms.compat import text_type, string_types class ReferencePropertyField(fields.SelectFieldBase): """ A field for ``db.ReferenceProperty``. The list items are rendered in a select. :param reference_class: A db.Model class which will be used to generate the default query to make the list of items. If this is not specified, The `query` property must be overridden before validation. :param get_label: If a string, use this attribute on the model class as the label associated with each option. If a one-argument callable, this callable will be passed model instance and expected to return the label text. Otherwise, the model object's `__str__` or `__unicode__` will be used. :param allow_blank: If set to true, a blank choice will be added to the top of the list to allow `None` to be chosen. :param blank_text: Use this to override the default blank option's label. """ widget = widgets.Select() def __init__(self, label=None, validators=None, reference_class=None, get_label=None, allow_blank=False, blank_text='', **kwargs): super(ReferencePropertyField, self).__init__(label, validators, **kwargs) if get_label is None: self.get_label = lambda x: x elif isinstance(get_label, string_types): self.get_label = operator.attrgetter(get_label) else: self.get_label = get_label self.allow_blank = allow_blank self.blank_text = blank_text self._set_data(None) if reference_class is not None: self.query = reference_class.all() def _get_data(self): if self._formdata is not None: for obj in self.query: if str(obj.key()) == self._formdata: self._set_data(obj) break return self._data def _set_data(self, data): self._data = data self._formdata = None data = property(_get_data, _set_data) def iter_choices(self): if self.allow_blank: yield ('__None', self.blank_text, self.data is None) for obj in self.query: key = str(obj.key()) label = self.get_label(obj) yield (key, label, (self.data.key() == obj.key()) if self.data else False) def process_formdata(self, valuelist): if valuelist: if valuelist[0] == '__None': self.data = None else: self._data = None self._formdata = valuelist[0] def pre_validate(self, form): if not self.allow_blank or self.data is not None: for obj in self.query: if str(self.data.key()) == str(obj.key()): break else: raise ValueError(self.gettext('Not a valid choice')) class KeyPropertyField(fields.SelectFieldBase): """ A field for ``ndb.KeyProperty``. The list items are rendered in a select. :param reference_class: A db.Model class which will be used to generate the default query to make the list of items. If this is not specified, The `query` property must be overridden before validation. :param get_label: If a string, use this attribute on the model class as the label associated with each option. If a one-argument callable, this callable will be passed model instance and expected to return the label text. Otherwise, the model object's `__str__` or `__unicode__` will be used. :param allow_blank: If set to true, a blank choice will be added to the top of the list to allow `None` to be chosen. :param blank_text: Use this to override the default blank option's label. """ widget = widgets.Select() def __init__(self, label=None, validators=None, reference_class=None, get_label=None, allow_blank=False, blank_text='', **kwargs): super(KeyPropertyField, self).__init__(label, validators, **kwargs) if get_label is None: self.get_label = lambda x: x elif isinstance(get_label, basestring): self.get_label = operator.attrgetter(get_label) else: self.get_label = get_label self.allow_blank = allow_blank self.blank_text = blank_text self._set_data(None) if reference_class is not None: self.query = reference_class.query() def _get_data(self): if self._formdata is not None: for obj in self.query: if str(obj.key.id()) == self._formdata: self._set_data(obj) break return self._data def _set_data(self, data): self._data = data self._formdata = None data = property(_get_data, _set_data) def iter_choices(self): if self.allow_blank: yield ('__None', self.blank_text, self.data is None) for obj in self.query: key = str(obj.key.id()) label = self.get_label(obj) yield (key, label, (self.data.key == obj.key) if self.data else False) def process_formdata(self, valuelist): if valuelist: if valuelist[0] == '__None': self.data = None else: self._data = None self._formdata = valuelist[0] def pre_validate(self, form): if self.data is not None: for obj in self.query: if self.data.key == obj.key: break else: raise ValueError(self.gettext('Not a valid choice')) elif not self.allow_blank: raise ValueError(self.gettext('Not a valid choice')) class StringListPropertyField(fields.TextAreaField): """ A field for ``db.StringListProperty``. The list items are rendered in a textarea. """ def _value(self): if self.raw_data: return self.raw_data[0] else: return self.data and text_type("\n".join(self.data)) or '' def process_formdata(self, valuelist): if valuelist: try: self.data = valuelist[0].splitlines() except ValueError: raise ValueError(self.gettext('Not a valid list')) class IntegerListPropertyField(fields.TextAreaField): """ A field for ``db.StringListProperty``. The list items are rendered in a textarea. """ def _value(self): if self.raw_data: return self.raw_data[0] else: return text_type('\n'.join(self.data)) if self.data else '' def process_formdata(self, valuelist): if valuelist: try: self.data = [int(value) for value in valuelist[0].splitlines()] except ValueError: raise ValueError(self.gettext('Not a valid integer list')) class GeoPtPropertyField(fields.TextField): def process_formdata(self, valuelist): if valuelist: try: lat, lon = valuelist[0].split(',') self.data = '%s,%s' % (decimal.Decimal(lat.strip()), decimal.Decimal(lon.strip()),) except (decimal.InvalidOperation, ValueError): raise ValueError('Not a valid coordinate location')
apache-2.0
fernandog/Medusa
ext/sqlalchemy/engine/__init__.py
1
20438
# engine/__init__.py # Copyright (C) 2005-2018 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """SQL connections, SQL execution and high-level DB-API interface. The engine package defines the basic components used to interface DB-API modules with higher-level statement construction, connection-management, execution and result contexts. The primary "entry point" class into this package is the Engine and its public constructor ``create_engine()``. This package includes: base.py Defines interface classes and some implementation classes which comprise the basic components used to interface between a DB-API, constructed and plain-text statements, connections, transactions, and results. default.py Contains default implementations of some of the components defined in base.py. All current database dialects use the classes in default.py as base classes for their own database-specific implementations. strategies.py The mechanics of constructing ``Engine`` objects are represented here. Defines the ``EngineStrategy`` class which represents how to go from arguments specified to the ``create_engine()`` function, to a fully constructed ``Engine``, including initialization of connection pooling, dialects, and specific subclasses of ``Engine``. threadlocal.py The ``TLEngine`` class is defined here, which is a subclass of the generic ``Engine`` and tracks ``Connection`` and ``Transaction`` objects against the identity of the current thread. This allows certain programming patterns based around the concept of a "thread-local connection" to be possible. The ``TLEngine`` is created by using the "threadlocal" engine strategy in conjunction with the ``create_engine()`` function. url.py Defines the ``URL`` class which represents the individual components of a string URL passed to ``create_engine()``. Also defines a basic module-loading strategy for the dialect specifier within a URL. """ from .interfaces import ( Connectable, CreateEnginePlugin, Dialect, ExecutionContext, ExceptionContext, # backwards compat Compiled, TypeCompiler ) from .base import ( Connection, Engine, NestedTransaction, RootTransaction, Transaction, TwoPhaseTransaction, ) from .result import ( BaseRowProxy, BufferedColumnResultProxy, BufferedColumnRow, BufferedRowResultProxy, FullyBufferedResultProxy, ResultProxy, RowProxy, ) from .util import ( connection_memoize ) from . import util, strategies # backwards compat from ..sql import ddl default_strategy = 'plain' def create_engine(*args, **kwargs): """Create a new :class:`.Engine` instance. The standard calling form is to send the URL as the first positional argument, usually a string that indicates database dialect and connection arguments:: engine = create_engine("postgresql://scott:tiger@localhost/test") Additional keyword arguments may then follow it which establish various options on the resulting :class:`.Engine` and its underlying :class:`.Dialect` and :class:`.Pool` constructs:: engine = create_engine("mysql://scott:tiger@hostname/dbname", encoding='latin1', echo=True) The string form of the URL is ``dialect[+driver]://user:password@host/dbname[?key=value..]``, where ``dialect`` is a database name such as ``mysql``, ``oracle``, ``postgresql``, etc., and ``driver`` the name of a DBAPI, such as ``psycopg2``, ``pyodbc``, ``cx_oracle``, etc. Alternatively, the URL can be an instance of :class:`~sqlalchemy.engine.url.URL`. ``**kwargs`` takes a wide variety of options which are routed towards their appropriate components. Arguments may be specific to the :class:`.Engine`, the underlying :class:`.Dialect`, as well as the :class:`.Pool`. Specific dialects also accept keyword arguments that are unique to that dialect. Here, we describe the parameters that are common to most :func:`.create_engine()` usage. Once established, the newly resulting :class:`.Engine` will request a connection from the underlying :class:`.Pool` once :meth:`.Engine.connect` is called, or a method which depends on it such as :meth:`.Engine.execute` is invoked. The :class:`.Pool` in turn will establish the first actual DBAPI connection when this request is received. The :func:`.create_engine` call itself does **not** establish any actual DBAPI connections directly. .. seealso:: :doc:`/core/engines` :doc:`/dialects/index` :ref:`connections_toplevel` :param case_sensitive=True: if False, result column names will match in a case-insensitive fashion, that is, ``row['SomeColumn']``. .. versionchanged:: 0.8 By default, result row names match case-sensitively. In version 0.7 and prior, all matches were case-insensitive. :param connect_args: a dictionary of options which will be passed directly to the DBAPI's ``connect()`` method as additional keyword arguments. See the example at :ref:`custom_dbapi_args`. :param convert_unicode=False: if set to True, sets the default behavior of ``convert_unicode`` on the :class:`.String` type to ``True``, regardless of a setting of ``False`` on an individual :class:`.String` type, thus causing all :class:`.String` -based columns to accommodate Python ``unicode`` objects. This flag is useful as an engine-wide setting when using a DBAPI that does not natively support Python ``unicode`` objects and raises an error when one is received (such as pyodbc with FreeTDS). See :class:`.String` for further details on what this flag indicates. :param creator: a callable which returns a DBAPI connection. This creation function will be passed to the underlying connection pool and will be used to create all new database connections. Usage of this function causes connection parameters specified in the URL argument to be bypassed. :param echo=False: if True, the Engine will log all statements as well as a repr() of their parameter lists to the engines logger, which defaults to sys.stdout. The ``echo`` attribute of ``Engine`` can be modified at any time to turn logging on and off. If set to the string ``"debug"``, result rows will be printed to the standard output as well. This flag ultimately controls a Python logger; see :ref:`dbengine_logging` for information on how to configure logging directly. :param echo_pool=False: if True, the connection pool will log all checkouts/checkins to the logging stream, which defaults to sys.stdout. This flag ultimately controls a Python logger; see :ref:`dbengine_logging` for information on how to configure logging directly. :param empty_in_strategy: The SQL compilation strategy to use when rendering an IN or NOT IN expression for :meth:`.ColumnOperators.in_` where the right-hand side is an empty set. This is a string value that may be one of ``static``, ``dynamic``, or ``dynamic_warn``. The ``static`` strategy is the default, and an IN comparison to an empty set will generate a simple false expression "1 != 1". The ``dynamic`` strategy behaves like that of SQLAlchemy 1.1 and earlier, emitting a false expression of the form "expr != expr", which has the effect of evaluting to NULL in the case of a null expression. ``dynamic_warn`` is the same as ``dynamic``, however also emits a warning when an empty set is encountered; this because the "dynamic" comparison is typically poorly performing on most databases. .. versionadded:: 1.2 Added the ``empty_in_strategy`` setting and additionally defaulted the behavior for empty-set IN comparisons to a static boolean expression. :param encoding: Defaults to ``utf-8``. This is the string encoding used by SQLAlchemy for string encode/decode operations which occur within SQLAlchemy, **outside of the DBAPI.** Most modern DBAPIs feature some degree of direct support for Python ``unicode`` objects, what you see in Python 2 as a string of the form ``u'some string'``. For those scenarios where the DBAPI is detected as not supporting a Python ``unicode`` object, this encoding is used to determine the source/destination encoding. It is **not used** for those cases where the DBAPI handles unicode directly. To properly configure a system to accommodate Python ``unicode`` objects, the DBAPI should be configured to handle unicode to the greatest degree as is appropriate - see the notes on unicode pertaining to the specific target database in use at :ref:`dialect_toplevel`. Areas where string encoding may need to be accommodated outside of the DBAPI include zero or more of: * the values passed to bound parameters, corresponding to the :class:`.Unicode` type or the :class:`.String` type when ``convert_unicode`` is ``True``; * the values returned in result set columns corresponding to the :class:`.Unicode` type or the :class:`.String` type when ``convert_unicode`` is ``True``; * the string SQL statement passed to the DBAPI's ``cursor.execute()`` method; * the string names of the keys in the bound parameter dictionary passed to the DBAPI's ``cursor.execute()`` as well as ``cursor.setinputsizes()`` methods; * the string column names retrieved from the DBAPI's ``cursor.description`` attribute. When using Python 3, the DBAPI is required to support *all* of the above values as Python ``unicode`` objects, which in Python 3 are just known as ``str``. In Python 2, the DBAPI does not specify unicode behavior at all, so SQLAlchemy must make decisions for each of the above values on a per-DBAPI basis - implementations are completely inconsistent in their behavior. :param execution_options: Dictionary execution options which will be applied to all connections. See :meth:`~sqlalchemy.engine.Connection.execution_options` :param implicit_returning=True: When ``True``, a RETURNING- compatible construct, if available, will be used to fetch newly generated primary key values when a single row INSERT statement is emitted with no existing returning() clause. This applies to those backends which support RETURNING or a compatible construct, including PostgreSQL, Firebird, Oracle, Microsoft SQL Server. Set this to ``False`` to disable the automatic usage of RETURNING. :param isolation_level: this string parameter is interpreted by various dialects in order to affect the transaction isolation level of the database connection. The parameter essentially accepts some subset of these string arguments: ``"SERIALIZABLE"``, ``"REPEATABLE_READ"``, ``"READ_COMMITTED"``, ``"READ_UNCOMMITTED"`` and ``"AUTOCOMMIT"``. Behavior here varies per backend, and individual dialects should be consulted directly. Note that the isolation level can also be set on a per-:class:`.Connection` basis as well, using the :paramref:`.Connection.execution_options.isolation_level` feature. .. seealso:: :attr:`.Connection.default_isolation_level` - view default level :paramref:`.Connection.execution_options.isolation_level` - set per :class:`.Connection` isolation level :ref:`SQLite Transaction Isolation <sqlite_isolation_level>` :ref:`PostgreSQL Transaction Isolation <postgresql_isolation_level>` :ref:`MySQL Transaction Isolation <mysql_isolation_level>` :ref:`session_transaction_isolation` - for the ORM :param label_length=None: optional integer value which limits the size of dynamically generated column labels to that many characters. If less than 6, labels are generated as "_(counter)". If ``None``, the value of ``dialect.max_identifier_length`` is used instead. :param listeners: A list of one or more :class:`~sqlalchemy.interfaces.PoolListener` objects which will receive connection pool events. :param logging_name: String identifier which will be used within the "name" field of logging records generated within the "sqlalchemy.engine" logger. Defaults to a hexstring of the object's id. :param max_overflow=10: the number of connections to allow in connection pool "overflow", that is connections that can be opened above and beyond the pool_size setting, which defaults to five. this is only used with :class:`~sqlalchemy.pool.QueuePool`. :param module=None: reference to a Python module object (the module itself, not its string name). Specifies an alternate DBAPI module to be used by the engine's dialect. Each sub-dialect references a specific DBAPI which will be imported before first connect. This parameter causes the import to be bypassed, and the given module to be used instead. Can be used for testing of DBAPIs as well as to inject "mock" DBAPI implementations into the :class:`.Engine`. :param paramstyle=None: The `paramstyle <http://legacy.python.org/dev/peps/pep-0249/#paramstyle>`_ to use when rendering bound parameters. This style defaults to the one recommended by the DBAPI itself, which is retrieved from the ``.paramstyle`` attribute of the DBAPI. However, most DBAPIs accept more than one paramstyle, and in particular it may be desirable to change a "named" paramstyle into a "positional" one, or vice versa. When this attribute is passed, it should be one of the values ``"qmark"``, ``"numeric"``, ``"named"``, ``"format"`` or ``"pyformat"``, and should correspond to a parameter style known to be supported by the DBAPI in use. :param pool=None: an already-constructed instance of :class:`~sqlalchemy.pool.Pool`, such as a :class:`~sqlalchemy.pool.QueuePool` instance. If non-None, this pool will be used directly as the underlying connection pool for the engine, bypassing whatever connection parameters are present in the URL argument. For information on constructing connection pools manually, see :ref:`pooling_toplevel`. :param poolclass=None: a :class:`~sqlalchemy.pool.Pool` subclass, which will be used to create a connection pool instance using the connection parameters given in the URL. Note this differs from ``pool`` in that you don't actually instantiate the pool in this case, you just indicate what type of pool to be used. :param pool_logging_name: String identifier which will be used within the "name" field of logging records generated within the "sqlalchemy.pool" logger. Defaults to a hexstring of the object's id. :param pool_pre_ping: boolean, if True will enable the connection pool "pre-ping" feature that tests connections for liveness upon each checkout. .. versionadded:: 1.2 .. seealso:: :ref:`pool_disconnects_pessimistic` :param pool_size=5: the number of connections to keep open inside the connection pool. This used with :class:`~sqlalchemy.pool.QueuePool` as well as :class:`~sqlalchemy.pool.SingletonThreadPool`. With :class:`~sqlalchemy.pool.QueuePool`, a ``pool_size`` setting of 0 indicates no limit; to disable pooling, set ``poolclass`` to :class:`~sqlalchemy.pool.NullPool` instead. :param pool_recycle=-1: this setting causes the pool to recycle connections after the given number of seconds has passed. It defaults to -1, or no timeout. For example, setting to 3600 means connections will be recycled after one hour. Note that MySQL in particular will disconnect automatically if no activity is detected on a connection for eight hours (although this is configurable with the MySQLDB connection itself and the server configuration as well). .. seealso:: :ref:`pool_setting_recycle` :param pool_reset_on_return='rollback': set the "reset on return" behavior of the pool, which is whether ``rollback()``, ``commit()``, or nothing is called upon connections being returned to the pool. See the docstring for ``reset_on_return`` at :class:`.Pool`. .. versionadded:: 0.7.6 :param pool_timeout=30: number of seconds to wait before giving up on getting a connection from the pool. This is only used with :class:`~sqlalchemy.pool.QueuePool`. :param plugins: string list of plugin names to load. See :class:`.CreateEnginePlugin` for background. .. versionadded:: 1.2.3 :param strategy='plain': selects alternate engine implementations. Currently available are: * the ``threadlocal`` strategy, which is described in :ref:`threadlocal_strategy`; * the ``mock`` strategy, which dispatches all statement execution to a function passed as the argument ``executor``. See `example in the FAQ <http://docs.sqlalchemy.org/en/latest/faq/metadata_schema.html#how-can-i-get-the-create-table-drop-table-output-as-a-string>`_. :param executor=None: a function taking arguments ``(sql, *multiparams, **params)``, to which the ``mock`` strategy will dispatch all statement execution. Used only by ``strategy='mock'``. """ strategy = kwargs.pop('strategy', default_strategy) strategy = strategies.strategies[strategy] return strategy.create(*args, **kwargs) def engine_from_config(configuration, prefix='sqlalchemy.', **kwargs): """Create a new Engine instance using a configuration dictionary. The dictionary is typically produced from a config file. The keys of interest to ``engine_from_config()`` should be prefixed, e.g. ``sqlalchemy.url``, ``sqlalchemy.echo``, etc. The 'prefix' argument indicates the prefix to be searched for. Each matching key (after the prefix is stripped) is treated as though it were the corresponding keyword argument to a :func:`.create_engine` call. The only required key is (assuming the default prefix) ``sqlalchemy.url``, which provides the :ref:`database URL <database_urls>`. A select set of keyword arguments will be "coerced" to their expected type based on string values. The set of arguments is extensible per-dialect using the ``engine_config_types`` accessor. :param configuration: A dictionary (typically produced from a config file, but this is not a requirement). Items whose keys start with the value of 'prefix' will have that prefix stripped, and will then be passed to :ref:`create_engine`. :param prefix: Prefix to match and then strip from keys in 'configuration'. :param kwargs: Each keyword argument to ``engine_from_config()`` itself overrides the corresponding item taken from the 'configuration' dictionary. Keyword arguments should *not* be prefixed. """ options = dict((key[len(prefix):], configuration[key]) for key in configuration if key.startswith(prefix)) options['_coerce_config'] = True options.update(kwargs) url = options.pop('url') return create_engine(url, **options) __all__ = ( 'create_engine', 'engine_from_config', )
gpl-3.0
qrkourier/ansible
lib/ansible/modules/database/misc/riak.py
29
7451
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, James Martin <jmartin@basho.com>, Drew Kerrigan <dkerrigan@basho.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: riak short_description: This module handles some common Riak operations description: - This module can be used to join nodes to a cluster, check the status of the cluster. version_added: "1.2" author: - "James Martin (@jsmartin)" - "Drew Kerrigan (@drewkerrigan)" options: command: description: - The command you would like to perform against the cluster. required: false default: null choices: ['ping', 'kv_test', 'join', 'plan', 'commit'] config_dir: description: - The path to the riak configuration directory required: false default: /etc/riak http_conn: description: - The ip address and port that is listening for Riak HTTP queries required: false default: 127.0.0.1:8098 target_node: description: - The target node for certain operations (join, ping) required: false default: riak@127.0.0.1 wait_for_handoffs: description: - Number of seconds to wait for handoffs to complete. required: false default: null wait_for_ring: description: - Number of seconds to wait for all nodes to agree on the ring. required: false default: null wait_for_service: description: - Waits for a riak service to come online before continuing. required: false default: None choices: ['kv'] validate_certs: description: - If C(no), SSL certificates will not be validated. This should only be used on personally controlled sites using self-signed certificates. required: false default: 'yes' choices: ['yes', 'no'] version_added: 1.5.1 ''' EXAMPLES = ''' # Join's a Riak node to another node - riak: command: join target_node: riak@10.1.1.1 # Wait for handoffs to finish. Use with async and poll. - riak: wait_for_handoffs: yes # Wait for riak_kv service to startup - riak: wait_for_service: kv ''' import json import time from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.urls import fetch_url def ring_check(module, riak_admin_bin): cmd = '%s ringready' % riak_admin_bin rc, out, err = module.run_command(cmd) if rc == 0 and 'TRUE All nodes agree on the ring' in out: return True else: return False def main(): module = AnsibleModule( argument_spec=dict( command=dict(required=False, default=None, choices=[ 'ping', 'kv_test', 'join', 'plan', 'commit']), config_dir=dict(default='/etc/riak', type='path'), http_conn=dict(required=False, default='127.0.0.1:8098'), target_node=dict(default='riak@127.0.0.1', required=False), wait_for_handoffs=dict(default=False, type='int'), wait_for_ring=dict(default=False, type='int'), wait_for_service=dict( required=False, default=None, choices=['kv']), validate_certs = dict(default='yes', type='bool')) ) command = module.params.get('command') http_conn = module.params.get('http_conn') target_node = module.params.get('target_node') wait_for_handoffs = module.params.get('wait_for_handoffs') wait_for_ring = module.params.get('wait_for_ring') wait_for_service = module.params.get('wait_for_service') #make sure riak commands are on the path riak_bin = module.get_bin_path('riak') riak_admin_bin = module.get_bin_path('riak-admin') timeout = time.time() + 120 while True: if time.time() > timeout: module.fail_json(msg='Timeout, could not fetch Riak stats.') (response, info) = fetch_url(module, 'http://%s/stats' % (http_conn), force=True, timeout=5) if info['status'] == 200: stats_raw = response.read() break time.sleep(5) # here we attempt to load those stats, try: stats = json.loads(stats_raw) except: module.fail_json(msg='Could not parse Riak stats.') node_name = stats['nodename'] nodes = stats['ring_members'] ring_size = stats['ring_creation_size'] rc, out, err = module.run_command([riak_bin, 'version'] ) version = out.strip() result = dict(node_name=node_name, nodes=nodes, ring_size=ring_size, version=version) if command == 'ping': cmd = '%s ping %s' % ( riak_bin, target_node ) rc, out, err = module.run_command(cmd) if rc == 0: result['ping'] = out else: module.fail_json(msg=out) elif command == 'kv_test': cmd = '%s test' % riak_admin_bin rc, out, err = module.run_command(cmd) if rc == 0: result['kv_test'] = out else: module.fail_json(msg=out) elif command == 'join': if nodes.count(node_name) == 1 and len(nodes) > 1: result['join'] = 'Node is already in cluster or staged to be in cluster.' else: cmd = '%s cluster join %s' % (riak_admin_bin, target_node) rc, out, err = module.run_command(cmd) if rc == 0: result['join'] = out result['changed'] = True else: module.fail_json(msg=out) elif command == 'plan': cmd = '%s cluster plan' % riak_admin_bin rc, out, err = module.run_command(cmd) if rc == 0: result['plan'] = out if 'Staged Changes' in out: result['changed'] = True else: module.fail_json(msg=out) elif command == 'commit': cmd = '%s cluster commit' % riak_admin_bin rc, out, err = module.run_command(cmd) if rc == 0: result['commit'] = out result['changed'] = True else: module.fail_json(msg=out) # this could take a while, recommend to run in async mode if wait_for_handoffs: timeout = time.time() + wait_for_handoffs while True: cmd = '%s transfers' % riak_admin_bin rc, out, err = module.run_command(cmd) if 'No transfers active' in out: result['handoffs'] = 'No transfers active.' break time.sleep(10) if time.time() > timeout: module.fail_json(msg='Timeout waiting for handoffs.') if wait_for_service: cmd = [riak_admin_bin, 'wait_for_service', 'riak_%s' % wait_for_service, node_name ] rc, out, err = module.run_command(cmd) result['service'] = out if wait_for_ring: timeout = time.time() + wait_for_ring while True: if ring_check(module, riak_admin_bin): break time.sleep(10) if time.time() > timeout: module.fail_json(msg='Timeout waiting for nodes to agree on ring.') result['ring_ready'] = ring_check(module, riak_admin_bin) module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
BizzCloud/PosBox
addons/l10n_in_hr_payroll/wizard/hr_yearly_salary_detail.py
374
2376
#-*- coding:utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2011 OpenERP SA (<http://openerp.com>). All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from openerp.osv import fields, osv class yearly_salary_detail(osv.osv_memory): _name ='yearly.salary.detail' _description = 'Hr Salary Employee By Category Report' _columns = { 'employee_ids': fields.many2many('hr.employee', 'payroll_emp_rel', 'payroll_id', 'employee_id', 'Employees', required=True), 'date_from': fields.date('Start Date', required=True), 'date_to': fields.date('End Date', required=True), } _defaults = { 'date_from': lambda *a: time.strftime('%Y-01-01'), 'date_to': lambda *a: time.strftime('%Y-%m-%d'), } def print_report(self, cr, uid, ids, context=None): """ To get the date and print the report @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param context: A standard dictionary @return: return report """ if context is None: context = {} datas = {'ids': context.get('active_ids', [])} res = self.read(cr, uid, ids, context=context) res = res and res[0] or {} datas.update({'form':res}) return self.pool['report'].get_action(cr, uid, ids, 'l10n_in_hr_payroll.report_hryearlysalary', data=datas, context=context) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
WhireCrow/openwrt-mt7620
staging_dir/target-mipsel_r2_uClibc-0.9.33.2/usr/lib/python2.7/test/test_optparse.py
29
61846
# # Test suite for Optik. Supplied by Johannes Gijsbers # (taradino@softhome.net) -- translated from the original Optik # test suite to this PyUnit-based version. # # $Id$ # import sys import os import re import copy import types import unittest from StringIO import StringIO from test import test_support from optparse import make_option, Option, \ TitledHelpFormatter, OptionParser, OptionGroup, \ SUPPRESS_USAGE, OptionError, OptionConflictError, \ BadOptionError, OptionValueError, Values from optparse import _match_abbrev from optparse import _parse_num retype = type(re.compile('')) class InterceptedError(Exception): def __init__(self, error_message=None, exit_status=None, exit_message=None): self.error_message = error_message self.exit_status = exit_status self.exit_message = exit_message def __str__(self): return self.error_message or self.exit_message or "intercepted error" class InterceptingOptionParser(OptionParser): def exit(self, status=0, msg=None): raise InterceptedError(exit_status=status, exit_message=msg) def error(self, msg): raise InterceptedError(error_message=msg) class BaseTest(unittest.TestCase): def assertParseOK(self, args, expected_opts, expected_positional_args): """Assert the options are what we expected when parsing arguments. Otherwise, fail with a nicely formatted message. Keyword arguments: args -- A list of arguments to parse with OptionParser. expected_opts -- The options expected. expected_positional_args -- The positional arguments expected. Returns the options and positional args for further testing. """ (options, positional_args) = self.parser.parse_args(args) optdict = vars(options) self.assertEqual(optdict, expected_opts, """ Options are %(optdict)s. Should be %(expected_opts)s. Args were %(args)s.""" % locals()) self.assertEqual(positional_args, expected_positional_args, """ Positional arguments are %(positional_args)s. Should be %(expected_positional_args)s. Args were %(args)s.""" % locals ()) return (options, positional_args) def assertRaises(self, func, args, kwargs, expected_exception, expected_message): """ Assert that the expected exception is raised when calling a function, and that the right error message is included with that exception. Arguments: func -- the function to call args -- positional arguments to `func` kwargs -- keyword arguments to `func` expected_exception -- exception that should be raised expected_message -- expected exception message (or pattern if a compiled regex object) Returns the exception raised for further testing. """ if args is None: args = () if kwargs is None: kwargs = {} try: func(*args, **kwargs) except expected_exception, err: actual_message = str(err) if isinstance(expected_message, retype): self.assertTrue(expected_message.search(actual_message), """\ expected exception message pattern: /%s/ actual exception message: '''%s''' """ % (expected_message.pattern, actual_message)) else: self.assertEqual(actual_message, expected_message, """\ expected exception message: '''%s''' actual exception message: '''%s''' """ % (expected_message, actual_message)) return err else: self.fail("""expected exception %(expected_exception)s not raised called %(func)r with args %(args)r and kwargs %(kwargs)r """ % locals ()) # -- Assertions used in more than one class -------------------- def assertParseFail(self, cmdline_args, expected_output): """ Assert the parser fails with the expected message. Caller must ensure that self.parser is an InterceptingOptionParser. """ try: self.parser.parse_args(cmdline_args) except InterceptedError, err: self.assertEqual(err.error_message, expected_output) else: self.assertFalse("expected parse failure") def assertOutput(self, cmdline_args, expected_output, expected_status=0, expected_error=None): """Assert the parser prints the expected output on stdout.""" save_stdout = sys.stdout encoding = getattr(save_stdout, 'encoding', None) try: try: sys.stdout = StringIO() if encoding: sys.stdout.encoding = encoding self.parser.parse_args(cmdline_args) finally: output = sys.stdout.getvalue() sys.stdout = save_stdout except InterceptedError, err: self.assertTrue( type(output) is types.StringType, "expected output to be an ordinary string, not %r" % type(output)) if output != expected_output: self.fail("expected: \n'''\n" + expected_output + "'''\nbut got \n'''\n" + output + "'''") self.assertEqual(err.exit_status, expected_status) self.assertEqual(err.exit_message, expected_error) else: self.assertFalse("expected parser.exit()") def assertTypeError(self, func, expected_message, *args): """Assert that TypeError is raised when executing func.""" self.assertRaises(func, args, None, TypeError, expected_message) def assertHelp(self, parser, expected_help): actual_help = parser.format_help() if actual_help != expected_help: raise self.failureException( 'help text failure; expected:\n"' + expected_help + '"; got:\n"' + actual_help + '"\n') # -- Test make_option() aka Option ------------------------------------- # It's not necessary to test correct options here. All the tests in the # parser.parse_args() section deal with those, because they're needed # there. class TestOptionChecks(BaseTest): def setUp(self): self.parser = OptionParser(usage=SUPPRESS_USAGE) def assertOptionError(self, expected_message, args=[], kwargs={}): self.assertRaises(make_option, args, kwargs, OptionError, expected_message) def test_opt_string_empty(self): self.assertTypeError(make_option, "at least one option string must be supplied") def test_opt_string_too_short(self): self.assertOptionError( "invalid option string 'b': must be at least two characters long", ["b"]) def test_opt_string_short_invalid(self): self.assertOptionError( "invalid short option string '--': must be " "of the form -x, (x any non-dash char)", ["--"]) def test_opt_string_long_invalid(self): self.assertOptionError( "invalid long option string '---': " "must start with --, followed by non-dash", ["---"]) def test_attr_invalid(self): self.assertOptionError( "option -b: invalid keyword arguments: bar, foo", ["-b"], {'foo': None, 'bar': None}) def test_action_invalid(self): self.assertOptionError( "option -b: invalid action: 'foo'", ["-b"], {'action': 'foo'}) def test_type_invalid(self): self.assertOptionError( "option -b: invalid option type: 'foo'", ["-b"], {'type': 'foo'}) self.assertOptionError( "option -b: invalid option type: 'tuple'", ["-b"], {'type': tuple}) def test_no_type_for_action(self): self.assertOptionError( "option -b: must not supply a type for action 'count'", ["-b"], {'action': 'count', 'type': 'int'}) def test_no_choices_list(self): self.assertOptionError( "option -b/--bad: must supply a list of " "choices for type 'choice'", ["-b", "--bad"], {'type': "choice"}) def test_bad_choices_list(self): typename = type('').__name__ self.assertOptionError( "option -b/--bad: choices must be a list of " "strings ('%s' supplied)" % typename, ["-b", "--bad"], {'type': "choice", 'choices':"bad choices"}) def test_no_choices_for_type(self): self.assertOptionError( "option -b: must not supply choices for type 'int'", ["-b"], {'type': 'int', 'choices':"bad"}) def test_no_const_for_action(self): self.assertOptionError( "option -b: 'const' must not be supplied for action 'store'", ["-b"], {'action': 'store', 'const': 1}) def test_no_nargs_for_action(self): self.assertOptionError( "option -b: 'nargs' must not be supplied for action 'count'", ["-b"], {'action': 'count', 'nargs': 2}) def test_callback_not_callable(self): self.assertOptionError( "option -b: callback not callable: 'foo'", ["-b"], {'action': 'callback', 'callback': 'foo'}) def dummy(self): pass def test_callback_args_no_tuple(self): self.assertOptionError( "option -b: callback_args, if supplied, " "must be a tuple: not 'foo'", ["-b"], {'action': 'callback', 'callback': self.dummy, 'callback_args': 'foo'}) def test_callback_kwargs_no_dict(self): self.assertOptionError( "option -b: callback_kwargs, if supplied, " "must be a dict: not 'foo'", ["-b"], {'action': 'callback', 'callback': self.dummy, 'callback_kwargs': 'foo'}) def test_no_callback_for_action(self): self.assertOptionError( "option -b: callback supplied ('foo') for non-callback option", ["-b"], {'action': 'store', 'callback': 'foo'}) def test_no_callback_args_for_action(self): self.assertOptionError( "option -b: callback_args supplied for non-callback option", ["-b"], {'action': 'store', 'callback_args': 'foo'}) def test_no_callback_kwargs_for_action(self): self.assertOptionError( "option -b: callback_kwargs supplied for non-callback option", ["-b"], {'action': 'store', 'callback_kwargs': 'foo'}) class TestOptionParser(BaseTest): def setUp(self): self.parser = OptionParser() self.parser.add_option("-v", "--verbose", "-n", "--noisy", action="store_true", dest="verbose") self.parser.add_option("-q", "--quiet", "--silent", action="store_false", dest="verbose") def test_add_option_no_Option(self): self.assertTypeError(self.parser.add_option, "not an Option instance: None", None) def test_add_option_invalid_arguments(self): self.assertTypeError(self.parser.add_option, "invalid arguments", None, None) def test_get_option(self): opt1 = self.parser.get_option("-v") self.assertIsInstance(opt1, Option) self.assertEqual(opt1._short_opts, ["-v", "-n"]) self.assertEqual(opt1._long_opts, ["--verbose", "--noisy"]) self.assertEqual(opt1.action, "store_true") self.assertEqual(opt1.dest, "verbose") def test_get_option_equals(self): opt1 = self.parser.get_option("-v") opt2 = self.parser.get_option("--verbose") opt3 = self.parser.get_option("-n") opt4 = self.parser.get_option("--noisy") self.assertTrue(opt1 is opt2 is opt3 is opt4) def test_has_option(self): self.assertTrue(self.parser.has_option("-v")) self.assertTrue(self.parser.has_option("--verbose")) def assertTrueremoved(self): self.assertTrue(self.parser.get_option("-v") is None) self.assertTrue(self.parser.get_option("--verbose") is None) self.assertTrue(self.parser.get_option("-n") is None) self.assertTrue(self.parser.get_option("--noisy") is None) self.assertFalse(self.parser.has_option("-v")) self.assertFalse(self.parser.has_option("--verbose")) self.assertFalse(self.parser.has_option("-n")) self.assertFalse(self.parser.has_option("--noisy")) self.assertTrue(self.parser.has_option("-q")) self.assertTrue(self.parser.has_option("--silent")) def test_remove_short_opt(self): self.parser.remove_option("-n") self.assertTrueremoved() def test_remove_long_opt(self): self.parser.remove_option("--verbose") self.assertTrueremoved() def test_remove_nonexistent(self): self.assertRaises(self.parser.remove_option, ('foo',), None, ValueError, "no such option 'foo'") def test_refleak(self): # If an OptionParser is carrying around a reference to a large # object, various cycles can prevent it from being GC'd in # a timely fashion. destroy() breaks the cycles to ensure stuff # can be cleaned up. big_thing = [42] refcount = sys.getrefcount(big_thing) parser = OptionParser() parser.add_option("-a", "--aaarggh") parser.big_thing = big_thing parser.destroy() #self.assertEqual(refcount, sys.getrefcount(big_thing)) del parser self.assertEqual(refcount, sys.getrefcount(big_thing)) class TestOptionValues(BaseTest): def setUp(self): pass def test_basics(self): values = Values() self.assertEqual(vars(values), {}) self.assertEqual(values, {}) self.assertNotEqual(values, {"foo": "bar"}) self.assertNotEqual(values, "") dict = {"foo": "bar", "baz": 42} values = Values(defaults=dict) self.assertEqual(vars(values), dict) self.assertEqual(values, dict) self.assertNotEqual(values, {"foo": "bar"}) self.assertNotEqual(values, {}) self.assertNotEqual(values, "") self.assertNotEqual(values, []) class TestTypeAliases(BaseTest): def setUp(self): self.parser = OptionParser() def test_str_aliases_string(self): self.parser.add_option("-s", type="str") self.assertEqual(self.parser.get_option("-s").type, "string") def test_new_type_object(self): self.parser.add_option("-s", type=str) self.assertEqual(self.parser.get_option("-s").type, "string") self.parser.add_option("-x", type=int) self.assertEqual(self.parser.get_option("-x").type, "int") def test_old_type_object(self): self.parser.add_option("-s", type=types.StringType) self.assertEqual(self.parser.get_option("-s").type, "string") self.parser.add_option("-x", type=types.IntType) self.assertEqual(self.parser.get_option("-x").type, "int") # Custom type for testing processing of default values. _time_units = { 's' : 1, 'm' : 60, 'h' : 60*60, 'd' : 60*60*24 } def _check_duration(option, opt, value): try: if value[-1].isdigit(): return int(value) else: return int(value[:-1]) * _time_units[value[-1]] except (ValueError, IndexError): raise OptionValueError( 'option %s: invalid duration: %r' % (opt, value)) class DurationOption(Option): TYPES = Option.TYPES + ('duration',) TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER) TYPE_CHECKER['duration'] = _check_duration class TestDefaultValues(BaseTest): def setUp(self): self.parser = OptionParser() self.parser.add_option("-v", "--verbose", default=True) self.parser.add_option("-q", "--quiet", dest='verbose') self.parser.add_option("-n", type="int", default=37) self.parser.add_option("-m", type="int") self.parser.add_option("-s", default="foo") self.parser.add_option("-t") self.parser.add_option("-u", default=None) self.expected = { 'verbose': True, 'n': 37, 'm': None, 's': "foo", 't': None, 'u': None } def test_basic_defaults(self): self.assertEqual(self.parser.get_default_values(), self.expected) def test_mixed_defaults_post(self): self.parser.set_defaults(n=42, m=-100) self.expected.update({'n': 42, 'm': -100}) self.assertEqual(self.parser.get_default_values(), self.expected) def test_mixed_defaults_pre(self): self.parser.set_defaults(x="barf", y="blah") self.parser.add_option("-x", default="frob") self.parser.add_option("-y") self.expected.update({'x': "frob", 'y': "blah"}) self.assertEqual(self.parser.get_default_values(), self.expected) self.parser.remove_option("-y") self.parser.add_option("-y", default=None) self.expected.update({'y': None}) self.assertEqual(self.parser.get_default_values(), self.expected) def test_process_default(self): self.parser.option_class = DurationOption self.parser.add_option("-d", type="duration", default=300) self.parser.add_option("-e", type="duration", default="6m") self.parser.set_defaults(n="42") self.expected.update({'d': 300, 'e': 360, 'n': 42}) self.assertEqual(self.parser.get_default_values(), self.expected) self.parser.set_process_default_values(False) self.expected.update({'d': 300, 'e': "6m", 'n': "42"}) self.assertEqual(self.parser.get_default_values(), self.expected) class TestProgName(BaseTest): """ Test that %prog expands to the right thing in usage, version, and help strings. """ def assertUsage(self, parser, expected_usage): self.assertEqual(parser.get_usage(), expected_usage) def assertVersion(self, parser, expected_version): self.assertEqual(parser.get_version(), expected_version) def test_default_progname(self): # Make sure that program name taken from sys.argv[0] by default. save_argv = sys.argv[:] try: sys.argv[0] = os.path.join("foo", "bar", "baz.py") parser = OptionParser("%prog ...", version="%prog 1.2") expected_usage = "Usage: baz.py ...\n" self.assertUsage(parser, expected_usage) self.assertVersion(parser, "baz.py 1.2") self.assertHelp(parser, expected_usage + "\n" + "Options:\n" " --version show program's version number and exit\n" " -h, --help show this help message and exit\n") finally: sys.argv[:] = save_argv def test_custom_progname(self): parser = OptionParser(prog="thingy", version="%prog 0.1", usage="%prog arg arg") parser.remove_option("-h") parser.remove_option("--version") expected_usage = "Usage: thingy arg arg\n" self.assertUsage(parser, expected_usage) self.assertVersion(parser, "thingy 0.1") self.assertHelp(parser, expected_usage + "\n") class TestExpandDefaults(BaseTest): def setUp(self): self.parser = OptionParser(prog="test") self.help_prefix = """\ Usage: test [options] Options: -h, --help show this help message and exit """ self.file_help = "read from FILE [default: %default]" self.expected_help_file = self.help_prefix + \ " -f FILE, --file=FILE read from FILE [default: foo.txt]\n" self.expected_help_none = self.help_prefix + \ " -f FILE, --file=FILE read from FILE [default: none]\n" def test_option_default(self): self.parser.add_option("-f", "--file", default="foo.txt", help=self.file_help) self.assertHelp(self.parser, self.expected_help_file) def test_parser_default_1(self): self.parser.add_option("-f", "--file", help=self.file_help) self.parser.set_default('file', "foo.txt") self.assertHelp(self.parser, self.expected_help_file) def test_parser_default_2(self): self.parser.add_option("-f", "--file", help=self.file_help) self.parser.set_defaults(file="foo.txt") self.assertHelp(self.parser, self.expected_help_file) def test_no_default(self): self.parser.add_option("-f", "--file", help=self.file_help) self.assertHelp(self.parser, self.expected_help_none) def test_default_none_1(self): self.parser.add_option("-f", "--file", default=None, help=self.file_help) self.assertHelp(self.parser, self.expected_help_none) def test_default_none_2(self): self.parser.add_option("-f", "--file", help=self.file_help) self.parser.set_defaults(file=None) self.assertHelp(self.parser, self.expected_help_none) def test_float_default(self): self.parser.add_option( "-p", "--prob", help="blow up with probability PROB [default: %default]") self.parser.set_defaults(prob=0.43) expected_help = self.help_prefix + \ " -p PROB, --prob=PROB blow up with probability PROB [default: 0.43]\n" self.assertHelp(self.parser, expected_help) def test_alt_expand(self): self.parser.add_option("-f", "--file", default="foo.txt", help="read from FILE [default: *DEFAULT*]") self.parser.formatter.default_tag = "*DEFAULT*" self.assertHelp(self.parser, self.expected_help_file) def test_no_expand(self): self.parser.add_option("-f", "--file", default="foo.txt", help="read from %default file") self.parser.formatter.default_tag = None expected_help = self.help_prefix + \ " -f FILE, --file=FILE read from %default file\n" self.assertHelp(self.parser, expected_help) # -- Test parser.parse_args() ------------------------------------------ class TestStandard(BaseTest): def setUp(self): options = [make_option("-a", type="string"), make_option("-b", "--boo", type="int", dest='boo'), make_option("--foo", action="append")] self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, option_list=options) def test_required_value(self): self.assertParseFail(["-a"], "-a option requires an argument") def test_invalid_integer(self): self.assertParseFail(["-b", "5x"], "option -b: invalid integer value: '5x'") def test_no_such_option(self): self.assertParseFail(["--boo13"], "no such option: --boo13") def test_long_invalid_integer(self): self.assertParseFail(["--boo=x5"], "option --boo: invalid integer value: 'x5'") def test_empty(self): self.assertParseOK([], {'a': None, 'boo': None, 'foo': None}, []) def test_shortopt_empty_longopt_append(self): self.assertParseOK(["-a", "", "--foo=blah", "--foo="], {'a': "", 'boo': None, 'foo': ["blah", ""]}, []) def test_long_option_append(self): self.assertParseOK(["--foo", "bar", "--foo", "", "--foo=x"], {'a': None, 'boo': None, 'foo': ["bar", "", "x"]}, []) def test_option_argument_joined(self): self.assertParseOK(["-abc"], {'a': "bc", 'boo': None, 'foo': None}, []) def test_option_argument_split(self): self.assertParseOK(["-a", "34"], {'a': "34", 'boo': None, 'foo': None}, []) def test_option_argument_joined_integer(self): self.assertParseOK(["-b34"], {'a': None, 'boo': 34, 'foo': None}, []) def test_option_argument_split_negative_integer(self): self.assertParseOK(["-b", "-5"], {'a': None, 'boo': -5, 'foo': None}, []) def test_long_option_argument_joined(self): self.assertParseOK(["--boo=13"], {'a': None, 'boo': 13, 'foo': None}, []) def test_long_option_argument_split(self): self.assertParseOK(["--boo", "111"], {'a': None, 'boo': 111, 'foo': None}, []) def test_long_option_short_option(self): self.assertParseOK(["--foo=bar", "-axyz"], {'a': 'xyz', 'boo': None, 'foo': ["bar"]}, []) def test_abbrev_long_option(self): self.assertParseOK(["--f=bar", "-axyz"], {'a': 'xyz', 'boo': None, 'foo': ["bar"]}, []) def test_defaults(self): (options, args) = self.parser.parse_args([]) defaults = self.parser.get_default_values() self.assertEqual(vars(defaults), vars(options)) def test_ambiguous_option(self): self.parser.add_option("--foz", action="store", type="string", dest="foo") self.assertParseFail(["--f=bar"], "ambiguous option: --f (--foo, --foz?)") def test_short_and_long_option_split(self): self.assertParseOK(["-a", "xyz", "--foo", "bar"], {'a': 'xyz', 'boo': None, 'foo': ["bar"]}, []), def test_short_option_split_long_option_append(self): self.assertParseOK(["--foo=bar", "-b", "123", "--foo", "baz"], {'a': None, 'boo': 123, 'foo': ["bar", "baz"]}, []) def test_short_option_split_one_positional_arg(self): self.assertParseOK(["-a", "foo", "bar"], {'a': "foo", 'boo': None, 'foo': None}, ["bar"]), def test_short_option_consumes_separator(self): self.assertParseOK(["-a", "--", "foo", "bar"], {'a': "--", 'boo': None, 'foo': None}, ["foo", "bar"]), self.assertParseOK(["-a", "--", "--foo", "bar"], {'a': "--", 'boo': None, 'foo': ["bar"]}, []), def test_short_option_joined_and_separator(self): self.assertParseOK(["-ab", "--", "--foo", "bar"], {'a': "b", 'boo': None, 'foo': None}, ["--foo", "bar"]), def test_hyphen_becomes_positional_arg(self): self.assertParseOK(["-ab", "-", "--foo", "bar"], {'a': "b", 'boo': None, 'foo': ["bar"]}, ["-"]) def test_no_append_versus_append(self): self.assertParseOK(["-b3", "-b", "5", "--foo=bar", "--foo", "baz"], {'a': None, 'boo': 5, 'foo': ["bar", "baz"]}, []) def test_option_consumes_optionlike_string(self): self.assertParseOK(["-a", "-b3"], {'a': "-b3", 'boo': None, 'foo': None}, []) def test_combined_single_invalid_option(self): self.parser.add_option("-t", action="store_true") self.assertParseFail(["-test"], "no such option: -e") class TestBool(BaseTest): def setUp(self): options = [make_option("-v", "--verbose", action="store_true", dest="verbose", default=''), make_option("-q", "--quiet", action="store_false", dest="verbose")] self.parser = OptionParser(option_list = options) def test_bool_default(self): self.assertParseOK([], {'verbose': ''}, []) def test_bool_false(self): (options, args) = self.assertParseOK(["-q"], {'verbose': 0}, []) self.assertTrue(options.verbose is False) def test_bool_true(self): (options, args) = self.assertParseOK(["-v"], {'verbose': 1}, []) self.assertTrue(options.verbose is True) def test_bool_flicker_on_and_off(self): self.assertParseOK(["-qvq", "-q", "-v"], {'verbose': 1}, []) class TestChoice(BaseTest): def setUp(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) self.parser.add_option("-c", action="store", type="choice", dest="choice", choices=["one", "two", "three"]) def test_valid_choice(self): self.assertParseOK(["-c", "one", "xyz"], {'choice': 'one'}, ["xyz"]) def test_invalid_choice(self): self.assertParseFail(["-c", "four", "abc"], "option -c: invalid choice: 'four' " "(choose from 'one', 'two', 'three')") def test_add_choice_option(self): self.parser.add_option("-d", "--default", choices=["four", "five", "six"]) opt = self.parser.get_option("-d") self.assertEqual(opt.type, "choice") self.assertEqual(opt.action, "store") class TestCount(BaseTest): def setUp(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) self.v_opt = make_option("-v", action="count", dest="verbose") self.parser.add_option(self.v_opt) self.parser.add_option("--verbose", type="int", dest="verbose") self.parser.add_option("-q", "--quiet", action="store_const", dest="verbose", const=0) def test_empty(self): self.assertParseOK([], {'verbose': None}, []) def test_count_one(self): self.assertParseOK(["-v"], {'verbose': 1}, []) def test_count_three(self): self.assertParseOK(["-vvv"], {'verbose': 3}, []) def test_count_three_apart(self): self.assertParseOK(["-v", "-v", "-v"], {'verbose': 3}, []) def test_count_override_amount(self): self.assertParseOK(["-vvv", "--verbose=2"], {'verbose': 2}, []) def test_count_override_quiet(self): self.assertParseOK(["-vvv", "--verbose=2", "-q"], {'verbose': 0}, []) def test_count_overriding(self): self.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"], {'verbose': 1}, []) def test_count_interspersed_args(self): self.assertParseOK(["--quiet", "3", "-v"], {'verbose': 1}, ["3"]) def test_count_no_interspersed_args(self): self.parser.disable_interspersed_args() self.assertParseOK(["--quiet", "3", "-v"], {'verbose': 0}, ["3", "-v"]) def test_count_no_such_option(self): self.assertParseFail(["-q3", "-v"], "no such option: -3") def test_count_option_no_value(self): self.assertParseFail(["--quiet=3", "-v"], "--quiet option does not take a value") def test_count_with_default(self): self.parser.set_default('verbose', 0) self.assertParseOK([], {'verbose':0}, []) def test_count_overriding_default(self): self.parser.set_default('verbose', 0) self.assertParseOK(["-vvv", "--verbose=2", "-q", "-v"], {'verbose': 1}, []) class TestMultipleArgs(BaseTest): def setUp(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) self.parser.add_option("-p", "--point", action="store", nargs=3, type="float", dest="point") def test_nargs_with_positional_args(self): self.assertParseOK(["foo", "-p", "1", "2.5", "-4.3", "xyz"], {'point': (1.0, 2.5, -4.3)}, ["foo", "xyz"]) def test_nargs_long_opt(self): self.assertParseOK(["--point", "-1", "2.5", "-0", "xyz"], {'point': (-1.0, 2.5, -0.0)}, ["xyz"]) def test_nargs_invalid_float_value(self): self.assertParseFail(["-p", "1.0", "2x", "3.5"], "option -p: " "invalid floating-point value: '2x'") def test_nargs_required_values(self): self.assertParseFail(["--point", "1.0", "3.5"], "--point option requires 3 arguments") class TestMultipleArgsAppend(BaseTest): def setUp(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) self.parser.add_option("-p", "--point", action="store", nargs=3, type="float", dest="point") self.parser.add_option("-f", "--foo", action="append", nargs=2, type="int", dest="foo") self.parser.add_option("-z", "--zero", action="append_const", dest="foo", const=(0, 0)) def test_nargs_append(self): self.assertParseOK(["-f", "4", "-3", "blah", "--foo", "1", "666"], {'point': None, 'foo': [(4, -3), (1, 666)]}, ["blah"]) def test_nargs_append_required_values(self): self.assertParseFail(["-f4,3"], "-f option requires 2 arguments") def test_nargs_append_simple(self): self.assertParseOK(["--foo=3", "4"], {'point': None, 'foo':[(3, 4)]}, []) def test_nargs_append_const(self): self.assertParseOK(["--zero", "--foo", "3", "4", "-z"], {'point': None, 'foo':[(0, 0), (3, 4), (0, 0)]}, []) class TestVersion(BaseTest): def test_version(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, version="%prog 0.1") save_argv = sys.argv[:] try: sys.argv[0] = os.path.join(os.curdir, "foo", "bar") self.assertOutput(["--version"], "bar 0.1\n") finally: sys.argv[:] = save_argv def test_no_version(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) self.assertParseFail(["--version"], "no such option: --version") # -- Test conflicting default values and parser.parse_args() ----------- class TestConflictingDefaults(BaseTest): """Conflicting default values: the last one should win.""" def setUp(self): self.parser = OptionParser(option_list=[ make_option("-v", action="store_true", dest="verbose", default=1)]) def test_conflict_default(self): self.parser.add_option("-q", action="store_false", dest="verbose", default=0) self.assertParseOK([], {'verbose': 0}, []) def test_conflict_default_none(self): self.parser.add_option("-q", action="store_false", dest="verbose", default=None) self.assertParseOK([], {'verbose': None}, []) class TestOptionGroup(BaseTest): def setUp(self): self.parser = OptionParser(usage=SUPPRESS_USAGE) def test_option_group_create_instance(self): group = OptionGroup(self.parser, "Spam") self.parser.add_option_group(group) group.add_option("--spam", action="store_true", help="spam spam spam spam") self.assertParseOK(["--spam"], {'spam': 1}, []) def test_add_group_no_group(self): self.assertTypeError(self.parser.add_option_group, "not an OptionGroup instance: None", None) def test_add_group_invalid_arguments(self): self.assertTypeError(self.parser.add_option_group, "invalid arguments", None, None) def test_add_group_wrong_parser(self): group = OptionGroup(self.parser, "Spam") group.parser = OptionParser() self.assertRaises(self.parser.add_option_group, (group,), None, ValueError, "invalid OptionGroup (wrong parser)") def test_group_manipulate(self): group = self.parser.add_option_group("Group 2", description="Some more options") group.set_title("Bacon") group.add_option("--bacon", type="int") self.assertTrue(self.parser.get_option_group("--bacon"), group) # -- Test extending and parser.parse_args() ---------------------------- class TestExtendAddTypes(BaseTest): def setUp(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, option_class=self.MyOption) self.parser.add_option("-a", None, type="string", dest="a") self.parser.add_option("-f", "--file", type="file", dest="file") def tearDown(self): if os.path.isdir(test_support.TESTFN): os.rmdir(test_support.TESTFN) elif os.path.isfile(test_support.TESTFN): os.unlink(test_support.TESTFN) class MyOption (Option): def check_file(option, opt, value): if not os.path.exists(value): raise OptionValueError("%s: file does not exist" % value) elif not os.path.isfile(value): raise OptionValueError("%s: not a regular file" % value) return value TYPES = Option.TYPES + ("file",) TYPE_CHECKER = copy.copy(Option.TYPE_CHECKER) TYPE_CHECKER["file"] = check_file def test_filetype_ok(self): open(test_support.TESTFN, "w").close() self.assertParseOK(["--file", test_support.TESTFN, "-afoo"], {'file': test_support.TESTFN, 'a': 'foo'}, []) def test_filetype_noexist(self): self.assertParseFail(["--file", test_support.TESTFN, "-afoo"], "%s: file does not exist" % test_support.TESTFN) def test_filetype_notfile(self): os.mkdir(test_support.TESTFN) self.assertParseFail(["--file", test_support.TESTFN, "-afoo"], "%s: not a regular file" % test_support.TESTFN) class TestExtendAddActions(BaseTest): def setUp(self): options = [self.MyOption("-a", "--apple", action="extend", type="string", dest="apple")] self.parser = OptionParser(option_list=options) class MyOption (Option): ACTIONS = Option.ACTIONS + ("extend",) STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",) TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",) def take_action(self, action, dest, opt, value, values, parser): if action == "extend": lvalue = value.split(",") values.ensure_value(dest, []).extend(lvalue) else: Option.take_action(self, action, dest, opt, parser, value, values) def test_extend_add_action(self): self.assertParseOK(["-afoo,bar", "--apple=blah"], {'apple': ["foo", "bar", "blah"]}, []) def test_extend_add_action_normal(self): self.assertParseOK(["-a", "foo", "-abar", "--apple=x,y"], {'apple': ["foo", "bar", "x", "y"]}, []) # -- Test callbacks and parser.parse_args() ---------------------------- class TestCallback(BaseTest): def setUp(self): options = [make_option("-x", None, action="callback", callback=self.process_opt), make_option("-f", "--file", action="callback", callback=self.process_opt, type="string", dest="filename")] self.parser = OptionParser(option_list=options) def process_opt(self, option, opt, value, parser_): if opt == "-x": self.assertEqual(option._short_opts, ["-x"]) self.assertEqual(option._long_opts, []) self.assertTrue(parser_ is self.parser) self.assertTrue(value is None) self.assertEqual(vars(parser_.values), {'filename': None}) parser_.values.x = 42 elif opt == "--file": self.assertEqual(option._short_opts, ["-f"]) self.assertEqual(option._long_opts, ["--file"]) self.assertTrue(parser_ is self.parser) self.assertEqual(value, "foo") self.assertEqual(vars(parser_.values), {'filename': None, 'x': 42}) setattr(parser_.values, option.dest, value) else: self.fail("Unknown option %r in process_opt." % opt) def test_callback(self): self.assertParseOK(["-x", "--file=foo"], {'filename': "foo", 'x': 42}, []) def test_callback_help(self): # This test was prompted by SF bug #960515 -- the point is # not to inspect the help text, just to make sure that # format_help() doesn't crash. parser = OptionParser(usage=SUPPRESS_USAGE) parser.remove_option("-h") parser.add_option("-t", "--test", action="callback", callback=lambda: None, type="string", help="foo") expected_help = ("Options:\n" " -t TEST, --test=TEST foo\n") self.assertHelp(parser, expected_help) class TestCallbackExtraArgs(BaseTest): def setUp(self): options = [make_option("-p", "--point", action="callback", callback=self.process_tuple, callback_args=(3, int), type="string", dest="points", default=[])] self.parser = OptionParser(option_list=options) def process_tuple(self, option, opt, value, parser_, len, type): self.assertEqual(len, 3) self.assertTrue(type is int) if opt == "-p": self.assertEqual(value, "1,2,3") elif opt == "--point": self.assertEqual(value, "4,5,6") value = tuple(map(type, value.split(","))) getattr(parser_.values, option.dest).append(value) def test_callback_extra_args(self): self.assertParseOK(["-p1,2,3", "--point", "4,5,6"], {'points': [(1,2,3), (4,5,6)]}, []) class TestCallbackMeddleArgs(BaseTest): def setUp(self): options = [make_option(str(x), action="callback", callback=self.process_n, dest='things') for x in range(-1, -6, -1)] self.parser = OptionParser(option_list=options) # Callback that meddles in rargs, largs def process_n(self, option, opt, value, parser_): # option is -3, -5, etc. nargs = int(opt[1:]) rargs = parser_.rargs if len(rargs) < nargs: self.fail("Expected %d arguments for %s option." % (nargs, opt)) dest = parser_.values.ensure_value(option.dest, []) dest.append(tuple(rargs[0:nargs])) parser_.largs.append(nargs) del rargs[0:nargs] def test_callback_meddle_args(self): self.assertParseOK(["-1", "foo", "-3", "bar", "baz", "qux"], {'things': [("foo",), ("bar", "baz", "qux")]}, [1, 3]) def test_callback_meddle_args_separator(self): self.assertParseOK(["-2", "foo", "--"], {'things': [('foo', '--')]}, [2]) class TestCallbackManyArgs(BaseTest): def setUp(self): options = [make_option("-a", "--apple", action="callback", nargs=2, callback=self.process_many, type="string"), make_option("-b", "--bob", action="callback", nargs=3, callback=self.process_many, type="int")] self.parser = OptionParser(option_list=options) def process_many(self, option, opt, value, parser_): if opt == "-a": self.assertEqual(value, ("foo", "bar")) elif opt == "--apple": self.assertEqual(value, ("ding", "dong")) elif opt == "-b": self.assertEqual(value, (1, 2, 3)) elif opt == "--bob": self.assertEqual(value, (-666, 42, 0)) def test_many_args(self): self.assertParseOK(["-a", "foo", "bar", "--apple", "ding", "dong", "-b", "1", "2", "3", "--bob", "-666", "42", "0"], {"apple": None, "bob": None}, []) class TestCallbackCheckAbbrev(BaseTest): def setUp(self): self.parser = OptionParser() self.parser.add_option("--foo-bar", action="callback", callback=self.check_abbrev) def check_abbrev(self, option, opt, value, parser): self.assertEqual(opt, "--foo-bar") def test_abbrev_callback_expansion(self): self.assertParseOK(["--foo"], {}, []) class TestCallbackVarArgs(BaseTest): def setUp(self): options = [make_option("-a", type="int", nargs=2, dest="a"), make_option("-b", action="store_true", dest="b"), make_option("-c", "--callback", action="callback", callback=self.variable_args, dest="c")] self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, option_list=options) def variable_args(self, option, opt, value, parser): self.assertTrue(value is None) value = [] rargs = parser.rargs while rargs: arg = rargs[0] if ((arg[:2] == "--" and len(arg) > 2) or (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")): break else: value.append(arg) del rargs[0] setattr(parser.values, option.dest, value) def test_variable_args(self): self.assertParseOK(["-a3", "-5", "--callback", "foo", "bar"], {'a': (3, -5), 'b': None, 'c': ["foo", "bar"]}, []) def test_consume_separator_stop_at_option(self): self.assertParseOK(["-c", "37", "--", "xxx", "-b", "hello"], {'a': None, 'b': True, 'c': ["37", "--", "xxx"]}, ["hello"]) def test_positional_arg_and_variable_args(self): self.assertParseOK(["hello", "-c", "foo", "-", "bar"], {'a': None, 'b': None, 'c':["foo", "-", "bar"]}, ["hello"]) def test_stop_at_option(self): self.assertParseOK(["-c", "foo", "-b"], {'a': None, 'b': True, 'c': ["foo"]}, []) def test_stop_at_invalid_option(self): self.assertParseFail(["-c", "3", "-5", "-a"], "no such option: -5") # -- Test conflict handling and parser.parse_args() -------------------- class ConflictBase(BaseTest): def setUp(self): options = [make_option("-v", "--verbose", action="count", dest="verbose", help="increment verbosity")] self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, option_list=options) def show_version(self, option, opt, value, parser): parser.values.show_version = 1 class TestConflict(ConflictBase): """Use the default conflict resolution for Optik 1.2: error.""" def assertTrueconflict_error(self, func): err = self.assertRaises( func, ("-v", "--version"), {'action' : "callback", 'callback' : self.show_version, 'help' : "show version"}, OptionConflictError, "option -v/--version: conflicting option string(s): -v") self.assertEqual(err.msg, "conflicting option string(s): -v") self.assertEqual(err.option_id, "-v/--version") def test_conflict_error(self): self.assertTrueconflict_error(self.parser.add_option) def test_conflict_error_group(self): group = OptionGroup(self.parser, "Group 1") self.assertTrueconflict_error(group.add_option) def test_no_such_conflict_handler(self): self.assertRaises( self.parser.set_conflict_handler, ('foo',), None, ValueError, "invalid conflict_resolution value 'foo'") class TestConflictResolve(ConflictBase): def setUp(self): ConflictBase.setUp(self) self.parser.set_conflict_handler("resolve") self.parser.add_option("-v", "--version", action="callback", callback=self.show_version, help="show version") def test_conflict_resolve(self): v_opt = self.parser.get_option("-v") verbose_opt = self.parser.get_option("--verbose") version_opt = self.parser.get_option("--version") self.assertTrue(v_opt is version_opt) self.assertTrue(v_opt is not verbose_opt) self.assertEqual(v_opt._long_opts, ["--version"]) self.assertEqual(version_opt._short_opts, ["-v"]) self.assertEqual(version_opt._long_opts, ["--version"]) self.assertEqual(verbose_opt._short_opts, []) self.assertEqual(verbose_opt._long_opts, ["--verbose"]) def test_conflict_resolve_help(self): self.assertOutput(["-h"], """\ Options: --verbose increment verbosity -h, --help show this help message and exit -v, --version show version """) def test_conflict_resolve_short_opt(self): self.assertParseOK(["-v"], {'verbose': None, 'show_version': 1}, []) def test_conflict_resolve_long_opt(self): self.assertParseOK(["--verbose"], {'verbose': 1}, []) def test_conflict_resolve_long_opts(self): self.assertParseOK(["--verbose", "--version"], {'verbose': 1, 'show_version': 1}, []) class TestConflictOverride(BaseTest): def setUp(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) self.parser.set_conflict_handler("resolve") self.parser.add_option("-n", "--dry-run", action="store_true", dest="dry_run", help="don't do anything") self.parser.add_option("--dry-run", "-n", action="store_const", const=42, dest="dry_run", help="dry run mode") def test_conflict_override_opts(self): opt = self.parser.get_option("--dry-run") self.assertEqual(opt._short_opts, ["-n"]) self.assertEqual(opt._long_opts, ["--dry-run"]) def test_conflict_override_help(self): self.assertOutput(["-h"], """\ Options: -h, --help show this help message and exit -n, --dry-run dry run mode """) def test_conflict_override_args(self): self.assertParseOK(["-n"], {'dry_run': 42}, []) # -- Other testing. ---------------------------------------------------- _expected_help_basic = """\ Usage: bar.py [options] Options: -a APPLE throw APPLEs at basket -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the evil spirits that cause trouble and mayhem) --foo=FOO store FOO in the foo list for later fooing -h, --help show this help message and exit """ _expected_help_long_opts_first = """\ Usage: bar.py [options] Options: -a APPLE throw APPLEs at basket --boo=NUM, -b NUM shout "boo!" NUM times (in order to frighten away all the evil spirits that cause trouble and mayhem) --foo=FOO store FOO in the foo list for later fooing --help, -h show this help message and exit """ _expected_help_title_formatter = """\ Usage ===== bar.py [options] Options ======= -a APPLE throw APPLEs at basket --boo=NUM, -b NUM shout "boo!" NUM times (in order to frighten away all the evil spirits that cause trouble and mayhem) --foo=FOO store FOO in the foo list for later fooing --help, -h show this help message and exit """ _expected_help_short_lines = """\ Usage: bar.py [options] Options: -a APPLE throw APPLEs at basket -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the evil spirits that cause trouble and mayhem) --foo=FOO store FOO in the foo list for later fooing -h, --help show this help message and exit """ class TestHelp(BaseTest): def setUp(self): self.parser = self.make_parser(80) def make_parser(self, columns): options = [ make_option("-a", type="string", dest='a', metavar="APPLE", help="throw APPLEs at basket"), make_option("-b", "--boo", type="int", dest='boo', metavar="NUM", help= "shout \"boo!\" NUM times (in order to frighten away " "all the evil spirits that cause trouble and mayhem)"), make_option("--foo", action="append", type="string", dest='foo', help="store FOO in the foo list for later fooing"), ] # We need to set COLUMNS for the OptionParser constructor, but # we must restore its original value -- otherwise, this test # screws things up for other tests when it's part of the Python # test suite. with test_support.EnvironmentVarGuard() as env: env['COLUMNS'] = str(columns) return InterceptingOptionParser(option_list=options) def assertHelpEquals(self, expected_output): if type(expected_output) is types.UnicodeType: encoding = self.parser._get_encoding(sys.stdout) expected_output = expected_output.encode(encoding, "replace") save_argv = sys.argv[:] try: # Make optparse believe bar.py is being executed. sys.argv[0] = os.path.join("foo", "bar.py") self.assertOutput(["-h"], expected_output) finally: sys.argv[:] = save_argv def test_help(self): self.assertHelpEquals(_expected_help_basic) def test_help_old_usage(self): self.parser.set_usage("Usage: %prog [options]") self.assertHelpEquals(_expected_help_basic) def test_help_long_opts_first(self): self.parser.formatter.short_first = 0 self.assertHelpEquals(_expected_help_long_opts_first) def test_help_title_formatter(self): with test_support.EnvironmentVarGuard() as env: env["COLUMNS"] = "80" self.parser.formatter = TitledHelpFormatter() self.assertHelpEquals(_expected_help_title_formatter) def test_wrap_columns(self): # Ensure that wrapping respects $COLUMNS environment variable. # Need to reconstruct the parser, since that's the only time # we look at $COLUMNS. self.parser = self.make_parser(60) self.assertHelpEquals(_expected_help_short_lines) def test_help_unicode(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE) self.parser.add_option("-a", action="store_true", help=u"ol\u00E9!") expect = u"""\ Options: -h, --help show this help message and exit -a ol\u00E9! """ self.assertHelpEquals(expect) def test_help_unicode_description(self): self.parser = InterceptingOptionParser(usage=SUPPRESS_USAGE, description=u"ol\u00E9!") expect = u"""\ ol\u00E9! Options: -h, --help show this help message and exit """ self.assertHelpEquals(expect) def test_help_description_groups(self): self.parser.set_description( "This is the program description for %prog. %prog has " "an option group as well as single options.") group = OptionGroup( self.parser, "Dangerous Options", "Caution: use of these options is at your own risk. " "It is believed that some of them bite.") group.add_option("-g", action="store_true", help="Group option.") self.parser.add_option_group(group) expect = """\ Usage: bar.py [options] This is the program description for bar.py. bar.py has an option group as well as single options. Options: -a APPLE throw APPLEs at basket -b NUM, --boo=NUM shout "boo!" NUM times (in order to frighten away all the evil spirits that cause trouble and mayhem) --foo=FOO store FOO in the foo list for later fooing -h, --help show this help message and exit Dangerous Options: Caution: use of these options is at your own risk. It is believed that some of them bite. -g Group option. """ self.assertHelpEquals(expect) self.parser.epilog = "Please report bugs to /dev/null." self.assertHelpEquals(expect + "\nPlease report bugs to /dev/null.\n") class TestMatchAbbrev(BaseTest): def test_match_abbrev(self): self.assertEqual(_match_abbrev("--f", {"--foz": None, "--foo": None, "--fie": None, "--f": None}), "--f") def test_match_abbrev_error(self): s = "--f" wordmap = {"--foz": None, "--foo": None, "--fie": None} self.assertRaises( _match_abbrev, (s, wordmap), None, BadOptionError, "ambiguous option: --f (--fie, --foo, --foz?)") class TestParseNumber(BaseTest): def setUp(self): self.parser = InterceptingOptionParser() self.parser.add_option("-n", type=int) self.parser.add_option("-l", type=long) def test_parse_num_fail(self): self.assertRaises( _parse_num, ("", int), {}, ValueError, re.compile(r"invalid literal for int().*: '?'?")) self.assertRaises( _parse_num, ("0xOoops", long), {}, ValueError, re.compile(r"invalid literal for long().*: '?0xOoops'?")) def test_parse_num_ok(self): self.assertEqual(_parse_num("0", int), 0) self.assertEqual(_parse_num("0x10", int), 16) self.assertEqual(_parse_num("0XA", long), 10L) self.assertEqual(_parse_num("010", long), 8L) self.assertEqual(_parse_num("0b11", int), 3) self.assertEqual(_parse_num("0b", long), 0L) def test_numeric_options(self): self.assertParseOK(["-n", "42", "-l", "0x20"], { "n": 42, "l": 0x20 }, []) self.assertParseOK(["-n", "0b0101", "-l010"], { "n": 5, "l": 8 }, []) self.assertParseFail(["-n008"], "option -n: invalid integer value: '008'") self.assertParseFail(["-l0b0123"], "option -l: invalid long integer value: '0b0123'") self.assertParseFail(["-l", "0x12x"], "option -l: invalid long integer value: '0x12x'") def test_main(): test_support.run_unittest(__name__) if __name__ == '__main__': test_main()
gpl-2.0
quxiaolong1504/django
tests/string_lookup/tests.py
290
2573
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TestCase from .models import Article, Bar, Base, Child, Foo, Whiz class StringLookupTests(TestCase): def test_string_form_referencing(self): """ Regression test for #1661 and #1662 Check that string form referencing of models works, both as pre and post reference, on all RelatedField types. """ f1 = Foo(name="Foo1") f1.save() f2 = Foo(name="Foo2") f2.save() w1 = Whiz(name="Whiz1") w1.save() b1 = Bar(name="Bar1", normal=f1, fwd=w1, back=f2) b1.save() self.assertEqual(b1.normal, f1) self.assertEqual(b1.fwd, w1) self.assertEqual(b1.back, f2) base1 = Base(name="Base1") base1.save() child1 = Child(name="Child1", parent=base1) child1.save() self.assertEqual(child1.parent, base1) def test_unicode_chars_in_queries(self): """ Regression tests for #3937 make sure we can use unicode characters in queries. If these tests fail on MySQL, it's a problem with the test setup. A properly configured UTF-8 database can handle this. """ fx = Foo(name='Bjorn', friend='François') fx.save() self.assertEqual(Foo.objects.get(friend__contains='\xe7'), fx) # We can also do the above query using UTF-8 strings. self.assertEqual(Foo.objects.get(friend__contains=b'\xc3\xa7'), fx) def test_queries_on_textfields(self): """ Regression tests for #5087 make sure we can perform queries on TextFields. """ a = Article(name='Test', text='The quick brown fox jumps over the lazy dog.') a.save() self.assertEqual(Article.objects.get(text__exact='The quick brown fox jumps over the lazy dog.'), a) self.assertEqual(Article.objects.get(text__contains='quick brown fox'), a) def test_ipaddress_on_postgresql(self): """ Regression test for #708 "like" queries on IP address fields require casting with HOST() (on PostgreSQL). """ a = Article(name='IP test', text='The body', submitted_from='192.0.2.100') a.save() self.assertEqual(repr(Article.objects.filter(submitted_from__contains='192.0.2')), repr([a])) # Test that the searches do not match the subnet mask (/32 in this case) self.assertEqual(Article.objects.filter(submitted_from__contains='32').count(), 0)
bsd-3-clause
zhongdai/gensim
gensim/corpora/sharded_corpus.py
63
35097
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Original author: Jan Hajic jr. # Copyright (C) 2015 Radim Rehurek and gensim team. # Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html """ This module implements a corpus class that stores its data in separate files called "shards". This is a compromise between speed (keeping the whole dataset in memory) and memory footprint (keeping the data on disk and reading from it on demand). The corpus is intended for situations where you need to use your data as numpy arrays for some iterative processing (like training something using SGD, which usually involves heavy matrix multiplication). """ from __future__ import print_function import logging import os import math import numpy import scipy.sparse as sparse import time logger = logging.getLogger(__name__) #: Specifies which dtype should be used for serializing the shards. _default_dtype = float try: import theano _default_dtype = theano.config.floatX except ImportError: logger.info('Could not import Theano, will use standard float for default ShardedCorpus dtype.') from six.moves import xrange import gensim from gensim.corpora import IndexedCorpus from gensim.interfaces import TransformedCorpus class ShardedCorpus(IndexedCorpus): """ This corpus is designed for situations where you need to train a model on matrices, with a large number of iterations. (It should be faster than gensim's other IndexedCorpus implementations for this use case; check the `benchmark_datasets.py` script. It should also serialize faster.) The corpus stores its data in separate files called "shards". This is a compromise between speed (keeping the whole dataset in memory) and memory footprint (keeping the data on disk and reading from it on demand). Persistence is done using the standard gensim load/save methods. .. note:: The dataset is **read-only**, there is - as opposed to gensim's Similarity class, which works similarly - no way of adding documents to the dataset (for now). You can use ShardedCorpus to serialize your data just like any other gensim corpus that implements serialization. However, because the data is saved as numpy 2-dimensional ndarrays (or scipy sparse matrices), you need to supply the dimension of your data to the corpus. (The dimension of word frequency vectors will typically be the size of the vocabulary, etc.) >>> corpus = gensim.utils.mock_data() >>> output_prefix = 'mydata.shdat' >>> ShardedCorpus.serialize(output_prefix, corpus, dim=1000) The `output_prefix` tells the ShardedCorpus where to put the data. Shards are saved as `output_prefix.0`, `output_prefix.1`, etc. All shards must be of the same size. The shards can be re-sized (which is essentially a re-serialization into new-size shards), but note that this operation will temporarily take twice as much disk space, because the old shards are not deleted until the new shards are safely in place. After serializing the data, the corpus will then save itself to the file `output_prefix`. On further initialization with the same `output_prefix`, the corpus will load the already built dataset unless the `overwrite` option is given. (A new object is "cloned" from the one saved to `output_prefix` previously.) To retrieve data, you can load the corpus and use it like a list: >>> sh_corpus = ShardedCorpus.load(output_prefix) >>> batch = sh_corpus[100:150] This will retrieve a numpy 2-dimensional array of 50 rows and 1000 columns (1000 was the dimension of the data we supplied to the corpus). To retrieve gensim-style sparse vectors, set the `gensim` property: >>> sh_corpus.gensim = True >>> batch = sh_corpus[100:150] The batch now will be a generator of gensim vectors. Since the corpus needs the data serialized in order to be able to operate, it will serialize data right away on initialization. Instead of calling `ShardedCorpus.serialize()`, you can just initialize and use the corpus right away: >>> corpus = ShardedCorpus(output_prefix, corpus, dim=1000) >>> batch = corpus[100:150] ShardedCorpus also supports working with scipy sparse matrices, both during retrieval and during serialization. If you want to serialize your data as sparse matrices, set the `sparse_serialization` flag. For retrieving your data as sparse matrices, use the `sparse_retrieval` flag. (You can also retrieve densely serialized data as sparse matrices, for the sake of completeness, and vice versa.) By default, the corpus will retrieve numpy ndarrays even if it was serialized into sparse matrices. >>> sparse_prefix = 'mydata.sparse.shdat' >>> ShardedCorpus.serialize(sparse_prefix, corpus, dim=1000, sparse_serialization=True) >>> sparse_corpus = ShardedCorpus.load(sparse_prefix) >>> batch = sparse_corpus[100:150] >>> type(batch) <type 'numpy.ndarray'> >>> sparse_corpus.sparse_retrieval = True >>> batch = sparse_corpus[100:150] <class 'scipy.sparse.csr.csr_matrix'> While you *can* touch the `sparse_retrieval` attribute during the life of a ShardedCorpus object, you should definitely not touch ` `sharded_serialization`! Changing the attribute will not miraculously re-serialize the data in the requested format. The CSR format is used for sparse data throughout. Internally, to retrieve data, the dataset keeps track of which shard is currently open and on a `__getitem__` request, either returns an item from the current shard, or opens a new one. The shard size is constant, except for the last shard. """ def __init__(self, output_prefix, corpus, dim=None, shardsize=4096, overwrite=False, sparse_serialization=False, sparse_retrieval=False, gensim=False): """Initializes the dataset. If `output_prefix` is not found, builds the shards. :type output_prefix: str :param output_prefix: The absolute path to the file from which shard filenames should be derived. The individual shards will be saved as `output_prefix.0`, `output_prefix.1`, etc. The `output_prefix` path then works as the filename to which the ShardedCorpus object itself will be automatically saved. Normally, gensim corpora do not do this, but ShardedCorpus needs to remember several serialization settings: namely the shard size and whether it was serialized in dense or sparse format. By saving automatically, any new ShardedCorpus with the same `output_prefix` will be able to find the information about the data serialized with the given prefix. If you want to *overwrite* your data serialized with some output prefix, set the `overwrite` flag to True. Of course, you can save your corpus separately as well using the `save()` method. :type corpus: gensim.interfaces.CorpusABC :param corpus: The source corpus from which to build the dataset. :type dim: int :param dim: Specify beforehand what the dimension of a dataset item should be. This is useful when initializing from a corpus that doesn't advertise its dimension, or when it does and you want to check that the corpus matches the expected dimension. **If `dim` is left unused and `corpus` does not provide its dimension in an expected manner, initialization will fail.** :type shardsize: int :param shardsize: How many data points should be in one shard. More data per shard means less shard reloading but higher memory usage and vice versa. :type overwrite: bool :param overwrite: If set, will build dataset from given corpus even if `output_prefix` already exists. :type sparse_serialization: bool :param sparse_serialization: If set, will save the data in a sparse form (as csr matrices). This is to speed up retrieval when you know you will be using sparse matrices. ..note:: This property **should not change** during the lifetime of the dataset. (If you find out you need to change from a sparse to a dense representation, the best practice is to create another ShardedCorpus object.) :type sparse_retrieval: bool :param sparse_retrieval: If set, will retrieve data as sparse vectors (numpy csr matrices). If unset, will return ndarrays. Note that retrieval speed for this option depends on how the dataset was serialized. If `sparse_serialization` was set, then setting `sparse_retrieval` will be faster. However, if the two settings do not correspond, the conversion on the fly will slow the dataset down. :type gensim: bool :param gensim: If set, will convert the output to gensim sparse vectors (list of tuples (id, value)) to make it behave like any other gensim corpus. This **will** slow the dataset down. """ self.output_prefix = output_prefix self.shardsize = shardsize self.n_docs = 0 self.offsets = [] self.n_shards = 0 self.dim = dim # This number may change during initialization/loading. # Sparse vs. dense serialization and retrieval. self.sparse_serialization = sparse_serialization self.sparse_retrieval = sparse_retrieval self.gensim = gensim # The "state" of the dataset. self.current_shard = None # The current shard itself (numpy ndarray) self.current_shard_n = None # Current shard is the current_shard_n-th self.current_offset = None # The index into the dataset which # corresponds to index 0 of current shard logger.info('Initializing sharded corpus with prefix ' '{0}'.format(output_prefix)) if (not os.path.isfile(output_prefix)) or overwrite: logger.info('Building from corpus...') self.init_shards(output_prefix, corpus, shardsize) # Save automatically, to facilitate re-loading # and retain information about how the corpus # was serialized. logger.info('Saving ShardedCorpus object to ' '{0}'.format(self.output_prefix)) self.save() else: logger.info('Cloning existing...') self.init_by_clone() def init_shards(self, output_prefix, corpus, shardsize=4096, dtype=_default_dtype): """Initialize shards from the corpus.""" if not gensim.utils.is_corpus(corpus): raise ValueError('Cannot initialize shards without a corpus to read' ' from! (Got corpus type: {0})'.format(type(corpus))) proposed_dim = self._guess_n_features(corpus) if proposed_dim != self.dim: if self.dim is None: logger.info('Deriving dataset dimension from corpus: ' '{0}'.format(proposed_dim)) else: logger.warn('Dataset dimension derived from input corpus diffe' 'rs from initialization argument, using corpus.' '(corpus {0}, init arg {1})'.format(proposed_dim, self.dim)) self.dim = proposed_dim self.offsets = [0] start_time = time.clock() logger.info('Running init from corpus.') for n, doc_chunk in enumerate(gensim.utils.grouper(corpus, chunksize=shardsize)): logger.info('Chunk no. {0} at {1} s'.format(n, time.clock() - start_time)) current_shard = numpy.zeros((len(doc_chunk), self.dim), dtype=dtype) logger.debug('Current chunk dimension: ' '{0} x {1}'.format(len(doc_chunk), self.dim)) for i, doc in enumerate(doc_chunk): doc = dict(doc) current_shard[i][list(doc)] = list(gensim.matutils.itervalues(doc)) # Handles the updating as well. if self.sparse_serialization: current_shard = sparse.csr_matrix(current_shard) self.save_shard(current_shard) end_time = time.clock() logger.info('Built {0} shards in {1} s.'.format(self.n_shards, end_time - start_time)) def init_by_clone(self): """ Initialize by copying over attributes of another ShardedCorpus instance saved to the output_prefix given at __init__(). """ temp = self.__class__.load(self.output_prefix) self.n_shards = temp.n_shards self.n_docs = temp.n_docs self.offsets = temp.offsets if temp.dim != self.dim: if self.dim is None: logger.info('Loaded dataset dimension: {0}'.format(temp.dim)) else: logger.warn('Loaded dataset dimension differs from init arg ' 'dimension, using loaded dim. ' '(loaded {0}, init {1})'.format(temp.dim, self.dim)) self.dim = temp.dim # To be consistent with the loaded data! def save_shard(self, shard, n=None, filename=None): """ Pickle the given shard. If `n` is not given, will consider the shard a new one. If `filename` is given, will use that file name instead of generating one. """ new_shard = False if n is None: n = self.n_shards # Saving the *next* one by default. new_shard = True if not filename: filename = self._shard_name(n) gensim.utils.pickle(shard, filename) if new_shard: self.offsets.append(self.offsets[-1] + shard.shape[0]) self.n_docs += shard.shape[0] self.n_shards += 1 def load_shard(self, n): """ Load (unpickle) the n-th shard as the "live" part of the dataset into the Dataset object.""" #logger.debug('ShardedCorpus loading shard {0}, ' # 'current shard: {1}'.format(n, self.current_shard_n)) # No-op if the shard is already open. if self.current_shard_n == n: return filename = self._shard_name(n) if not os.path.isfile(filename): raise ValueError('Attempting to load nonexistent shard no. {0}'.format(n)) shard = gensim.utils.unpickle(filename) self.current_shard = shard self.current_shard_n = n self.current_offset = self.offsets[n] def reset(self): """ Reset to no shard at all. Used for saving. """ self.current_shard = None self.current_shard_n = None self.current_offset = None def shard_by_offset(self, offset): """ Determine which shard the given offset belongs to. If the offset is greater than the number of available documents, raises a `ValueError`. Assumes that all shards have the same size. """ k = int(offset / self.shardsize) if offset >= self.n_docs: raise ValueError('Too high offset specified ({0}), available ' 'docs: {1}'.format(offset, self.n_docs)) if offset < 0: raise ValueError('Negative offset {0} currently not' ' supported.'.format(offset)) return k k = -1 for i, o in enumerate(self.offsets): if o > offset: # Condition should fire for every valid offset, # since the last offset is n_docs (one-past-end). k = i - 1 # First offset is always 0, so i is at least 1. break return k def in_current(self, offset): """ Determine whether the given offset falls within the current shard. """ return (self.current_offset <= offset) \ and (offset < self.offsets[self.current_shard_n + 1]) def in_next(self, offset): """ Determine whether the given offset falls within the next shard. This is a very small speedup: typically, we will be iterating through the data forward. Could save considerable time with a very large number of smaller shards. """ if self.current_shard_n == self.n_shards: return False # There's no next shard. return (self.offsets[self.current_shard_n + 1] <= offset) \ and (offset < self.offsets[self.current_shard_n + 2]) def resize_shards(self, shardsize): """ Re-process the dataset to new shard size. This may take pretty long. Also, note that you need some space on disk for this one (we're assuming there is enough disk space for double the size of the dataset and that there is enough memory for old + new shardsize). :type shardsize: int :param shardsize: The new shard size. """ # Determine how many new shards there will be n_new_shards = int(math.floor(self.n_docs / float(shardsize))) if self.n_docs % shardsize != 0: n_new_shards += 1 new_shard_names = [] new_offsets = [0] for new_shard_idx in xrange(n_new_shards): new_start = shardsize * new_shard_idx new_stop = new_start + shardsize # Last shard? if new_stop > self.n_docs: # Sanity check assert new_shard_idx == n_new_shards - 1, \ 'Shard no. {0} that ends at {1} over last document' \ ' ({2}) is not the last projected shard ({3})???' \ ''.format(new_shard_idx, new_stop, self.n_docs, n_new_shards) new_stop = self.n_docs new_shard = self[new_start:new_stop] new_shard_name = self._resized_shard_name(new_shard_idx) new_shard_names.append(new_shard_name) try: self.save_shard(new_shard, new_shard_idx, new_shard_name) except Exception: # Clean up on unsuccessful resize. for new_shard_name in new_shard_names: os.remove(new_shard_name) raise new_offsets.append(new_stop) # Move old shard files out, new ones in. Complicated due to possibility # of exceptions. old_shard_names = [self._shard_name(n) for n in xrange(self.n_shards)] try: for old_shard_n, old_shard_name in enumerate(old_shard_names): os.remove(old_shard_name) except Exception as e: logger.error('Exception occurred during old shard no. {0} ' 'removal: {1}.\nAttempting to at least move ' 'new shards in.'.format(old_shard_n, str(e))) finally: # If something happens with cleaning up - try to at least get the # new guys in. try: for shard_n, new_shard_name in enumerate(new_shard_names): os.rename(new_shard_name, self._shard_name(shard_n)) # If something happens when we're in this stage, we're screwed. except Exception as e: print(e) raise RuntimeError('Resizing completely failed for some reason.' ' Sorry, dataset is probably ruined...') finally: # Sets the new shard stats. self.n_shards = n_new_shards self.offsets = new_offsets self.shardsize = shardsize self.reset() def _shard_name(self, n): """Generate the name for the n-th shard.""" return self.output_prefix + '.' + str(n) def _resized_shard_name(self, n): """ Generate the name for the n-th new shard temporary file when resizing dataset. The file will then be re-named to standard shard name. """ return self.output_prefix + '.resize-temp.' + str(n) def _guess_n_features(self, corpus): """Attempt to guess number of features in `corpus`.""" n_features = None if hasattr(corpus, 'dim'): # print 'Guessing from \'dim\' attribute.' n_features = corpus.dim elif hasattr(corpus, 'dictionary'): # print 'GUessing from dictionary.' n_features = len(corpus.dictionary) elif hasattr(corpus, 'n_out'): # print 'Guessing from \'n_out\' attribute.' n_features = corpus.n_out elif hasattr(corpus, 'num_terms'): # print 'Guessing from \'num_terms\' attribute.' n_features = corpus.num_terms elif isinstance(corpus, TransformedCorpus): # TransformedCorpus: first check if the transformer object # defines some output dimension; if it doesn't, relegate guessing # to the corpus that is being transformed. This may easily fail! try: return self._guess_n_features(corpus.obj) except TypeError: return self._guess_n_features(corpus.corpus) else: if not self.dim: raise TypeError('Couldn\'t find number of features, ' 'refusing to guess (dimension set to {0},' 'type of corpus: {1}).'.format(self.dim, type(corpus))) else: logger.warn('Couldn\'t find number of features, trusting ' 'supplied dimension ({0})'.format(self.dim)) n_features = self.dim if self.dim and n_features != self.dim: logger.warn('Discovered inconsistent dataset dim ({0}) and ' 'feature count from corpus ({1}). Coercing to dimension' ' given by argument.'.format(self.dim, n_features)) return n_features def __len__(self): return self.n_docs def _ensure_shard(self, offset): # No shard loaded if self.current_shard is None: shard_n = self.shard_by_offset(offset) self.load_shard(shard_n) # Find appropriate shard, if necessary elif not self.in_current(offset): if self.in_next(offset): self.load_shard(self.current_shard_n + 1) else: shard_n = self.shard_by_offset(offset) self.load_shard(shard_n) def get_by_offset(self, offset): """As opposed to getitem, this one only accepts ints as offsets.""" self._ensure_shard(offset) result = self.current_shard[offset - self.current_offset] return result def __getitem__(self, offset): """ Retrieve the given row of the dataset. Supports slice notation. """ if isinstance(offset, list): # Handle all serialization & retrieval options. if self.sparse_serialization: l_result = sparse.vstack([self.get_by_offset(i) for i in offset]) if self.gensim: l_result = self._getitem_sparse2gensim(l_result) elif not self.sparse_retrieval: l_result = numpy.array(l_result.todense()) else: l_result = numpy.array([self.get_by_offset(i) for i in offset]) if self.gensim: l_result = self._getitem_dense2gensim(l_result) elif self.sparse_retrieval: l_result = sparse.csr_matrix(l_result) return l_result elif isinstance(offset, slice): start = offset.start stop = offset.stop if stop > self.n_docs: raise IndexError('Requested slice offset {0} out of range' ' ({1} docs)'.format(stop, self.n_docs)) # - get range of shards over which to iterate first_shard = self.shard_by_offset(start) last_shard = self.n_shards - 1 if not stop == self.n_docs: last_shard = self.shard_by_offset(stop) # This fails on one-past # slice indexing; that's why there's a code branch here. #logger.debug('ShardedCorpus: Retrieving slice {0}: ' # 'shard {1}'.format((offset.start, offset.stop), # (first_shard, last_shard))) self.load_shard(first_shard) # The easy case: both in one shard. if first_shard == last_shard: s_result = self.current_shard[start - self.current_offset: stop - self.current_offset] # Handle different sparsity settings: s_result = self._getitem_format(s_result) return s_result # The hard case: the slice is distributed across multiple shards # - initialize numpy.zeros() s_result = numpy.zeros((stop - start, self.dim), dtype=self.current_shard.dtype) if self.sparse_serialization: s_result = sparse.csr_matrix((0, self.dim), dtype=self.current_shard.dtype) # - gradually build it up. We will be using three set of start:stop # indexes: # - into the dataset (these are the indexes the caller works with) # - into the current shard # - into the result # Indexes into current result rows. These are always smaller than # the dataset indexes by `start` (as we move over the shards, # we're moving by the same number of rows through the result). result_start = 0 result_stop = self.offsets[self.current_shard_n + 1] - start # Indexes into current shard. These are trickiest: # - if in starting shard, these are from (start - current_offset) # to self.shardsize # - if in intermediate shard, these are from 0 to self.shardsize # - if in ending shard, these are from 0 # to (stop - current_offset) shard_start = start - self.current_offset shard_stop = self.offsets[self.current_shard_n + 1] - \ self.current_offset #s_result[result_start:result_stop] = self.current_shard[ # shard_start:shard_stop] s_result = self.__add_to_slice(s_result, result_start, result_stop, shard_start, shard_stop) # First and last get special treatment, these are in between for shard_n in xrange(first_shard+1, last_shard): self.load_shard(shard_n) result_start = result_stop result_stop += self.shardsize shard_start = 0 shard_stop = self.shardsize s_result = self.__add_to_slice(s_result, result_start, result_stop, shard_start, shard_stop) # Last shard self.load_shard(last_shard) result_start = result_stop result_stop += stop - self.current_offset shard_start = 0 shard_stop = stop - self.current_offset s_result = self.__add_to_slice(s_result, result_start, result_stop, shard_start, shard_stop) s_result = self._getitem_format(s_result) return s_result else: s_result = self.get_by_offset(offset) s_result = self._getitem_format(s_result) return s_result def __add_to_slice(self, s_result, result_start, result_stop, start, stop): """ Add the rows of the current shard from `start` to `stop` into rows `result_start` to `result_stop` of `s_result`. Operation is based on the self.sparse_serialize setting. If the shard contents are dense, then s_result is assumed to be an ndarray that already supports row indices `result_start:result_stop`. If the shard contents are sparse, assumes that s_result has `result_start` rows and we should add them up to `result_stop`. Returns the resulting s_result. """ if (result_stop - result_start) != (stop - start): raise ValueError('Result start/stop range different than stop/start' 'range (%d - %d vs. %d - %d)'.format(result_start, result_stop, start, stop)) # Dense data: just copy using numpy's slice notation if not self.sparse_serialization: s_result[result_start:result_stop] = self.current_shard[start:stop] return s_result # A bit more difficult, we're using a different structure to build the # result. else: if s_result.shape != (result_start, self.dim): raise ValueError('Assuption about sparse s_result shape ' 'invalid: {0} expected rows, {1} real ' 'rows.'.format(result_start, s_result.shape[0])) tmp_matrix = self.current_shard[start:stop] s_result = sparse.vstack([s_result, tmp_matrix]) return s_result def _getitem_format(self, s_result): if self.sparse_serialization: if self.gensim: s_result = self._getitem_sparse2gensim(s_result) elif not self.sparse_retrieval: s_result = numpy.array(s_result.todense()) else: if self.gensim: s_result = self._getitem_dense2gensim(s_result) elif self.sparse_retrieval: s_result = sparse.csr_matrix(s_result) return s_result def _getitem_sparse2gensim(self, result): """ Change given sparse result matrix to gensim sparse vectors. Uses the internals of the sparse matrix to make this fast. """ def row_sparse2gensim(row_idx, csr_matrix): indices = csr_matrix.indices[csr_matrix.indptr[row_idx]:csr_matrix.indptr[row_idx+1]] g_row = [(col_idx, csr_matrix[row_idx, col_idx]) for col_idx in indices] return g_row output = (row_sparse2gensim(i, result) for i in xrange(result.shape[0])) return output def _getitem_dense2gensim(self, result): """Change given dense result matrix to gensim sparse vectors.""" if len(result.shape) == 1: output = gensim.matutils.full2sparse(result) else: output = (gensim.matutils.full2sparse(result[i]) for i in xrange(result.shape[0])) return output # Overriding the IndexedCorpus and other corpus superclass methods def __iter__(self): """ Yield dataset items one by one (generator). """ for i in xrange(len(self)): yield self[i] def save(self, *args, **kwargs): """ Save itself (the wrapper) in clean state (after calling `reset()`) to the output_prefix file. If you wish to save to a different file, use the `fname` argument as the first positional arg. """ # Can we save to a different file than output_prefix? Well, why not? if len(args) == 0: args = tuple([self.output_prefix]) attrs_to_ignore = ['current_shard', 'current_shard_n', 'current_offset'] if 'ignore' not in kwargs: kwargs['ignore'] = frozenset(attrs_to_ignore) else: kwargs['ignore'] = frozenset([v for v in kwargs['ignore']] + attrs_to_ignore) super(ShardedCorpus, self).save(*args, **kwargs) # # self.reset() # with smart_open(self.output_prefix, 'wb') as pickle_handle: # cPickle.dump(self, pickle_handle) @classmethod def load(cls, fname, mmap=None): """ Load itself in clean state. `mmap` has no effect here. """ return super(ShardedCorpus, cls).load(fname, mmap) @staticmethod def save_corpus(fname, corpus, id2word=None, progress_cnt=1000, metadata=False, **kwargs): """ Implement a serialization interface. Do not call directly; use the `serialize` method instead. Note that you might need some ShardedCorpus init parameters, most likely the dimension (`dim`). Again, pass these as `kwargs` to the `serialize` method. All this thing does is initialize a ShardedCorpus from a corpus with the `output_prefix` argument set to the `fname` parameter of this method. The initialization of a ShardedCorpus takes care of serializing the data (in dense form) to shards. Ignore the parameters id2word, progress_cnt and metadata. They currently do nothing and are here only to provide a compatible method signature with superclass. """ ShardedCorpus(fname, corpus, **kwargs) @classmethod def serialize(serializer, fname, corpus, id2word=None, index_fname=None, progress_cnt=None, labels=None, metadata=False, **kwargs): """ Iterate through the document stream `corpus`, saving the documents as a ShardedCorpus to `fname`. Use this method instead of calling `save_corpus` directly. You may need to supply some kwargs that are used upon dataset creation (namely: `dim`, unless the dataset can infer the dimension from the given corpus). Ignore the parameters id2word, index_fname, progress_cnt, labels and metadata. They currently do nothing and are here only to provide a compatible method signature with superclass.""" serializer.save_corpus(fname, corpus, id2word=id2word, progress_cnt=progress_cnt, metadata=metadata, **kwargs)
gpl-3.0
Workday/OpenFrame
tools/telemetry/catapult_base/dependency_manager/cloud_storage_info.py
1
3811
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import stat from catapult_base import cloud_storage from catapult_base.dependency_manager import exceptions class CloudStorageInfo(object): def __init__(self, cs_bucket, cs_hash, download_path, cs_remote_path, version_in_cs=None, archive_info=None): """ Container for the information needed to download a dependency from cloud storage. Args: cs_bucket: The cloud storage bucket the dependency is located in. cs_hash: The hash of the file stored in cloud storage. download_path: Where the file should be downloaded to. cs_remote_path: Where the file is stored in the cloud storage bucket. version_in_cs: The version of the file stored in cloud storage. archive_info: An instance of ArchiveInfo if this dependency is an archive. Else None. """ self._download_path = download_path self._cs_remote_path = cs_remote_path self._cs_bucket = cs_bucket self._cs_hash = cs_hash self._version_in_cs = version_in_cs self._archive_info = archive_info if not self._has_minimum_data: raise ValueError( 'Not enough information specified to initialize a cloud storage info.' ' %s' % self) def GetRemotePath(self): """Gets the path to a downloaded version of the dependency. May not download the file if it has already been downloaded. Will unzip the downloaded file if a non-empty archive_info was passed in at init. Returns: A path to an executable that was stored in cloud_storage, or None if not found. Raises: CredentialsError: If cloud_storage credentials aren't configured. PermissionError: If cloud_storage credentials are configured, but not with an account that has permission to download the needed file. NotFoundError: If the needed file does not exist where expected in cloud_storage or the downloaded zip file. ServerError: If an internal server error is hit while downloading the needed file. CloudStorageError: If another error occured while downloading the remote path. FileNotFoundError: If the download was otherwise unsuccessful. """ if not self._has_minimum_data: return None download_dir = os.path.dirname(self._download_path) if not os.path.exists(download_dir): os.makedirs(download_dir) dependency_path = self._download_path cloud_storage.GetIfHashChanged( self._cs_remote_path, self._download_path, self._cs_bucket, self._cs_hash) if not os.path.exists(dependency_path): raise exceptions.FileNotFoundError(dependency_path) logging.error('has archive_info %s', self._archive_info) if self.has_archive_info: dependency_path = self._archive_info.GetUnzippedPath() else: mode = os.stat(dependency_path).st_mode os.chmod(dependency_path, mode | stat.S_IXUSR) return os.path.abspath(dependency_path) @property def version_in_cs(self): return self._version_in_cs @property def _has_minimum_data(self): return all([self._cs_bucket, self._cs_remote_path, self._download_path, self._cs_hash]) @property def has_archive_info(self): return bool(self._archive_info) def __repr__(self): return ( 'CloudStorageInfo(download_path=%s, cs_remote_path=%s, cs_bucket=%s, ' 'cs_hash=%s, version_in_cs=%s, archive_info=%s)' % ( self._download_path, self._cs_remote_path, self._cs_bucket, self._cs_hash, self._version_in_cs, self._archive_info))
bsd-3-clause
tedelhourani/ansible
lib/ansible/modules/cloud/amazon/efs.py
10
21018
#!/usr/bin/python # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified'} DOCUMENTATION = ''' --- module: efs short_description: create and maintain EFS file systems description: - Module allows create, search and destroy Amazon EFS file systems version_added: "2.2" requirements: [ boto3 ] author: - "Ryan Sydnor (@ryansydnor)" - "Artem Kazakov (@akazakov)" options: state: description: - Allows to create, search and destroy Amazon EFS file system required: false default: 'present' choices: ['present', 'absent'] name: description: - Creation Token of Amazon EFS file system. Required for create. Either name or ID required for delete. required: false default: None id: description: - ID of Amazon EFS. Either name or ID required for delete. required: false default: None performance_mode: description: - File system's performance mode to use. Only takes effect during creation. required: false default: 'general_purpose' choices: ['general_purpose', 'max_io'] tags: description: - "List of tags of Amazon EFS. Should be defined as dictionary In case of 'present' state with list of tags and existing EFS (matched by 'name'), tags of EFS will be replaced with provided data." required: false default: None targets: description: - "List of mounted targets. It should be a list of dictionaries, every dictionary should include next attributes: - subnet_id - Mandatory. The ID of the subnet to add the mount target in. - ip_address - Optional. A valid IPv4 address within the address range of the specified subnet. - security_groups - Optional. List of security group IDs, of the form 'sg-xxxxxxxx'. These must be for the same VPC as subnet specified This data may be modified for existing EFS using state 'present' and new list of mount targets." required: false default: None wait: description: - "In case of 'present' state should wait for EFS 'available' life cycle state (of course, if current state not 'deleting' or 'deleted') In case of 'absent' state should wait for EFS 'deleted' life cycle state" required: false default: "no" choices: ["yes", "no"] wait_timeout: description: - How long the module should wait (in seconds) for desired state before returning. Zero means wait as long as necessary. required: false default: 0 extends_documentation_fragment: - aws ''' EXAMPLES = ''' # EFS provisioning - efs: state: present name: myTestEFS tags: name: myTestNameTag purpose: file-storage targets: - subnet_id: subnet-748c5d03 security_groups: [ "sg-1a2b3c4d" ] # Modifying EFS data - efs: state: present name: myTestEFS tags: name: myAnotherTestTag targets: - subnet_id: subnet-7654fdca security_groups: [ "sg-4c5d6f7a" ] # Deleting EFS - efs: state: absent name: myTestEFS ''' RETURN = ''' creation_time: description: timestamp of creation date returned: always type: string sample: "2015-11-16 07:30:57-05:00" creation_token: description: EFS creation token returned: always type: string sample: "console-88609e04-9a0e-4a2e-912c-feaa99509961" file_system_id: description: ID of the file system returned: always type: string sample: "fs-xxxxxxxx" life_cycle_state: description: state of the EFS file system returned: always type: string sample: "creating, available, deleting, deleted" mount_point: description: url of file system returned: always type: string sample: ".fs-xxxxxxxx.efs.us-west-2.amazonaws.com:/" mount_targets: description: list of mount targets returned: always type: list sample: [ { "file_system_id": "fs-a7ad440e", "ip_address": "172.31.17.173", "life_cycle_state": "available", "mount_target_id": "fsmt-d8907871", "network_interface_id": "eni-6e387e26", "owner_id": "740748460359", "security_groups": [ "sg-a30b22c6" ], "subnet_id": "subnet-e265c895" }, ... ] name: description: name of the file system returned: always type: string sample: "my-efs" number_of_mount_targets: description: the number of targets mounted returned: always type: int sample: 3 owner_id: description: AWS account ID of EFS owner returned: always type: string sample: "XXXXXXXXXXXX" size_in_bytes: description: size of the file system in bytes as of a timestamp returned: always type: dict sample: { "timestamp": "2015-12-21 13:59:59-05:00", "value": 12288 } performance_mode: description: performance mode of the file system returned: always type: string sample: "generalPurpose" tags: description: tags on the efs instance returned: always type: dict sample: { "name": "my-efs", "key": "Value" } ''' from time import sleep from time import time as timestamp try: from botocore.exceptions import ClientError except ImportError as e: pass # Taken care of by ec2.HAS_BOTO3 from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import (HAS_BOTO3, boto3_conn, camel_dict_to_snake_dict, ec2_argument_spec, get_aws_connection_info) def _index_by_key(key, items): return dict((item[key], item) for item in items) class EFSConnection(object): DEFAULT_WAIT_TIMEOUT_SECONDS = 0 STATE_CREATING = 'creating' STATE_AVAILABLE = 'available' STATE_DELETING = 'deleting' STATE_DELETED = 'deleted' def __init__(self, module, region, **aws_connect_params): try: self.connection = boto3_conn(module, conn_type='client', resource='efs', region=region, **aws_connect_params) except Exception as e: module.fail_json(msg="Failed to connect to AWS: %s" % str(e)) self.region = region self.wait = module.params.get('wait') self.wait_timeout = module.params.get('wait_timeout') def get_file_systems(self, **kwargs): """ Returns generator of file systems including all attributes of FS """ items = iterate_all( 'FileSystems', self.connection.describe_file_systems, **kwargs ) for item in items: item['Name'] = item['CreationToken'] item['CreationTime'] = str(item['CreationTime']) """ Suffix of network path to be used as NFS device for mount. More detail here: http://docs.aws.amazon.com/efs/latest/ug/gs-step-three-connect-to-ec2-instance.html """ item['MountPoint'] = '.%s.efs.%s.amazonaws.com:/' % (item['FileSystemId'], self.region) if 'Timestamp' in item['SizeInBytes']: item['SizeInBytes']['Timestamp'] = str(item['SizeInBytes']['Timestamp']) if item['LifeCycleState'] == self.STATE_AVAILABLE: item['Tags'] = self.get_tags(FileSystemId=item['FileSystemId']) item['MountTargets'] = list(self.get_mount_targets(FileSystemId=item['FileSystemId'])) else: item['Tags'] = {} item['MountTargets'] = [] yield item def get_tags(self, **kwargs): """ Returns tag list for selected instance of EFS """ tags = iterate_all( 'Tags', self.connection.describe_tags, **kwargs ) return dict((tag['Key'], tag['Value']) for tag in tags) def get_mount_targets(self, **kwargs): """ Returns mount targets for selected instance of EFS """ targets = iterate_all( 'MountTargets', self.connection.describe_mount_targets, **kwargs ) for target in targets: if target['LifeCycleState'] == self.STATE_AVAILABLE: target['SecurityGroups'] = list(self.get_security_groups( MountTargetId=target['MountTargetId'] )) else: target['SecurityGroups'] = [] yield target def get_security_groups(self, **kwargs): """ Returns security groups for selected instance of EFS """ return iterate_all( 'SecurityGroups', self.connection.describe_mount_target_security_groups, **kwargs ) def get_file_system_id(self, name): """ Returns ID of instance by instance name """ info = first_or_default(iterate_all( 'FileSystems', self.connection.describe_file_systems, CreationToken=name )) return info and info['FileSystemId'] or None def get_file_system_state(self, name, file_system_id=None): """ Returns state of filesystem by EFS id/name """ info = first_or_default(iterate_all( 'FileSystems', self.connection.describe_file_systems, CreationToken=name, FileSystemId=file_system_id )) return info and info['LifeCycleState'] or self.STATE_DELETED def get_mount_targets_in_state(self, file_system_id, states=None): """ Returns states of mount targets of selected EFS with selected state(s) (optional) """ targets = iterate_all( 'MountTargets', self.connection.describe_mount_targets, FileSystemId=file_system_id ) if states: if not isinstance(states, list): states = [states] targets = filter(lambda target: target['LifeCycleState'] in states, targets) return list(targets) def create_file_system(self, name, performance_mode): """ Creates new filesystem with selected name """ changed = False state = self.get_file_system_state(name) if state in [self.STATE_DELETING, self.STATE_DELETED]: wait_for( lambda: self.get_file_system_state(name), self.STATE_DELETED ) self.connection.create_file_system(CreationToken=name, PerformanceMode=performance_mode) changed = True # we always wait for the state to be available when creating. # if we try to take any actions on the file system before it's available # we'll throw errors wait_for( lambda: self.get_file_system_state(name), self.STATE_AVAILABLE, self.wait_timeout ) return changed def converge_file_system(self, name, tags, targets): """ Change attributes (mount targets and tags) of filesystem by name """ result = False fs_id = self.get_file_system_id(name) if tags is not None: tags_to_create, _, tags_to_delete = dict_diff(self.get_tags(FileSystemId=fs_id), tags) if tags_to_delete: self.connection.delete_tags( FileSystemId=fs_id, TagKeys=[item[0] for item in tags_to_delete] ) result = True if tags_to_create: self.connection.create_tags( FileSystemId=fs_id, Tags=[{'Key': item[0], 'Value': item[1]} for item in tags_to_create] ) result = True if targets is not None: incomplete_states = [self.STATE_CREATING, self.STATE_DELETING] wait_for( lambda: len(self.get_mount_targets_in_state(fs_id, incomplete_states)), 0 ) current_targets = _index_by_key('SubnetId', self.get_mount_targets(FileSystemId=fs_id)) targets = _index_by_key('SubnetId', targets) targets_to_create, intersection, targets_to_delete = dict_diff(current_targets, targets, True) # To modify mount target it should be deleted and created again changed = [sid for sid in intersection if not targets_equal(['SubnetId', 'IpAddress', 'NetworkInterfaceId'], current_targets[sid], targets[sid])] targets_to_delete = list(targets_to_delete) + changed targets_to_create = list(targets_to_create) + changed if targets_to_delete: for sid in targets_to_delete: self.connection.delete_mount_target( MountTargetId=current_targets[sid]['MountTargetId'] ) wait_for( lambda: len(self.get_mount_targets_in_state(fs_id, incomplete_states)), 0 ) result = True if targets_to_create: for sid in targets_to_create: self.connection.create_mount_target( FileSystemId=fs_id, **targets[sid] ) wait_for( lambda: len(self.get_mount_targets_in_state(fs_id, incomplete_states)), 0, self.wait_timeout ) result = True # If no security groups were passed into the module, then do not change it. security_groups_to_update = [sid for sid in intersection if 'SecurityGroups' in targets[sid] and current_targets[sid]['SecurityGroups'] != targets[sid]['SecurityGroups']] if security_groups_to_update: for sid in security_groups_to_update: self.connection.modify_mount_target_security_groups( MountTargetId=current_targets[sid]['MountTargetId'], SecurityGroups=targets[sid].get('SecurityGroups', None) ) result = True return result def delete_file_system(self, name, file_system_id=None): """ Removes EFS instance by id/name """ result = False state = self.get_file_system_state(name, file_system_id) if state in [self.STATE_CREATING, self.STATE_AVAILABLE]: wait_for( lambda: self.get_file_system_state(name), self.STATE_AVAILABLE ) if not file_system_id: file_system_id = self.get_file_system_id(name) self.delete_mount_targets(file_system_id) self.connection.delete_file_system(FileSystemId=file_system_id) result = True if self.wait: wait_for( lambda: self.get_file_system_state(name), self.STATE_DELETED, self.wait_timeout ) return result def delete_mount_targets(self, file_system_id): """ Removes mount targets by EFS id """ wait_for( lambda: len(self.get_mount_targets_in_state(file_system_id, self.STATE_CREATING)), 0 ) targets = self.get_mount_targets_in_state(file_system_id, self.STATE_AVAILABLE) for target in targets: self.connection.delete_mount_target(MountTargetId=target['MountTargetId']) wait_for( lambda: len(self.get_mount_targets_in_state(file_system_id, self.STATE_DELETING)), 0 ) return len(targets) > 0 def iterate_all(attr, map_method, **kwargs): """ Method creates iterator from boto result set """ args = dict((key, value) for (key, value) in kwargs.items() if value is not None) wait = 1 while True: try: data = map_method(**args) for elm in data[attr]: yield elm if 'NextMarker' in data: args['Marker'] = data['Nextmarker'] continue break except ClientError as e: if e.response['Error']['Code'] == "ThrottlingException" and wait < 600: sleep(wait) wait = wait * 2 continue else: raise def targets_equal(keys, a, b): """ Method compare two mount targets by specified attributes """ for key in keys: if key in b and a[key] != b[key]: return False return True def dict_diff(dict1, dict2, by_key=False): """ Helper method to calculate difference of two dictionaries """ keys1 = set(dict1.keys() if by_key else dict1.items()) keys2 = set(dict2.keys() if by_key else dict2.items()) intersection = keys1 & keys2 return keys2 ^ intersection, intersection, keys1 ^ intersection def first_or_default(items, default=None): """ Helper method to fetch first element of list (if exists) """ for item in items: return item return default def wait_for(callback, value, timeout=EFSConnection.DEFAULT_WAIT_TIMEOUT_SECONDS): """ Helper method to wait for desired value returned by callback method """ wait_start = timestamp() while True: if callback() != value: if timeout != 0 and (timestamp() - wait_start > timeout): raise RuntimeError('Wait timeout exceeded (' + str(timeout) + ' sec)') else: sleep(5) continue break def main(): """ Module action handler """ argument_spec = ec2_argument_spec() argument_spec.update(dict( state=dict(required=False, type='str', choices=["present", "absent"], default="present"), id=dict(required=False, type='str', default=None), name=dict(required=False, type='str', default=None), tags=dict(required=False, type="dict", default={}), targets=dict(required=False, type="list", default=[]), performance_mode=dict(required=False, type='str', choices=["general_purpose", "max_io"], default="general_purpose"), wait=dict(required=False, type="bool", default=False), wait_timeout=dict(required=False, type="int", default=0) )) module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') region, _, aws_connect_params = get_aws_connection_info(module, boto3=True) connection = EFSConnection(module, region, **aws_connect_params) name = module.params.get('name') fs_id = module.params.get('id') tags = module.params.get('tags') target_translations = { 'ip_address': 'IpAddress', 'security_groups': 'SecurityGroups', 'subnet_id': 'SubnetId' } targets = [dict((target_translations[key], value) for (key, value) in x.items()) for x in module.params.get('targets')] performance_mode_translations = { 'general_purpose': 'generalPurpose', 'max_io': 'maxIO' } performance_mode = performance_mode_translations[module.params.get('performance_mode')] changed = False state = str(module.params.get('state')).lower() if state == 'present': if not name: module.fail_json(msg='Name parameter is required for create') changed = connection.create_file_system(name, performance_mode) changed = connection.converge_file_system(name=name, tags=tags, targets=targets) or changed result = first_or_default(connection.get_file_systems(CreationToken=name)) elif state == 'absent': if not name and not fs_id: module.fail_json(msg='Either name or id parameter is required for delete') changed = connection.delete_file_system(name, fs_id) result = None if result: result = camel_dict_to_snake_dict(result) module.exit_json(changed=changed, efs=result) if __name__ == '__main__': main()
gpl-3.0
smallyear/linuxLearn
salt/salt/states/reg.py
1
13518
# -*- coding: utf-8 -*- r''' =========================== Manage the Windows registry =========================== Many python developers think of registry keys as if they were python keys in a dictionary which is not the case. The windows registry is broken down into the following components: ----- Hives ----- This is the top level of the registry. They all begin with HKEY. - HKEY_CLASSES_ROOT (HKCR) - HKEY_CURRENT_USER(HKCU) - HKEY_LOCAL MACHINE (HKLM) - HKEY_USER (HKU) - HKEY_CURRENT_CONFIG ---- Keys ---- Hives contain keys. These are basically the folders beneath the hives. They can contain any number of subkeys. ----------------- Values or Entries ----------------- Values or Entries are the name/data pairs beneath the keys and subkeys. All keys have a default name/data pair. It is usually "(Default)"="(value not set)". The actual value for the name and the date is Null. The registry editor will display "(Default)" and "(value not set)". ------- Example ------- The following example is taken from the windows startup portion of the registry: ``` [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run] "RTHDVCPL"="\"C:\\Program Files\\Realtek\\Audio\\HDA\\RtkNGUI64.exe\" -s" "NvBackend"="\"C:\\Program Files (x86)\\NVIDIA Corporation\\Update Core\\NvBackend.exe\"" "BTMTrayAgent"="rundll32.exe \"C:\\Program Files (x86)\\Intel\\Bluetooth\\btmshellex.dll\",TrayApp" ``` In this example these are the values for each: Hive: `HKEY_LOCAL_MACHINE` Key and subkeys: `SOFTWARE\Microsoft\Windows\CurrentVersion\Run` Value: - There are 3 value names: `RTHDVCPL`, `NvBackend`, and `BTMTrayAgent` - Each value name has a corresponding value ''' from __future__ import absolute_import # Import python libs import logging # Import salt libs import salt.utils log = logging.getLogger(__name__) def __virtual__(): ''' Load this state if the reg module exists ''' return 'reg' if 'reg.read_key' in __salt__ else False def _parse_key_value(key): ''' split the full path in the registry to the key and the rest ''' splt = key.split("\\") hive = splt.pop(0) vname = splt.pop(-1) key = '\\'.join(splt) return hive, key, vname def _parse_key(key): ''' split the hive from the key ''' splt = key.split("\\") hive = splt.pop(0) key = '\\'.join(splt) return hive, key def present(name, value=None, vname=None, vdata=None, vtype='REG_SZ', reflection=True, use_32bit_registry=False): ''' Ensure a registry key or value is present. :param str name: A string value representing the full path of the key to include the HIVE, Key, and all Subkeys. For example: ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` Valid hive values include: - HKEY_CURRENT_USER or HKCU - HKEY_LOCAL_MACHINE or HKLM - HKEY_USERS or HKU :param str value: Deprecated. Use vname and vdata instead. Included here for backwards compatibility. :param str vname: The name of the value you'd like to create beneath the Key. If this parameter is not passed it will assume you want to set the (Default) value :param str vdata: The value you'd like to set for the Key. If a value name (vname) is passed, this will be the data for that value name. If not, this will be the (Default) value for the key. The type for the (Default) value is always REG_SZ and cannot be changed. This parameter is optional. If not passed, the Key will be created with no associated item/value pairs. :param str vtype: The value type for the data you wish to store in the registry. Valid values are: - REG_BINARY - REG_DWORD - REG_EXPAND_SZ - REG_MULTI_SZ - REG_SZ (Default) :param bool reflection: On 64 bit machines a duplicate value will be created in the ``Wow6432Node`` for 32bit programs. This only applies to the SOFTWARE key. This option is ignored on 32bit operating systems. This value defaults to True. Set it to False to disable reflection. .. deprecated:: 2015.8.2 Use `use_32bit_registry` instead. The parameter seems to have no effect since Windows 7 / Windows 2008R2 removed support for reflection. The parameter will be removed in Boron. :param bool use_32bit_registry: Use the 32bit portion of the registry. Applies only to 64bit windows. 32bit Windows will ignore this parameter. Default if False. :return: Returns a dictionary showing the results of the registry operation. :rtype: dict The following example will set the ``(Default)`` value for the ``SOFTWARE\\Salt`` key in the ``HKEY_CURRENT_USER`` hive to ``0.15.3``. The value will not be reflected in ``Wow6432Node``: Example: .. code-block:: yaml HKEY_CURRENT_USER\\SOFTWARE\\Salt: reg.present: - vdata: 0.15.3 - reflection: False The following example will set the value for the ``version`` entry under the ``SOFTWARE\\Salt`` key in the ``HKEY_CURRENT_USER`` hive to ``0.15.3``. The value will be reflected in ``Wow6432Node``: Example: .. code-block:: yaml HKEY_CURRENT_USER\\SOFTWARE\\Salt: reg.present: - vname: version - vdata: 0.15.3 In the above example the path is interpreted as follows: - ``HKEY_CURRENT_USER`` is the hive - ``SOFTWARE\\Salt`` is the key - ``vname`` is the value name ('version') that will be created under the key - ``vdata`` is the data that will be assigned to 'version' ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} # This is for backwards compatibility # If 'value' is passed a value, vdata becomes value and the vname is # obtained from the key path if value or value in [0, '']: hive, key, vname = _parse_key_value(name) vdata = value ret['comment'] = 'State file is using deprecated syntax. Please update.' salt.utils.warn_until( 'Boron', 'The \'value\' argument has been deprecated. ' 'Please use vdata instead.' ) else: hive, key = _parse_key(name) # Determine what to do reg_current = __salt__['reg.read_value'](hive=hive, key=key, vname=vname, use_32bit_registry=use_32bit_registry) if vdata == reg_current['vdata'] and reg_current['success']: ret['comment'] = '{0} in {1} is already configured'.\ format(vname if vname else '(Default)', name) return ret add_change = {'Key': r'{0}\{1}'.format(hive, key), 'Entry': '{0}'.format(vname if vname else '(Default)'), 'Value': '{0}'.format(vdata)} # Check for test option if __opts__['test']: ret['result'] = None ret['changes'] = {'reg': {'Will add': add_change}} return ret # Configure the value ret['result'] = __salt__['reg.set_value'](hive=hive, key=key, vname=vname, vdata=vdata, vtype=vtype, use_32bit_registry=use_32bit_registry) if not ret['result']: ret['changes'] = {} ret['comment'] = r'Failed to add {0} to {1}\{2}'.format(name, hive, key) else: ret['changes'] = {'reg': {'Added': add_change}} ret['comment'] = r'Added {0} to {1}\{2}'.format(name, hive, key) return ret def absent(name, vname=None, use_32bit_registry=False): ''' Ensure a registry value is removed. To remove a key use key_absent. :param str name: A string value representing the full path of the key to include the HIVE, Key, and all Subkeys. For example: ``HKEY_LOCAL_MACHINE\\SOFTWARE\\Salt`` Valid hive values include: - HKEY_CURRENT_USER or HKCU - HKEY_LOCAL_MACHINE or HKLM - HKEY_USERS or HKU :param str vname: The name of the value you'd like to create beneath the Key. If this parameter is not passed it will assume you want to set the (Default) value :param bool use_32bit_registry: Use the 32bit portion of the registry. Applies only to 64bit windows. 32bit Windows will ignore this parameter. Default if False. :return: Returns a dictionary showing the results of the registry operation. :rtype: dict CLI Example: .. code-block:: yaml 'HKEY_CURRENT_USER\\SOFTWARE\\Salt\\version': reg.absent In the above example the path is interpreted as follows: - ``HKEY_CURRENT_USER`` is the hive - ``SOFTWARE\\Salt`` is the key - ``version`` is the value name So the value ``version`` will be deleted from the ``SOFTWARE\\Salt`` key in the ``HKEY_CURRENT_USER`` hive. ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} hive, key = _parse_key(name) # Determine what to do reg_check = __salt__['reg.read_value'](hive=hive, key=key, vname=vname, use_32bit_registry=use_32bit_registry) if not reg_check['success'] or reg_check['vdata'] == '(value not set)': if not vname: hive, key, vname = _parse_key_value(name) reg_check = __salt__['reg.read_value'](hive=hive, key=key, vname=vname, use_32bit_registry=use_32bit_registry) if not reg_check['success'] or reg_check['vdata'] == '(value not set)': ret['comment'] = '{0} is already absent'.format(name) return ret else: ret['comment'] = '{0} is already absent'.format(name) return ret remove_change = {'Key': r'{0}\{1}'.format(hive, key), 'Entry': '{0}'.format(vname if vname else '(Default)')} # Check for test option if __opts__['test']: ret['result'] = None ret['changes'] = {'reg': {'Will remove': remove_change}} return ret # Delete the value ret['result'] = __salt__['reg.delete_value'](hive=hive, key=key, vname=vname, use_32bit_registry=use_32bit_registry) if not ret['result']: ret['changes'] = {} ret['comment'] = r'Failed to remove {0} from {1}'.format(key, hive) else: ret['changes'] = {'reg': {'Removed': remove_change}} ret['comment'] = r'Removed {0} from {1}'.format(key, hive) return ret def key_absent(name, force=False, use_32bit_registry=False): r''' .. versionadded:: 2015.5.4 Ensure a registry key is removed. This will remove a key and all value entries it contains. It will fail if the key contains subkeys. :param str name: A string representing the full path to the key to be removed to include the hive and the keypath. The hive can be any of the following: - HKEY_LOCAL_MACHINE or HKLM - HKEY_CURRENT_USER or HKCU - HKEY_USER or HKU :param bool force: A boolean value indicating that all subkeys should be deleted with the key. If force=False and subkeys exists beneath the key you want to delete, key_absent will fail. Use with caution. The default is False. :return: Returns a dictionary showing the results of the registry operation. :rtype: dict The following example will delete the ``SOFTWARE\Salt`` key and all subkeys under the ``HKEY_CURRENT_USER`` hive. Example: .. code-block:: yaml 'HKEY_CURRENT_USER\SOFTWARE\Salt': reg.key_absent: - force: True In the above example the path is interpreted as follows: - ``HKEY_CURRENT_USER`` is the hive - ``SOFTWARE\Salt`` is the key ''' ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''} hive, key = _parse_key(name) # Determine what to do if not __salt__['reg.read_value'](hive=hive, key=key, use_32bit_registry=use_32bit_registry)['success']: ret['comment'] = '{0} is already absent'.format(name) return ret ret['changes'] = {'reg': { 'Removed': { 'Key': r'{0}\{1}'.format(hive, key) }}} # Check for test option if __opts__['test']: ret['result'] = None return ret # Delete the value __salt__['reg.delete_key_recursive'](hive=hive, key=key, use_32bit_registry=use_32bit_registry) if __salt__['reg.read_value'](hive=hive, key=key, use_32bit_registry=use_32bit_registry)['success']: ret['result'] = False ret['changes'] = {} ret['comment'] = 'Failed to remove registry key {0}'.format(name) return ret
apache-2.0
Naakh/naakh-py
naakh/api_client.py
1
20321
# coding: utf-8 """ Copyright 2016 SmartBear Software 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. ref: https://github.com/swagger-api/swagger-codegen """ from __future__ import absolute_import from . import models from .rest import RESTClientObject from .rest import ApiException import os import re import sys import urllib import json import mimetypes import random import tempfile import threading from datetime import datetime from datetime import date # python 2 and python 3 compatibility library from six import iteritems try: # for python3 from urllib.parse import quote except ImportError: # for python2 from urllib import quote from .configuration import Configuration class ApiClient(object): """ Generic API client for Swagger client library builds. Swagger generic API client. This client handles the client- server communication, and is invariant across implementations. Specifics of the methods and models for each application are generated from the Swagger templates. NOTE: This class is auto generated by the swagger code generator program. Ref: https://github.com/swagger-api/swagger-codegen Do not edit the class manually. :param host: The base path for the server to call. :param header_name: a header to pass when making calls to the API. :param header_value: a header value to pass when making calls to the API. """ def __init__(self, host=None, header_name=None, header_value=None, cookie=None): """ Constructor of the class. """ self.rest_client = RESTClientObject() self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value if host is None: self.host = Configuration().host else: self.host = host self.cookie = cookie # Set default User-Agent. self.user_agent = 'Python-Swagger/0.0.3' @property def user_agent(self): """ Gets user agent. """ return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): """ Sets user agent. """ self.default_headers['User-Agent'] = value def set_default_header(self, header_name, header_value): self.default_headers[header_name] = header_value def __call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None): # headers parameters header_params = header_params or {} header_params.update(self.default_headers) if self.cookie: header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) for k, v in iteritems(path_params): replacement = quote(str(self.to_path_value(v))) resource_path = resource_path.\ replace('{' + k + '}', replacement) # query parameters if query_params: query_params = self.sanitize_for_serialization(query_params) query_params = {k: self.to_path_value(v) for k, v in iteritems(query_params)} # post parameters if post_params or files: post_params = self.prepare_post_parameters(post_params, files) post_params = self.sanitize_for_serialization(post_params) # auth setting self.update_params_for_auth(header_params, query_params, auth_settings) # body if body: body = self.sanitize_for_serialization(body) # request url url = self.host + resource_path # perform request and return response response_data = self.request(method, url, query_params=query_params, headers=header_params, post_params=post_params, body=body) self.last_response = response_data # deserialize response data if response_type: deserialized_data = self.deserialize(response_data, response_type) else: deserialized_data = None if callback: callback(deserialized_data) else: return deserialized_data def to_path_value(self, obj): """ Takes value and turn it into a string suitable for inclusion in the path, by url-encoding. :param obj: object or string value. :return string: quoted value. """ if type(obj) == list: return ','.join(obj) else: return str(obj) def sanitize_for_serialization(self, obj): """ Builds a JSON POST object. If obj is None, return None. If obj is str, int, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, sanitize each element in the list. If obj is dict, return the dict. If obj is swagger model, return the properties dict. :param obj: The data to serialize. :return: The serialized form of data. """ types = (str, int, float, bool, tuple) if sys.version_info < (3,0): types = types + (unicode,) if isinstance(obj, type(None)): return None elif isinstance(obj, types): return obj elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj] elif isinstance(obj, (datetime, date)): return obj.isoformat() else: if isinstance(obj, dict): obj_dict = obj else: # Convert model obj to dict except # attributes `swagger_types`, `attribute_map` # and attributes which value is not None. # Convert attribute name to json key in # model definition for request. obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) for attr, _ in iteritems(obj.swagger_types) if getattr(obj, attr) is not None} return {key: self.sanitize_for_serialization(val) for key, val in iteritems(obj_dict)} def deserialize(self, response, response_type): """ Deserializes response into an object. :param response: RESTResponse object to be deserialized. :param response_type: class literal for deserialzied object, or string of class name. :return: deserialized object. """ # handle file downloading # save response body into a tmp file and return the instance if "file" == response_type: return self.__deserialize_file(response) # fetch data from response object try: data = json.loads(response.data) except ValueError: data = response.data return self.__deserialize(data, response_type) def __deserialize(self, data, klass): """ Deserializes dict, list, str into an object. :param data: dict, list or str. :param klass: class literal, or string of class name. :return: object. """ if data is None: return None if type(klass) == str: if klass.startswith('list['): sub_kls = re.match('list\[(.*)\]', klass).group(1) return [self.__deserialize(sub_data, sub_kls) for sub_data in data] if klass.startswith('dict('): sub_kls = re.match('dict\(([^,]*), (.*)\)', klass).group(2) return {k: self.__deserialize(v, sub_kls) for k, v in iteritems(data)} # convert str to class # for native types if klass in ['int', 'float', 'str', 'bool', "date", 'datetime', "object"]: klass = eval(klass) # for model types else: klass = eval('models.' + klass) if klass in [int, float, str, bool]: return self.__deserialize_primitive(data, klass) elif klass == object: return self.__deserialize_object(data) elif klass == date: return self.__deserialize_date(data) elif klass == datetime: return self.__deserialize_datatime(data) else: return self.__deserialize_model(data, klass) def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, body=None, post_params=None, files=None, response_type=None, auth_settings=None, callback=None): """ Makes the HTTP request (synchronous) and return the deserialized data. To make an async request, define a function for callback. :param resource_path: Path to method endpoint. :param method: Method to call. :param path_params: Path parameters in the url. :param query_params: Query parameters in the url. :param header_params: Header parameters to be placed in the request header. :param body: Request body. :param post_params dict: Request post form parameters, for `application/x-www-form-urlencoded`, `multipart/form-data`. :param auth_settings list: Auth Settings names for the request. :param response: Response data type. :param files dict: key -> filename, value -> filepath, for `multipart/form-data`. :param callback function: Callback function for asynchronous request. If provide this parameter, the request will be called asynchronously. :return: If provide parameter callback, the request will be called asynchronously. The method will return the request thread. If parameter callback is None, then the method will return the response directly. """ if callback is None: return self.__call_api(resource_path, method, path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, callback) else: thread = threading.Thread(target=self.__call_api, args=(resource_path, method, path_params, query_params, header_params, body, post_params, files, response_type, auth_settings, callback)) thread.start() return thread def request(self, method, url, query_params=None, headers=None, post_params=None, body=None): """ Makes the HTTP request using RESTClient. """ if method == "GET": return self.rest_client.GET(url, query_params=query_params, headers=headers) elif method == "HEAD": return self.rest_client.HEAD(url, query_params=query_params, headers=headers) elif method == "OPTIONS": return self.rest_client.OPTIONS(url, query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "POST": return self.rest_client.POST(url, query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "PUT": return self.rest_client.PUT(url, query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "PATCH": return self.rest_client.PATCH(url, query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "DELETE": return self.rest_client.DELETE(url, query_params=query_params, headers=headers) else: raise ValueError( "http method must be `GET`, `HEAD`," " `POST`, `PATCH`, `PUT` or `DELETE`." ) def prepare_post_parameters(self, post_params=None, files=None): """ Builds form parameters. :param post_params: Normal form parameters. :param files: File parameters. :return: Form parameters with files. """ params = {} if post_params: params.update(post_params) if files: for k, v in iteritems(files): if not v: continue with open(v, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() mimetype = mimetypes.\ guess_type(filename)[0] or 'application/octet-stream' params[k] = tuple([filename, filedata, mimetype]) return params def select_header_accept(self, accepts): """ Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). """ if not accepts: return accepts = list(map(lambda x: x.lower(), accepts)) if 'application/json' in accepts: return 'application/json' else: return ', '.join(accepts) def select_header_content_type(self, content_types): """ Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. :return: Content-Type (e.g. application/json). """ if not content_types: return 'application/json' content_types = list(map(lambda x: x.lower(), content_types)) if 'application/json' in content_types: return 'application/json' else: return content_types[0] def update_params_for_auth(self, headers, querys, auth_settings): """ Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. :param querys: Query parameters dict to be updated. :param auth_settings: Authentication setting identifiers list. """ config = Configuration() if not auth_settings: return for auth in auth_settings: auth_setting = config.auth_settings().get(auth) if auth_setting: if not auth_setting['value']: continue elif auth_setting['in'] == 'header': headers[auth_setting['key']] = auth_setting['value'] elif auth_setting['in'] == 'query': querys[auth_setting['key']] = auth_setting['value'] else: raise ValueError( 'Authentication token must be in `query` or `header`' ) def __deserialize_file(self, response): """ Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. :param response: RESTResponse. :return: file path. """ config = Configuration() fd, path = tempfile.mkstemp(dir=config.temp_folder_path) os.close(fd) os.remove(path) content_disposition = response.getheader("Content-Disposition") if content_disposition: filename = re.\ search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition).\ group(1) path = os.path.join(os.path.dirname(path), filename) with open(path, "w") as f: f.write(response.data) return path def __deserialize_primitive(self, data, klass): """ Deserializes string to primitive type. :param data: str. :param klass: class literal. :return: int, float, str, bool. """ try: value = klass(data) except UnicodeEncodeError: value = unicode(data) except TypeError: value = data return value def __deserialize_object(self, value): """ Return a original value. :return: object. """ return value def __deserialize_date(self, string): """ Deserializes string to date. :param string: str. :return: date. """ try: from dateutil.parser import parse return parse(string).date() except ImportError: return string except ValueError: raise ApiException( status=0, reason="Failed to parse `{0}` into a date object" .format(string) ) def __deserialize_datatime(self, string): """ Deserializes string to datetime. The string should be in iso8601 datetime format. :param string: str. :return: datetime. """ try: from dateutil.parser import parse return parse(string) except ImportError: return string except ValueError: raise ApiException( status=0, reason="Failed to parse `{0}` into a datetime object". format(string) ) def __deserialize_model(self, data, klass): """ Deserializes list or dict to model. :param data: dict, list. :param klass: class literal. :return: model object. """ instance = klass() for attr, attr_type in iteritems(instance.swagger_types): if data is not None \ and instance.attribute_map[attr] in data\ and isinstance(data, (list, dict)): value = data[instance.attribute_map[attr]] if attr_type == 'Metadata': # Small hack. Because the generated code does not handle # the metadata object well setattr(instance, attr, value) else: setattr(instance, attr, self.__deserialize(value, attr_type)) return instance
mit
Dangetsu/vnr
Frameworks/Sakura/py/apps/browser/curtheme.py
2
1237
# coding: utf8 # curtheme.py # 10/6/2012 jichi #_PYTHON_PATH = os.path.dirname(sys.executable) #_CURSOR_PATH = os.path.abspath(_PYTHON_PATH + "/../Sakura/res/cursors") #def beep(): # print '\a' # #from Qt5.QtWidgets import QApplication # #QApplication.beep() # Mouse theme from sakurakit import skos if skos.WIN: from sakurakit.skdebug import dprint OS_CURSORS = {} # {IDC:HCURSOR} import atexit import win32api, win32con from sakurakit import skwinapi def load(): import config for idc_name, curfile in config.CURSOR_LOCATIONS.iteritems(): idc = getattr(win32con, idc_name) assert idc, "invalid idc name" OS_CURSORS[idc] = skwinapi.CopyCursor( win32api.LoadCursor(0, idc)) hcur = skwinapi.LoadCursorFromFileW(curfile) if hcur: skwinapi.SetSystemCursor(hcur, idc) dprint("pass") def unload(): if OS_CURSORS: for idc, hcur in OS_CURSORS.iteritems(): skwinapi.SetSystemCursor(hcur, idc) OS_CURSORS.clear() dprint("pass") #import atexit #atexit.register(unload) from PySide.QtCore import QCoreApplication QCoreApplication.instance().aboutToQuit.connect(unload) else: def load(): pass def unload(): pass # EOF
gpl-3.0
zimmerle/gnuradio
gr-uhd/examples/python/usrp_wfm_rcv2_nogui.py
9
6103
#!/usr/bin/env python # # Copyright 2005-2007,2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # # GNU Radio 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 GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # from gnuradio import gr, optfir, audio, blks2, uhd from gnuradio.eng_option import eng_option from optparse import OptionParser import sys import math class wfm_rx_block (gr.top_block): def __init__(self): gr.top_block.__init__(self) parser=OptionParser(option_class=eng_option) parser.add_option("-a", "--args", type="string", default="", help="UHD device address args [default=%default]") parser.add_option("", "--spec", type="string", default="A:0 A:0", help="Subdevice of UHD device where appropriate") parser.add_option("-A", "--antenna", type="string", default=None, help="select Rx Antenna where appropriate") parser.add_option("", "--f1", type="eng_float", default=100.7e6, help="set 1st station frequency to FREQ", metavar="FREQ") parser.add_option("", "--f2", type="eng_float", default=102.5e6, help="set 2nd station freq to FREQ", metavar="FREQ") parser.add_option("-g", "--gain", type="eng_float", default=40, help="set gain in dB (default is midpoint)") parser.add_option("-O", "--audio-output", type="string", default="", help="pcm device name. E.g., hw:0,0 or surround51 or /dev/dsp") parser.add_option("", "--freq-min", type="eng_float", default=87.9e6, help="Set a minimum frequency [default=%default]") parser.add_option("", "--freq-max", type="eng_float", default=108.1e6, help="Set a maximum frequency [default=%default]") (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) if abs(options.f1 - options.f2) > 5.5e6: print "Sorry, two stations must be within 5.5MHz of each other" raise SystemExit f = (options.f1, options.f2) self.vol = .1 self.state = "FREQ" self.fm_freq_min = options.freq_min self.fm_freq_max = options.freq_max # build graph stream_args = uhd.stream_args('fc32', channels=range(2)) self.u = uhd.usrp_source(device_addr=options.args, stream_args=stream_args) # Set front end channel mapping self.u.set_subdev_spec(options.spec) usrp_rate = 320e3 demod_rate = 320e3 audio_rate = 32e3 audio_decim = int(demod_rate / audio_rate) self.u.set_samp_rate(usrp_rate) dev_rate = self.u.get_samp_rate() # Make sure dboard can suppor the required frequencies frange = self.u.get_freq_range() if(frange.start() > self.fm_freq_max or frange.stop() < self.fm_freq_min): sys.stderr.write("Radio does not support required frequency range.\n") sys.exit(1) # sound card as final sink self.audio_sink = audio.sink(int(audio_rate), options.audio_output) # taps for channel filter nfilts = 32 chan_coeffs = optfir.low_pass (nfilts, # gain nfilts*usrp_rate, # sampling rate 80e3, # passband cutoff 115e3, # stopband cutoff 0.1, # passband ripple 60) # stopband attenuation rrate = usrp_rate / dev_rate # set front end PLL to middle frequency mid_freq = (f[0] + f[1]) / 2.0 if options.gain is None: # if no gain was specified, use the mid-point in dB g = self.u.get_gain_range() options.gain = float(g.start()+g.stop())/2.0 for n in range(2): chan_filt = blks2.pfb_arb_resampler_ccf(rrate, chan_coeffs, nfilts) guts = blks2.wfm_rcv (demod_rate, audio_decim) volume_control = gr.multiply_const_ff(self.vol) #self.connect((self.di, n), chan_filt) self.connect((self.u, n), chan_filt) self.connect(chan_filt, guts, volume_control) self.connect(volume_control, (self.audio_sink, n)) # Test the the requested frequencies are in range if(f[n] < self.fm_freq_min or f[n] > self.fm_freq_max): sys.stderr.write("Requested frequency is outside of required frequency range.\n") sys.exit(1) # Tune each channel by setting the RF freq to mid_freq and the # DDC freq to f[n]. tr = uhd.tune_request(f[n], rf_freq=mid_freq, rf_freq_policy=uhd.tune_request.POLICY_MANUAL) self.u.set_center_freq(tr, n) # Set gain for each channel self.set_gain(options.gain, n) # Set the antenna if(options.antenna): self.u.set_antenna(options.antenna, n) def set_vol (self, vol): self.vol = vol self.volume_control.set_k(self.vol) def set_gain(self, gain, n): self.u.set_gain(gain, n) if __name__ == '__main__': tb = wfm_rx_block() try: tb.run() except KeyboardInterrupt: pass
gpl-3.0
wuhengzhi/chromium-crosswalk
tools/usb_gadget/hid_gadget_test.py
41
9446
#!/usr/bin/python # Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import unittest import mock import hid_constants import hid_descriptors import hid_gadget import usb_constants report_desc = hid_descriptors.ReportDescriptor( hid_descriptors.UsagePage(0xFF00), # Vendor Defined hid_descriptors.Usage(0x00), hid_descriptors.Collection( hid_constants.CollectionType.APPLICATION, hid_descriptors.LogicalMinimum(0, force_length=1), hid_descriptors.LogicalMaximum(255, force_length=2), hid_descriptors.ReportSize(8), hid_descriptors.ReportCount(8), hid_descriptors.Input(hid_descriptors.Data, hid_descriptors.Variable, hid_descriptors.Absolute, hid_descriptors.BufferedBytes), hid_descriptors.Output(hid_descriptors.Data, hid_descriptors.Variable, hid_descriptors.Absolute, hid_descriptors.BufferedBytes), hid_descriptors.Feature(hid_descriptors.Data, hid_descriptors.Variable, hid_descriptors.Absolute, hid_descriptors.BufferedBytes) ) ) combo_report_desc = hid_descriptors.ReportDescriptor( hid_descriptors.ReportID(1), report_desc, hid_descriptors.ReportID(2), report_desc ) class HidGadgetTest(unittest.TestCase): def test_bad_intervals(self): with self.assertRaisesRegexp(ValueError, 'Full speed'): hid_gadget.HidGadget(report_desc, features={}, interval_ms=50000, vendor_id=0, product_id=0) with self.assertRaisesRegexp(ValueError, 'High speed'): hid_gadget.HidGadget(report_desc, features={}, interval_ms=5000, vendor_id=0, product_id=0) def test_get_string_descriptor(self): g = hid_gadget.HidGadget(report_desc=report_desc, features={}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) g.AddStringDescriptor(2, 'HID Gadget') desc = g.ControlRead(0x80, 6, 0x0302, 0x0409, 255) self.assertEquals(desc, '\x16\x03H\0I\0D\0 \0G\0a\0d\0g\0e\0t\0') def test_get_report_descriptor(self): g = hid_gadget.HidGadget(report_desc=report_desc, features={}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) desc = g.ControlRead(0x81, 6, 0x2200, 0, 63) self.assertEquals(desc, report_desc) def test_set_idle(self): g = hid_gadget.HidGadget(report_desc=report_desc, features={}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) self.assertTrue(g.ControlWrite(0x21, 0x0A, 0, 0, '')) def test_class_wrong_target(self): g = hid_gadget.HidGadget(report_desc=report_desc, features={}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) self.assertIsNone(g.ControlRead(0xA0, 0, 0, 0, 0)) # Device self.assertIsNone(g.ControlRead(0xA1, 0, 0, 1, 0)) # Interface 1 self.assertIsNone(g.ControlWrite(0x20, 0, 0, 0, '')) # Device self.assertIsNone(g.ControlWrite(0x21, 0, 0, 1, '')) # Interface 1 def test_send_report_zero(self): g = hid_gadget.HidGadget(report_desc=report_desc, features={}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) g.SendReport(0, 'Hello world!') chip.SendPacket.assert_called_once_with(0x81, 'Hello world!') def test_send_multiple_reports(self): g = hid_gadget.HidGadget(report_desc=report_desc, features={}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) g.SendReport(1, 'Hello!') g.SendReport(2, 'World!') chip.SendPacket.assert_has_calls([ mock.call(0x81, '\x01Hello!'), mock.call(0x81, '\x02World!'), ]) class TestFeature(hid_gadget.HidFeature): def SetInputReport(self, data): self.input_report = data return True def SetOutputReport(self, data): self.output_report = data return True def SetFeatureReport(self, data): self.feature_report = data return True def GetInputReport(self): return 'Input report.' def GetOutputReport(self): return 'Output report.' def GetFeatureReport(self): return 'Feature report.' class HidFeatureTest(unittest.TestCase): def test_disconnected(self): feature = TestFeature() with self.assertRaisesRegexp(RuntimeError, 'not connected'): feature.SendReport('Hello world!') def test_send_report(self): feature = TestFeature() g = hid_gadget.HidGadget(report_desc, features={1: feature}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) feature.SendReport('Hello world!') chip.SendPacket.assert_called_once_with(0x81, '\x01Hello world!') g.Disconnected() def test_get_bad_report(self): feature = TestFeature() g = hid_gadget.HidGadget(report_desc, features={1: feature}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) self.assertIsNone(g.ControlRead(0xA1, 1, 0x0102, 0, 8)) def test_set_bad_report(self): feature = TestFeature() g = hid_gadget.HidGadget(report_desc, features={1: feature}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) self.assertIsNone(g.ControlWrite(0x21, 0x09, 0x0102, 0, 'Hello!')) def test_get_input_report(self): feature = TestFeature() g = hid_gadget.HidGadget(report_desc, features={1: feature}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) report = g.ControlRead(0xA1, 1, 0x0101, 0, 8) self.assertEquals(report, 'Input re') def test_set_input_report(self): feature = TestFeature() g = hid_gadget.HidGadget(report_desc, features={1: feature}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) self.assertTrue(g.ControlWrite(0x21, 0x09, 0x0101, 0, 'Hello!')) self.assertEquals(feature.input_report, 'Hello!') def test_get_output_report(self): feature = TestFeature() g = hid_gadget.HidGadget(report_desc, features={1: feature}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) report = g.ControlRead(0xA1, 1, 0x0201, 0, 8) self.assertEquals(report, 'Output r') def test_set_output_report(self): feature = TestFeature() g = hid_gadget.HidGadget(report_desc, features={1: feature}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) self.assertTrue(g.ControlWrite(0x21, 0x09, 0x0201, 0, 'Hello!')) self.assertEquals(feature.output_report, 'Hello!') def test_receive_interrupt(self): feature = TestFeature() g = hid_gadget.HidGadget(report_desc, features={1: feature}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) g.SetConfiguration(1) g.ReceivePacket(0x01, '\x01Hello!') self.assertFalse(chip.HaltEndpoint.called) self.assertEquals(feature.output_report, 'Hello!') def test_receive_interrupt_report_zero(self): feature = TestFeature() g = hid_gadget.HidGadget(report_desc, features={0: feature}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) g.SetConfiguration(1) g.ReceivePacket(0x01, 'Hello!') self.assertFalse(chip.HaltEndpoint.called) self.assertEquals(feature.output_report, 'Hello!') def test_receive_bad_interrupt(self): feature = TestFeature() g = hid_gadget.HidGadget(report_desc, features={1: feature}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) g.SetConfiguration(1) g.ReceivePacket(0x01, '\x00Hello!') chip.HaltEndpoint.assert_called_once_with(0x01) def test_get_feature_report(self): feature = TestFeature() g = hid_gadget.HidGadget(report_desc, features={1: feature}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) report = g.ControlRead(0xA1, 1, 0x0301, 0, 8) self.assertEquals(report, 'Feature ') def test_set_feature_report(self): feature = TestFeature() g = hid_gadget.HidGadget(report_desc, features={1: feature}, vendor_id=0, product_id=0) chip = mock.Mock() g.Connected(chip, usb_constants.Speed.HIGH) self.assertTrue(g.ControlWrite(0x21, 0x09, 0x0301, 0, 'Hello!')) self.assertEquals(feature.feature_report, 'Hello!') if __name__ == '__main__': unittest.main()
bsd-3-clause
pinheadmz/bitcoin
test/functional/p2p-segwit.py
9
92913
#!/usr/bin/env python3 # Copyright (c) 2016 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test segwit transactions and blocks on P2P network.""" from test_framework.mininode import * from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * from test_framework.script import * from test_framework.blocktools import create_block, create_coinbase, add_witness_commitment, WITNESS_COMMITMENT_HEADER from test_framework.key import CECKey, CPubKey import time import random from binascii import hexlify # The versionbit bit used to signal activation of SegWit VB_WITNESS_BIT = 1 VB_PERIOD = 144 VB_ACTIVATION_THRESHOLD = 108 VB_TOP_BITS = 0x20000000 MAX_SIGOP_COST = 80000 # Calculate the virtual size of a witness block: # (base + witness/4) def get_virtual_size(witness_block): base_size = len(witness_block.serialize()) total_size = len(witness_block.serialize(with_witness=True)) # the "+3" is so we round up vsize = int((3*base_size + total_size + 3)/4) return vsize # Note: we can reduce code by using SingleNodeConnCB (in master, not 0.12) class TestNode(NodeConnCB): def __init__(self): NodeConnCB.__init__(self) self.connection = None self.ping_counter = 1 self.last_pong = msg_pong(0) self.sleep_time = 0.05 self.getdataset = set() self.last_reject = None def add_connection(self, conn): self.connection = conn # Wrapper for the NodeConn's send_message function def send_message(self, message): self.connection.send_message(message) def on_inv(self, conn, message): self.last_inv = message def on_block(self, conn, message): self.last_block = message.block self.last_block.calc_sha256() def on_getdata(self, conn, message): for inv in message.inv: self.getdataset.add(inv.hash) self.last_getdata = message def on_getheaders(self, conn, message): self.last_getheaders = message def on_pong(self, conn, message): self.last_pong = message def on_reject(self, conn, message): self.last_reject = message # Syncing helpers def sync(self, test_function, timeout=60): while timeout > 0: with mininode_lock: if test_function(): return time.sleep(self.sleep_time) timeout -= self.sleep_time raise AssertionError("Sync failed to complete") def sync_with_ping(self, timeout=60): self.send_message(msg_ping(nonce=self.ping_counter)) test_function = lambda: self.last_pong.nonce == self.ping_counter self.sync(test_function, timeout) self.ping_counter += 1 return def wait_for_block(self, blockhash, timeout=60): test_function = lambda: self.last_block != None and self.last_block.sha256 == blockhash self.sync(test_function, timeout) return def wait_for_getdata(self, timeout=60): test_function = lambda: self.last_getdata != None self.sync(test_function, timeout) def wait_for_getheaders(self, timeout=60): test_function = lambda: self.last_getheaders != None self.sync(test_function, timeout) def wait_for_inv(self, expected_inv, timeout=60): test_function = lambda: self.last_inv != expected_inv self.sync(test_function, timeout) def announce_tx_and_wait_for_getdata(self, tx, timeout=60): with mininode_lock: self.last_getdata = None self.send_message(msg_inv(inv=[CInv(1, tx.sha256)])) self.wait_for_getdata(timeout) return def announce_block_and_wait_for_getdata(self, block, use_header, timeout=60): with mininode_lock: self.last_getdata = None self.last_getheaders = None msg = msg_headers() msg.headers = [ CBlockHeader(block) ] if use_header: self.send_message(msg) else: self.send_message(msg_inv(inv=[CInv(2, block.sha256)])) self.wait_for_getheaders() self.send_message(msg) self.wait_for_getdata() return def announce_block(self, block, use_header): with mininode_lock: self.last_getdata = None if use_header: msg = msg_headers() msg.headers = [ CBlockHeader(block) ] self.send_message(msg) else: self.send_message(msg_inv(inv=[CInv(2, block.sha256)])) def request_block(self, blockhash, inv_type, timeout=60): with mininode_lock: self.last_block = None self.send_message(msg_getdata(inv=[CInv(inv_type, blockhash)])) self.wait_for_block(blockhash, timeout) return self.last_block def test_transaction_acceptance(self, tx, with_witness, accepted, reason=None): tx_message = msg_tx(tx) if with_witness: tx_message = msg_witness_tx(tx) self.send_message(tx_message) self.sync_with_ping() assert_equal(tx.hash in self.connection.rpc.getrawmempool(), accepted) if (reason != None and not accepted): # Check the rejection reason as well. with mininode_lock: assert_equal(self.last_reject.reason, reason) # Test whether a witness block had the correct effect on the tip def test_witness_block(self, block, accepted, with_witness=True): if with_witness: self.send_message(msg_witness_block(block)) else: self.send_message(msg_block(block)) self.sync_with_ping() assert_equal(self.connection.rpc.getbestblockhash() == block.hash, accepted) # Used to keep track of anyone-can-spend outputs that we can use in the tests class UTXO(object): def __init__(self, sha256, n, nValue): self.sha256 = sha256 self.n = n self.nValue = nValue # Helper for getting the script associated with a P2PKH def GetP2PKHScript(pubkeyhash): return CScript([CScriptOp(OP_DUP), CScriptOp(OP_HASH160), pubkeyhash, CScriptOp(OP_EQUALVERIFY), CScriptOp(OP_CHECKSIG)]) # Add signature for a P2PK witness program. def sign_P2PK_witness_input(script, txTo, inIdx, hashtype, value, key): tx_hash = SegwitVersion1SignatureHash(script, txTo, inIdx, hashtype, value) signature = key.sign(tx_hash) + chr(hashtype).encode('latin-1') txTo.wit.vtxinwit[inIdx].scriptWitness.stack = [signature, script] txTo.rehash() class SegWitTest(BitcoinTestFramework): def __init__(self): super().__init__() self.setup_clean_chain = True self.num_nodes = 3 def setup_network(self): self.nodes = [] self.nodes.append(start_node(0, self.options.tmpdir, ["-whitelist=127.0.0.1"])) # Start a node for testing IsStandard rules. self.nodes.append(start_node(1, self.options.tmpdir, ["-whitelist=127.0.0.1", "-acceptnonstdtxn=0"])) connect_nodes(self.nodes[0], 1) # Disable segwit's bip9 parameter to simulate upgrading after activation. self.nodes.append(start_node(2, self.options.tmpdir, ["-whitelist=127.0.0.1", "-bip9params=segwit:0:0"])) connect_nodes(self.nodes[0], 2) ''' Helpers ''' # Build a block on top of node0's tip. def build_next_block(self, nVersion=4): tip = self.nodes[0].getbestblockhash() height = self.nodes[0].getblockcount() + 1 block_time = self.nodes[0].getblockheader(tip)["mediantime"] + 1 block = create_block(int(tip, 16), create_coinbase(height), block_time) block.nVersion = nVersion block.rehash() return block # Adds list of transactions to block, adds witness commitment, then solves. def update_witness_block_with_transactions(self, block, tx_list, nonce=0): block.vtx.extend(tx_list) add_witness_commitment(block, nonce) block.solve() return ''' Individual tests ''' def test_witness_services(self): self.log.info("Verifying NODE_WITNESS service bit") assert((self.test_node.connection.nServices & NODE_WITNESS) != 0) # See if sending a regular transaction works, and create a utxo # to use in later tests. def test_non_witness_transaction(self): # Mine a block with an anyone-can-spend coinbase, # let it mature, then try to spend it. self.log.info("Testing non-witness transaction") block = self.build_next_block(nVersion=1) block.solve() self.test_node.send_message(msg_block(block)) self.test_node.sync_with_ping() # make sure the block was processed txid = block.vtx[0].sha256 self.nodes[0].generate(99) # let the block mature # Create a transaction that spends the coinbase tx = CTransaction() tx.vin.append(CTxIn(COutPoint(txid, 0), b"")) tx.vout.append(CTxOut(49*100000000, CScript([OP_TRUE]))) tx.calc_sha256() # Check that serializing it with or without witness is the same # This is a sanity check of our testing framework. assert_equal(msg_tx(tx).serialize(), msg_witness_tx(tx).serialize()) self.test_node.send_message(msg_witness_tx(tx)) self.test_node.sync_with_ping() # make sure the tx was processed assert(tx.hash in self.nodes[0].getrawmempool()) # Save this transaction for later self.utxo.append(UTXO(tx.sha256, 0, 49*100000000)) self.nodes[0].generate(1) # Verify that blocks with witnesses are rejected before activation. def test_unnecessary_witness_before_segwit_activation(self): self.log.info("Testing behavior of unnecessary witnesses") # For now, rely on earlier tests to have created at least one utxo for # us to use assert(len(self.utxo) > 0) assert(get_bip9_status(self.nodes[0], 'segwit')['status'] != 'active') tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, CScript([OP_TRUE]))) tx.wit.vtxinwit.append(CTxInWitness()) tx.wit.vtxinwit[0].scriptWitness.stack = [CScript([CScriptNum(1)])] # Verify the hash with witness differs from the txid # (otherwise our testing framework must be broken!) tx.rehash() assert(tx.sha256 != tx.calc_sha256(with_witness=True)) # Construct a segwit-signaling block that includes the transaction. block = self.build_next_block(nVersion=(VB_TOP_BITS|(1 << VB_WITNESS_BIT))) self.update_witness_block_with_transactions(block, [tx]) # Sending witness data before activation is not allowed (anti-spam # rule). self.test_node.test_witness_block(block, accepted=False) # TODO: fix synchronization so we can test reject reason # Right now, bitcoind delays sending reject messages for blocks # until the future, making synchronization here difficult. #assert_equal(self.test_node.last_reject.reason, "unexpected-witness") # But it should not be permanently marked bad... # Resend without witness information. self.test_node.send_message(msg_block(block)) self.test_node.sync_with_ping() assert_equal(self.nodes[0].getbestblockhash(), block.hash) sync_blocks(self.nodes) # Create a p2sh output -- this is so we can pass the standardness # rules (an anyone-can-spend OP_TRUE would be rejected, if not wrapped # in P2SH). p2sh_program = CScript([OP_TRUE]) p2sh_pubkey = hash160(p2sh_program) scriptPubKey = CScript([OP_HASH160, p2sh_pubkey, OP_EQUAL]) # Now check that unnecessary witnesses can't be used to blind a node # to a transaction, eg by violating standardness checks. tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, scriptPubKey)) tx2.rehash() self.test_node.test_transaction_acceptance(tx2, False, True) self.nodes[0].generate(1) sync_blocks(self.nodes) # We'll add an unnecessary witness to this transaction that would cause # it to be non-standard, to test that violating policy with a witness before # segwit activation doesn't blind a node to a transaction. Transactions # rejected for having a witness before segwit activation shouldn't be added # to the rejection cache. tx3 = CTransaction() tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), CScript([p2sh_program]))) tx3.vout.append(CTxOut(tx2.vout[0].nValue-1000, scriptPubKey)) tx3.wit.vtxinwit.append(CTxInWitness()) tx3.wit.vtxinwit[0].scriptWitness.stack = [b'a'*400000] tx3.rehash() # Note that this should be rejected for the premature witness reason, # rather than a policy check, since segwit hasn't activated yet. self.std_node.test_transaction_acceptance(tx3, True, False, b'no-witness-yet') # If we send without witness, it should be accepted. self.std_node.test_transaction_acceptance(tx3, False, True) # Now create a new anyone-can-spend utxo for the next test. tx4 = CTransaction() tx4.vin.append(CTxIn(COutPoint(tx3.sha256, 0), CScript([p2sh_program]))) tx4.vout.append(CTxOut(tx3.vout[0].nValue-1000, CScript([OP_TRUE]))) tx4.rehash() self.test_node.test_transaction_acceptance(tx3, False, True) self.test_node.test_transaction_acceptance(tx4, False, True) self.nodes[0].generate(1) sync_blocks(self.nodes) # Update our utxo list; we spent the first entry. self.utxo.pop(0) self.utxo.append(UTXO(tx4.sha256, 0, tx4.vout[0].nValue)) # Mine enough blocks for segwit's vb state to be 'started'. def advance_to_segwit_started(self): height = self.nodes[0].getblockcount() # Will need to rewrite the tests here if we are past the first period assert(height < VB_PERIOD - 1) # Genesis block is 'defined'. assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'defined') # Advance to end of period, status should now be 'started' self.nodes[0].generate(VB_PERIOD-height-1) assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'started') # Mine enough blocks to lock in segwit, but don't activate. # TODO: we could verify that lockin only happens at the right threshold of # signalling blocks, rather than just at the right period boundary. def advance_to_segwit_lockin(self): height = self.nodes[0].getblockcount() assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'started') # Advance to end of period, and verify lock-in happens at the end self.nodes[0].generate(VB_PERIOD-1) height = self.nodes[0].getblockcount() assert((height % VB_PERIOD) == VB_PERIOD - 2) assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'started') self.nodes[0].generate(1) assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'locked_in') # Mine enough blocks to activate segwit. # TODO: we could verify that activation only happens at the right threshold # of signalling blocks, rather than just at the right period boundary. def advance_to_segwit_active(self): assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'locked_in') height = self.nodes[0].getblockcount() self.nodes[0].generate(VB_PERIOD - (height%VB_PERIOD) - 2) assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'locked_in') self.nodes[0].generate(1) assert_equal(get_bip9_status(self.nodes[0], 'segwit')['status'], 'active') # This test can only be run after segwit has activated def test_witness_commitments(self): self.log.info("Testing witness commitments") # First try a correct witness commitment. block = self.build_next_block() add_witness_commitment(block) block.solve() # Test the test -- witness serialization should be different assert(msg_witness_block(block).serialize() != msg_block(block).serialize()) # This empty block should be valid. self.test_node.test_witness_block(block, accepted=True) # Try to tweak the nonce block_2 = self.build_next_block() add_witness_commitment(block_2, nonce=28) block_2.solve() # The commitment should have changed! assert(block_2.vtx[0].vout[-1] != block.vtx[0].vout[-1]) # This should also be valid. self.test_node.test_witness_block(block_2, accepted=True) # Now test commitments with actual transactions assert (len(self.utxo) > 0) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) # Let's construct a witness program witness_program = CScript([OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, scriptPubKey)) tx.rehash() # tx2 will spend tx1, and send back to a regular anyone-can-spend address tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, witness_program)) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [witness_program] tx2.rehash() block_3 = self.build_next_block() self.update_witness_block_with_transactions(block_3, [tx, tx2], nonce=1) # Add an extra OP_RETURN output that matches the witness commitment template, # even though it has extra data after the incorrect commitment. # This block should fail. block_3.vtx[0].vout.append(CTxOut(0, CScript([OP_RETURN, WITNESS_COMMITMENT_HEADER + ser_uint256(2), 10]))) block_3.vtx[0].rehash() block_3.hashMerkleRoot = block_3.calc_merkle_root() block_3.rehash() block_3.solve() self.test_node.test_witness_block(block_3, accepted=False) # Add a different commitment with different nonce, but in the # right location, and with some funds burned(!). # This should succeed (nValue shouldn't affect finding the # witness commitment). add_witness_commitment(block_3, nonce=0) block_3.vtx[0].vout[0].nValue -= 1 block_3.vtx[0].vout[-1].nValue += 1 block_3.vtx[0].rehash() block_3.hashMerkleRoot = block_3.calc_merkle_root() block_3.rehash() assert(len(block_3.vtx[0].vout) == 4) # 3 OP_returns block_3.solve() self.test_node.test_witness_block(block_3, accepted=True) # Finally test that a block with no witness transactions can # omit the commitment. block_4 = self.build_next_block() tx3 = CTransaction() tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), b"")) tx3.vout.append(CTxOut(tx.vout[0].nValue-1000, witness_program)) tx3.rehash() block_4.vtx.append(tx3) block_4.hashMerkleRoot = block_4.calc_merkle_root() block_4.solve() self.test_node.test_witness_block(block_4, with_witness=False, accepted=True) # Update available utxo's for use in later test. self.utxo.pop(0) self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) def test_block_malleability(self): self.log.info("Testing witness block malleability") # Make sure that a block that has too big a virtual size # because of a too-large coinbase witness is not permanently # marked bad. block = self.build_next_block() add_witness_commitment(block) block.solve() block.vtx[0].wit.vtxinwit[0].scriptWitness.stack.append(b'a'*5000000) assert(get_virtual_size(block) > MAX_BLOCK_BASE_SIZE) # We can't send over the p2p network, because this is too big to relay # TODO: repeat this test with a block that can be relayed self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True))) assert(self.nodes[0].getbestblockhash() != block.hash) block.vtx[0].wit.vtxinwit[0].scriptWitness.stack.pop() assert(get_virtual_size(block) < MAX_BLOCK_BASE_SIZE) self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True))) assert(self.nodes[0].getbestblockhash() == block.hash) # Now make sure that malleating the witness nonce doesn't # result in a block permanently marked bad. block = self.build_next_block() add_witness_commitment(block) block.solve() # Change the nonce -- should not cause the block to be permanently # failed block.vtx[0].wit.vtxinwit[0].scriptWitness.stack = [ ser_uint256(1) ] self.test_node.test_witness_block(block, accepted=False) # Changing the witness nonce doesn't change the block hash block.vtx[0].wit.vtxinwit[0].scriptWitness.stack = [ ser_uint256(0) ] self.test_node.test_witness_block(block, accepted=True) def test_witness_block_size(self): self.log.info("Testing witness block size limit") # TODO: Test that non-witness carrying blocks can't exceed 1MB # Skipping this test for now; this is covered in p2p-fullblocktest.py # Test that witness-bearing blocks are limited at ceil(base + wit/4) <= 1MB. block = self.build_next_block() assert(len(self.utxo) > 0) # Create a P2WSH transaction. # The witness program will be a bunch of OP_2DROP's, followed by OP_TRUE. # This should give us plenty of room to tweak the spending tx's # virtual size. NUM_DROPS = 200 # 201 max ops per script! NUM_OUTPUTS = 50 witness_program = CScript([OP_2DROP]*NUM_DROPS + [OP_TRUE]) witness_hash = uint256_from_str(sha256(witness_program)) scriptPubKey = CScript([OP_0, ser_uint256(witness_hash)]) prevout = COutPoint(self.utxo[0].sha256, self.utxo[0].n) value = self.utxo[0].nValue parent_tx = CTransaction() parent_tx.vin.append(CTxIn(prevout, b"")) child_value = int(value/NUM_OUTPUTS) for i in range(NUM_OUTPUTS): parent_tx.vout.append(CTxOut(child_value, scriptPubKey)) parent_tx.vout[0].nValue -= 50000 assert(parent_tx.vout[0].nValue > 0) parent_tx.rehash() child_tx = CTransaction() for i in range(NUM_OUTPUTS): child_tx.vin.append(CTxIn(COutPoint(parent_tx.sha256, i), b"")) child_tx.vout = [CTxOut(value - 100000, CScript([OP_TRUE]))] for i in range(NUM_OUTPUTS): child_tx.wit.vtxinwit.append(CTxInWitness()) child_tx.wit.vtxinwit[-1].scriptWitness.stack = [b'a'*195]*(2*NUM_DROPS) + [witness_program] child_tx.rehash() self.update_witness_block_with_transactions(block, [parent_tx, child_tx]) vsize = get_virtual_size(block) additional_bytes = (MAX_BLOCK_BASE_SIZE - vsize)*4 i = 0 while additional_bytes > 0: # Add some more bytes to each input until we hit MAX_BLOCK_BASE_SIZE+1 extra_bytes = min(additional_bytes+1, 55) block.vtx[-1].wit.vtxinwit[int(i/(2*NUM_DROPS))].scriptWitness.stack[i%(2*NUM_DROPS)] = b'a'*(195+extra_bytes) additional_bytes -= extra_bytes i += 1 block.vtx[0].vout.pop() # Remove old commitment add_witness_commitment(block) block.solve() vsize = get_virtual_size(block) assert_equal(vsize, MAX_BLOCK_BASE_SIZE + 1) # Make sure that our test case would exceed the old max-network-message # limit assert(len(block.serialize(True)) > 2*1024*1024) self.test_node.test_witness_block(block, accepted=False) # Now resize the second transaction to make the block fit. cur_length = len(block.vtx[-1].wit.vtxinwit[0].scriptWitness.stack[0]) block.vtx[-1].wit.vtxinwit[0].scriptWitness.stack[0] = b'a'*(cur_length-1) block.vtx[0].vout.pop() add_witness_commitment(block) block.solve() assert(get_virtual_size(block) == MAX_BLOCK_BASE_SIZE) self.test_node.test_witness_block(block, accepted=True) # Update available utxo's self.utxo.pop(0) self.utxo.append(UTXO(block.vtx[-1].sha256, 0, block.vtx[-1].vout[0].nValue)) # submitblock will try to add the nonce automatically, so that mining # software doesn't need to worry about doing so itself. def test_submit_block(self): block = self.build_next_block() # Try using a custom nonce and then don't supply it. # This shouldn't possibly work. add_witness_commitment(block, nonce=1) block.vtx[0].wit = CTxWitness() # drop the nonce block.solve() self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True))) assert(self.nodes[0].getbestblockhash() != block.hash) # Now redo commitment with the standard nonce, but let bitcoind fill it in. add_witness_commitment(block, nonce=0) block.vtx[0].wit = CTxWitness() block.solve() self.nodes[0].submitblock(bytes_to_hex_str(block.serialize(True))) assert_equal(self.nodes[0].getbestblockhash(), block.hash) # This time, add a tx with non-empty witness, but don't supply # the commitment. block_2 = self.build_next_block() add_witness_commitment(block_2) block_2.solve() # Drop commitment and nonce -- submitblock should not fill in. block_2.vtx[0].vout.pop() block_2.vtx[0].wit = CTxWitness() self.nodes[0].submitblock(bytes_to_hex_str(block_2.serialize(True))) # Tip should not advance! assert(self.nodes[0].getbestblockhash() != block_2.hash) # Consensus tests of extra witness data in a transaction. def test_extra_witness_data(self): self.log.info("Testing extra witness data in tx") assert(len(self.utxo) > 0) block = self.build_next_block() witness_program = CScript([OP_DROP, OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) # First try extra witness data on a tx that doesn't require a witness tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-2000, scriptPubKey)) tx.vout.append(CTxOut(1000, CScript([OP_TRUE]))) # non-witness output tx.wit.vtxinwit.append(CTxInWitness()) tx.wit.vtxinwit[0].scriptWitness.stack = [CScript([])] tx.rehash() self.update_witness_block_with_transactions(block, [tx]) # Extra witness data should not be allowed. self.test_node.test_witness_block(block, accepted=False) # Try extra signature data. Ok if we're not spending a witness output. block.vtx[1].wit.vtxinwit = [] block.vtx[1].vin[0].scriptSig = CScript([OP_0]) block.vtx[1].rehash() add_witness_commitment(block) block.solve() self.test_node.test_witness_block(block, accepted=True) # Now try extra witness/signature data on an input that DOES require a # witness tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) # witness output tx2.vin.append(CTxIn(COutPoint(tx.sha256, 1), b"")) # non-witness tx2.vout.append(CTxOut(tx.vout[0].nValue, CScript([OP_TRUE]))) tx2.wit.vtxinwit.extend([CTxInWitness(), CTxInWitness()]) tx2.wit.vtxinwit[0].scriptWitness.stack = [ CScript([CScriptNum(1)]), CScript([CScriptNum(1)]), witness_program ] tx2.wit.vtxinwit[1].scriptWitness.stack = [ CScript([OP_TRUE]) ] block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx2]) # This has extra witness data, so it should fail. self.test_node.test_witness_block(block, accepted=False) # Now get rid of the extra witness, but add extra scriptSig data tx2.vin[0].scriptSig = CScript([OP_TRUE]) tx2.vin[1].scriptSig = CScript([OP_TRUE]) tx2.wit.vtxinwit[0].scriptWitness.stack.pop(0) tx2.wit.vtxinwit[1].scriptWitness.stack = [] tx2.rehash() add_witness_commitment(block) block.solve() # This has extra signature data for a witness input, so it should fail. self.test_node.test_witness_block(block, accepted=False) # Now get rid of the extra scriptsig on the witness input, and verify # success (even with extra scriptsig data in the non-witness input) tx2.vin[0].scriptSig = b"" tx2.rehash() add_witness_commitment(block) block.solve() self.test_node.test_witness_block(block, accepted=True) # Update utxo for later tests self.utxo.pop(0) self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) def test_max_witness_push_length(self): ''' Should only allow up to 520 byte pushes in witness stack ''' self.log.info("Testing maximum witness push size") MAX_SCRIPT_ELEMENT_SIZE = 520 assert(len(self.utxo)) block = self.build_next_block() witness_program = CScript([OP_DROP, OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, scriptPubKey)) tx.rehash() tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, CScript([OP_TRUE]))) tx2.wit.vtxinwit.append(CTxInWitness()) # First try a 521-byte stack element tx2.wit.vtxinwit[0].scriptWitness.stack = [ b'a'*(MAX_SCRIPT_ELEMENT_SIZE+1), witness_program ] tx2.rehash() self.update_witness_block_with_transactions(block, [tx, tx2]) self.test_node.test_witness_block(block, accepted=False) # Now reduce the length of the stack element tx2.wit.vtxinwit[0].scriptWitness.stack[0] = b'a'*(MAX_SCRIPT_ELEMENT_SIZE) add_witness_commitment(block) block.solve() self.test_node.test_witness_block(block, accepted=True) # Update the utxo for later tests self.utxo.pop() self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) def test_max_witness_program_length(self): # Can create witness outputs that are long, but can't be greater than # 10k bytes to successfully spend self.log.info("Testing maximum witness program length") assert(len(self.utxo)) MAX_PROGRAM_LENGTH = 10000 # This program is 19 max pushes (9937 bytes), then 64 more opcode-bytes. long_witness_program = CScript([b'a'*520]*19 + [OP_DROP]*63 + [OP_TRUE]) assert(len(long_witness_program) == MAX_PROGRAM_LENGTH+1) long_witness_hash = sha256(long_witness_program) long_scriptPubKey = CScript([OP_0, long_witness_hash]) block = self.build_next_block() tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, long_scriptPubKey)) tx.rehash() tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, CScript([OP_TRUE]))) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [b'a']*44 + [long_witness_program] tx2.rehash() self.update_witness_block_with_transactions(block, [tx, tx2]) self.test_node.test_witness_block(block, accepted=False) # Try again with one less byte in the witness program witness_program = CScript([b'a'*520]*19 + [OP_DROP]*62 + [OP_TRUE]) assert(len(witness_program) == MAX_PROGRAM_LENGTH) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) tx.vout[0] = CTxOut(tx.vout[0].nValue, scriptPubKey) tx.rehash() tx2.vin[0].prevout.hash = tx.sha256 tx2.wit.vtxinwit[0].scriptWitness.stack = [b'a']*43 + [witness_program] tx2.rehash() block.vtx = [block.vtx[0]] self.update_witness_block_with_transactions(block, [tx, tx2]) self.test_node.test_witness_block(block, accepted=True) self.utxo.pop() self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) def test_witness_input_length(self): ''' Ensure that vin length must match vtxinwit length ''' self.log.info("Testing witness input length") assert(len(self.utxo)) witness_program = CScript([OP_DROP, OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) # Create a transaction that splits our utxo into many outputs tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) nValue = self.utxo[0].nValue for i in range(10): tx.vout.append(CTxOut(int(nValue/10), scriptPubKey)) tx.vout[0].nValue -= 1000 assert(tx.vout[0].nValue >= 0) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) # Try various ways to spend tx that should all break. # This "broken" transaction serializer will not normalize # the length of vtxinwit. class BrokenCTransaction(CTransaction): def serialize_with_witness(self): flags = 0 if not self.wit.is_null(): flags |= 1 r = b"" r += struct.pack("<i", self.nVersion) if flags: dummy = [] r += ser_vector(dummy) r += struct.pack("<B", flags) r += ser_vector(self.vin) r += ser_vector(self.vout) if flags & 1: r += self.wit.serialize() r += struct.pack("<I", self.nLockTime) return r tx2 = BrokenCTransaction() for i in range(10): tx2.vin.append(CTxIn(COutPoint(tx.sha256, i), b"")) tx2.vout.append(CTxOut(nValue-3000, CScript([OP_TRUE]))) # First try using a too long vtxinwit for i in range(11): tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[i].scriptWitness.stack = [b'a', witness_program] block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=False) # Now try using a too short vtxinwit tx2.wit.vtxinwit.pop() tx2.wit.vtxinwit.pop() block.vtx = [block.vtx[0]] self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=False) # Now make one of the intermediate witnesses be incorrect tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[-1].scriptWitness.stack = [b'a', witness_program] tx2.wit.vtxinwit[5].scriptWitness.stack = [ witness_program ] block.vtx = [block.vtx[0]] self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=False) # Fix the broken witness and the block should be accepted. tx2.wit.vtxinwit[5].scriptWitness.stack = [b'a', witness_program] block.vtx = [block.vtx[0]] self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=True) self.utxo.pop() self.utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) def test_witness_tx_relay_before_segwit_activation(self): self.log.info("Testing relay of witness transactions") # Generate a transaction that doesn't require a witness, but send it # with a witness. Should be rejected for premature-witness, but should # not be added to recently rejected list. assert(len(self.utxo)) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, CScript([OP_TRUE]))) tx.wit.vtxinwit.append(CTxInWitness()) tx.wit.vtxinwit[0].scriptWitness.stack = [ b'a' ] tx.rehash() tx_hash = tx.sha256 tx_value = tx.vout[0].nValue # Verify that if a peer doesn't set nServices to include NODE_WITNESS, # the getdata is just for the non-witness portion. self.old_node.announce_tx_and_wait_for_getdata(tx) assert(self.old_node.last_getdata.inv[0].type == 1) # Since we haven't delivered the tx yet, inv'ing the same tx from # a witness transaction ought not result in a getdata. try: self.test_node.announce_tx_and_wait_for_getdata(tx, timeout=2) self.log.error("Error: duplicate tx getdata!") assert(False) except AssertionError as e: pass # Delivering this transaction with witness should fail (no matter who # its from) assert_equal(len(self.nodes[0].getrawmempool()), 0) assert_equal(len(self.nodes[1].getrawmempool()), 0) self.old_node.test_transaction_acceptance(tx, with_witness=True, accepted=False) self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=False) # But eliminating the witness should fix it self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True) # Cleanup: mine the first transaction and update utxo self.nodes[0].generate(1) assert_equal(len(self.nodes[0].getrawmempool()), 0) self.utxo.pop(0) self.utxo.append(UTXO(tx_hash, 0, tx_value)) # After segwit activates, verify that mempool: # - rejects transactions with unnecessary/extra witnesses # - accepts transactions with valid witnesses # and that witness transactions are relayed to non-upgraded peers. def test_tx_relay_after_segwit_activation(self): self.log.info("Testing relay of witness transactions") # Generate a transaction that doesn't require a witness, but send it # with a witness. Should be rejected because we can't use a witness # when spending a non-witness output. assert(len(self.utxo)) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, CScript([OP_TRUE]))) tx.wit.vtxinwit.append(CTxInWitness()) tx.wit.vtxinwit[0].scriptWitness.stack = [ b'a' ] tx.rehash() tx_hash = tx.sha256 # Verify that unnecessary witnesses are rejected. self.test_node.announce_tx_and_wait_for_getdata(tx) assert_equal(len(self.nodes[0].getrawmempool()), 0) self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=False) # Verify that removing the witness succeeds. self.test_node.announce_tx_and_wait_for_getdata(tx) self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True) # Now try to add extra witness data to a valid witness tx. witness_program = CScript([OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx_hash, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, scriptPubKey)) tx2.rehash() tx3 = CTransaction() tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), b"")) tx3.wit.vtxinwit.append(CTxInWitness()) # Add too-large for IsStandard witness and check that it does not enter reject filter p2sh_program = CScript([OP_TRUE]) p2sh_pubkey = hash160(p2sh_program) witness_program2 = CScript([b'a'*400000]) tx3.vout.append(CTxOut(tx2.vout[0].nValue-1000, CScript([OP_HASH160, p2sh_pubkey, OP_EQUAL]))) tx3.wit.vtxinwit[0].scriptWitness.stack = [witness_program2] tx3.rehash() # Node will not be blinded to the transaction self.std_node.announce_tx_and_wait_for_getdata(tx3) self.std_node.test_transaction_acceptance(tx3, True, False, b'tx-size') self.std_node.announce_tx_and_wait_for_getdata(tx3) self.std_node.test_transaction_acceptance(tx3, True, False, b'tx-size') # Remove witness stuffing, instead add extra witness push on stack tx3.vout[0] = CTxOut(tx2.vout[0].nValue-1000, CScript([OP_TRUE])) tx3.wit.vtxinwit[0].scriptWitness.stack = [CScript([CScriptNum(1)]), witness_program ] tx3.rehash() self.test_node.test_transaction_acceptance(tx2, with_witness=True, accepted=True) self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=False) # Get rid of the extra witness, and verify acceptance. tx3.wit.vtxinwit[0].scriptWitness.stack = [ witness_program ] # Also check that old_node gets a tx announcement, even though this is # a witness transaction. self.old_node.wait_for_inv(CInv(1, tx2.sha256)) # wait until tx2 was inv'ed self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=True) self.old_node.wait_for_inv(CInv(1, tx3.sha256)) # Test that getrawtransaction returns correct witness information # hash, size, vsize raw_tx = self.nodes[0].getrawtransaction(tx3.hash, 1) assert_equal(int(raw_tx["hash"], 16), tx3.calc_sha256(True)) assert_equal(raw_tx["size"], len(tx3.serialize_with_witness())) vsize = (len(tx3.serialize_with_witness()) + 3*len(tx3.serialize_without_witness()) + 3) / 4 assert_equal(raw_tx["vsize"], vsize) assert_equal(len(raw_tx["vin"][0]["txinwitness"]), 1) assert_equal(raw_tx["vin"][0]["txinwitness"][0], hexlify(witness_program).decode('ascii')) assert(vsize != raw_tx["size"]) # Cleanup: mine the transactions and update utxo for next test self.nodes[0].generate(1) assert_equal(len(self.nodes[0].getrawmempool()), 0) self.utxo.pop(0) self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) # Test that block requests to NODE_WITNESS peer are with MSG_WITNESS_FLAG # This is true regardless of segwit activation. # Also test that we don't ask for blocks from unupgraded peers def test_block_relay(self, segwit_activated): self.log.info("Testing block relay") blocktype = 2|MSG_WITNESS_FLAG # test_node has set NODE_WITNESS, so all getdata requests should be for # witness blocks. # Test announcing a block via inv results in a getdata, and that # announcing a version 4 or random VB block with a header results in a getdata block1 = self.build_next_block() block1.solve() self.test_node.announce_block_and_wait_for_getdata(block1, use_header=False) assert(self.test_node.last_getdata.inv[0].type == blocktype) self.test_node.test_witness_block(block1, True) block2 = self.build_next_block(nVersion=4) block2.solve() self.test_node.announce_block_and_wait_for_getdata(block2, use_header=True) assert(self.test_node.last_getdata.inv[0].type == blocktype) self.test_node.test_witness_block(block2, True) block3 = self.build_next_block(nVersion=(VB_TOP_BITS | (1<<15))) block3.solve() self.test_node.announce_block_and_wait_for_getdata(block3, use_header=True) assert(self.test_node.last_getdata.inv[0].type == blocktype) self.test_node.test_witness_block(block3, True) # Check that we can getdata for witness blocks or regular blocks, # and the right thing happens. if segwit_activated == False: # Before activation, we should be able to request old blocks with # or without witness, and they should be the same. chain_height = self.nodes[0].getblockcount() # Pick 10 random blocks on main chain, and verify that getdata's # for MSG_BLOCK, MSG_WITNESS_BLOCK, and rpc getblock() are equal. all_heights = list(range(chain_height+1)) random.shuffle(all_heights) all_heights = all_heights[0:10] for height in all_heights: block_hash = self.nodes[0].getblockhash(height) rpc_block = self.nodes[0].getblock(block_hash, False) block_hash = int(block_hash, 16) block = self.test_node.request_block(block_hash, 2) wit_block = self.test_node.request_block(block_hash, 2|MSG_WITNESS_FLAG) assert_equal(block.serialize(True), wit_block.serialize(True)) assert_equal(block.serialize(), hex_str_to_bytes(rpc_block)) else: # After activation, witness blocks and non-witness blocks should # be different. Verify rpc getblock() returns witness blocks, while # getdata respects the requested type. block = self.build_next_block() self.update_witness_block_with_transactions(block, []) # This gives us a witness commitment. assert(len(block.vtx[0].wit.vtxinwit) == 1) assert(len(block.vtx[0].wit.vtxinwit[0].scriptWitness.stack) == 1) self.test_node.test_witness_block(block, accepted=True) # Now try to retrieve it... rpc_block = self.nodes[0].getblock(block.hash, False) non_wit_block = self.test_node.request_block(block.sha256, 2) wit_block = self.test_node.request_block(block.sha256, 2|MSG_WITNESS_FLAG) assert_equal(wit_block.serialize(True), hex_str_to_bytes(rpc_block)) assert_equal(wit_block.serialize(False), non_wit_block.serialize()) assert_equal(wit_block.serialize(True), block.serialize(True)) # Test size, vsize, weight rpc_details = self.nodes[0].getblock(block.hash, True) assert_equal(rpc_details["size"], len(block.serialize(True))) assert_equal(rpc_details["strippedsize"], len(block.serialize(False))) weight = 3*len(block.serialize(False)) + len(block.serialize(True)) assert_equal(rpc_details["weight"], weight) # Upgraded node should not ask for blocks from unupgraded block4 = self.build_next_block(nVersion=4) block4.solve() self.old_node.getdataset = set() # Blocks can be requested via direct-fetch (immediately upon processing the announcement) # or via parallel download (with an indeterminate delay from processing the announcement) # so to test that a block is NOT requested, we could guess a time period to sleep for, # and then check. We can avoid the sleep() by taking advantage of transaction getdata's # being processed after block getdata's, and announce a transaction as well, # and then check to see if that particular getdata has been received. self.old_node.announce_block(block4, use_header=False) self.old_node.announce_tx_and_wait_for_getdata(block4.vtx[0]) assert(block4.sha256 not in self.old_node.getdataset) # V0 segwit outputs should be standard after activation, but not before. def test_standardness_v0(self, segwit_activated): self.log.info("Testing standardness of v0 outputs (%s activation)" % ("after" if segwit_activated else "before")) assert(len(self.utxo)) witness_program = CScript([OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) p2sh_pubkey = hash160(witness_program) p2sh_scriptPubKey = CScript([OP_HASH160, p2sh_pubkey, OP_EQUAL]) # First prepare a p2sh output (so that spending it will pass standardness) p2sh_tx = CTransaction() p2sh_tx.vin = [CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")] p2sh_tx.vout = [CTxOut(self.utxo[0].nValue-1000, p2sh_scriptPubKey)] p2sh_tx.rehash() # Mine it on test_node to create the confirmed output. self.test_node.test_transaction_acceptance(p2sh_tx, with_witness=True, accepted=True) self.nodes[0].generate(1) sync_blocks(self.nodes) # Now test standardness of v0 P2WSH outputs. # Start by creating a transaction with two outputs. tx = CTransaction() tx.vin = [CTxIn(COutPoint(p2sh_tx.sha256, 0), CScript([witness_program]))] tx.vout = [CTxOut(p2sh_tx.vout[0].nValue-10000, scriptPubKey)] tx.vout.append(CTxOut(8000, scriptPubKey)) # Might burn this later tx.rehash() self.std_node.test_transaction_acceptance(tx, with_witness=True, accepted=segwit_activated) # Now create something that looks like a P2PKH output. This won't be spendable. scriptPubKey = CScript([OP_0, hash160(witness_hash)]) tx2 = CTransaction() if segwit_activated: # if tx was accepted, then we spend the second output. tx2.vin = [CTxIn(COutPoint(tx.sha256, 1), b"")] tx2.vout = [CTxOut(7000, scriptPubKey)] tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [witness_program] else: # if tx wasn't accepted, we just re-spend the p2sh output we started with. tx2.vin = [CTxIn(COutPoint(p2sh_tx.sha256, 0), CScript([witness_program]))] tx2.vout = [CTxOut(p2sh_tx.vout[0].nValue-1000, scriptPubKey)] tx2.rehash() self.std_node.test_transaction_acceptance(tx2, with_witness=True, accepted=segwit_activated) # Now update self.utxo for later tests. tx3 = CTransaction() if segwit_activated: # tx and tx2 were both accepted. Don't bother trying to reclaim the # P2PKH output; just send tx's first output back to an anyone-can-spend. sync_mempools([self.nodes[0], self.nodes[1]]) tx3.vin = [CTxIn(COutPoint(tx.sha256, 0), b"")] tx3.vout = [CTxOut(tx.vout[0].nValue-1000, CScript([OP_TRUE]))] tx3.wit.vtxinwit.append(CTxInWitness()) tx3.wit.vtxinwit[0].scriptWitness.stack = [witness_program] tx3.rehash() self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=True) else: # tx and tx2 didn't go anywhere; just clean up the p2sh_tx output. tx3.vin = [CTxIn(COutPoint(p2sh_tx.sha256, 0), CScript([witness_program]))] tx3.vout = [CTxOut(p2sh_tx.vout[0].nValue-1000, witness_program)] tx3.rehash() self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=True) self.nodes[0].generate(1) sync_blocks(self.nodes) self.utxo.pop(0) self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) assert_equal(len(self.nodes[1].getrawmempool()), 0) # Verify that future segwit upgraded transactions are non-standard, # but valid in blocks. Can run this before and after segwit activation. def test_segwit_versions(self): self.log.info("Testing standardness/consensus for segwit versions (0-16)") assert(len(self.utxo)) NUM_TESTS = 17 # will test OP_0, OP1, ..., OP_16 if (len(self.utxo) < NUM_TESTS): tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) split_value = (self.utxo[0].nValue - 4000) // NUM_TESTS for i in range(NUM_TESTS): tx.vout.append(CTxOut(split_value, CScript([OP_TRUE]))) tx.rehash() block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) self.utxo.pop(0) for i in range(NUM_TESTS): self.utxo.append(UTXO(tx.sha256, i, split_value)) sync_blocks(self.nodes) temp_utxo = [] tx = CTransaction() count = 0 witness_program = CScript([OP_TRUE]) witness_hash = sha256(witness_program) assert_equal(len(self.nodes[1].getrawmempool()), 0) for version in list(range(OP_1, OP_16+1)) + [OP_0]: count += 1 # First try to spend to a future version segwit scriptPubKey. scriptPubKey = CScript([CScriptOp(version), witness_hash]) tx.vin = [CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")] tx.vout = [CTxOut(self.utxo[0].nValue-1000, scriptPubKey)] tx.rehash() self.std_node.test_transaction_acceptance(tx, with_witness=True, accepted=False) self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=True) self.utxo.pop(0) temp_utxo.append(UTXO(tx.sha256, 0, tx.vout[0].nValue)) self.nodes[0].generate(1) # Mine all the transactions sync_blocks(self.nodes) assert(len(self.nodes[0].getrawmempool()) == 0) # Finally, verify that version 0 -> version 1 transactions # are non-standard scriptPubKey = CScript([CScriptOp(OP_1), witness_hash]) tx2 = CTransaction() tx2.vin = [CTxIn(COutPoint(tx.sha256, 0), b"")] tx2.vout = [CTxOut(tx.vout[0].nValue-1000, scriptPubKey)] tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [ witness_program ] tx2.rehash() # Gets accepted to test_node, because standardness of outputs isn't # checked with fRequireStandard self.test_node.test_transaction_acceptance(tx2, with_witness=True, accepted=True) self.std_node.test_transaction_acceptance(tx2, with_witness=True, accepted=False) temp_utxo.pop() # last entry in temp_utxo was the output we just spent temp_utxo.append(UTXO(tx2.sha256, 0, tx2.vout[0].nValue)) # Spend everything in temp_utxo back to an OP_TRUE output. tx3 = CTransaction() total_value = 0 for i in temp_utxo: tx3.vin.append(CTxIn(COutPoint(i.sha256, i.n), b"")) tx3.wit.vtxinwit.append(CTxInWitness()) total_value += i.nValue tx3.wit.vtxinwit[-1].scriptWitness.stack = [witness_program] tx3.vout.append(CTxOut(total_value - 1000, CScript([OP_TRUE]))) tx3.rehash() # Spending a higher version witness output is not allowed by policy, # even with fRequireStandard=false. self.test_node.test_transaction_acceptance(tx3, with_witness=True, accepted=False) self.test_node.sync_with_ping() with mininode_lock: assert(b"reserved for soft-fork upgrades" in self.test_node.last_reject.reason) # Building a block with the transaction must be valid, however. block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx2, tx3]) self.test_node.test_witness_block(block, accepted=True) sync_blocks(self.nodes) # Add utxo to our list self.utxo.append(UTXO(tx3.sha256, 0, tx3.vout[0].nValue)) def test_premature_coinbase_witness_spend(self): self.log.info("Testing premature coinbase witness spend") block = self.build_next_block() # Change the output of the block to be a witness output. witness_program = CScript([OP_TRUE]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) block.vtx[0].vout[0].scriptPubKey = scriptPubKey # This next line will rehash the coinbase and update the merkle # root, and solve. self.update_witness_block_with_transactions(block, []) self.test_node.test_witness_block(block, accepted=True) spend_tx = CTransaction() spend_tx.vin = [CTxIn(COutPoint(block.vtx[0].sha256, 0), b"")] spend_tx.vout = [CTxOut(block.vtx[0].vout[0].nValue, witness_program)] spend_tx.wit.vtxinwit.append(CTxInWitness()) spend_tx.wit.vtxinwit[0].scriptWitness.stack = [ witness_program ] spend_tx.rehash() # Now test a premature spend. self.nodes[0].generate(98) sync_blocks(self.nodes) block2 = self.build_next_block() self.update_witness_block_with_transactions(block2, [spend_tx]) self.test_node.test_witness_block(block2, accepted=False) # Advancing one more block should allow the spend. self.nodes[0].generate(1) block2 = self.build_next_block() self.update_witness_block_with_transactions(block2, [spend_tx]) self.test_node.test_witness_block(block2, accepted=True) sync_blocks(self.nodes) def test_signature_version_1(self): self.log.info("Testing segwit signature hash version 1") key = CECKey() key.set_secretbytes(b"9") pubkey = CPubKey(key.get_pubkey()) witness_program = CScript([pubkey, CScriptOp(OP_CHECKSIG)]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) # First create a witness output for use in the tests. assert(len(self.utxo)) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, scriptPubKey)) tx.rehash() self.test_node.test_transaction_acceptance(tx, with_witness=True, accepted=True) # Mine this transaction in preparation for following tests. block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) sync_blocks(self.nodes) self.utxo.pop(0) # Test each hashtype prev_utxo = UTXO(tx.sha256, 0, tx.vout[0].nValue) for sigflag in [ 0, SIGHASH_ANYONECANPAY ]: for hashtype in [SIGHASH_ALL, SIGHASH_NONE, SIGHASH_SINGLE]: hashtype |= sigflag block = self.build_next_block() tx = CTransaction() tx.vin.append(CTxIn(COutPoint(prev_utxo.sha256, prev_utxo.n), b"")) tx.vout.append(CTxOut(prev_utxo.nValue - 1000, scriptPubKey)) tx.wit.vtxinwit.append(CTxInWitness()) # Too-large input value sign_P2PK_witness_input(witness_program, tx, 0, hashtype, prev_utxo.nValue+1, key) self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=False) # Too-small input value sign_P2PK_witness_input(witness_program, tx, 0, hashtype, prev_utxo.nValue-1, key) block.vtx.pop() # remove last tx self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=False) # Now try correct value sign_P2PK_witness_input(witness_program, tx, 0, hashtype, prev_utxo.nValue, key) block.vtx.pop() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) prev_utxo = UTXO(tx.sha256, 0, tx.vout[0].nValue) # Test combinations of signature hashes. # Split the utxo into a lot of outputs. # Randomly choose up to 10 to spend, sign with different hashtypes, and # output to a random number of outputs. Repeat NUM_TESTS times. # Ensure that we've tested a situation where we use SIGHASH_SINGLE with # an input index > number of outputs. NUM_TESTS = 500 temp_utxos = [] tx = CTransaction() tx.vin.append(CTxIn(COutPoint(prev_utxo.sha256, prev_utxo.n), b"")) split_value = prev_utxo.nValue // NUM_TESTS for i in range(NUM_TESTS): tx.vout.append(CTxOut(split_value, scriptPubKey)) tx.wit.vtxinwit.append(CTxInWitness()) sign_P2PK_witness_input(witness_program, tx, 0, SIGHASH_ALL, prev_utxo.nValue, key) for i in range(NUM_TESTS): temp_utxos.append(UTXO(tx.sha256, i, split_value)) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) block = self.build_next_block() used_sighash_single_out_of_bounds = False for i in range(NUM_TESTS): # Ping regularly to keep the connection alive if (not i % 100): self.test_node.sync_with_ping() # Choose random number of inputs to use. num_inputs = random.randint(1, 10) # Create a slight bias for producing more utxos num_outputs = random.randint(1, 11) random.shuffle(temp_utxos) assert(len(temp_utxos) > num_inputs) tx = CTransaction() total_value = 0 for i in range(num_inputs): tx.vin.append(CTxIn(COutPoint(temp_utxos[i].sha256, temp_utxos[i].n), b"")) tx.wit.vtxinwit.append(CTxInWitness()) total_value += temp_utxos[i].nValue split_value = total_value // num_outputs for i in range(num_outputs): tx.vout.append(CTxOut(split_value, scriptPubKey)) for i in range(num_inputs): # Now try to sign each input, using a random hashtype. anyonecanpay = 0 if random.randint(0, 1): anyonecanpay = SIGHASH_ANYONECANPAY hashtype = random.randint(1, 3) | anyonecanpay sign_P2PK_witness_input(witness_program, tx, i, hashtype, temp_utxos[i].nValue, key) if (hashtype == SIGHASH_SINGLE and i >= num_outputs): used_sighash_single_out_of_bounds = True tx.rehash() for i in range(num_outputs): temp_utxos.append(UTXO(tx.sha256, i, split_value)) temp_utxos = temp_utxos[num_inputs:] block.vtx.append(tx) # Test the block periodically, if we're close to maxblocksize if (get_virtual_size(block) > MAX_BLOCK_BASE_SIZE - 1000): self.update_witness_block_with_transactions(block, []) self.test_node.test_witness_block(block, accepted=True) block = self.build_next_block() if (not used_sighash_single_out_of_bounds): self.log.info("WARNING: this test run didn't attempt SIGHASH_SINGLE with out-of-bounds index value") # Test the transactions we've added to the block if (len(block.vtx) > 1): self.update_witness_block_with_transactions(block, []) self.test_node.test_witness_block(block, accepted=True) # Now test witness version 0 P2PKH transactions pubkeyhash = hash160(pubkey) scriptPKH = CScript([OP_0, pubkeyhash]) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(temp_utxos[0].sha256, temp_utxos[0].n), b"")) tx.vout.append(CTxOut(temp_utxos[0].nValue, scriptPKH)) tx.wit.vtxinwit.append(CTxInWitness()) sign_P2PK_witness_input(witness_program, tx, 0, SIGHASH_ALL, temp_utxos[0].nValue, key) tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue, CScript([OP_TRUE]))) script = GetP2PKHScript(pubkeyhash) sig_hash = SegwitVersion1SignatureHash(script, tx2, 0, SIGHASH_ALL, tx.vout[0].nValue) signature = key.sign(sig_hash) + b'\x01' # 0x1 is SIGHASH_ALL # Check that we can't have a scriptSig tx2.vin[0].scriptSig = CScript([signature, pubkey]) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx, tx2]) self.test_node.test_witness_block(block, accepted=False) # Move the signature to the witness. block.vtx.pop() tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [signature, pubkey] tx2.vin[0].scriptSig = b"" tx2.rehash() self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=True) temp_utxos.pop(0) # Update self.utxos for later tests. Just spend everything in # temp_utxos to a corresponding entry in self.utxos tx = CTransaction() index = 0 for i in temp_utxos: # Just spend to our usual anyone-can-spend output # Use SIGHASH_SINGLE|SIGHASH_ANYONECANPAY so we can build up # the signatures as we go. tx.vin.append(CTxIn(COutPoint(i.sha256, i.n), b"")) tx.vout.append(CTxOut(i.nValue, CScript([OP_TRUE]))) tx.wit.vtxinwit.append(CTxInWitness()) sign_P2PK_witness_input(witness_program, tx, index, SIGHASH_SINGLE|SIGHASH_ANYONECANPAY, i.nValue, key) index += 1 block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) for i in range(len(tx.vout)): self.utxo.append(UTXO(tx.sha256, i, tx.vout[i].nValue)) # Test P2SH wrapped witness programs. def test_p2sh_witness(self, segwit_activated): self.log.info("Testing P2SH witness transactions") assert(len(self.utxo)) # Prepare the p2sh-wrapped witness output witness_program = CScript([OP_DROP, OP_TRUE]) witness_hash = sha256(witness_program) p2wsh_pubkey = CScript([OP_0, witness_hash]) p2sh_witness_hash = hash160(p2wsh_pubkey) scriptPubKey = CScript([OP_HASH160, p2sh_witness_hash, OP_EQUAL]) scriptSig = CScript([p2wsh_pubkey]) # a push of the redeem script # Fund the P2SH output tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) tx.vout.append(CTxOut(self.utxo[0].nValue-1000, scriptPubKey)) tx.rehash() # Verify mempool acceptance and block validity self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True, with_witness=segwit_activated) sync_blocks(self.nodes) # Now test attempts to spend the output. spend_tx = CTransaction() spend_tx.vin.append(CTxIn(COutPoint(tx.sha256, 0), scriptSig)) spend_tx.vout.append(CTxOut(tx.vout[0].nValue-1000, CScript([OP_TRUE]))) spend_tx.rehash() # This transaction should not be accepted into the mempool pre- or # post-segwit. Mempool acceptance will use SCRIPT_VERIFY_WITNESS which # will require a witness to spend a witness program regardless of # segwit activation. Note that older bitcoind's that are not # segwit-aware would also reject this for failing CLEANSTACK. self.test_node.test_transaction_acceptance(spend_tx, with_witness=False, accepted=False) # Try to put the witness script in the scriptSig, should also fail. spend_tx.vin[0].scriptSig = CScript([p2wsh_pubkey, b'a']) spend_tx.rehash() self.test_node.test_transaction_acceptance(spend_tx, with_witness=False, accepted=False) # Now put the witness script in the witness, should succeed after # segwit activates. spend_tx.vin[0].scriptSig = scriptSig spend_tx.rehash() spend_tx.wit.vtxinwit.append(CTxInWitness()) spend_tx.wit.vtxinwit[0].scriptWitness.stack = [ b'a', witness_program ] # Verify mempool acceptance self.test_node.test_transaction_acceptance(spend_tx, with_witness=True, accepted=segwit_activated) block = self.build_next_block() self.update_witness_block_with_transactions(block, [spend_tx]) # If we're before activation, then sending this without witnesses # should be valid. If we're after activation, then sending this with # witnesses should be valid. if segwit_activated: self.test_node.test_witness_block(block, accepted=True) else: self.test_node.test_witness_block(block, accepted=True, with_witness=False) # Update self.utxo self.utxo.pop(0) self.utxo.append(UTXO(spend_tx.sha256, 0, spend_tx.vout[0].nValue)) # Test the behavior of starting up a segwit-aware node after the softfork # has activated. As segwit requires different block data than pre-segwit # nodes would have stored, this requires special handling. # To enable this test, pass --oldbinary=<path-to-pre-segwit-bitcoind> to # the test. def test_upgrade_after_activation(self, node, node_id): self.log.info("Testing software upgrade after softfork activation") assert(node_id != 0) # node0 is assumed to be a segwit-active bitcoind # Make sure the nodes are all up sync_blocks(self.nodes) # Restart with the new binary stop_node(node, node_id) self.nodes[node_id] = start_node(node_id, self.options.tmpdir) connect_nodes(self.nodes[0], node_id) sync_blocks(self.nodes) # Make sure that this peer thinks segwit has activated. assert(get_bip9_status(node, 'segwit')['status'] == "active") # Make sure this peers blocks match those of node0. height = node.getblockcount() while height >= 0: block_hash = node.getblockhash(height) assert_equal(block_hash, self.nodes[0].getblockhash(height)) assert_equal(self.nodes[0].getblock(block_hash), node.getblock(block_hash)) height -= 1 def test_witness_sigops(self): '''Ensure sigop counting is correct inside witnesses.''' self.log.info("Testing sigops limit") assert(len(self.utxo)) # Keep this under MAX_OPS_PER_SCRIPT (201) witness_program = CScript([OP_TRUE, OP_IF, OP_TRUE, OP_ELSE] + [OP_CHECKMULTISIG]*5 + [OP_CHECKSIG]*193 + [OP_ENDIF]) witness_hash = sha256(witness_program) scriptPubKey = CScript([OP_0, witness_hash]) sigops_per_script = 20*5 + 193*1 # We'll produce 2 extra outputs, one with a program that would take us # over max sig ops, and one with a program that would exactly reach max # sig ops outputs = (MAX_SIGOP_COST // sigops_per_script) + 2 extra_sigops_available = MAX_SIGOP_COST % sigops_per_script # We chose the number of checkmultisigs/checksigs to make this work: assert(extra_sigops_available < 100) # steer clear of MAX_OPS_PER_SCRIPT # This script, when spent with the first # N(=MAX_SIGOP_COST//sigops_per_script) outputs of our transaction, # would push us just over the block sigop limit. witness_program_toomany = CScript([OP_TRUE, OP_IF, OP_TRUE, OP_ELSE] + [OP_CHECKSIG]*(extra_sigops_available + 1) + [OP_ENDIF]) witness_hash_toomany = sha256(witness_program_toomany) scriptPubKey_toomany = CScript([OP_0, witness_hash_toomany]) # If we spend this script instead, we would exactly reach our sigop # limit (for witness sigops). witness_program_justright = CScript([OP_TRUE, OP_IF, OP_TRUE, OP_ELSE] + [OP_CHECKSIG]*(extra_sigops_available) + [OP_ENDIF]) witness_hash_justright = sha256(witness_program_justright) scriptPubKey_justright = CScript([OP_0, witness_hash_justright]) # First split our available utxo into a bunch of outputs split_value = self.utxo[0].nValue // outputs tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) for i in range(outputs): tx.vout.append(CTxOut(split_value, scriptPubKey)) tx.vout[-2].scriptPubKey = scriptPubKey_toomany tx.vout[-1].scriptPubKey = scriptPubKey_justright tx.rehash() block_1 = self.build_next_block() self.update_witness_block_with_transactions(block_1, [tx]) self.test_node.test_witness_block(block_1, accepted=True) tx2 = CTransaction() # If we try to spend the first n-1 outputs from tx, that should be # too many sigops. total_value = 0 for i in range(outputs-1): tx2.vin.append(CTxIn(COutPoint(tx.sha256, i), b"")) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[-1].scriptWitness.stack = [ witness_program ] total_value += tx.vout[i].nValue tx2.wit.vtxinwit[-1].scriptWitness.stack = [ witness_program_toomany ] tx2.vout.append(CTxOut(total_value, CScript([OP_TRUE]))) tx2.rehash() block_2 = self.build_next_block() self.update_witness_block_with_transactions(block_2, [tx2]) self.test_node.test_witness_block(block_2, accepted=False) # Try dropping the last input in tx2, and add an output that has # too many sigops (contributing to legacy sigop count). checksig_count = (extra_sigops_available // 4) + 1 scriptPubKey_checksigs = CScript([OP_CHECKSIG]*checksig_count) tx2.vout.append(CTxOut(0, scriptPubKey_checksigs)) tx2.vin.pop() tx2.wit.vtxinwit.pop() tx2.vout[0].nValue -= tx.vout[-2].nValue tx2.rehash() block_3 = self.build_next_block() self.update_witness_block_with_transactions(block_3, [tx2]) self.test_node.test_witness_block(block_3, accepted=False) # If we drop the last checksig in this output, the tx should succeed. block_4 = self.build_next_block() tx2.vout[-1].scriptPubKey = CScript([OP_CHECKSIG]*(checksig_count-1)) tx2.rehash() self.update_witness_block_with_transactions(block_4, [tx2]) self.test_node.test_witness_block(block_4, accepted=True) # Reset the tip back down for the next test sync_blocks(self.nodes) for x in self.nodes: x.invalidateblock(block_4.hash) # Try replacing the last input of tx2 to be spending the last # output of tx block_5 = self.build_next_block() tx2.vout.pop() tx2.vin.append(CTxIn(COutPoint(tx.sha256, outputs-1), b"")) tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[-1].scriptWitness.stack = [ witness_program_justright ] tx2.rehash() self.update_witness_block_with_transactions(block_5, [tx2]) self.test_node.test_witness_block(block_5, accepted=True) # TODO: test p2sh sigop counting def test_getblocktemplate_before_lockin(self): self.log.info("Testing getblocktemplate setting of segwit versionbit (before lockin)") # Node0 is segwit aware, node2 is not. for node in [self.nodes[0], self.nodes[2]]: gbt_results = node.getblocktemplate() block_version = gbt_results['version'] # If we're not indicating segwit support, we will still be # signalling for segwit activation. assert_equal((block_version & (1 << VB_WITNESS_BIT) != 0), node == self.nodes[0]) # If we don't specify the segwit rule, then we won't get a default # commitment. assert('default_witness_commitment' not in gbt_results) # Workaround: # Can either change the tip, or change the mempool and wait 5 seconds # to trigger a recomputation of getblocktemplate. txid = int(self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1), 16) # Using mocktime lets us avoid sleep() sync_mempools(self.nodes) self.nodes[0].setmocktime(int(time.time())+10) self.nodes[2].setmocktime(int(time.time())+10) for node in [self.nodes[0], self.nodes[2]]: gbt_results = node.getblocktemplate({"rules" : ["segwit"]}) block_version = gbt_results['version'] if node == self.nodes[2]: # If this is a non-segwit node, we should still not get a witness # commitment, nor a version bit signalling segwit. assert_equal(block_version & (1 << VB_WITNESS_BIT), 0) assert('default_witness_commitment' not in gbt_results) else: # For segwit-aware nodes, check the version bit and the witness # commitment are correct. assert(block_version & (1 << VB_WITNESS_BIT) != 0) assert('default_witness_commitment' in gbt_results) witness_commitment = gbt_results['default_witness_commitment'] # TODO: this duplicates some code from blocktools.py, would be nice # to refactor. # Check that default_witness_commitment is present. block = CBlock() witness_root = block.get_merkle_root([ser_uint256(0), ser_uint256(txid)]) check_commitment = uint256_from_str(hash256(ser_uint256(witness_root)+ser_uint256(0))) from test_framework.blocktools import WITNESS_COMMITMENT_HEADER output_data = WITNESS_COMMITMENT_HEADER + ser_uint256(check_commitment) script = CScript([OP_RETURN, output_data]) assert_equal(witness_commitment, bytes_to_hex_str(script)) # undo mocktime self.nodes[0].setmocktime(0) self.nodes[2].setmocktime(0) # Uncompressed pubkeys are no longer supported in default relay policy, # but (for now) are still valid in blocks. def test_uncompressed_pubkey(self): self.log.info("Testing uncompressed pubkeys") # Segwit transactions using uncompressed pubkeys are not accepted # under default policy, but should still pass consensus. key = CECKey() key.set_secretbytes(b"9") key.set_compressed(False) pubkey = CPubKey(key.get_pubkey()) assert_equal(len(pubkey), 65) # This should be an uncompressed pubkey assert(len(self.utxo) > 0) utxo = self.utxo.pop(0) # Test 1: P2WPKH # First create a P2WPKH output that uses an uncompressed pubkey pubkeyhash = hash160(pubkey) scriptPKH = CScript([OP_0, pubkeyhash]) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(utxo.sha256, utxo.n), b"")) tx.vout.append(CTxOut(utxo.nValue-1000, scriptPKH)) tx.rehash() # Confirm it in a block. block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx]) self.test_node.test_witness_block(block, accepted=True) # Now try to spend it. Send it to a P2WSH output, which we'll # use in the next test. witness_program = CScript([pubkey, CScriptOp(OP_CHECKSIG)]) witness_hash = sha256(witness_program) scriptWSH = CScript([OP_0, witness_hash]) tx2 = CTransaction() tx2.vin.append(CTxIn(COutPoint(tx.sha256, 0), b"")) tx2.vout.append(CTxOut(tx.vout[0].nValue-1000, scriptWSH)) script = GetP2PKHScript(pubkeyhash) sig_hash = SegwitVersion1SignatureHash(script, tx2, 0, SIGHASH_ALL, tx.vout[0].nValue) signature = key.sign(sig_hash) + b'\x01' # 0x1 is SIGHASH_ALL tx2.wit.vtxinwit.append(CTxInWitness()) tx2.wit.vtxinwit[0].scriptWitness.stack = [ signature, pubkey ] tx2.rehash() # Should fail policy test. self.test_node.test_transaction_acceptance(tx2, True, False, b'non-mandatory-script-verify-flag (Using non-compressed keys in segwit)') # But passes consensus. block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx2]) self.test_node.test_witness_block(block, accepted=True) # Test 2: P2WSH # Try to spend the P2WSH output created in last test. # Send it to a P2SH(P2WSH) output, which we'll use in the next test. p2sh_witness_hash = hash160(scriptWSH) scriptP2SH = CScript([OP_HASH160, p2sh_witness_hash, OP_EQUAL]) scriptSig = CScript([scriptWSH]) tx3 = CTransaction() tx3.vin.append(CTxIn(COutPoint(tx2.sha256, 0), b"")) tx3.vout.append(CTxOut(tx2.vout[0].nValue-1000, scriptP2SH)) tx3.wit.vtxinwit.append(CTxInWitness()) sign_P2PK_witness_input(witness_program, tx3, 0, SIGHASH_ALL, tx2.vout[0].nValue, key) # Should fail policy test. self.test_node.test_transaction_acceptance(tx3, True, False, b'non-mandatory-script-verify-flag (Using non-compressed keys in segwit)') # But passes consensus. block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx3]) self.test_node.test_witness_block(block, accepted=True) # Test 3: P2SH(P2WSH) # Try to spend the P2SH output created in the last test. # Send it to a P2PKH output, which we'll use in the next test. scriptPubKey = GetP2PKHScript(pubkeyhash) tx4 = CTransaction() tx4.vin.append(CTxIn(COutPoint(tx3.sha256, 0), scriptSig)) tx4.vout.append(CTxOut(tx3.vout[0].nValue-1000, scriptPubKey)) tx4.wit.vtxinwit.append(CTxInWitness()) sign_P2PK_witness_input(witness_program, tx4, 0, SIGHASH_ALL, tx3.vout[0].nValue, key) # Should fail policy test. self.test_node.test_transaction_acceptance(tx4, True, False, b'non-mandatory-script-verify-flag (Using non-compressed keys in segwit)') block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx4]) self.test_node.test_witness_block(block, accepted=True) # Test 4: Uncompressed pubkeys should still be valid in non-segwit # transactions. tx5 = CTransaction() tx5.vin.append(CTxIn(COutPoint(tx4.sha256, 0), b"")) tx5.vout.append(CTxOut(tx4.vout[0].nValue-1000, CScript([OP_TRUE]))) (sig_hash, err) = SignatureHash(scriptPubKey, tx5, 0, SIGHASH_ALL) signature = key.sign(sig_hash) + b'\x01' # 0x1 is SIGHASH_ALL tx5.vin[0].scriptSig = CScript([signature, pubkey]) tx5.rehash() # Should pass policy and consensus. self.test_node.test_transaction_acceptance(tx5, True, True) block = self.build_next_block() self.update_witness_block_with_transactions(block, [tx5]) self.test_node.test_witness_block(block, accepted=True) self.utxo.append(UTXO(tx5.sha256, 0, tx5.vout[0].nValue)) def test_non_standard_witness(self): self.log.info("Testing detection of non-standard P2WSH witness") pad = chr(1).encode('latin-1') # Create scripts for tests scripts = [] scripts.append(CScript([OP_DROP] * 100)) scripts.append(CScript([OP_DROP] * 99)) scripts.append(CScript([pad * 59] * 59 + [OP_DROP] * 60)) scripts.append(CScript([pad * 59] * 59 + [OP_DROP] * 61)) p2wsh_scripts = [] assert(len(self.utxo)) tx = CTransaction() tx.vin.append(CTxIn(COutPoint(self.utxo[0].sha256, self.utxo[0].n), b"")) # For each script, generate a pair of P2WSH and P2SH-P2WSH output. outputvalue = (self.utxo[0].nValue - 1000) // (len(scripts) * 2) for i in scripts: p2wsh = CScript([OP_0, sha256(i)]) p2sh = hash160(p2wsh) p2wsh_scripts.append(p2wsh) tx.vout.append(CTxOut(outputvalue, p2wsh)) tx.vout.append(CTxOut(outputvalue, CScript([OP_HASH160, p2sh, OP_EQUAL]))) tx.rehash() txid = tx.sha256 self.test_node.test_transaction_acceptance(tx, with_witness=False, accepted=True) self.nodes[0].generate(1) sync_blocks(self.nodes) # Creating transactions for tests p2wsh_txs = [] p2sh_txs = [] for i in range(len(scripts)): p2wsh_tx = CTransaction() p2wsh_tx.vin.append(CTxIn(COutPoint(txid,i*2))) p2wsh_tx.vout.append(CTxOut(outputvalue - 5000, CScript([OP_0, hash160(hex_str_to_bytes(""))]))) p2wsh_tx.wit.vtxinwit.append(CTxInWitness()) p2wsh_tx.rehash() p2wsh_txs.append(p2wsh_tx) p2sh_tx = CTransaction() p2sh_tx.vin.append(CTxIn(COutPoint(txid,i*2+1), CScript([p2wsh_scripts[i]]))) p2sh_tx.vout.append(CTxOut(outputvalue - 5000, CScript([OP_0, hash160(hex_str_to_bytes(""))]))) p2sh_tx.wit.vtxinwit.append(CTxInWitness()) p2sh_tx.rehash() p2sh_txs.append(p2sh_tx) # Testing native P2WSH # Witness stack size, excluding witnessScript, over 100 is non-standard p2wsh_txs[0].wit.vtxinwit[0].scriptWitness.stack = [pad] * 101 + [scripts[0]] self.std_node.test_transaction_acceptance(p2wsh_txs[0], True, False, b'bad-witness-nonstandard') # Non-standard nodes should accept self.test_node.test_transaction_acceptance(p2wsh_txs[0], True, True) # Stack element size over 80 bytes is non-standard p2wsh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 81] * 100 + [scripts[1]] self.std_node.test_transaction_acceptance(p2wsh_txs[1], True, False, b'bad-witness-nonstandard') # Non-standard nodes should accept self.test_node.test_transaction_acceptance(p2wsh_txs[1], True, True) # Standard nodes should accept if element size is not over 80 bytes p2wsh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 80] * 100 + [scripts[1]] self.std_node.test_transaction_acceptance(p2wsh_txs[1], True, True) # witnessScript size at 3600 bytes is standard p2wsh_txs[2].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, scripts[2]] self.test_node.test_transaction_acceptance(p2wsh_txs[2], True, True) self.std_node.test_transaction_acceptance(p2wsh_txs[2], True, True) # witnessScript size at 3601 bytes is non-standard p2wsh_txs[3].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, pad, scripts[3]] self.std_node.test_transaction_acceptance(p2wsh_txs[3], True, False, b'bad-witness-nonstandard') # Non-standard nodes should accept self.test_node.test_transaction_acceptance(p2wsh_txs[3], True, True) # Repeating the same tests with P2SH-P2WSH p2sh_txs[0].wit.vtxinwit[0].scriptWitness.stack = [pad] * 101 + [scripts[0]] self.std_node.test_transaction_acceptance(p2sh_txs[0], True, False, b'bad-witness-nonstandard') self.test_node.test_transaction_acceptance(p2sh_txs[0], True, True) p2sh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 81] * 100 + [scripts[1]] self.std_node.test_transaction_acceptance(p2sh_txs[1], True, False, b'bad-witness-nonstandard') self.test_node.test_transaction_acceptance(p2sh_txs[1], True, True) p2sh_txs[1].wit.vtxinwit[0].scriptWitness.stack = [pad * 80] * 100 + [scripts[1]] self.std_node.test_transaction_acceptance(p2sh_txs[1], True, True) p2sh_txs[2].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, scripts[2]] self.test_node.test_transaction_acceptance(p2sh_txs[2], True, True) self.std_node.test_transaction_acceptance(p2sh_txs[2], True, True) p2sh_txs[3].wit.vtxinwit[0].scriptWitness.stack = [pad, pad, pad, scripts[3]] self.std_node.test_transaction_acceptance(p2sh_txs[3], True, False, b'bad-witness-nonstandard') self.test_node.test_transaction_acceptance(p2sh_txs[3], True, True) self.nodes[0].generate(1) # Mine and clean up the mempool of non-standard node # Valid but non-standard transactions in a block should be accepted by standard node sync_blocks(self.nodes) assert_equal(len(self.nodes[0].getrawmempool()), 0) assert_equal(len(self.nodes[1].getrawmempool()), 0) self.utxo.pop(0) def run_test(self): # Setup the p2p connections and start up the network thread. self.test_node = TestNode() # sets NODE_WITNESS|NODE_NETWORK self.old_node = TestNode() # only NODE_NETWORK self.std_node = TestNode() # for testing node1 (fRequireStandard=true) self.p2p_connections = [self.test_node, self.old_node] self.connections = [] self.connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], self.test_node, services=NODE_NETWORK|NODE_WITNESS)) self.connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], self.old_node, services=NODE_NETWORK)) self.connections.append(NodeConn('127.0.0.1', p2p_port(1), self.nodes[1], self.std_node, services=NODE_NETWORK|NODE_WITNESS)) self.test_node.add_connection(self.connections[0]) self.old_node.add_connection(self.connections[1]) self.std_node.add_connection(self.connections[2]) NetworkThread().start() # Start up network handling in another thread # Keep a place to store utxo's that can be used in later tests self.utxo = [] # Test logic begins here self.test_node.wait_for_verack() self.log.info("Starting tests before segwit lock in:") self.test_witness_services() # Verifies NODE_WITNESS self.test_non_witness_transaction() # non-witness tx's are accepted self.test_unnecessary_witness_before_segwit_activation() self.test_block_relay(segwit_activated=False) # Advance to segwit being 'started' self.advance_to_segwit_started() sync_blocks(self.nodes) self.test_getblocktemplate_before_lockin() sync_blocks(self.nodes) # At lockin, nothing should change. self.log.info("Testing behavior post lockin, pre-activation") self.advance_to_segwit_lockin() # Retest unnecessary witnesses self.test_unnecessary_witness_before_segwit_activation() self.test_witness_tx_relay_before_segwit_activation() self.test_block_relay(segwit_activated=False) self.test_p2sh_witness(segwit_activated=False) self.test_standardness_v0(segwit_activated=False) sync_blocks(self.nodes) # Now activate segwit self.log.info("Testing behavior after segwit activation") self.advance_to_segwit_active() sync_blocks(self.nodes) # Test P2SH witness handling again self.test_p2sh_witness(segwit_activated=True) self.test_witness_commitments() self.test_block_malleability() self.test_witness_block_size() self.test_submit_block() self.test_extra_witness_data() self.test_max_witness_push_length() self.test_max_witness_program_length() self.test_witness_input_length() self.test_block_relay(segwit_activated=True) self.test_tx_relay_after_segwit_activation() self.test_standardness_v0(segwit_activated=True) self.test_segwit_versions() self.test_premature_coinbase_witness_spend() self.test_uncompressed_pubkey() self.test_signature_version_1() self.test_non_standard_witness() sync_blocks(self.nodes) self.test_upgrade_after_activation(self.nodes[2], 2) self.test_witness_sigops() if __name__ == '__main__': SegWitTest().main()
mit
wenhulove333/ScutServer
Sample/Koudai/Server/release/Script/PyScript/Action/action1484.py
2
5026
import clr, sys clr.AddReference('ZyGames.Framework.Common'); clr.AddReference('ZyGames.Framework'); clr.AddReference('ZyGames.Framework.Game'); clr.AddReference('ZyGames.Tianjiexing.Model'); clr.AddReference('ZyGames.Tianjiexing.BLL'); clr.AddReference('ZyGames.Tianjiexing.Lang'); from action import * from lang import Lang from ZyGames.Framework.Common.Log import * from ZyGames.Tianjiexing.Model import * from ZyGames.Tianjiexing.BLL import * from ZyGames.Tianjiexing.Lang import * from ZyGames.Framework.Game.Cache import * from ZyGames.Framework.Game.Service import * from ZyGames.Framework.Common import * from ZyGames.Framework.Cache.Generic import * from ZyGames.Tianjiexing.Model.Config import * # 1484_佣兵技能更换接口 class UrlParam(HttpParam): def __init__(self): HttpParam.__init__(self) self.generaID = 0; self.abilityID = 0; self.userItemID = ''; self.ops = 0; self.Position = 0; class ActionResult(DataResult): def __init__(self): DataResult.__init__(self) def getUrlElement(httpGet, parent): urlParam = UrlParam(); if httpGet.Contains("Ops")\ and httpGet.Contains("AbilityID")\ and httpGet.Contains("UserItemID")\ and httpGet.Contains("GeneralID"): urlParam.ops = httpGet.GetIntValue("Ops", 0, 1 ) urlParam.abilityID = httpGet.GetIntValue("AbilityID") urlParam.userItemID = httpGet.GetStringValue("UserItemID", 36, 36 ) urlParam.generaID = httpGet.GetIntValue("GeneralID") urlParam.Position = httpGet.GetIntValue("Position") else: urlParam.Result = False; return urlParam def takeAction(urlParam, parent): actionResult = ActionResult(); userId = parent.Current.UserId; # 获取匹配的 GeneralID 记录 cacheSetGeneral = ConfigCacheSet[GeneralInfo](); general = cacheSetGeneral.FindKey(urlParam.generaID.ToString()) cacheSetAbility = ConfigCacheSet[AbilityInfo](); ability = cacheSetAbility.FindKey(urlParam.abilityID.ToString()); # 根据 UserID 和 GeneralID 获取匹配的一条记录 cacheSetUserGeneral = GameDataCacheSet[UserGeneral](); userGeneral = cacheSetUserGeneral.FindKey(userId.ToString(),urlParam.generaID.ToString()); # 根据 UserID 获取 AbilityList cacheSetUserAbility = GameDataCacheSet[UserAbility](); userAbility = cacheSetUserAbility.FindKey(userId.ToString()); if (userGeneral == None or userAbility == None or general == None or ability == None): parent.ErrorCode = LanguageManager.GetLang().ErrorCode; parent.ErrorInfo = LanguageManager.GetLang().LoadDataError; actionResult.Result = False; return actionResult; # 获取 JSON 中的一个匹配记录对象 userAbilityInfo = userAbility.AbilityList.Find(lambda x: x.UserItemID == urlParam.userItemID); if not userAbilityInfo: parent.ErrorCode = LanguageManager.GetLang().ErrorCode; parent.ErrorInfo = LanguageManager.GetLang().St1484_OperateDefaultAbility; actionResult.Result = False; return actionResult; # 当该魂技的值已经存在且佣兵的值不为0时,直接返回 #if userAbilityInfo.AbilityID == urlParam.abilityID and userAbilityInfo.GeneralID == userGeneral.GeneralID: ##if userAbilityInfo.AbilityID == urlParam.abilityID and userGeneral.GeneralID == urlParam.generaID: # actionResult.Result = False; # return actionResult; # 不允许对默认附带魂技进行操作(不管是装配还是卸下) if general.AbilityID == ability.AbilityID: parent.ErrorCode = Lang.getLang("ErrorCode"); parent.ErrorInfo = Lang.getLang("St1484_OperateDefaultAbilityError"); actionResult.Result = False; return actionResult; if urlParam.ops == 0: # 装配 # 查找该佣兵是否已经存在该魂技 isExist = userAbility.AbilityList.Find(lambda x: x.AbilityID == urlParam.abilityID and x.GeneralID == userGeneral.GeneralID); if isExist: parent.ErrorCode = Lang.getLang("ErrorCode"); parent.ErrorInfo = Lang.getLang("St1484_GeneralAndAbilityIsExist"); actionResult.Result = False; return actionResult; # 更换魂技(根据该佣兵ID和位置将原来的记录赋0) generalAbilitiyRecord = userAbility.AbilityList.Find(lambda x: x.GeneralID == urlParam.generaID and x.Position == urlParam.Position); if generalAbilitiyRecord: generalAbilitiyRecord.GeneralID = 0; generalAbilitiyRecord.Position = 0; userAbilityInfo.GeneralID = urlParam.generaID; userAbilityInfo.Position = urlParam.Position; else: # 卸下 userAbilityInfo.GeneralID = 0; userAbilityInfo.Position = 0; return actionResult; def buildPacket(writer, urlParam, actionResult): #输出 return True;
mit
nysan/yocto-autobuilder
lib/python2.6/site-packages/Twisted-11.0.0-py2.6-linux-x86_64.egg/twisted/lore/lmath.py
60
3037
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ LaTeX-defined image support for Lore documents. """ import os, tempfile from xml.dom import minidom as dom from twisted.web import domhelpers import latex, tree, lint, default class MathLatexSpitter(latex.LatexSpitter): start_html = '\\documentclass{amsart}\n' def visitNode_div_latexmacros(self, node): self.writer(domhelpers.getNodeText(node)) def visitNode_span_latexformula(self, node): self.writer('\[') self.writer(domhelpers.getNodeText(node)) self.writer('\]') def formulaeToImages(document, dir, _system=os.system): # gather all macros macros = '' for node in domhelpers.findElementsWithAttribute(document, 'class', 'latexmacros'): macros += domhelpers.getNodeText(node) node.parentNode.removeChild(node) i = 0 for node in domhelpers.findElementsWithAttribute(document, 'class', 'latexformula'): latexText='''\\documentclass[12pt]{amsart}%s \\begin{document}\[%s\] \\end{document}''' % (macros, domhelpers.getNodeText(node)) # This file really should be cleaned up by this function, or placed # somewhere such that the calling code can find it and clean it up. file = tempfile.mktemp() f = open(file+'.tex', 'w') f.write(latexText) f.close() _system('latex %s.tex' % file) _system('dvips %s.dvi -o %s.ps' % (os.path.basename(file), file)) baseimgname = 'latexformula%d.png' % i imgname = os.path.join(dir, baseimgname) i += 1 _system('pstoimg -type png -crop a -trans -interlace -out ' '%s %s.ps' % (imgname, file)) newNode = dom.parseString( '<span><br /><img src="%s" /><br /></span>' % ( baseimgname,)).documentElement node.parentNode.replaceChild(newNode, node) def doFile(fn, docsdir, ext, url, templ, linkrel='', d=None): d = d or {} doc = tree.parseFileAndReport(fn) formulaeToImages(doc, os.path.dirname(fn)) cn = templ.cloneNode(1) tree.munge(doc, cn, linkrel, docsdir, fn, ext, url, d) cn.writexml(open(os.path.splitext(fn)[0]+ext, 'wb')) class ProcessingFunctionFactory(default.ProcessingFunctionFactory): latexSpitters = {None: MathLatexSpitter} def getDoFile(self): return doFile def getLintChecker(self): checker = lint.getDefaultChecker() checker.allowedClasses = checker.allowedClasses.copy() oldDiv = checker.allowedClasses['div'] oldSpan = checker.allowedClasses['span'] checker.allowedClasses['div'] = lambda x:oldDiv(x) or x=='latexmacros' checker.allowedClasses['span'] = (lambda x:oldSpan(x) or x=='latexformula') return checker factory = ProcessingFunctionFactory()
gpl-2.0
rfaulkner/databayes
http/databayes_api/views.py
1
13088
""" Defines the routing endpoints of the RESTful API for databayes. Each method corresponds to an API action and returns the status of the action and the output. This layer handles communication to the databayes daemon. IMPORTANT NOTE! - Only one of these server instances should be running to avoid race conditions """ from databayes_api import app, log, redisio, config, \ gen_queue_id, exists_queue_item import json, time from flask import render_template, redirect, url_for, \ request, escape, flash, g, session, Response ERR_MSG_BADLY_FORMED_REQUEST = 'Malformed request, try again' # UTILITY METHODS def handle_queue_validation(): """ Method for handling queue validation in the view logic :return: """ qid = str(gen_queue_id()) iterations = 0 while exists_queue_item(qid): if iterations == config.REDIS_QUEUE_COUNTER_MAX: return -1 # Indicates failure qid = str(gen_queue_id()) iterations += 1 return str(qid) def unpack_query_params(request): """ Helper method to fetch query paramaters for command requests :param request: :return: """ ret = dict() ret['ok'] = True ret['types'] = [] ret['fields'] = [] ret['fields1'] = [] ret['fields2'] = [] ret['values1'] = [] ret['values2'] = [] ret['message'] = '' ret['fields'] = request.args.get('fields').split(',') \ if request.args.get('fields') else [] ret['types'] = request.args.get('types').split(',') \ if request.args.get('fields') else [] ret['fields1'] = request.args.get('fields1').split(',') \ if request.args.get('fields1') else [] ret['fields2'] = request.args.get('fields2').split(',') \ if request.args.get('fields2') else [] ret['values1'] = request.args.get('values1').split(',') \ if request.args.get('values1') else [] ret['values2'] = request.args.get('values2').split(',') \ if request.args.get('values2') else [] if len(ret['fields']) != len(ret['types']) or \ len(ret['fields1']) != len(ret['values1']) or \ len(ret['fields2']) != len(ret['values2']): ret['ok'] = False ret['message'] = 'Count of fields and types or values do not match' return ret def wait_for_response(qid, poll_frequency=10.0, max_tries=5): """ Handles polling a response from the redis queue determined by id. Returns an empty response if it never arrives. :param qid: int redis queue id :param poll_frequency: int millisecond frequency of a poll :param max_tries: int poll no more times than this :return: string response written to redis from the daemon """ rsp = "" for i in xrange(max_tries): rsp = redisio.DataIORedis().read(config.DBY_RSP_QUEUE_PREFIX + qid) if rsp: # got response, stop polling break time.sleep(float(poll_frequency) / 1000.0) return rsp # --- VIEW METHODS --- # ==================== def get_arg_str(fields, values, delimiter): """ Synthesizes argument strings for entity attributes for databayes. Length of fields and values must be equal. :param fields: list of field names :param values: list of field values :param delimeter: str, relevant delimeter :return: argument string """ items = [] for i in xrange(len(fields)): items.append(str(fields[i]) + str(delimiter) + str(values[i])) return ",".join(items) def view_switch(view, args): """ General method which implements view logic :param view: str, view to construct a response for :param args: view arguments passed along :return: text response from databayes or error """ log.debug('Processing view: "{0}"'.format(view)) log.debug('Processing args: "{0}"'.format(str(args))) query_param_obj = unpack_query_params(request) if (not query_param_obj['ok']): return Response(json.dumps([query_param_obj['message']]), mimetype='application/json') # Retrieve a valid queue item qid = handle_queue_validation() if qid == -1: return Response(json.dumps(['Queue is full, try again later.']), mimetype='application/json') # Construct command cmd = "" if view == 'define_entity': if 'values' in query_param_obj.keys() and \ 'fields' in query_param_obj.keys(): arg_str = get_arg_str(query_param_obj['fields'], query_param_obj['values'], '_') else: arg_str = "" log.info('Warning: entity has no attributes') cmd = 'def {0}({1})'.format(args['entity'], arg_str) \ if arg_str else 'def ' + str(args['entity']) elif view == 'add_relation': arg_str_1 = get_arg_str(query_param_obj['fields1'], query_param_obj['values1'], '=') arg_str_2 = get_arg_str(query_param_obj['fields2'], query_param_obj['values2'], '=') cmd = 'add rel {0}({1}) {2}({3})'.format(args['entity_1'], arg_str_1, args['entity_2'], arg_str_2) elif view == 'generate': pass elif view == 'list_entity': cmd = 'lst ent {0}'.format(args['pattern']) elif view == 'list_relation': arg_str_1 = get_arg_str(query_param_obj['fields1'], query_param_obj['values1'], '=') arg_str_2 = get_arg_str(query_param_obj['fields2'], query_param_obj['values2'], '=') cmd = 'lst rel {0}({1}) {2}({3})'.format(args['entity_1'], arg_str_1, args['entity_2'], arg_str_2) elif view == 'remove_entity': cmd = 'rm ent {0}'.format(args['entity']) elif view == 'remove_relation': arg_str_1 = get_arg_str(query_param_obj['fields1'], query_param_obj['values1'], '=') arg_str_2 = get_arg_str(query_param_obj['fields2'], query_param_obj['values2'], '=') cmd = 'rm rel {0}({1}) {2}({3})'.format(args['entity_1'], arg_str_1, args['entity_2'], arg_str_2) log.info('sending command: "{0}"'.format(cmd)) # Send cmd to databayes daemon redisio.DataIORedis().connect() redisio.DataIORedis().write(config.DBY_CMD_QUEUE_PREFIX + qid, cmd) # check response rsp = wait_for_response(qid) if not rsp: rsp = "Could not find response before max retires expired." return rsp def home(entity): """ Defines web interface to the tool and help. """ # TODO - add content here, primarily an interface to an instance # run on rackspace host return Response("Welcome to databayes!", mimetype='application/json') def version(entity): """ Basic version info for databayes """ return Response("databayes v1. 2015. Ryan Faulkner", mimetype='application/json') def define_entity(entity): """ Handles remote requests to databayes for entity definition Translation: def e(<f1>_<t1>, <f2>_<t2>, ...) -> /def/e?fields=f1,f2,...&types=t1,t2,... :return: JSON response indicating status of action & output """ try: return Response( json.dumps([view_switch('define_entity', {'entity': entity})]), mimetype='application/json') except Exception as e: log.error(e.message) return Response( json.dumps([ERR_MSG_BADLY_FORMED_REQUEST]), mimetype='application/json') def add_relation(entity_1, entity_2): """ Handles remote requests to databayes for adding relations Translation: add rel e1(<f1_1>_<v1_1>,...) e2(<f2_1>_<v2_1>,...) -> /add/rel/e1/e2?fields1=f1_1,...&types1=t1_1,... &fields2=f2_1,...&types2=t2_1,... :return: JSON response indicating status of action & output """ try: return Response( json.dumps([view_switch( 'add_relation', {'entity_1': entity_1, 'entity_2': entity_2})]), mimetype='application/json') except Exception as e: log.error(e.message) return Response( json.dumps([ERR_MSG_BADLY_FORMED_REQUEST]), mimetype='application/json') def generate(entity_1, entity_2): """ Handles remote requests to databayes for generating samples Translation: gen e1(<f1_1>_<v1_1>,...) constrain e2(<f2_1>_<v2_1>,...) -> /gen/e1/e2?fields1=f1_1,...&types1=t1_1,...&fields2=f2_1,...&types2=t2_1,... :return: JSON response indicating status of action & output """ try: return Response( json.dumps( [view_switch('generate', {'entity_1': entity_1, 'entity_2': entity_2})]), mimetype='application/json') except Exception as e: log.error(e.message) return Response( json.dumps([ERR_MSG_BADLY_FORMED_REQUEST]), mimetype='application/json') def list_entity(pattern): """ Handles remote requests to databayes for listing entities Translation: lst ent regex -> /lst/ent/regex :return: JSON response indicating status of action & output """ try: return Response( json.dumps([view_switch('list_entity', {'pattern': pattern})]), mimetype='application/json') except Exception as e: log.error(e.message) return Response( json.dumps([ERR_MSG_BADLY_FORMED_REQUEST]), mimetype='application/json') def list_relation(entity_1, entity_2): """ Handles remote requests to databayes for listing relations Translation: lst rel regex1 regex2 -> /lst/ent/regex1/regex2 :return: JSON response indicating status of action & output """ try: return Response( json.dumps( [view_switch('list_relation', {'entity_1': entity_1, 'entity_2': entity_2})]), mimetype='application/json') except Exception as e: log.error(e.message) return Response( json.dumps([ERR_MSG_BADLY_FORMED_REQUEST]), mimetype='application/json') def remove_entity(entity): """ Handles remote requests to databayes for removing entities Translation: rm ent e -> /rm/ent/e :return: JSON response indicating status of action & output """ try: return Response( json.dumps([view_switch('remove_entity', {'entity': entity})]), mimetype='application/json') except Exception as e: log.error(e.message) return Response( json.dumps([ERR_MSG_BADLY_FORMED_REQUEST]), mimetype='application/json') def remove_relation(entity_1, entity_2): """ Handles remote requests to databayes for removing relations Translation: rm rel e1(<f1_1>_<v1_1>,...) e2(<f2_1>_<v2_1>,...) -> /rm/rel/e1/e2?fields1=f1_1,...&values1=t1_1,...&fields2=f2_1, ...&values2=t2_1,... :return: JSON response indicating status of action & output """ try: return Response( json.dumps( [view_switch('remove_relation', {'entity_1': entity_1, 'entity_2': entity_2})]), mimetype='application/json') except Exception as e: log.error(e.message) return Response( json.dumps([ERR_MSG_BADLY_FORMED_REQUEST]), mimetype='application/json') # Stores view references in structure view_list = { home.__name__: home, version.__name__: version, define_entity.__name__: define_entity, add_relation.__name__: add_relation, generate.__name__: generate, list_entity.__name__: list_entity, list_relation.__name__: list_relation, remove_entity.__name__: remove_entity, remove_relation.__name__: remove_relation, } route_deco = { home.__name__: app.route('/', methods=['GET']), version.__name__: app.route('/v', methods=['GET']), define_entity.__name__: app.route('/def/<entity>', methods=['GET', 'POST']), add_relation.__name__: app.route('/add/<entity_1>/<entity_2>', methods=['GET', 'POST']), generate.__name__: app.route('/gen', methods=['GET', 'POST']), list_entity.__name__: app.route('/lst/ent/<pattern>', methods=['GET', 'POST']), list_relation.__name__: app.route('/lst/rel/<pattern_1>/<pattern_2>', methods=['GET', 'POST']), remove_entity.__name__: app.route('/rm/ent/<entity>', methods=['GET', 'POST']), remove_relation.__name__: app.route('/rm/rel/<entity_1>/<entity_2>', methods=['GET', 'POST']), } # Apply decorators to views def init_views(): for key in route_deco: log.info('Registering view - {0}'.format(key)) route = route_deco[key] view_method = view_list[key] view_list[key] = route(view_method)
apache-2.0
adharaengine/AdharaDB
test.py
1
9327
import unittest import tempfile from tempfile import NamedTemporaryFile from ZODB import DB, config from ZODB.FileStorage import FileStorage from db import Graph, Element, Edge, Node from backends import DictionaryBackend, ZODBBTreeBackend class TestGraph(unittest.TestCase): def setUp(self): self.g = Graph(DictionaryBackend()) def test_iter_(self): elements = self.g.add_nodes(4) elements.append(self.g.add_edge(elements[0], elements[1],{'keye':'valuee'})) elements.append(self.g.add_edge(elements[0], elements[2],{'keye':'valuee'})) self.assertEqual(len(elements),6) for n in self.g: self.assertIsInstance(n, Element) self.assertIn(n, elements) def test_getersetter_(self): node = self.g.add_node({'keyn':'valuen'}) self.g[node] = {'keyn2':'valuen2'} self.assertEqual(self.g[node], {'keyn':'valuen','keyn2':'valuen2'}) def test_add_node(self): n = self.g.add_node() self.assertIsInstance(n, Element) for node in self.g.nodes: self.assertIsInstance(node, Element) self.assertIn(n, self.g.nodes) def test_add_nodes(self): nodes = self.g.add_nodes(4) self.assertIsInstance(nodes,list) self.assertEqual(len(nodes),4) for n in nodes: self.assertIsInstance(n, Element) def test_nodes(self): self.g.add_nodes(5) for n in self.g.nodes: self.assertIsInstance(n, Element) def test_add_edge(self): nodes = self.g.add_nodes(5) for idx, val in enumerate(nodes): try: self.g.add_edge(val,nodes[idx+1]) except IndexError: pass for e in self.g.edges: self.assertIsInstance(e, Element) self.assertFalse(e.directed) def test_add_directed_edge(self): nodes = self.g.add_nodes(5) for idx, val in enumerate(nodes): try: self.g.add_edge(val,nodes[idx+1],directed=True) except IndexError: pass for e in self.g.edges: self.assertIsInstance(e, Element) self.assertTrue(e.directed) def test_add_edges(self): nodes = self.g.add_nodes(5) edge_list = [] for idx, val in enumerate(nodes): try: edge_list.append((val, nodes[idx+1], {'test':1, 't':'test'})) except IndexError: pass edges = self.g.add_edges(edge_list) for e in edges: self.assertIsInstance(e, Element) def test_get_attributes(self): node = self.g.add_node({'keyn':'valuen'}) node2 = self.g.add_node({'keyn2':'valuen2'}) edge = self.g.add_edge(node,node2,{'keye':'valuee'}) self.assertEqual(self.g[node],{'keyn':'valuen'}) self.assertEqual(self.g[node2],{'keyn2':'valuen2'}) self.assertEqual(self.g[edge],{'keye':'valuee'}) def test_add_attributes(self): node = self.g.add_node({'keyn':'valuen'}) self.g[node] = {'keyn2':'valuen2'} self.assertEqual(self.g[node], {'keyn':'valuen','keyn2':'valuen2'}) def test_del_node(self): node = self.g.add_node({'keyn':'valuen'}) node2 = self.g.add_node({'keyn2':'valuen2'}) self.g.del_node(node2) for n in self.g.nodes: self.assertEqual(n,node) for a in self.g.attribute_store: self.assertEqual(a,node) def test_del_edge(self): node = self.g.add_node({'keyn':'valuen'}) node2 = self.g.add_node({'keyn2':'valuen2'}) node3 = self.g.add_node({'keyn3':'valuen3'}) edge = self.g.add_edge(node,node2,{'keye':'valuee'}) edge2 = self.g.add_edge(node,node3,{'keye':'valuee'}) edge3 = self.g.add_edge(node2,node3) self.g.del_edge(edge2) for e in self.g.edges: self.assertIn(e,[edge,edge3]) for a in self.g.attribute_store: self.assertIn(e,[node,node2,node3,edge,edge3]) def test_graph(self): n1 = self.g.add_node() n2 = self.g.add_node() n3 = self.g.add_node() e1 = self.g.add_edge(n1,n2) e2 = self.g.add_edge(n1,n3) self.assertIn(e1,self.g.edges) self.assertIn(e2,self.g.edges) self.assertIn(n2, n1.neighbors) self.assertIn(n1, n2.neighbors) self.assertIn(n3, n1.neighbors) def test_add_weighted_node(self): n = self.g.add_node(weight=7) self.assertIsInstance(n, Element) for node in self.g.nodes: self.assertIsInstance(node, Element) self.assertIn(n, self.g.nodes) self.assertEqual(n.weight, 7) class TestGraphZODB(TestGraph): def setUp(self): storage = FileStorage(NamedTemporaryFile().name) db = DB(storage) connection = db.open() root = connection.root self.g = Graph(backend=ZODBBTreeBackend(root)) class TestElement(unittest.TestCase): def setUp(self): self.g = Graph(DictionaryBackend()) def test_eq_ne_(self): e = Element(self.g) if e == e: pass else: self.fail('Element object does not compare equal to itself!') e2 = Element(self.g) if e != e2: pass else: self.fail('Two different Element objects compare equal!') self.assertNotEqual(e, e2) self.assertEqual(e, e) def test_lt_gt_le_ge_(self): e = Element(self.g) e2 = Element(self.g) #we don't know wether e2 will be less or greater than e, so test is limited if e > e2: pass if e >= e2: pass if e < e2: pass if e <= e2: pass def test_hash_(self): e = Element(self.g) e2 = Element(self.g) self.assertTrue(e.__hash__() != e2.__hash__()) def test_repr_(self): e = Element(self.g) self.assertIsInstance(e.__repr__(), str) def test_setattr_(self): e = Element(self.g) with self.assertRaises(TypeError): e.id = 3 def test_str_(self): e = Element(self.g) self.assertIsInstance(str(e), str) def test_weight(self): e = Element(self.g) e.weight = 9 self.assertEqual(e.weight, 9) class TestElementZODB(TestElement): def setUp(self): storage = FileStorage(NamedTemporaryFile().name) db = DB(storage) connection = db.open() root = connection.root self.g = Graph(backend=ZODBBTreeBackend(root)) class TestNode(TestElement): def test_delete(self): n = self.g.add_node() n.delete() self.assertNotIn(n, self.g) def test_neighbors(self): nodes = self.g.add_nodes(3) self.g.add_edge(nodes[0], nodes[1]) self.g.add_edge(nodes[0], nodes[2]) self.assertIn(nodes[1], nodes[0].neighbors) self.assertIn(nodes[2], nodes[0].neighbors) def test_edges(self): nodes = self.g.add_nodes(3) e1 = self.g.add_edge(nodes[0], nodes[1]) e2 = self.g.add_edge(nodes[0], nodes[2]) self.assertIn(e1, nodes[0].edges) self.assertIn(e2, nodes[0].edges) for e in nodes[0].edges: self.assertIsInstance(e, Edge) def test_iter_(self): nodes = self.g.add_nodes(3) e1 = self.g.add_edge(nodes[0], nodes[1]) e2 = self.g.add_edge(nodes[0], nodes[2]) self.assertIn(e1, nodes[0]) self.assertIn(e2, nodes[0]) self.assertIn(nodes[1], nodes[0]) self.assertIn(nodes[2], nodes[0]) def test_getitem_setitem_(self): node = self.g.add_node({'keyn':'valuen'}) node['keyn2'] = 'valuen2' self.assertEqual(node['keyn'],'valuen') self.assertEqual(node['keyn2'],'valuen2') class TestNodeZODB(TestNode): def setUp(self): storage = FileStorage(NamedTemporaryFile().name) db = DB(storage) connection = db.open() root = connection.root self.g = Graph(backend=ZODBBTreeBackend(root)) class TestEdge(TestElement): def test_delete(self): n1 = self.g.add_node() n2 = self.g.add_node() e = self.g.add_edge(n1, n2) e.delete() self.assertNotIn(e, self.g) def test_nodes(self): nodes = self.g.add_nodes(2) e1 = self.g.add_edge(nodes[0], nodes[1]) for n in e1.nodes: self.assertIsInstance(n, Node) self.assertIn(n, nodes) def test_iter_(self): nodes = self.g.add_nodes(2) e1 = self.g.add_edge(nodes[0], nodes[1]) for n in e1: self.assertIsInstance(n, Node) self.assertIn(n, nodes) def test_getitem_setitem_(self): nodes = self.g.add_nodes(2) e1 = self.g.add_edge(nodes[0], nodes[1]) e1['key2'] = 'value2' self.assertEqual(e1['key2'],'value2') class TestEdgeZODB(TestEdge): def setUp(self): storage = FileStorage(NamedTemporaryFile().name) db = DB(storage) connection = db.open() root = connection.root self.g = Graph(backend=ZODBBTreeBackend(root))
apache-2.0
brianjimenez/lightdock
lightdock/test/gso/test_coordinates.py
1
6927
"""Tests for Coordinates class""" from nose.tools import assert_almost_equals from nose.tools import raises import os from lightdock.gso.coordinates import Coordinates from lightdock.gso.coordinates import CoordinatesFileReader from lightdock.error.lightdock_errors import GSOCoordinatesError class TestCoordinates: def setUp(self): self.values_2D = [1.0, 2.0] self.values_3D = [1.0, 2.0, 3.0] def tearDown(self): pass def test_create_coordinates_2D(self): coordinates = Coordinates(self.values_2D) assert coordinates.dimension == 2 for i in range(coordinates.dimension): assert_almost_equals(self.values_2D[i], coordinates[i]) def test_create_coordinates_3D(self): coordinates = Coordinates(self.values_3D) assert coordinates.dimension == 3 for i in range(coordinates.dimension): assert_almost_equals(self.values_3D[i], coordinates[i]) def test_check_equal_coordinates_2D(self): coordinates1 = Coordinates(self.values_2D) coordinates2 = Coordinates(self.values_2D) assert coordinates1 == coordinates2 assert not coordinates1 != coordinates2 def test_check_not_equal_coordinates_2D_and_3D(self): coordinates1 = Coordinates(self.values_2D) coordinates2 = Coordinates(self.values_3D) assert not coordinates1 == coordinates2 assert coordinates1 != coordinates2 def test_index_assigment(self): coordinates = Coordinates(self.values_2D) assert_almost_equals(self.values_2D[0], coordinates[0]) assert_almost_equals(self.values_2D[1], coordinates[1]) coordinates[0] = -1.0 assert_almost_equals(-1.0, coordinates[0]) assert_almost_equals(self.values_2D[1], coordinates[1]) def test_clone_coordinates(self): coordinates1 = Coordinates(self.values_2D) coordinates2 = coordinates1.clone() assert coordinates1 == coordinates2 coordinates2[0] = -1.0 assert coordinates1 != coordinates2 def test_coordinates_addition(self): coordinates1 = Coordinates(self.values_2D) coordinates2 = Coordinates(self.values_2D) expected = Coordinates([2.0, 4.0]) assert expected == coordinates1 + coordinates2 def test_coordinates_subtraction(self): coordinates1 = Coordinates(self.values_2D) coordinates2 = Coordinates(self.values_2D) expected = Coordinates([0.0, 0.0]) assert expected == coordinates1 - coordinates2 def test_coordinates_addition_and_assigment(self): coordinates1 = Coordinates(self.values_2D) coordinates2 = Coordinates(self.values_2D) expected = Coordinates([2.0, 4.0]) coordinates1 += coordinates2 assert expected == coordinates1 def test_coordinates_subtraction_and_assigment(self): coordinates1 = Coordinates(self.values_2D) coordinates2 = Coordinates(self.values_2D) expected = Coordinates([0.0, 0.0]) coordinates1 -= coordinates2 assert expected == coordinates1 def test_norm(self): coordinates = Coordinates(self.values_2D) assert_almost_equals(2.236067977, coordinates.norm()) def test_distance_same_coordinate(self): coordinates = Coordinates(self.values_2D) assert_almost_equals(0.0, coordinates.distance(coordinates)) def test_distance_different_coordinates(self): coordinates1 = Coordinates([0., 0., 0.]) coordinates2 = Coordinates([20., 0., 21.]) assert_almost_equals(29.0, coordinates1.distance(coordinates2)) def test_distance2_same_coordinate(self): coordinates = Coordinates(self.values_2D) assert_almost_equals(0.0, coordinates.distance2(coordinates)) def test_sum_of_squares(self): coordinates = Coordinates(self.values_2D) assert_almost_equals(5.0, coordinates.sum_of_squares()) def test_distance2_different_coordinates(self): coordinates1 = Coordinates(self.values_2D) coordinates2 = Coordinates([2.0, 3.0]) assert_almost_equals(2.0, coordinates1.distance2(coordinates2)) def test_multiplication_and_assigment(self): coordinates = Coordinates(self.values_3D) expected = Coordinates([-3.0, -6.0, -9.0]) coordinates *= -3.0 assert expected == coordinates def test_multiplication(self): coordinates = Coordinates(self.values_3D) expected = Coordinates([-3.0, -6.0, -9.0]) assert expected == (coordinates * -3.0) def test_move_different_coordinates(self): coordinates1 = Coordinates(self.values_2D) coordinates2 = Coordinates([0.0, 1.0]) expected = Coordinates([-1.12132034356, -0.12132034356]) assert expected == coordinates1.move(coordinates2, 3.0) def test_move_same_coordinate(self): coordinates1 = Coordinates(self.values_2D) assert coordinates1 == coordinates1.move(coordinates1) class TestCoordinatesFileReader: def setUp(self): self.golden_data_path = os.path.normpath(os.path.dirname(os.path.realpath(__file__))) + '/golden_data/' def tearDown(self): pass def test_read_coordinates_from_file(self): reader = CoordinatesFileReader(2) coordinates = reader.get_coordinates_from_file(self.golden_data_path + 'initial_positions.txt') assert 50 == len(coordinates) assert "(0.745916, -0.92056)" == str(coordinates[0]) assert "(-2.29363, -0.229427)" == str(coordinates[9]) assert "(0.617171, -2.85014)" == str(coordinates[-1]) @raises(GSOCoordinatesError) def test_read_coordinates_from_file_with_errors(self): reader = CoordinatesFileReader(2) coordinates = reader.get_coordinates_from_file(self.golden_data_path + 'initial_positions_with_error.txt') assert len(coordinates) @raises(GSOCoordinatesError) def test_read_coordinates_from_file_with_error_in_column(self): reader = CoordinatesFileReader(2) coordinates = reader.get_coordinates_from_file(self.golden_data_path + 'initial_positions_with_wrong_column.txt') assert len(coordinates) @raises(GSOCoordinatesError) def test_read_coordinates_from_file_no_file(self): reader = CoordinatesFileReader(2) coordinates = reader.get_coordinates_from_file(self.golden_data_path + 'no_file.txt') assert len(coordinates)
gpl-3.0
LohithBlaze/scikit-learn
sklearn/tests/test_metaestimators.py
226
4954
"""Common tests for metaestimators""" import functools import numpy as np from sklearn.base import BaseEstimator from sklearn.externals.six import iterkeys from sklearn.datasets import make_classification from sklearn.utils.testing import assert_true, assert_false, assert_raises from sklearn.pipeline import Pipeline from sklearn.grid_search import GridSearchCV, RandomizedSearchCV from sklearn.feature_selection import RFE, RFECV from sklearn.ensemble import BaggingClassifier class DelegatorData(object): def __init__(self, name, construct, skip_methods=(), fit_args=make_classification()): self.name = name self.construct = construct self.fit_args = fit_args self.skip_methods = skip_methods DELEGATING_METAESTIMATORS = [ DelegatorData('Pipeline', lambda est: Pipeline([('est', est)])), DelegatorData('GridSearchCV', lambda est: GridSearchCV( est, param_grid={'param': [5]}, cv=2), skip_methods=['score']), DelegatorData('RandomizedSearchCV', lambda est: RandomizedSearchCV( est, param_distributions={'param': [5]}, cv=2, n_iter=1), skip_methods=['score']), DelegatorData('RFE', RFE, skip_methods=['transform', 'inverse_transform', 'score']), DelegatorData('RFECV', RFECV, skip_methods=['transform', 'inverse_transform', 'score']), DelegatorData('BaggingClassifier', BaggingClassifier, skip_methods=['transform', 'inverse_transform', 'score', 'predict_proba', 'predict_log_proba', 'predict']) ] def test_metaestimator_delegation(): # Ensures specified metaestimators have methods iff subestimator does def hides(method): @property def wrapper(obj): if obj.hidden_method == method.__name__: raise AttributeError('%r is hidden' % obj.hidden_method) return functools.partial(method, obj) return wrapper class SubEstimator(BaseEstimator): def __init__(self, param=1, hidden_method=None): self.param = param self.hidden_method = hidden_method def fit(self, X, y=None, *args, **kwargs): self.coef_ = np.arange(X.shape[1]) return True def _check_fit(self): if not hasattr(self, 'coef_'): raise RuntimeError('Estimator is not fit') @hides def inverse_transform(self, X, *args, **kwargs): self._check_fit() return X @hides def transform(self, X, *args, **kwargs): self._check_fit() return X @hides def predict(self, X, *args, **kwargs): self._check_fit() return np.ones(X.shape[0]) @hides def predict_proba(self, X, *args, **kwargs): self._check_fit() return np.ones(X.shape[0]) @hides def predict_log_proba(self, X, *args, **kwargs): self._check_fit() return np.ones(X.shape[0]) @hides def decision_function(self, X, *args, **kwargs): self._check_fit() return np.ones(X.shape[0]) @hides def score(self, X, *args, **kwargs): self._check_fit() return 1.0 methods = [k for k in iterkeys(SubEstimator.__dict__) if not k.startswith('_') and not k.startswith('fit')] methods.sort() for delegator_data in DELEGATING_METAESTIMATORS: delegate = SubEstimator() delegator = delegator_data.construct(delegate) for method in methods: if method in delegator_data.skip_methods: continue assert_true(hasattr(delegate, method)) assert_true(hasattr(delegator, method), msg="%s does not have method %r when its delegate does" % (delegator_data.name, method)) # delegation before fit raises an exception assert_raises(Exception, getattr(delegator, method), delegator_data.fit_args[0]) delegator.fit(*delegator_data.fit_args) for method in methods: if method in delegator_data.skip_methods: continue # smoke test delegation getattr(delegator, method)(delegator_data.fit_args[0]) for method in methods: if method in delegator_data.skip_methods: continue delegate = SubEstimator(hidden_method=method) delegator = delegator_data.construct(delegate) assert_false(hasattr(delegate, method)) assert_false(hasattr(delegator, method), msg="%s has method %r when its delegate does not" % (delegator_data.name, method))
bsd-3-clause
jkyeung/XlsxWriter
xlsxwriter/test/table/test_table01.py
1
1893
############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2016, John McNamara, jmcnamara@cpan.org # import unittest from ...compatibility import StringIO from ..helperfunctions import _xml_to_list from ...table import Table from ...worksheet import Worksheet from ...workbook import WorksheetMeta from ...sharedstrings import SharedStringTable class TestAssembleTable(unittest.TestCase): """ Test assembling a complete Table file. """ def test_assemble_xml_file(self): """Test writing a table""" self.maxDiff = None worksheet = Worksheet() worksheet.worksheet_meta = WorksheetMeta() worksheet.str_table = SharedStringTable() worksheet.add_table('C3:F13') worksheet._prepare_tables(1, {}) fh = StringIO() table = Table() table._set_filehandle(fh) table._set_properties(worksheet.tables[0]) table._assemble_xml_file() exp = _xml_to_list(""" <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="1" name="Table1" displayName="Table1" ref="C3:F13" totalsRowShown="0"> <autoFilter ref="C3:F13"/> <tableColumns count="4"> <tableColumn id="1" name="Column1"/> <tableColumn id="2" name="Column2"/> <tableColumn id="3" name="Column3"/> <tableColumn id="4" name="Column4"/> </tableColumns> <tableStyleInfo name="TableStyleMedium9" showFirstColumn="0" showLastColumn="0" showRowStripes="1" showColumnStripes="0"/> </table> """) got = _xml_to_list(fh.getvalue()) self.assertEqual(got, exp)
bsd-2-clause
flexiant/xen
tools/xm-test/tests/create/08_create_mem128_pos.py
42
1164
#!/usr/bin/python # Copyright (C) International Business Machines Corp., 2005 # Author: Li Ge <lge@us.ibm.com> # Test Description: # Positive Test # Test for creating domain with mem=. import sys import re import time from XmTestLib import * rdpath = os.environ.get("RD_PATH") if not rdpath: rdpath = "../ramdisk" #get current free memory info mem = int(getInfo("free_memory")) if mem < 128: SKIP("This test needs 128 MB of free memory (%i MB avail)" % mem) #create a domain with mem=128 config={"memory": 128} domain_mem128=XmTestDomain(extraConfig=config) #start it try: domain_mem128.start(noConsole=True) except DomainError, e: if verbose: print "Failed to create test domain_mem128 because:" print e.extra FAIL(str(e)) #verify it is running with 128MB mem eyecatcher1 = str(isDomainRunning(domain_mem128.getName())) if eyecatcher1 != "True": FAIL("Failed to verify that a 128MB domain started") eyecatcher2 = getDomMem(domain_mem128.getName()) if eyecatcher2 not in range(126, 129): FAIL("Started domain with 128MB, but it got %i MB" % eyecatcher2) #stop the domain (nice shutdown) domain_mem128.stop()
gpl-2.0
IndraVikas/scikit-learn
examples/hetero_feature_union.py
288
6236
""" ============================================= Feature Union with Heterogeneous Data Sources ============================================= Datasets can often contain components of that require different feature extraction and processing pipelines. This scenario might occur when: 1. Your dataset consists of heterogeneous data types (e.g. raster images and text captions) 2. Your dataset is stored in a Pandas DataFrame and different columns require different processing pipelines. This example demonstrates how to use :class:`sklearn.feature_extraction.FeatureUnion` on a dataset containing different types of features. We use the 20-newsgroups dataset and compute standard bag-of-words features for the subject line and body in separate pipelines as well as ad hoc features on the body. We combine them (with weights) using a FeatureUnion and finally train a classifier on the combined set of features. The choice of features is not particularly helpful, but serves to illustrate the technique. """ # Author: Matt Terry <matt.terry@gmail.com> # # License: BSD 3 clause from __future__ import print_function import numpy as np from sklearn.base import BaseEstimator, TransformerMixin from sklearn.datasets import fetch_20newsgroups from sklearn.datasets.twenty_newsgroups import strip_newsgroup_footer from sklearn.datasets.twenty_newsgroups import strip_newsgroup_quoting from sklearn.decomposition import TruncatedSVD from sklearn.feature_extraction import DictVectorizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics import classification_report from sklearn.pipeline import FeatureUnion from sklearn.pipeline import Pipeline from sklearn.svm import SVC class ItemSelector(BaseEstimator, TransformerMixin): """For data grouped by feature, select subset of data at a provided key. The data is expected to be stored in a 2D data structure, where the first index is over features and the second is over samples. i.e. >> len(data[key]) == n_samples Please note that this is the opposite convention to sklearn feature matrixes (where the first index corresponds to sample). ItemSelector only requires that the collection implement getitem (data[key]). Examples include: a dict of lists, 2D numpy array, Pandas DataFrame, numpy record array, etc. >> data = {'a': [1, 5, 2, 5, 2, 8], 'b': [9, 4, 1, 4, 1, 3]} >> ds = ItemSelector(key='a') >> data['a'] == ds.transform(data) ItemSelector is not designed to handle data grouped by sample. (e.g. a list of dicts). If your data is structured this way, consider a transformer along the lines of `sklearn.feature_extraction.DictVectorizer`. Parameters ---------- key : hashable, required The key corresponding to the desired value in a mappable. """ def __init__(self, key): self.key = key def fit(self, x, y=None): return self def transform(self, data_dict): return data_dict[self.key] class TextStats(BaseEstimator, TransformerMixin): """Extract features from each document for DictVectorizer""" def fit(self, x, y=None): return self def transform(self, posts): return [{'length': len(text), 'num_sentences': text.count('.')} for text in posts] class SubjectBodyExtractor(BaseEstimator, TransformerMixin): """Extract the subject & body from a usenet post in a single pass. Takes a sequence of strings and produces a dict of sequences. Keys are `subject` and `body`. """ def fit(self, x, y=None): return self def transform(self, posts): features = np.recarray(shape=(len(posts),), dtype=[('subject', object), ('body', object)]) for i, text in enumerate(posts): headers, _, bod = text.partition('\n\n') bod = strip_newsgroup_footer(bod) bod = strip_newsgroup_quoting(bod) features['body'][i] = bod prefix = 'Subject:' sub = '' for line in headers.split('\n'): if line.startswith(prefix): sub = line[len(prefix):] break features['subject'][i] = sub return features pipeline = Pipeline([ # Extract the subject & body ('subjectbody', SubjectBodyExtractor()), # Use FeatureUnion to combine the features from subject and body ('union', FeatureUnion( transformer_list=[ # Pipeline for pulling features from the post's subject line ('subject', Pipeline([ ('selector', ItemSelector(key='subject')), ('tfidf', TfidfVectorizer(min_df=50)), ])), # Pipeline for standard bag-of-words model for body ('body_bow', Pipeline([ ('selector', ItemSelector(key='body')), ('tfidf', TfidfVectorizer()), ('best', TruncatedSVD(n_components=50)), ])), # Pipeline for pulling ad hoc features from post's body ('body_stats', Pipeline([ ('selector', ItemSelector(key='body')), ('stats', TextStats()), # returns a list of dicts ('vect', DictVectorizer()), # list of dicts -> feature matrix ])), ], # weight components in FeatureUnion transformer_weights={ 'subject': 0.8, 'body_bow': 0.5, 'body_stats': 1.0, }, )), # Use a SVC classifier on the combined features ('svc', SVC(kernel='linear')), ]) # limit the list of categories to make running this exmaple faster. categories = ['alt.atheism', 'talk.religion.misc'] train = fetch_20newsgroups(random_state=1, subset='train', categories=categories, ) test = fetch_20newsgroups(random_state=1, subset='test', categories=categories, ) pipeline.fit(train.data, train.target) y = pipeline.predict(test.data) print(classification_report(y, test.target))
bsd-3-clause
Nitaco/ansible
lib/ansible/modules/storage/zfs/zpool_facts.py
52
6554
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Adam Števko <adam.stevko@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: zpool_facts short_description: Gather facts about ZFS pools. description: - Gather facts from ZFS pool properties. version_added: "2.3" author: Adam Števko (@xen0l) options: name: description: - ZFS pool name. aliases: [ "pool", "zpool" ] required: false parsable: description: - Specifies if property values should be displayed in machine friendly format. type: bool default: False required: false properties: description: - Specifies which dataset properties should be queried in comma-separated format. For more information about dataset properties, check zpool(1M) man page. aliases: [ "props" ] default: all required: false ''' EXAMPLES = ''' # Gather facts about ZFS pool rpool - zpool_facts: pool=rpool # Gather space usage about all imported ZFS pools - zpool_facts: properties='free,size' - debug: msg='ZFS pool {{ item.name }} has {{ item.free }} free space out of {{ item.size }}.' with_items: '{{ ansible_zfs_pools }}' ''' RETURN = ''' ansible_facts: description: Dictionary containing all the detailed information about the ZFS pool facts returned: always type: complex contains: ansible_zfs_pools: description: ZFS pool facts returned: always type: string sample: { "allocated": "3.46G", "altroot": "-", "autoexpand": "off", "autoreplace": "off", "bootfs": "rpool/ROOT/openindiana", "cachefile": "-", "capacity": "6%", "comment": "-", "dedupditto": "0", "dedupratio": "1.00x", "delegation": "on", "expandsize": "-", "failmode": "wait", "feature@async_destroy": "enabled", "feature@bookmarks": "enabled", "feature@edonr": "enabled", "feature@embedded_data": "active", "feature@empty_bpobj": "active", "feature@enabled_txg": "active", "feature@extensible_dataset": "enabled", "feature@filesystem_limits": "enabled", "feature@hole_birth": "active", "feature@large_blocks": "enabled", "feature@lz4_compress": "active", "feature@multi_vdev_crash_dump": "enabled", "feature@sha512": "enabled", "feature@skein": "enabled", "feature@spacemap_histogram": "active", "fragmentation": "3%", "free": "46.3G", "freeing": "0", "guid": "15729052870819522408", "health": "ONLINE", "leaked": "0", "listsnapshots": "off", "name": "rpool", "readonly": "off", "size": "49.8G", "version": "-" } name: description: ZFS pool name returned: always type: string sample: rpool parsable: description: if parsable output should be provided in machine friendly format. returned: if 'parsable' is set to True type: boolean sample: True ''' from collections import defaultdict from ansible.module_utils.six import iteritems from ansible.module_utils.basic import AnsibleModule class ZPoolFacts(object): def __init__(self, module): self.module = module self.name = module.params['name'] self.parsable = module.params['parsable'] self.properties = module.params['properties'] self._pools = defaultdict(dict) self.facts = [] def pool_exists(self): cmd = [self.module.get_bin_path('zpool')] cmd.append('list') cmd.append(self.name) (rc, out, err) = self.module.run_command(cmd) if rc == 0: return True else: return False def get_facts(self): cmd = [self.module.get_bin_path('zpool')] cmd.append('get') cmd.append('-H') if self.parsable: cmd.append('-p') cmd.append('-o') cmd.append('name,property,value') cmd.append(self.properties) if self.name: cmd.append(self.name) (rc, out, err) = self.module.run_command(cmd) if rc == 0: for line in out.splitlines(): pool, property, value = line.split('\t') self._pools[pool].update({property: value}) for k, v in iteritems(self._pools): v.update({'name': k}) self.facts.append(v) return {'ansible_zfs_pools': self.facts} else: self.module.fail_json(msg='Error while trying to get facts about ZFS pool: %s' % self.name, stderr=err, rc=rc) def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=False, aliases=['pool', 'zpool'], type='str'), parsable=dict(required=False, default=False, type='bool'), properties=dict(required=False, default='all', type='str'), ), supports_check_mode=True ) zpool_facts = ZPoolFacts(module) result = {} result['changed'] = False result['name'] = zpool_facts.name if zpool_facts.parsable: result['parsable'] = zpool_facts.parsable if zpool_facts.name is not None: if zpool_facts.pool_exists(): result['ansible_facts'] = zpool_facts.get_facts() else: module.fail_json(msg='ZFS pool %s does not exist!' % zpool_facts.name) else: result['ansible_facts'] = zpool_facts.get_facts() module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
flwh/KK_mt6589_iq451
prebuilts/python/linux-x86/2.7.5/lib/python2.7/lib2to3/fixes/fix_itertools_imports.py
325
2094
""" Fixer for imports of itertools.(imap|ifilter|izip|ifilterfalse) """ # Local imports from lib2to3 import fixer_base from lib2to3.fixer_util import BlankLine, syms, token class FixItertoolsImports(fixer_base.BaseFix): BM_compatible = True PATTERN = """ import_from< 'from' 'itertools' 'import' imports=any > """ %(locals()) def transform(self, node, results): imports = results['imports'] if imports.type == syms.import_as_name or not imports.children: children = [imports] else: children = imports.children for child in children[::2]: if child.type == token.NAME: member = child.value name_node = child elif child.type == token.STAR: # Just leave the import as is. return else: assert child.type == syms.import_as_name name_node = child.children[0] member_name = name_node.value if member_name in (u'imap', u'izip', u'ifilter'): child.value = None child.remove() elif member_name in (u'ifilterfalse', u'izip_longest'): node.changed() name_node.value = (u'filterfalse' if member_name[1] == u'f' else u'zip_longest') # Make sure the import statement is still sane children = imports.children[:] or [imports] remove_comma = True for child in children: if remove_comma and child.type == token.COMMA: child.remove() else: remove_comma ^= True while children and children[-1].type == token.COMMA: children.pop().remove() # If there are no imports left, just get rid of the entire statement if (not (imports.children or getattr(imports, 'value', None)) or imports.parent is None): p = node.prefix node = BlankLine() node.prefix = p return node
gpl-2.0
purisc-group/purisc
compiler/class_def/conversions/arithmetic.py
1
29184
from helpers import next_subleq from helpers import subleq from helpers import clear import re def add(instr, assem): a = instr.args[0]; b = instr.args[1]; c = instr.result; t0 = assem.getNextTemp(); #check for literals if re.match("\d+",a): if a not in assem.dataMem: assem.dataMem[a] = a; if re.match("\d+",b): if b not in assem.dataMem: assem.dataMem[b] = b; assem.progMem.append("\n// " + instr.raw); assem.subleq(t0,t0,"NEXT"); assem.subleq(a,t0,"NEXT"); assem.subleq(b,t0,"NEXT"); assem.subleq(c,c,"NEXT"); assem.subleq(t0,c,"NEXT"); def sub(instr, assem): a = instr.args[0]; b = instr.args[1]; c = instr.result; #check for literals if re.match("\d+",a): if a not in assem.dataMem: assem.dataMem[a] = a; if re.match("\d+",b): if b not in assem.dataMem: assem.dataMem[b] = b; assem.progMem.append("\n // " + instr.raw); assem.subleq(c,c,"NEXT"); assem.subleq(t0,t0,"NEXT"); assem.subleq(a,t0,"NEXT"); assem.subleq(t0,c,"NEXT"); assem.subleq(b,c,"NEXT"); def mul(instr, assem): arg1 = instr.args[0]; arg2 = instr.args[1]; result = instr.result; c = assem.getNextReserved("workingResult"); # will hold the value of the negative answer until it is flipped at the end if necessary a = assem.getNextReserved("mul"); b = assem.getNextReserved("mul"); flip = assem.getNextReserved("flip"); i0 = assem.getNextReserved("i"); operand = assem.getNextReserved("operand"); power = assem.getNextReserved("power"); decomp = assem.getNextReserved("decomp"); decomp_ = assem.getNextReserved("mul_decomp_"); powers = assem.getNextReserved("powers"); p_ = "powersOf2_"; #labels flipA = assem.getNextReserved("flipA"); checkB = assem.getNextReserved("checkB"); flipB = assem.getNextReserved("flipB"); continue0 = assem.getNextReserved("continue0_"); continue1 = assem.getNextReserved("continue1_"); aLess = assem.getNextReserved("aLess"); continue2 = assem.getNextReserved("continue2_"); begin = assem.getNextReserved("begin"); p_0 = assem.getNextReserved("p_0_"); d_0 = assem.getNextReserved("d_0_"); p_1 = assem.getNextReserved("p_1_"); less = assem.getNextReserved("less"); test = assem.getNextReserved("test"); restore = assem.getNextReserved("restore"); continue3 = assem.getNextReserved("continue3_"); begin2 = assem.getNextReserved("begin2_"); d_2 = assem.getNextReserved("d_2_"); d_3 = assem.getNextReserved("d_3_"); d_4 = assem.getNextReserved("d_4_"); add = assem.getNextReserved("add"); regardless = assem.getNextReserved("regardless"); flipSign = assem.getNextReserved("flipSign"); finish = assem.getNextReserved("finish"); noflipA = assem.getNextReserved("noFlipA"); noflipB = assem.getNextReserved("noFlipB"); t0 = assem.getNextTemp(); t1 = assem.getNextTemp(); t3 = assem.getNextTemp(); t4 = assem.getNextTemp(); assem.progMem.append("\n// " + instr.raw); #determine the sign of the result assem.subleq(a,a,"NEXT"); #check the sign of A assem.subleq(b,b,"NEXT"); assem.subleq(flip,flip,"NEXT"); assem.subleq(t0,t0,"NEXT"); assem.subleq(arg1,t0,noflipA); assem.subleq(t0,a,"NEXT"); assem.subleq(1,flip,checkB); assem.subleq(noflipA + ":" + arg1,a,"NEXT"); assem.subleq(checkB + ":" + t0,t0,"NEXT"); #check the sign of B assem.subleq(arg2,t0,noflipB); assem.subleq(t0,b,"NEXT"); assem.subleq(-1,flip,"NEXT"); assem.subleq(t0,t0,continue0); assem.subleq(noflipB + ":" + arg2,b,"NEXT"); #determine the operand assem.subleq(continue0 + ":" + operand,operand,"NEXT"); assem.subleq(power,power,"NEXT"); assem.subleq(a,b,aLess); assem.subleq(a,power,"NEXT"); assem.subleq(b,operand,"NEXT"); assem.subleq(t0,t0,"NEXT"); assem.subleq(power,t0,"NEXT"); assem.subleq(t0,operand,"NEXT"); assem.subleq(t0,t0,continue1); assem.subleq(aLess + ":" + a,operand,"NEXT"); assem.subleq(b,power,"NEXT"); assem.subleq(t0,t0,'NEXT'); assem.subleq(operand,t0,"NEXT"); assem.subleq(t0,power,"NEXT"); #decompose the operand into powers of 2 #maxPower = -1; # for i = 30 -> 0 #if operand - 2^i >= 0 #powers[i] = 1 #operand = operand - 2^i #maxPower == -1 #maxPower = i #if operand - 2^i == 0: #break; two_i = assem.getNextReserved("two_i"); decomp_i = assem.getNextReserved("decomp_i"); restore = assem.getNextReserved("restore"); maxPower = assem.getNextReserved("maxPower"); maxFlag = assem.getNextReserved("maxFlag"); notMax = assem.getNextReserved("notMax"); continue2 = assem.getNextReserved("continue2"); incr0 = assem.getNextReserved("inc"); loop0 = assem.getNextReserved("loop"); t4 = assem.getNextTemp(); assem.dataMem[-2] = -2; assem.dataMem[0] = 0; #setup loop assem.subleq(continue1 + ":" + i0,i0,"NEXT"); assem.subleq(-30,i0,"NEXT"); assem.subleq(two_i,two_i,"NEXT"); assem.subleq("powersOf2_",two_i,"NEXT"); assem.subleq(30,two_i,"NEXT"); assem.subleq(decomp_i,decomp_i,"NEXT"); assem.subleq("mul_decomp_",decomp_i,"NEXT"); assem.subleq(30,decomp_i,"NEXT"); assem.subleq(maxPower,maxPower,"NEXT"); assem.subleq(maxFlag,maxFlag,"NEXT"); assem.subleq(-2,maxFlag, "NEXT"); assem.subleq(loop0 + ":" + p_0,p_0,"NEXT"); assem.subleq(two_i,p_0,"NEXT"); assem.subleq(d_0,d_0,"NEXT"); assem.subleq(decomp_i,d_0,"NEXT"); assem.subleq(p_1,p_1,"NEXT"); assem.subleq(two_i,p_1,"NEXT"); assem.subleq(p_0 + ":#1",operand,"NEXT"); #operand = operand - 2^i assem.subleq(-1,operand,restore); #add one to handle zero case assem.subleq(1,operand,"NEXT"); assem.subleq(-1,d_0 + ":#1","NEXT"); #subtract the one assem.subleq(1,maxFlag,notMax); assem.subleq(i0,maxPower,"NEXT"); assem.subleq(notMax + ":0",operand,continue2); assem.subleq(t0,t0,incr0); assem.subleq(restore + ":" + t0,t0,"NEXT"); assem.subleq(p_1 + ":#1",t0,"NEXT"); assem.subleq(t0,operand,"NEXT"); assem.subleq(1,operand,"NEXT"); #decrement and repeat if necessary assem.subleq(incr0 + ":-1",decomp_i,"NEXT"); assem.subleq(-1,two_i,"NEXT"); assem.subleq(1,i0,"NEXT"); assem.subleq(t0,t0,"NEXT"); assem.subleq(i0,t0,loop0); #do successive additions of powers of 2 i1 = assem.getNextReserved("i"); adder = assem.getNextReserved("adder"); op = assem.getNextReserved("op"); loop2 = assem.getNextReserved("loop"); continue3 = assem.getNextReserved("continue3"); continueLoop = assem.getNextReserved("contLoop"); d_3 = assem.getNextReserved("d_3"); noADD = assem.getNextReserved("noAdd"); assem.subleq(continue2 + ":" + i1,i1,"NEXT"); assem.subleq("2938483",t0,"NEXT"); assem.subleq(t0,t0,"NEXT"); assem.subleq(maxPower,t0,"NEXT") assem.subleq(t1,t1,"NEXT"); assem.subleq(t0,t1,"NEXT"); assem.subleq(maxPower,maxPower,"NEXT"); assem.subleq(t1,maxPower,"NEXT"); assem.subleq(adder,adder,"NEXT"); assem.subleq(op,op,"NEXT"); assem.subleq(power,op,"NEXT"); assem.subleq(op,adder,'NEXT'); assem.subleq(decomp_i,decomp_i,"NEXT"); assem.subleq("mul_decomp_",decomp_i,"NEXT"); assem.subleq(c,c,"NEXT"); assem.subleq(loop2 + ":" + maxPower,i1,continueLoop); #for i = 0 -> maxPower assem.subleq(t0,t0,continue3); assem.subleq(continueLoop + ":" + t0,t0,"NEXT"); assem.subleq(d_3,d_3,"NEXT"); assem.subleq(decomp_i,d_3,"NEXT"); assem.subleq(maxPower,t0,"NEXT"); #restore i to what it was before comparison assem.subleq(t0,i1,"NEXT"); assem.subleq(0,d_3 + ":#1",noADD); assem.subleq(adder,c,"NEXT"); assem.subleq(noADD + ":" + t0,t0,"NEXT"); assem.subleq(adder,t0,"NEXT"); assem.subleq(t0,adder,"NEXT"); #increment stuff assem.subleq(-1,i1,"NEXT"); assem.subleq(1,decomp_i,"NEXT"); assem.subleq(t0,t0,loop2); assem.subleq(continue3 + ":" + t0,t0,"NEXT"); #determine sign. c is the negative right now so flip if flip flag == 0 done = assem.getNextReserved("done"); ansPos = assem.getNextReserved("ansPos"); ansNeg = assem.getNextReserved("ansNeg"); '''assem.subleq(result,result,"NEXT"); assem.subleq(flip,result,"NEXT"); assem.subleq(t0,t0,"#-1");''' assem.subleq(-1,flip,ansNeg); assem.subleq(1,flip,ansPos); assem.subleq(t0,t0,ansNeg); assem.subleq(ansPos + ":" + result,result,"NEXT"); assem.subleq(c,result,"NEXT"); assem.subleq(t0,t0,done); assem.subleq(ansNeg + ":" + t0,t0,"NEXT"); assem.subleq(c,t0,"NEXT"); assem.subleq(t0,result,"NEXT"); assem.subleq(done + ":" + t0,t0,"NEXT"); assem.dataMem["1"] = "#1"; assem.dataMem["-30"] = "#-30"; assem.dataMem["0"] = "#0"; assem.dataMem["30"] = "#30"; assem.dataMem["-1"] = "#-1"; assem.dataMem["2"] = "#2"; assem.dataMem["2938483"] = "#2938483"; #space for the powers of 2 assem.dataMem["powersOf2_1"] = "#1" assem.dataMem["powersOf2_2"] = "#2" assem.dataMem["powersOf2_4"] = "#4" assem.dataMem["powersOf2_8"] = "#8" assem.dataMem["powersOf2_16"] = "#16" assem.dataMem["powersOf2_32"] = "#32" assem.dataMem["powersOf2_64"] = "#64" assem.dataMem["powersOf2_128"] = "#128" assem.dataMem["powersOf2_256"] = "#256" assem.dataMem["powersOf2_512"] = "#512" assem.dataMem["powersOf2_1024"] = "#1024" assem.dataMem["powersOf2_2048"] = "#2048" assem.dataMem["powersOf2_4096"] = "#4096" assem.dataMem["powersOf2_8192"] = "#8192" assem.dataMem["powersOf2_16384"] = "#16384" assem.dataMem["powersOf2_32768"] = "#32768" assem.dataMem["powersOf2_65536"] = "#65536" assem.dataMem["powersOf2_131072"] = "#131072" assem.dataMem["powersOf2_262144"] = "#262144" assem.dataMem["powersOf2_524288"] = "#524288" assem.dataMem["powersOf2_1048576"] = "#1048576" assem.dataMem["powersOf2_2097152"] = "#2097152" assem.dataMem["powersOf2_4194304"] = "#4194304" assem.dataMem["powersOf2_8388608"] = "#8388608" assem.dataMem["powersOf2_16777216"] = "#16777216" assem.dataMem["powersOf2_33554432"] = "#33554432" assem.dataMem["powersOf2_67108864"] = "#67108864" assem.dataMem["powersOf2_134217728"] = "#134217728" assem.dataMem["powersOf2_268435456"] = "#268435456" assem.dataMem["powersOf2_536870912"] = "#536870912" assem.dataMem["powersOf2_1073741824"] = "#1073741824" assem.dataMem["powersOf2_"] = "&powersOf2_1" #space for the decomposition, will be reused every multiplication assem.dataMem["mul_decomp_0"] = "#0" assem.dataMem["mul_decomp_1"] = "#0" assem.dataMem["mul_decomp_2"] = "#0" assem.dataMem["mul_decomp_3"] = "#0" assem.dataMem["mul_decomp_4"] = "#0" assem.dataMem["mul_decomp_5"] = "#0" assem.dataMem["mul_decomp_6"] = "#0" assem.dataMem["mul_decomp_7"] = "#0" assem.dataMem["mul_decomp_8"] = "#0" assem.dataMem["mul_decomp_9"] = "#0" assem.dataMem["mul_decomp_10"] = "#0" assem.dataMem["mul_decomp_11"] = "#0" assem.dataMem["mul_decomp_12"] = "#0" assem.dataMem["mul_decomp_13"] = "#0" assem.dataMem["mul_decomp_14"] = "#0" assem.dataMem["mul_decomp_15"] = "#0" assem.dataMem["mul_decomp_16"] = "#0" assem.dataMem["mul_decomp_17"] = "#0" assem.dataMem["mul_decomp_18"] = "#0" assem.dataMem["mul_decomp_19"] = "#0" assem.dataMem["mul_decomp_20"] = "#0" assem.dataMem["mul_decomp_21"] = "#0" assem.dataMem["mul_decomp_22"] = "#0" assem.dataMem["mul_decomp_23"] = "#0" assem.dataMem["mul_decomp_24"] = "#0" assem.dataMem["mul_decomp_25"] = "#0" assem.dataMem["mul_decomp_26"] = "#0" assem.dataMem["mul_decomp_27"] = "#0" assem.dataMem["mul_decomp_28"] = "#0" assem.dataMem["mul_decomp_29"] = "#0" assem.dataMem["mul_decomp_30"] = "#0" assem.dataMem["mul_decomp_"] = "&mul_decomp_0" def div(instr, assem): arg1 = instr.args[0]; arg2 = instr.args[1]; c = instr.result; a = assem.getNextReserved("A"); b = assem.getNextReserved("B"); num = assem.getNextReserved("num"); denom = assem.getNextReserved("denom"); t0 = assem.getNextTemp(); t1 = assem.getNextTemp(); flip = assem.getNextReserved("flip"); noflipA = assem.getNextReserved("noflipA"); noflipB = assem.getNextReserved("noflipB"); checkB = assem.getNextReserved("checkB"); continue0 = assem.getNextReserved("continue"); continue1 = assem.getNextReserved("continue"); zero = assem.getNextReserved("zero"); done = assem.getNextReserved("done"); i0 = assem.getNextReserved("i"); loop0 = assem.getNextReserved("loop"); d_0 = assem.getNextReserved("d_0"); d_1 = assem.getNextReserved("d_1"); d_2 = assem.getNextReserved("d_2"); d_3 = assem.getNextReserved("d_3"); d_prev_0 = assem.getNextReserved("d_prev_0"); d_prev_1 = assem.getNextReserved("d_prev_1"); d_prev_2 = assem.getNextReserved("d_prev_2"); assem.progMem.append("\n// " + instr.raw); #check for signs assem.subleq(a,a,"NEXT"); #check the sign of A assem.subleq(b,b,"NEXT"); assem.subleq(flip,flip,"NEXT"); assem.subleq(t0,t0,"NEXT"); assem.subleq(arg1,t0,noflipA); assem.subleq(arg1,a,"NEXT"); assem.subleq(1,flip,checkB); assem.subleq(noflipA + ":" + t0,a,"NEXT"); assem.subleq(checkB + ":" + t0,t0,"NEXT"); #check the sign of B assem.subleq(arg2,t0,noflipB); assem.subleq(t0,b,"NEXT"); assem.subleq(-1,flip,"NEXT"); assem.subleq(t0,t0,continue1); assem.subleq(noflipB + ":" + arg2,b,"NEXT"); #compute d*2^i assem.subleq(continue1 + ":" + b,"div_d_pwrs_0","NEXT"); assem.subleq(i0,i0,"NEXT"); assem.subleq(-1,i0,"NEXT"); #for i = 1 -> 30 assem.subleq(loop0 + ":" + t0,t0,"NEXT"); assem.subleq(t1,t1,"NEXT"); assem.subleq("div_d_pwrs_",t1,"NEXT"); #dereference d[i] assem.subleq(i0,t1,"NEXT"); assem.subleq(d_0,d_0,"NEXT"); #change the appropriate instructions pointing to d[i] assem.subleq(t1,d_0,"NEXT"); assem.subleq(d_1,d_1,"NEXT"); assem.subleq(t1,d_1,"NEXT"); assem.subleq(d_2,d_2,"NEXT"); assem.subleq(t1,d_2,"NEXT"); assem.subleq(d_3,d_3,"NEXT"); assem.subleq(t1,d_3,"NEXT"); assem.subleq(-1,t1,"NEXT"); #dereference d[i-1] assem.subleq(d_prev_0,d_prev_0,"NEXT"); #rewrite the appropriate instructions pointing to d[i-1] assem.subleq(t1,d_prev_0,"NEXT"); assem.subleq(d_prev_0 + ":#1",t0,"NEXT"); assem.subleq(d_0 + ":#1",d_1 + ":#1", "NEXT"); assem.subleq(t0,d_2 + ":#1","NEXT"); assem.subleq(t0,d_3 + ":#1","NEXT"); assem.subleq(-1,i0,"NEXT"); assem.subleq(t0,t0,"NEXT"); assem.subleq(i0,t0,"NEXT"); assem.subleq(t1,t1,"NEXT"); assem.subleq(t0,t1,"NEXT"); assem.subleq(30,t1,loop0); #for i = 30 -> 0 #if n - d*2^i >= 0 #n = n - d #result += 2^i # if n-d*2^i == 0 #break loop1 = assem.getNextReserved("loop"); n = assem.getNextReserved("n"); i1 = assem.getNextReserved("i"); inc = assem.getNextReserved("inc"); restore = assem.getNextReserved("restore"); break0 = assem.getNextReserved("break0"); continue2 = assem.getNextReserved("continue2"); d_i = "d_i"; #pointer to d*2^i two_i = "two_i"; #pointer to 2^i d_0 = assem.getNextReserved("d_0"); d_1 = assem.getNextReserved("d_1"); p_0 = assem.getNextReserved("p_0"); assem.subleq(c,c,"NEXT"); assem.subleq(n,n,"NEXT"); #setupt loop assem.subleq(t0,t0,"NEXT"); assem.subleq(a,t0,"NEXT"); assem.subleq(t0,n,"NEXT") assem.subleq(i1,i1,"NEXT"); assem.subleq(-30,i1,"NEXT"); assem.subleq(loop1 + ":" + d_0,d_0,"NEXT"); assem.subleq(t0,t0,"NEXT"); assem.subleq(d_i,t0,"NEXT"); assem.subleq(t0,d_0,"NEXT"); assem.subleq(d_1,d_1,"NEXT"); assem.subleq(t0,d_1,"NEXT"); assem.subleq(p_0,p_0,"NEXT"); assem.subleq(t0,t0,"NEXT"); assem.subleq(two_i,t0,"NEXT"); assem.subleq(t0,p_0,"NEXT"); assem.subleq(d_0 + ":#1",n,"NEXT"); assem.subleq(-1,n,restore); assem.subleq(t1,t1,"NEXT"); assem.subleq(p_0 + ":#1",t1,"NEXT"); assem.subleq(t1,c,"NEXT"); assem.subleq(1,n,break0); #restore n to n = n -d*2^i and also break if necessary assem.subleq(t0,t0,inc); assem.subleq(break0 + ":" + t0,t0,continue2); assem.subleq(restore + ":" + t0,t0,"NEXT"); assem.subleq(d_1 + ":#1",t0,"NEXT"); assem.subleq(t0,n,"NEXT"); assem.subleq(1,n,"NEXT"); assem.subleq(inc + ":1",i1,"NEXT"); #decrement and check assem.subleq(1,d_i,"NEXT"); assem.subleq(1,two_i,"NEXT"); assem.subleq(t0,t0,"NEXT"); assem.subleq(i1,t0,loop1); #assem.subleq(continue2 + ":" + t0,t0,"NEXT"); #fli if necessary flipResult = assem.getNextReserved("flipResult"); assem.subleq(continue2 +":-1" ,flip,flipResult); assem.subleq(1,flip,done); assem.subleq(flipResult + ":" + t0,t0,"NEXT"); assem.subleq(c,t0,"NEXT"); assem.subleq(c,c,"NEXT"); assem.subleq(t1,t1,"NEXT"); assem.subleq(t0,t1,"NEXT"); assem.subleq(t1,c,"NEXT"); #done assem.subleq(done + ":" + t0,t0,"NEXT"); assem.dataMem[-1] = -1; assem.dataMem[1] = 1; assem.dataMem[30] = 30; assem.dataMem[-30] = -30; assem.dataMem["div_d_pwrs_0"] = "#0" assem.dataMem["div_d_pwrs_1"] = "#0" assem.dataMem["div_d_pwrs_2"] = "#0" assem.dataMem["div_d_pwrs_3"] = "#0" assem.dataMem["div_d_pwrs_4"] = "#0" assem.dataMem["div_d_pwrs_5"] = "#0" assem.dataMem["div_d_pwrs_6"] = "#0" assem.dataMem["div_d_pwrs_7"] = "#0" assem.dataMem["div_d_pwrs_8"] = "#0" assem.dataMem["div_d_pwrs_9"] = "#0" assem.dataMem["div_d_pwrs_10"] = "#0" assem.dataMem["div_d_pwrs_11"] = "#0" assem.dataMem["div_d_pwrs_12"] = "#0" assem.dataMem["div_d_pwrs_13"] = "#0" assem.dataMem["div_d_pwrs_14"] = "#0" assem.dataMem["div_d_pwrs_15"] = "#0" assem.dataMem["div_d_pwrs_16"] = "#0" assem.dataMem["div_d_pwrs_17"] = "#0" assem.dataMem["div_d_pwrs_18"] = "#0" assem.dataMem["div_d_pwrs_19"] = "#0" assem.dataMem["div_d_pwrs_20"] = "#0" assem.dataMem["div_d_pwrs_21"] = "#0" assem.dataMem["div_d_pwrs_22"] = "#0" assem.dataMem["div_d_pwrs_23"] = "#0" assem.dataMem["div_d_pwrs_24"] = "#0" assem.dataMem["div_d_pwrs_25"] = "#0" assem.dataMem["div_d_pwrs_26"] = "#0" assem.dataMem["div_d_pwrs_27"] = "#0" assem.dataMem["div_d_pwrs_28"] = "#0" assem.dataMem["div_d_pwrs_29"] = "#0" assem.dataMem["div_d_pwrs_30"] = "#0" assem.dataMem["div_d_pwrs_"] = "&div_d_pwrs_0" assem.dataMem["powersOf2_1"] = "#1" assem.dataMem["powersOf2_2"] = "#2" assem.dataMem["powersOf2_4"] = "#4" assem.dataMem["powersOf2_8"] = "#8" assem.dataMem["powersOf2_16"] = "#16" assem.dataMem["powersOf2_32"] = "#32" assem.dataMem["powersOf2_64"] = "#64" assem.dataMem["powersOf2_128"] = "#128" assem.dataMem["powersOf2_256"] = "#256" assem.dataMem["powersOf2_512"] = "#512" assem.dataMem["powersOf2_1024"] = "#1024" assem.dataMem["powersOf2_2048"] = "#2048" assem.dataMem["powersOf2_4096"] = "#4096" assem.dataMem["powersOf2_8192"] = "#8192" assem.dataMem["powersOf2_16384"] = "#16384" assem.dataMem["powersOf2_32768"] = "#32768" assem.dataMem["powersOf2_65536"] = "#65536" assem.dataMem["powersOf2_131072"] = "#131072" assem.dataMem["powersOf2_262144"] = "#262144" assem.dataMem["powersOf2_524288"] = "#524288" assem.dataMem["powersOf2_1048576"] = "#1048576" assem.dataMem["powersOf2_2097152"] = "#2097152" assem.dataMem["powersOf2_4194304"] = "#4194304" assem.dataMem["powersOf2_8388608"] = "#8388608" assem.dataMem["powersOf2_16777216"] = "#16777216" assem.dataMem["powersOf2_33554432"] = "#33554432" assem.dataMem["powersOf2_67108864"] = "#67108864" assem.dataMem["powersOf2_134217728"] = "#134217728" assem.dataMem["powersOf2_268435456"] = "#268435456" assem.dataMem["powersOf2_536870912"] = "#536870912" assem.dataMem["powersOf2_1073741824"] = "#1073741824" assem.dataMem["powersOf2_"] = "&powersOf2_1" assem.dataMem["d_i"] = "&div_d_pwrs_30"; assem.dataMem["two_i"] = "&powersOf2_1073741824"; def mod(instr, assem): arg1 = instr.args[0]; arg2 = instr.args[1]; c = instr.result; a = assem.getNextReserved("A"); b = assem.getNextReserved("B"); num = assem.getNextReserved("num"); denom = assem.getNextReserved("denom"); t0 = assem.getNextTemp(); t1 = assem.getNextTemp(); flip = assem.getNextReserved("flip"); noflipA = assem.getNextReserved("noflipA"); noflipB = assem.getNextReserved("noflipB"); checkB = assem.getNextReserved("checkB"); continue0 = assem.getNextReserved("continue"); continue1 = assem.getNextReserved("continue"); zero = assem.getNextReserved("zero"); done = assem.getNextReserved("done"); i0 = assem.getNextReserved("i"); loop0 = assem.getNextReserved("loop"); d_0 = assem.getNextReserved("d_0"); d_1 = assem.getNextReserved("d_1"); d_2 = assem.getNextReserved("d_2"); d_3 = assem.getNextReserved("d_3"); d_prev_0 = assem.getNextReserved("d_prev_0"); d_prev_1 = assem.getNextReserved("d_prev_1"); d_prev_2 = assem.getNextReserved("d_prev_2"); assem.progMem.append("\n// " + instr.raw); #check for signs assem.subleq(a,a,"NEXT"); #check the sign of A assem.subleq(b,b,"NEXT"); assem.subleq(flip,flip,"NEXT"); assem.subleq(t0,t0,"NEXT"); assem.subleq(arg1,t0,noflipA); assem.subleq(arg1,a,"NEXT"); assem.subleq(1,flip,checkB); assem.subleq(noflipA + ":" + t0,a,"NEXT"); assem.subleq(checkB + ":" + t0,t0,"NEXT"); #check the sign of B assem.subleq(arg2,t0,noflipB); assem.subleq(t0,b,"NEXT"); assem.subleq(-1,flip,"NEXT"); assem.subleq(t0,t0,continue1); assem.subleq(noflipB + ":" + arg2,b,"NEXT"); #compute d*2^i assem.subleq(continue1 + ":" + b,"div_d_pwrs_0","NEXT"); assem.subleq(i0,i0,"NEXT"); assem.subleq(-1,i0,"NEXT"); #for i = 1 -> 30 assem.subleq(loop0 + ":" + t0,t0,"NEXT"); assem.subleq(t1,t1,"NEXT"); assem.subleq("div_d_pwrs_",t1,"NEXT"); #dereference d[i] assem.subleq(i0,t1,"NEXT"); assem.subleq(d_0,d_0,"NEXT"); #change the appropriate instructions pointing to d[i] assem.subleq(t1,d_0,"NEXT"); assem.subleq(d_1,d_1,"NEXT"); assem.subleq(t1,d_1,"NEXT"); assem.subleq(d_2,d_2,"NEXT"); assem.subleq(t1,d_2,"NEXT"); assem.subleq(d_3,d_3,"NEXT"); assem.subleq(t1,d_3,"NEXT"); assem.subleq(-1,t1,"NEXT"); #dereference d[i-1] assem.subleq(d_prev_0,d_prev_0,"NEXT"); #rewrite the appropriate instructions pointing to d[i-1] assem.subleq(t1,d_prev_0,"NEXT"); assem.subleq(d_prev_0 + ":#1",t0,"NEXT"); assem.subleq(d_0 + ":#1",d_1 + ":#1", "NEXT"); assem.subleq(t0,d_2 + ":#1","NEXT"); assem.subleq(t0,d_3 + ":#1","NEXT"); assem.subleq(-1,i0,"NEXT"); assem.subleq(t0,t0,"NEXT"); assem.subleq(i0,t0,"NEXT"); assem.subleq(t1,t1,"NEXT"); assem.subleq(t0,t1,"NEXT"); assem.subleq(30,t1,loop0); #for i = 30 -> 0 #if n - d*2^i >= 0 #n = n - d #result += 2^i # if n-d*2^i == 0 #break loop1 = assem.getNextReserved("loop"); n = assem.getNextReserved("n"); i1 = assem.getNextReserved("i"); inc = assem.getNextReserved("inc"); restore = assem.getNextReserved("restore"); break0 = assem.getNextReserved("break0"); continue2 = assem.getNextReserved("continue2"); d_i = "d_i"; #pointer to d*2^i two_i = "two_i"; #pointer to 2^i d_0 = assem.getNextReserved("d_0"); d_1 = assem.getNextReserved("d_1"); p_0 = assem.getNextReserved("p_0"); assem.subleq(c,c,"NEXT"); assem.subleq(n,n,"NEXT"); #setupt loop assem.subleq(t0,t0,"NEXT"); assem.subleq(a,t0,"NEXT"); assem.subleq(t0,n,"NEXT") assem.subleq(i1,i1,"NEXT"); assem.subleq(-30,i1,"NEXT"); assem.subleq(loop1 + ":" + d_0,d_0,"NEXT"); assem.subleq(t0,t0,"NEXT"); assem.subleq(d_i,t0,"NEXT"); assem.subleq(t0,d_0,"NEXT"); assem.subleq(d_1,d_1,"NEXT"); assem.subleq(t0,d_1,"NEXT"); assem.subleq(p_0,p_0,"NEXT"); assem.subleq(t0,t0,"NEXT"); assem.subleq(two_i,t0,"NEXT"); assem.subleq(t0,p_0,"NEXT"); assem.subleq(d_0 + ":#1",n,"NEXT"); assem.subleq(-1,n,restore); assem.subleq(t1,t1,"NEXT"); assem.subleq(p_0 + ":#1",t1,"NEXT"); assem.subleq(t1,c,"NEXT"); assem.subleq(1,n,break0); #restore n to n = n -d*2^i and also break if necessary assem.subleq(t0,t0,inc); assem.subleq(break0 + ":" + t0,t0,continue2); assem.subleq(restore + ":" + t0,t0,"NEXT"); assem.subleq(d_1 + ":#1",t0,"NEXT"); assem.subleq(t0,n,"NEXT"); assem.subleq(1,n,"NEXT"); assem.subleq(inc + ":1",i1,"NEXT"); #decrement and check assem.subleq(1,d_i,"NEXT"); assem.subleq(1,two_i,"NEXT"); assem.subleq(t0,t0,"NEXT"); assem.subleq(i1,t0,loop1); #assem.subleq(continue2 + ":" + t0,t0,"NEXT"); #fli if necessary flipResult = assem.getNextReserved("flipResult"); assem.subleq(continue2 +":-1" ,flip,flipResult); assem.subleq(1,flip,done); assem.subleq(flipResult + ":" + t0,t0,"NEXT"); assem.subleq(c,t0,"NEXT"); assem.subleq(c,c,"NEXT"); assem.subleq(t1,t1,"NEXT"); assem.subleq(t0,t1,"NEXT"); assem.subleq(t1,c,"NEXT"); #done assem.subleq(done + ":" + t0,t0,"NEXT"); assem.dataMem[-1] = -1; assem.dataMem[1] = 1; assem.dataMem[30] = 30; assem.dataMem[-30] = -30; assem.dataMem["div_d_pwrs_0"] = "#0" assem.dataMem["div_d_pwrs_1"] = "#0" assem.dataMem["div_d_pwrs_2"] = "#0" assem.dataMem["div_d_pwrs_3"] = "#0" assem.dataMem["div_d_pwrs_4"] = "#0" assem.dataMem["div_d_pwrs_5"] = "#0" assem.dataMem["div_d_pwrs_6"] = "#0" assem.dataMem["div_d_pwrs_7"] = "#0" assem.dataMem["div_d_pwrs_8"] = "#0" assem.dataMem["div_d_pwrs_9"] = "#0" assem.dataMem["div_d_pwrs_10"] = "#0" assem.dataMem["div_d_pwrs_11"] = "#0" assem.dataMem["div_d_pwrs_12"] = "#0" assem.dataMem["div_d_pwrs_13"] = "#0" assem.dataMem["div_d_pwrs_14"] = "#0" assem.dataMem["div_d_pwrs_15"] = "#0" assem.dataMem["div_d_pwrs_16"] = "#0" assem.dataMem["div_d_pwrs_17"] = "#0" assem.dataMem["div_d_pwrs_18"] = "#0" assem.dataMem["div_d_pwrs_19"] = "#0" assem.dataMem["div_d_pwrs_20"] = "#0" assem.dataMem["div_d_pwrs_21"] = "#0" assem.dataMem["div_d_pwrs_22"] = "#0" assem.dataMem["div_d_pwrs_23"] = "#0" assem.dataMem["div_d_pwrs_24"] = "#0" assem.dataMem["div_d_pwrs_25"] = "#0" assem.dataMem["div_d_pwrs_26"] = "#0" assem.dataMem["div_d_pwrs_27"] = "#0" assem.dataMem["div_d_pwrs_28"] = "#0" assem.dataMem["div_d_pwrs_29"] = "#0" assem.dataMem["div_d_pwrs_30"] = "#0" assem.dataMem["div_d_pwrs_"] = "&div_d_pwrs_0" assem.dataMem["powersOf2_1"] = "#1" assem.dataMem["powersOf2_2"] = "#2" assem.dataMem["powersOf2_4"] = "#4" assem.dataMem["powersOf2_8"] = "#8" assem.dataMem["powersOf2_16"] = "#16" assem.dataMem["powersOf2_32"] = "#32" assem.dataMem["powersOf2_64"] = "#64" assem.dataMem["powersOf2_128"] = "#128" assem.dataMem["powersOf2_256"] = "#256" assem.dataMem["powersOf2_512"] = "#512" assem.dataMem["powersOf2_1024"] = "#1024" assem.dataMem["powersOf2_2048"] = "#2048" assem.dataMem["powersOf2_4096"] = "#4096" assem.dataMem["powersOf2_8192"] = "#8192" assem.dataMem["powersOf2_16384"] = "#16384" assem.dataMem["powersOf2_32768"] = "#32768" assem.dataMem["powersOf2_65536"] = "#65536" assem.dataMem["powersOf2_131072"] = "#131072" assem.dataMem["powersOf2_262144"] = "#262144" assem.dataMem["powersOf2_524288"] = "#524288" assem.dataMem["powersOf2_1048576"] = "#1048576" assem.dataMem["powersOf2_2097152"] = "#2097152" assem.dataMem["powersOf2_4194304"] = "#4194304" assem.dataMem["powersOf2_8388608"] = "#8388608" assem.dataMem["powersOf2_16777216"] = "#16777216" assem.dataMem["powersOf2_33554432"] = "#33554432" assem.dataMem["powersOf2_67108864"] = "#67108864" assem.dataMem["powersOf2_134217728"] = "#134217728" assem.dataMem["powersOf2_268435456"] = "#268435456" assem.dataMem["powersOf2_536870912"] = "#536870912" assem.dataMem["powersOf2_1073741824"] = "#1073741824" assem.dataMem["powersOf2_"] = "&powersOf2_1" assem.dataMem["d_i"] = "&div_d_pwrs_30"; assem.dataMem["two_i"] = "&powersOf2_1073741824"; def parseArgs(argStr): arg1 = re.findall("(?<=\s)[^\s,]+(?=,)",argStr)[0]; arg2 = re.findall("(?<=,\s)\s*\S+",argStr)[0]; return [arg1.strip(),arg2.strip()]
gpl-2.0
julian-klode/python-apt
doc/source/examples/dpkg-contents.py
2
1894
#!/usr/bin/python """Emulate dpkg --contents""" from __future__ import print_function import grp import pwd import stat import sys import time import apt_inst def format_mode(member): """Return the symbolic mode""" mode = member.mode if member.isdir(): s_mode = "d" elif member.islnk(): s_mode = "h" else: s_mode = "-" s_mode += ((mode & stat.S_IRUSR) and "r" or "-") s_mode += ((mode & stat.S_IWUSR) and "w" or "-") s_mode += ((mode & stat.S_IXUSR) and (mode & stat.S_ISUID and "s" or "x") or (mode & stat.S_ISUID and "S" or "-")) s_mode += ((mode & stat.S_IRGRP) and "r" or "-") s_mode += ((mode & stat.S_IWGRP) and "w" or "-") s_mode += ((mode & stat.S_IXGRP) and (mode & stat.S_ISGID and "s" or "x") or (mode & stat.S_ISGID and "S" or "-")) s_mode += ((mode & stat.S_IROTH) and "r" or "-") s_mode += ((mode & stat.S_IWOTH) and "w" or "-") s_mode += ((mode & stat.S_IXOTH) and "x" or "-") return s_mode def callback(member, data): """callback for deb_extract""" s_mode = format_mode(member) s_owner = "%s/%s" % (pwd.getpwuid(member.uid)[0], grp.getgrgid(member.gid)[0]) s_size = "%9d" % member.size s_time = time.strftime("%Y-%m-%d %H:%M", time.localtime(member.mtime)) s_name = (member.name if member.name.startswith(".") else ("./" + member.name)) if member.islnk(): s_name += " link to %s" % member.linkname print(s_mode, s_owner, s_size, s_time, s_name) def main(): """Main function""" if len(sys.argv) < 2: print("need filename argumnet", file=sys.stderr) sys.exit(1) fobj = open(sys.argv[1]) try: apt_inst.DebFile(fobj).data.go(callback) finally: fobj.close() if __name__ == "__main__": main()
gpl-2.0
ttiurani/gsutil
gslib/tests/test_trace.py
20
1679
# -*- coding: utf-8 -*- # 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. """Integration tests for gsutil --trace-token option.""" from __future__ import absolute_import from gslib.cs_api_map import ApiSelector import gslib.tests.testcase as testcase from gslib.tests.testcase.integration_testcase import SkipForS3 from gslib.tests.util import ObjectToURI as suri @SkipForS3('--trace-token is supported only on GCS JSON API.') class TestTraceTokenOption(testcase.GsUtilIntegrationTestCase): """Integration tests for gsutil --trace-token option.""" def test_minus_tracetoken_cat(self): """Tests cat command with trace-token option.""" key_uri = self.CreateObject(contents='0123456789') (_, stderr) = self.RunGsUtil( ['-D', '--trace-token=THISISATOKEN', 'cat', suri(key_uri)], return_stdout=True, return_stderr=True) if self.test_api == ApiSelector.JSON: self.assertIn('You are running gsutil with trace output enabled.', stderr) self.assertRegexpMatches( stderr, r'.*GET.*b/%s/o/%s\?.*&trace=token%%3ATHISISATOKEN' % (key_uri.bucket_name, key_uri.object_name))
apache-2.0
sontek/rethinkdb
external/v8_3.30.33.16/build/gyp/test/mac/gyptest-framework-headers.py
344
1103
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies that mac_framework_headers works properly. """ import TestGyp import sys if sys.platform == 'darwin': # TODO(thakis): Make this work with ninja, make. http://crbug.com/129013 test = TestGyp.TestGyp(formats=['xcode']) CHDIR = 'framework-headers' test.run_gyp('test.gyp', chdir=CHDIR) # Test that headers are installed for frameworks test.build('test.gyp', 'test_framework_headers_framework', chdir=CHDIR) test.built_file_must_exist( 'TestFramework.framework/Versions/A/TestFramework', chdir=CHDIR) test.built_file_must_exist( 'TestFramework.framework/Versions/A/Headers/myframework.h', chdir=CHDIR) # Test that headers are installed for static libraries. test.build('test.gyp', 'test_framework_headers_static', chdir=CHDIR) test.built_file_must_exist('libTestLibrary.a', chdir=CHDIR) test.built_file_must_exist('include/myframework.h', chdir=CHDIR) test.pass_test()
agpl-3.0
markmuetz/stormtracks
stormtracks/results.py
1
3180
import os from glob import glob import pandas as pd from load_settings import settings from utils.utils import compress_file, decompress_file RESULTS_TPL = '{0}.hdf' class ResultNotFound(Exception): '''Simple exception thrown if result cannot be found in results manager or on disk''' pass class StormtracksResultsManager(object): '''Manager class that is responsible for loading and saving all python results Simple key/value store. Load/saves to settings.OUTPUT_DIR. ''' def __init__(self, name, output_dir=None): self.name = name if output_dir: self.output_dir = output_dir else: self.output_dir = settings.OUTPUT_DIR def save_result(self, year, result_key, result): '''Saves a given result based on year, user chosen result_key''' dirname = os.path.join(self.output_dir, self.name) if not os.path.exists(dirname): os.makedirs(dirname) filename = RESULTS_TPL.format(year) print('saving {0}'.format(filename)) path = os.path.join(dirname, filename) result.to_hdf(path, result_key) def get_result(self, year, result_key): '''Returns a result from an HDF file.''' dirname = os.path.join(self.output_dir, self.name) filename = RESULTS_TPL.format(year) path = os.path.join(dirname, filename) try: result = pd.read_hdf(path, result_key) except Exception, e: raise ResultNotFound return result def delete(self, year, result_key): '''Deletes a specific result from disk''' raise NotImplementedError('Not sure how to delete one result') def compress_year(self, year, delete=False): '''Compresses a given year's dir and then optionally deletes that year''' year_filename = os.path.join(self.output_dir, self.name, RESULTS_TPL.format(year)) compressed_filename = compress_file(year_filename) if delete: self.delete_year(year) return compressed_filename def delete_year(self, year): '''Deletes a year (use with caution!)''' year_filename = os.path.join(self.output_dir, self.name, RESULTS_TPL.format(year)) os.remove(year_filename) def decompress_year(self, year): '''Decompresses a given year's tarball''' filename = os.path.join(self.output_dir, self.name, '{0}.bz2'.format(RESULTS_TPL.format(year))) decompress_file(filename) def list_years(self): '''List all saved years''' years = [] dirname = os.path.join(self.output_dir, self.name) for year_dirname in glob(os.path.join(dirname, '*')): try: year = int(os.path.splitext(os.path.basename(year_dirname))[0]) years.append(year) except: pass return sorted(years) def list_results(self, year): '''List all results saved for a particular year''' dirname = os.path.join(self.output_dir, self.name) print(os.path.join(dirname, RESULTS_TPL.format(year))) store = pd.HDFStore(os.path.join(dirname, RESULTS_TPL.format(year))) results = [field[0][1:] for field in store.items()] store.close() return sorted(results)
mit
KohlsTechnology/ansible
lib/ansible/modules/cloud/amazon/ec2_vpc_nat_gateway.py
25
32418
#!/usr/bin/python # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ec2_vpc_nat_gateway short_description: Manage AWS VPC NAT Gateways. description: - Ensure the state of AWS VPC NAT Gateways based on their id, allocation and subnet ids. version_added: "2.2" requirements: [boto3, botocore] options: state: description: - Ensure NAT Gateway is present or absent. default: "present" choices: ["present", "absent"] nat_gateway_id: description: - The id AWS dynamically allocates to the NAT Gateway on creation. This is required when the absent option is present. subnet_id: description: - The id of the subnet to create the NAT Gateway in. This is required with the present option. allocation_id: description: - The id of the elastic IP allocation. If this is not passed and the eip_address is not passed. An EIP is generated for this NAT Gateway. eip_address: description: - The elastic IP address of the EIP you want attached to this NAT Gateway. If this is not passed and the allocation_id is not passed, an EIP is generated for this NAT Gateway. if_exist_do_not_create: description: - if a NAT Gateway exists already in the subnet_id, then do not create a new one. required: false default: false release_eip: description: - Deallocate the EIP from the VPC. - Option is only valid with the absent state. - You should use this with the wait option. Since you can not release an address while a delete operation is happening. default: 'yes' wait: description: - Wait for operation to complete before returning. default: 'no' wait_timeout: description: - How many seconds to wait for an operation to complete before timing out. default: 300 client_token: description: - Optional unique token to be used during create to ensure idempotency. When specifying this option, ensure you specify the eip_address parameter as well otherwise any subsequent runs will fail. author: - "Allen Sanabria (@linuxdynasty)" - "Jon Hadfield (@jonhadfield)" - "Karen Cheng(@Etherdaemon)" extends_documentation_fragment: - aws - ec2 ''' EXAMPLES = ''' # Note: These examples do not set authentication details, see the AWS Guide for details. - name: Create new nat gateway with client token. ec2_vpc_nat_gateway: state: present subnet_id: subnet-12345678 eip_address: 52.1.1.1 region: ap-southeast-2 client_token: abcd-12345678 register: new_nat_gateway - name: Create new nat gateway using an allocation-id. ec2_vpc_nat_gateway: state: present subnet_id: subnet-12345678 allocation_id: eipalloc-12345678 region: ap-southeast-2 register: new_nat_gateway - name: Create new nat gateway, using an EIP address and wait for available status. ec2_vpc_nat_gateway: state: present subnet_id: subnet-12345678 eip_address: 52.1.1.1 wait: yes region: ap-southeast-2 register: new_nat_gateway - name: Create new nat gateway and allocate new EIP. ec2_vpc_nat_gateway: state: present subnet_id: subnet-12345678 wait: yes region: ap-southeast-2 register: new_nat_gateway - name: Create new nat gateway and allocate new EIP if a nat gateway does not yet exist in the subnet. ec2_vpc_nat_gateway: state: present subnet_id: subnet-12345678 wait: yes region: ap-southeast-2 if_exist_do_not_create: true register: new_nat_gateway - name: Delete nat gateway using discovered nat gateways from facts module. ec2_vpc_nat_gateway: state: absent region: ap-southeast-2 wait: yes nat_gateway_id: "{{ item.NatGatewayId }}" release_eip: yes register: delete_nat_gateway_result with_items: "{{ gateways_to_remove.result }}" - name: Delete nat gateway and wait for deleted status. ec2_vpc_nat_gateway: state: absent nat_gateway_id: nat-12345678 wait: yes wait_timeout: 500 region: ap-southeast-2 - name: Delete nat gateway and release EIP. ec2_vpc_nat_gateway: state: absent nat_gateway_id: nat-12345678 release_eip: yes wait: yes wait_timeout: 300 region: ap-southeast-2 ''' RETURN = ''' create_time: description: The ISO 8601 date time formatin UTC. returned: In all cases. type: string sample: "2016-03-05T05:19:20.282000+00:00'" nat_gateway_id: description: id of the VPC NAT Gateway returned: In all cases. type: string sample: "nat-0d1e3a878585988f8" subnet_id: description: id of the Subnet returned: In all cases. type: string sample: "subnet-12345" state: description: The current state of the NAT Gateway. returned: In all cases. type: string sample: "available" vpc_id: description: id of the VPC. returned: In all cases. type: string sample: "vpc-12345" nat_gateway_addresses: description: List of dictionairies containing the public_ip, network_interface_id, private_ip, and allocation_id. returned: In all cases. type: string sample: [ { 'public_ip': '52.52.52.52', 'network_interface_id': 'eni-12345', 'private_ip': '10.0.0.100', 'allocation_id': 'eipalloc-12345' } ] ''' import datetime import random import time try: import botocore except ImportError: pass # caught by imported HAS_BOTO3 from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ec2 import (ec2_argument_spec, get_aws_connection_info, boto3_conn, camel_dict_to_snake_dict, HAS_BOTO3) DRY_RUN_GATEWAYS = [ { "nat_gateway_id": "nat-123456789", "subnet_id": "subnet-123456789", "nat_gateway_addresses": [ { "public_ip": "55.55.55.55", "network_interface_id": "eni-1234567", "private_ip": "10.0.0.102", "allocation_id": "eipalloc-1234567" } ], "state": "available", "create_time": "2016-03-05T05:19:20.282000+00:00", "vpc_id": "vpc-12345678" } ] DRY_RUN_ALLOCATION_UNCONVERTED = { 'Addresses': [ { 'PublicIp': '55.55.55.55', 'Domain': 'vpc', 'AllocationId': 'eipalloc-1234567' } ] } DRY_RUN_MSGS = 'DryRun Mode:' def get_nat_gateways(client, subnet_id=None, nat_gateway_id=None, states=None, check_mode=False): """Retrieve a list of NAT Gateways Args: client (botocore.client.EC2): Boto3 client Kwargs: subnet_id (str): The subnet_id the nat resides in. nat_gateway_id (str): The Amazon nat id. states (list): States available (pending, failed, available, deleting, and deleted) default=None Basic Usage: >>> client = boto3.client('ec2') >>> subnet_id = 'subnet-12345678' >>> get_nat_gateways(client, subnet_id) [ true, "", { "nat_gateway_id": "nat-123456789", "subnet_id": "subnet-123456789", "nat_gateway_addresses": [ { "public_ip": "55.55.55.55", "network_interface_id": "eni-1234567", "private_ip": "10.0.0.102", "allocation_id": "eipalloc-1234567" } ], "state": "deleted", "create_time": "2016-03-05T00:33:21.209000+00:00", "delete_time": "2016-03-05T00:36:37.329000+00:00", "vpc_id": "vpc-12345678" } Returns: Tuple (bool, str, list) """ params = dict() err_msg = "" gateways_retrieved = False existing_gateways = list() if not states: states = ['available', 'pending'] if nat_gateway_id: params['NatGatewayIds'] = [nat_gateway_id] else: params['Filter'] = [ { 'Name': 'subnet-id', 'Values': [subnet_id] }, { 'Name': 'state', 'Values': states } ] try: if not check_mode: gateways = client.describe_nat_gateways(**params)['NatGateways'] if gateways: for gw in gateways: existing_gateways.append(camel_dict_to_snake_dict(gw)) gateways_retrieved = True else: gateways_retrieved = True if nat_gateway_id: if DRY_RUN_GATEWAYS[0]['nat_gateway_id'] == nat_gateway_id: existing_gateways = DRY_RUN_GATEWAYS elif subnet_id: if DRY_RUN_GATEWAYS[0]['subnet_id'] == subnet_id: existing_gateways = DRY_RUN_GATEWAYS err_msg = '{0} Retrieving gateways'.format(DRY_RUN_MSGS) except botocore.exceptions.ClientError as e: err_msg = str(e) return gateways_retrieved, err_msg, existing_gateways def wait_for_status(client, wait_timeout, nat_gateway_id, status, check_mode=False): """Wait for the NAT Gateway to reach a status Args: client (botocore.client.EC2): Boto3 client wait_timeout (int): Number of seconds to wait, until this timeout is reached. nat_gateway_id (str): The Amazon nat id. status (str): The status to wait for. examples. status=available, status=deleted Basic Usage: >>> client = boto3.client('ec2') >>> subnet_id = 'subnet-12345678' >>> allocation_id = 'eipalloc-12345678' >>> wait_for_status(client, subnet_id, allocation_id) [ true, "", { "nat_gateway_id": "nat-123456789", "subnet_id": "subnet-1234567", "nat_gateway_addresses": [ { "public_ip": "55.55.55.55", "network_interface_id": "eni-1234567", "private_ip": "10.0.0.102", "allocation_id": "eipalloc-12345678" } ], "state": "deleted", "create_time": "2016-03-05T00:33:21.209000+00:00", "delete_time": "2016-03-05T00:36:37.329000+00:00", "vpc_id": "vpc-12345677" } ] Returns: Tuple (bool, str, dict) """ polling_increment_secs = 5 wait_timeout = time.time() + wait_timeout status_achieved = False nat_gateway = dict() states = ['pending', 'failed', 'available', 'deleting', 'deleted'] err_msg = "" while wait_timeout > time.time(): try: gws_retrieved, err_msg, nat_gateways = ( get_nat_gateways( client, nat_gateway_id=nat_gateway_id, states=states, check_mode=check_mode ) ) if gws_retrieved and nat_gateways: nat_gateway = nat_gateways[0] if check_mode: nat_gateway['state'] = status if nat_gateway.get('state') == status: status_achieved = True break elif nat_gateway.get('state') == 'failed': err_msg = nat_gateway.get('failure_message') break elif nat_gateway.get('state') == 'pending': if 'failure_message' in nat_gateway: err_msg = nat_gateway.get('failure_message') status_achieved = False break else: time.sleep(polling_increment_secs) except botocore.exceptions.ClientError as e: err_msg = str(e) if not status_achieved: err_msg = "Wait time out reached, while waiting for results" return status_achieved, err_msg, nat_gateway def gateway_in_subnet_exists(client, subnet_id, allocation_id=None, check_mode=False): """Retrieve all NAT Gateways for a subnet. Args: subnet_id (str): The subnet_id the nat resides in. Kwargs: allocation_id (str): The EIP Amazon identifier. default = None Basic Usage: >>> client = boto3.client('ec2') >>> subnet_id = 'subnet-1234567' >>> allocation_id = 'eipalloc-1234567' >>> gateway_in_subnet_exists(client, subnet_id, allocation_id) ( [ { "nat_gateway_id": "nat-123456789", "subnet_id": "subnet-123456789", "nat_gateway_addresses": [ { "public_ip": "55.55.55.55", "network_interface_id": "eni-1234567", "private_ip": "10.0.0.102", "allocation_id": "eipalloc-1234567" } ], "state": "deleted", "create_time": "2016-03-05T00:33:21.209000+00:00", "delete_time": "2016-03-05T00:36:37.329000+00:00", "vpc_id": "vpc-1234567" } ], False ) Returns: Tuple (list, bool) """ allocation_id_exists = False gateways = [] states = ['available', 'pending'] gws_retrieved, _, gws = ( get_nat_gateways( client, subnet_id, states=states, check_mode=check_mode ) ) if not gws_retrieved: return gateways, allocation_id_exists for gw in gws: for address in gw['nat_gateway_addresses']: if allocation_id: if address.get('allocation_id') == allocation_id: allocation_id_exists = True gateways.append(gw) else: gateways.append(gw) return gateways, allocation_id_exists def get_eip_allocation_id_by_address(client, eip_address, check_mode=False): """Release an EIP from your EIP Pool Args: client (botocore.client.EC2): Boto3 client eip_address (str): The Elastic IP Address of the EIP. Kwargs: check_mode (bool): if set to true, do not run anything and falsify the results. Basic Usage: >>> client = boto3.client('ec2') >>> eip_address = '52.87.29.36' >>> get_eip_allocation_id_by_address(client, eip_address) 'eipalloc-36014da3' Returns: Tuple (str, str) """ params = { 'PublicIps': [eip_address], } allocation_id = None err_msg = "" try: if not check_mode: allocations = client.describe_addresses(**params)['Addresses'] if len(allocations) == 1: allocation = allocations[0] else: allocation = None else: dry_run_eip = ( DRY_RUN_ALLOCATION_UNCONVERTED['Addresses'][0]['PublicIp'] ) if dry_run_eip == eip_address: allocation = DRY_RUN_ALLOCATION_UNCONVERTED['Addresses'][0] else: allocation = None if allocation: if allocation.get('Domain') != 'vpc': err_msg = ( "EIP {0} is a non-VPC EIP, please allocate a VPC scoped EIP" .format(eip_address) ) else: allocation_id = allocation.get('AllocationId') else: err_msg = ( "EIP {0} does not exist".format(eip_address) ) except botocore.exceptions.ClientError as e: err_msg = str(e) return allocation_id, err_msg def allocate_eip_address(client, check_mode=False): """Release an EIP from your EIP Pool Args: client (botocore.client.EC2): Boto3 client Kwargs: check_mode (bool): if set to true, do not run anything and falsify the results. Basic Usage: >>> client = boto3.client('ec2') >>> allocate_eip_address(client) True Returns: Tuple (bool, str) """ ip_allocated = False new_eip = None err_msg = '' params = { 'Domain': 'vpc', } try: if check_mode: ip_allocated = True random_numbers = ( ''.join(str(x) for x in random.sample(range(0, 9), 7)) ) new_eip = 'eipalloc-{0}'.format(random_numbers) else: new_eip = client.allocate_address(**params)['AllocationId'] ip_allocated = True err_msg = 'eipalloc id {0} created'.format(new_eip) except botocore.exceptions.ClientError as e: err_msg = str(e) return ip_allocated, err_msg, new_eip def release_address(client, allocation_id, check_mode=False): """Release an EIP from your EIP Pool Args: client (botocore.client.EC2): Boto3 client allocation_id (str): The eip Amazon identifier. Kwargs: check_mode (bool): if set to true, do not run anything and falsify the results. Basic Usage: >>> client = boto3.client('ec2') >>> allocation_id = "eipalloc-123456" >>> release_address(client, allocation_id) True Returns: Boolean, string """ err_msg = '' if check_mode: return True, '' ip_released = False try: client.describe_addresses(AllocationIds=[allocation_id]) except botocore.exceptions.ClientError as e: # IP address likely already released # Happens with gateway in 'deleted' state that # still lists associations return True, str(e) try: client.release_address(AllocationId=allocation_id) ip_released = True except botocore.exceptions.ClientError as e: err_msg = str(e) return ip_released, err_msg def create(client, subnet_id, allocation_id, client_token=None, wait=False, wait_timeout=0, if_exist_do_not_create=False, check_mode=False): """Create an Amazon NAT Gateway. Args: client (botocore.client.EC2): Boto3 client subnet_id (str): The subnet_id the nat resides in. allocation_id (str): The eip Amazon identifier. Kwargs: if_exist_do_not_create (bool): if a nat gateway already exists in this subnet, than do not create another one. default = False wait (bool): Wait for the nat to be in the deleted state before returning. default = False wait_timeout (int): Number of seconds to wait, until this timeout is reached. default = 0 client_token (str): default = None Basic Usage: >>> client = boto3.client('ec2') >>> subnet_id = 'subnet-1234567' >>> allocation_id = 'eipalloc-1234567' >>> create(client, subnet_id, allocation_id, if_exist_do_not_create=True, wait=True, wait_timeout=500) [ true, "", { "nat_gateway_id": "nat-123456789", "subnet_id": "subnet-1234567", "nat_gateway_addresses": [ { "public_ip": "55.55.55.55", "network_interface_id": "eni-1234567", "private_ip": "10.0.0.102", "allocation_id": "eipalloc-1234567" } ], "state": "deleted", "create_time": "2016-03-05T00:33:21.209000+00:00", "delete_time": "2016-03-05T00:36:37.329000+00:00", "vpc_id": "vpc-1234567" } ] Returns: Tuple (bool, str, list) """ params = { 'SubnetId': subnet_id, 'AllocationId': allocation_id } request_time = datetime.datetime.utcnow() changed = False success = False token_provided = False err_msg = "" if client_token: token_provided = True params['ClientToken'] = client_token try: if not check_mode: result = camel_dict_to_snake_dict(client.create_nat_gateway(**params)["NatGateway"]) else: result = DRY_RUN_GATEWAYS[0] result['create_time'] = datetime.datetime.utcnow() result['nat_gateway_addresses'][0]['allocation_id'] = allocation_id result['subnet_id'] = subnet_id success = True changed = True create_time = result['create_time'].replace(tzinfo=None) if token_provided and (request_time > create_time): changed = False elif wait: success, err_msg, result = ( wait_for_status( client, wait_timeout, result['nat_gateway_id'], 'available', check_mode=check_mode ) ) if success: err_msg = ( 'NAT gateway {0} created'.format(result['nat_gateway_id']) ) except botocore.exceptions.ClientError as e: if "IdempotentParameterMismatch" in e.message: err_msg = ( 'NAT Gateway does not support update and token has already been provided: ' + str(e) ) else: err_msg = str(e) success = False changed = False result = None return success, changed, err_msg, result def pre_create(client, subnet_id, allocation_id=None, eip_address=None, if_exist_do_not_create=False, wait=False, wait_timeout=0, client_token=None, check_mode=False): """Create an Amazon NAT Gateway. Args: client (botocore.client.EC2): Boto3 client subnet_id (str): The subnet_id the nat resides in. Kwargs: allocation_id (str): The EIP Amazon identifier. default = None eip_address (str): The Elastic IP Address of the EIP. default = None if_exist_do_not_create (bool): if a nat gateway already exists in this subnet, than do not create another one. default = False wait (bool): Wait for the nat to be in the deleted state before returning. default = False wait_timeout (int): Number of seconds to wait, until this timeout is reached. default = 0 client_token (str): default = None Basic Usage: >>> client = boto3.client('ec2') >>> subnet_id = 'subnet-w4t12897' >>> allocation_id = 'eipalloc-36014da3' >>> pre_create(client, subnet_id, allocation_id, if_exist_do_not_create=True, wait=True, wait_timeout=500) [ true, "", { "nat_gateway_id": "nat-03835afb6e31df79b", "subnet_id": "subnet-w4t12897", "nat_gateway_addresses": [ { "public_ip": "52.87.29.36", "network_interface_id": "eni-5579742d", "private_ip": "10.0.0.102", "allocation_id": "eipalloc-36014da3" } ], "state": "deleted", "create_time": "2016-03-05T00:33:21.209000+00:00", "delete_time": "2016-03-05T00:36:37.329000+00:00", "vpc_id": "vpc-w68571b5" } ] Returns: Tuple (bool, bool, str, list) """ success = False changed = False err_msg = "" results = list() if not allocation_id and not eip_address: existing_gateways, allocation_id_exists = ( gateway_in_subnet_exists(client, subnet_id, check_mode=check_mode) ) if len(existing_gateways) > 0 and if_exist_do_not_create: success = True changed = False results = existing_gateways[0] err_msg = ( 'NAT Gateway {0} already exists in subnet_id {1}' .format( existing_gateways[0]['nat_gateway_id'], subnet_id ) ) return success, changed, err_msg, results else: success, err_msg, allocation_id = ( allocate_eip_address(client, check_mode=check_mode) ) if not success: return success, 'False', err_msg, dict() elif eip_address or allocation_id: if eip_address and not allocation_id: allocation_id, err_msg = ( get_eip_allocation_id_by_address( client, eip_address, check_mode=check_mode ) ) if not allocation_id: success = False changed = False return success, changed, err_msg, dict() existing_gateways, allocation_id_exists = ( gateway_in_subnet_exists( client, subnet_id, allocation_id, check_mode=check_mode ) ) if len(existing_gateways) > 0 and (allocation_id_exists or if_exist_do_not_create): success = True changed = False results = existing_gateways[0] err_msg = ( 'NAT Gateway {0} already exists in subnet_id {1}' .format( existing_gateways[0]['nat_gateway_id'], subnet_id ) ) return success, changed, err_msg, results success, changed, err_msg, results = create( client, subnet_id, allocation_id, client_token, wait, wait_timeout, if_exist_do_not_create, check_mode=check_mode ) return success, changed, err_msg, results def remove(client, nat_gateway_id, wait=False, wait_timeout=0, release_eip=False, check_mode=False): """Delete an Amazon NAT Gateway. Args: client (botocore.client.EC2): Boto3 client nat_gateway_id (str): The Amazon nat id. Kwargs: wait (bool): Wait for the nat to be in the deleted state before returning. wait_timeout (int): Number of seconds to wait, until this timeout is reached. release_eip (bool): Once the nat has been deleted, you can deallocate the eip from the vpc. Basic Usage: >>> client = boto3.client('ec2') >>> nat_gw_id = 'nat-03835afb6e31df79b' >>> remove(client, nat_gw_id, wait=True, wait_timeout=500, release_eip=True) [ true, "", { "nat_gateway_id": "nat-03835afb6e31df79b", "subnet_id": "subnet-w4t12897", "nat_gateway_addresses": [ { "public_ip": "52.87.29.36", "network_interface_id": "eni-5579742d", "private_ip": "10.0.0.102", "allocation_id": "eipalloc-36014da3" } ], "state": "deleted", "create_time": "2016-03-05T00:33:21.209000+00:00", "delete_time": "2016-03-05T00:36:37.329000+00:00", "vpc_id": "vpc-w68571b5" } ] Returns: Tuple (bool, str, list) """ params = { 'NatGatewayId': nat_gateway_id } success = False changed = False err_msg = "" results = list() states = ['pending', 'available'] try: exist, _, gw = ( get_nat_gateways( client, nat_gateway_id=nat_gateway_id, states=states, check_mode=check_mode ) ) if exist and len(gw) == 1: results = gw[0] if not check_mode: client.delete_nat_gateway(**params) allocation_id = ( results['nat_gateway_addresses'][0]['allocation_id'] ) changed = True success = True err_msg = ( 'NAT gateway {0} is in a deleting state. Delete was successful' .format(nat_gateway_id) ) if wait: status_achieved, err_msg, results = ( wait_for_status( client, wait_timeout, nat_gateway_id, 'deleted', check_mode=check_mode ) ) if status_achieved: err_msg = ( 'NAT gateway {0} was deleted successfully' .format(nat_gateway_id) ) except botocore.exceptions.ClientError as e: err_msg = str(e) if release_eip: eip_released, eip_err = ( release_address(client, allocation_id, check_mode) ) if not eip_released: err_msg = ( "{0}: Failed to release EIP {1}: {2}" .format(err_msg, allocation_id, eip_err) ) success = False return success, changed, err_msg, results def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( subnet_id=dict(type='str'), eip_address=dict(type='str'), allocation_id=dict(type='str'), if_exist_do_not_create=dict(type='bool', default=False), state=dict(default='present', choices=['present', 'absent']), wait=dict(type='bool', default=False), wait_timeout=dict(type='int', default=320, required=False), release_eip=dict(type='bool', default=False), nat_gateway_id=dict(type='str'), client_token=dict(type='str'), ) ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, mutually_exclusive=[ ['allocation_id', 'eip_address'] ], required_if=[['state', 'absent', ['nat_gateway_id']], ['state', 'present', ['subnet_id']]] ) # Validate Requirements if not HAS_BOTO3: module.fail_json(msg='botocore/boto3 is required.') state = module.params.get('state').lower() check_mode = module.check_mode subnet_id = module.params.get('subnet_id') allocation_id = module.params.get('allocation_id') eip_address = module.params.get('eip_address') nat_gateway_id = module.params.get('nat_gateway_id') wait = module.params.get('wait') wait_timeout = module.params.get('wait_timeout') release_eip = module.params.get('release_eip') client_token = module.params.get('client_token') if_exist_do_not_create = module.params.get('if_exist_do_not_create') try: region, ec2_url, aws_connect_kwargs = ( get_aws_connection_info(module, boto3=True) ) client = ( boto3_conn( module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs ) ) except botocore.exceptions.ClientError as e: module.fail_json(msg="Boto3 Client Error - " + str(e.msg)) changed = False err_msg = '' if state == 'present': success, changed, err_msg, results = ( pre_create( client, subnet_id, allocation_id, eip_address, if_exist_do_not_create, wait, wait_timeout, client_token, check_mode=check_mode ) ) else: success, changed, err_msg, results = ( remove( client, nat_gateway_id, wait, wait_timeout, release_eip, check_mode=check_mode ) ) if not success: module.fail_json( msg=err_msg, success=success, changed=changed ) else: module.exit_json( msg=err_msg, success=success, changed=changed, **results ) if __name__ == '__main__': main()
gpl-3.0
ebar0n/SD-NumerosSemiprimos
program/server.py
2
7490
import socketserver import threading import time import sys from util import read_json, send_json, return_rangos_primos, \ ping, return_rangos_semiprimos global coun_connections coun_connections = 0 global json_primos json_primos = {} global json_semiprimos json_semiprimos = { 'primos': [] } global json_semiprimos_rangos json_semiprimos_rangos = { 'primos': [] } class MyTCPServer( socketserver.ThreadingMixIn, socketserver.TCPServer): pass class MyTCPServerHandler(socketserver.BaseRequestHandler): bufer = '' def display_coun_connections(self, num): global coun_connections coun_connections += num if num == 1: print ('\nCliente ADD') else: print ('\nCliente DEL') print ('Total {0}'.format(coun_connections)) def handle(self): cur_thread = threading.current_thread() self.name = cur_thread.name self.display_coun_connections(1) try: global json_primos global json_semiprimos while True: if json_primos: for rango in json_primos: if not rango['asignado']: self.rango = rango self.rango['asignado'] = True send_json( self.rango, self.request ) print ('Rango de primos asignado: {0}'.format(self.rango)) break band = True if hasattr(self, "rango"): while True: print ("Esperando resp") data, bufer = read_json( self.bufer, self.request ) if data: # obteniendo resp de los primos self.rango['primos'] = data['primos'] print ("Rango de primos encontrados: {0}".format(self.rango)) band = True for rango in json_primos: if rango['primos']: if rango["procesado"] is False: json_semiprimos["primos"] += rango['primos'] rango["procesado"] = True else: band = False if band is False: for rango in json_primos: if not rango['asignado']: self.rango = rango self.rango['asignado'] = True send_json( self.rango, self.request ) print ('Rango de primos asignado: {0}'.format(self.rango)) break else: break time.sleep(2) break else: ping(self.request) time.sleep(2) # Repartir carga de semiprimos print ("\n\nCalcular semiprimos") global json_semiprimos_rangos while True: if json_semiprimos_rangos: for rango in json_semiprimos_rangos: if not rango['asignado']: self.rango = rango self.rango['asignado'] = True send_json( self.rango, self.request ) print ('Rango de primos asignado: {0}'.format(self.rango)) print ("Esperando semiprimos") data, bufer = read_json( self.bufer, self.request ) print (data["semiprimos"]) time.sleep(2) except Exception as e: #print('Exception wile receiving message: ', e) pass if hasattr(self, "rango"): if 'primos' in self.rango: if not self.rango["primos"]: self.rango['asignado'] = False print ("El rango: {0} sera reasignado".format(self.rango)) if 'semiprimos' in self.rango: if not self.rango["semiprimos"]: self.rango['asignado'] = False print ("El rango: {0} sera reasignado".format(self.rango)) def finish(self): self.display_coun_connections(-1) if __name__ == '__main__': try: if len(sys.argv) == 2: server = MyTCPServer( ('0.0.0.0', int(sys.argv[1])), MyTCPServerHandler ) server_thread = threading.Thread( target=server.serve_forever ) server_thread.daemon = True server_thread.start() limite = int(input('Introduzca limite de semiprimos a calcular: ')) while True: if coun_connections < 1: print ('\nEsperando clientes...') time.sleep(3) else: break print ('\n{0} Clientes activos'.format(coun_connections)) json_primos = return_rangos_primos( limite, coun_connections ) while True: if coun_connections < 1: print ('\nEsperando clientes...') time.sleep(3) else: break while True: if json_semiprimos["primos"]: band = True for rango in json_primos: if not rango['primos']: band = False if band: json_semiprimos["primos"].sort() print ("\nPrimos calculados {0}".format(json_semiprimos["primos"])) json_semiprimos_rangos = return_rangos_semiprimos( json_semiprimos["primos"], limite, coun_connections, ) print ("\nRangos para calcular semiprimos {0}".format(json_semiprimos_rangos)) break time.sleep(3) print ("\nEsperando semiprimos:") while True: time.sleep(1) except KeyboardInterrupt: print ('Cierre todos los clientes conectado...') server.shutdown()
gpl-2.0
CoolCloud/ansible
examples/scripts/yaml_to_ini.py
133
7634
# (c) 2012, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. import ansible.constants as C from ansible.inventory.host import Host from ansible.inventory.group import Group from ansible import errors from ansible import utils import os import yaml import sys from six import iteritems class InventoryParserYaml(object): ''' Host inventory parser for ansible ''' def __init__(self, filename=C.DEFAULT_HOST_LIST): sys.stderr.write("WARNING: YAML inventory files are deprecated in 0.6 and will be removed in 0.7, to migrate" + " download and run https://github.com/ansible/ansible/blob/devel/examples/scripts/yaml_to_ini.py\n") fh = open(filename) data = fh.read() fh.close() self._hosts = {} self._parse(data) def _make_host(self, hostname): if hostname in self._hosts: return self._hosts[hostname] else: host = Host(hostname) self._hosts[hostname] = host return host # see file 'test/yaml_hosts' for syntax def _parse(self, data): # FIXME: refactor into subfunctions all = Group('all') ungrouped = Group('ungrouped') all.add_child_group(ungrouped) self.groups = dict(all=all, ungrouped=ungrouped) grouped_hosts = [] yaml = utils.parse_yaml(data) # first add all groups for item in yaml: if type(item) == dict and 'group' in item: group = Group(item['group']) for subresult in item.get('hosts',[]): if type(subresult) in [ str, unicode ]: host = self._make_host(subresult) group.add_host(host) grouped_hosts.append(host) elif type(subresult) == dict: host = self._make_host(subresult['host']) vars = subresult.get('vars',{}) if type(vars) == list: for subitem in vars: for (k,v) in subitem.items(): host.set_variable(k,v) elif type(vars) == dict: for (k,v) in subresult.get('vars',{}).items(): host.set_variable(k,v) else: raise errors.AnsibleError("unexpected type for variable") group.add_host(host) grouped_hosts.append(host) vars = item.get('vars',{}) if type(vars) == dict: for (k,v) in item.get('vars',{}).items(): group.set_variable(k,v) elif type(vars) == list: for subitem in vars: if type(subitem) != dict: raise errors.AnsibleError("expected a dictionary") for (k,v) in subitem.items(): group.set_variable(k,v) self.groups[group.name] = group all.add_child_group(group) # add host definitions for item in yaml: if type(item) in [ str, unicode ]: host = self._make_host(item) if host not in grouped_hosts: ungrouped.add_host(host) elif type(item) == dict and 'host' in item: host = self._make_host(item['host']) vars = item.get('vars', {}) if type(vars)==list: varlist, vars = vars, {} for subitem in varlist: vars.update(subitem) for (k,v) in vars.items(): host.set_variable(k,v) groups = item.get('groups', {}) if type(groups) in [ str, unicode ]: groups = [ groups ] if type(groups)==list: for subitem in groups: if subitem in self.groups: group = self.groups[subitem] else: group = Group(subitem) self.groups[group.name] = group all.add_child_group(group) group.add_host(host) grouped_hosts.append(host) if host not in grouped_hosts: ungrouped.add_host(host) # make sure ungrouped.hosts is the complement of grouped_hosts ungrouped_hosts = [host for host in ungrouped.hosts if host not in grouped_hosts] if __name__ == "__main__": if len(sys.argv) != 2: print "usage: yaml_to_ini.py /path/to/ansible/hosts" sys.exit(1) result = "" original = sys.argv[1] yamlp = InventoryParserYaml(filename=sys.argv[1]) dirname = os.path.dirname(original) group_names = [ g.name for g in yamlp.groups.values() ] for group_name in sorted(group_names): record = yamlp.groups[group_name] if group_name == 'all': continue hosts = record.hosts result = result + "[%s]\n" % record.name for h in hosts: result = result + "%s\n" % h.name result = result + "\n" groupfiledir = os.path.join(dirname, "group_vars") if not os.path.exists(groupfiledir): print "* creating: %s" % groupfiledir os.makedirs(groupfiledir) groupfile = os.path.join(groupfiledir, group_name) print "* writing group variables for %s into %s" % (group_name, groupfile) groupfh = open(groupfile, 'w') groupfh.write(yaml.dump(record.get_variables())) groupfh.close() for (host_name, host_record) in iteritems(yamlp._hosts): hostfiledir = os.path.join(dirname, "host_vars") if not os.path.exists(hostfiledir): print "* creating: %s" % hostfiledir os.makedirs(hostfiledir) hostfile = os.path.join(hostfiledir, host_record.name) print "* writing host variables for %s into %s" % (host_record.name, hostfile) hostfh = open(hostfile, 'w') hostfh.write(yaml.dump(host_record.get_variables())) hostfh.close() # also need to keep a hash of variables per each host # and variables per each group # and write those to disk newfilepath = os.path.join(dirname, "hosts.new") fdh = open(newfilepath, 'w') fdh.write(result) fdh.close() print "* COMPLETE: review your new inventory file and replace your original when ready" print "* new inventory file saved as %s" % newfilepath print "* edit group specific variables in %s/group_vars/" % dirname print "* edit host specific variables in %s/host_vars/" % dirname # now need to write this to disk as (oldname).new # and inform the user
gpl-3.0
mlperf/inference_results_v0.7
closed/DellEMC/code/dlrm/tensorrt/accuracy-dlrm.py
18
3009
#! /usr/bin/env python3 # Copyright (c) 2020, NVIDIA CORPORATION. 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. import os, sys sys.path.insert(0, os.getcwd()) import argparse import json import numpy as np from sklearn.metrics import roc_auc_score import datetime def evaluate(log_path, ground_truth_file, sample_partition_file): print("Loading ground truths...") ground_truths = np.load(ground_truth_file) print("Done loading ground truths.") print("Loading sample partition...") sample_partition = np.load(sample_partition_file) print("Parsing LoadGen accuracy log...") expected = [] predicted = [] with open(log_path) as f: predictions = json.load(f) for counter, prediction in enumerate(predictions): if counter % 1000 == 0: print("[{:}] {:} / {:}".format(datetime.datetime.now(), counter, len(predictions))) qsl_idx = prediction["qsl_idx"] assert qsl_idx < len(sample_partition), "qsl_idx exceeds total number of samples in validation dataset" data = np.frombuffer(bytes.fromhex(prediction["data"]), np.float32) start_idx = sample_partition[qsl_idx] end_idx = sample_partition[qsl_idx+1] assert len(data) == end_idx - start_idx, "Length of predictions does not match number of pairs in sample" for i in data: predicted.append(np.nan_to_num(i)) for i in range(start_idx, end_idx): expected.append(ground_truths[i]) print("Done parsing LoadGen accuracy log.") print("Evaluating results...") score = roc_auc_score(expected, predicted) print("Done evaluating results.") print("auc={:.3f}%".format(score * 100)) def main(): parser = argparse.ArgumentParser("Accuracy checker for BERT benchmark from LoadGen logs") parser.add_argument("--mlperf-accuracy-file", help="Path to LoadGen log produced in AccuracyOnly mode") parser.add_argument("--ground-truth-file", help="Path to ground_truth.npy file", default="build/preprocessed_data/criteo/full_recalib/ground_truth.npy") parser.add_argument("--sample-partition-file", help="Path to sample partition file", default=os.path.join(os.environ.get("PREPROCESSED_DATA_DIR", "build/preprocessed_data"), "criteo", "full_recalib", "sample_partition.npy")) args = parser.parse_args() evaluate(args.mlperf_accuracy_file, args.ground_truth_file, args.sample_partition_file) if __name__ == "__main__": main()
apache-2.0
bmannix/selenium
py/selenium/webdriver/opera/options.py
100
3385
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from selenium.webdriver.chrome.options import Options as ChromeOptions from selenium.webdriver.common.desired_capabilities import DesiredCapabilities class Options(ChromeOptions): def __init__(self): ChromeOptions.__init__(self) self._android_package_name = '' self._android_device_socket = '' self._android_command_line_file = '' @property def android_package_name(self): """ Returns the name of the Opera package """ return self._android_package_name @android_package_name.setter def android_package_name(self, value): """ Allows you to set the package name :Args: - value: devtools socket name """ self._android_package_name = value @property def android_device_socket(self): """ Returns the name of the devtools socket """ return self._android_device_socket @android_device_socket.setter def android_device_socket(self, value): """ Allows you to set the devtools socket name :Args: - value: devtools socket name """ self._android_device_socket = value @property def android_command_line_file(self): """ Returns the path of the command line file """ return self._android_command_line_file @android_command_line_file.setter def android_command_line_file(self, value): """ Allows you to set where the command line file lives :Args: - value: command line file path """ self._android_command_line_file = value def to_capabilities(self): """ Creates a capabilities with all the options that have been set and returns a dictionary with everything """ capabilities = ChromeOptions.to_capabilities(self) capabilities.update(DesiredCapabilities.OPERA) opera_options = capabilities["operaOptions"] = \ capabilities.pop("chromeOptions") if self.android_package_name: opera_options["androidPackage"] = self.android_package_name if self.android_device_socket: opera_options["androidDeviceSocket"] = self.android_device_socket if self.android_command_line_file: opera_options["androidCommandLineFile"] = \ self.android_command_line_file return capabilities class AndroidOptions(Options): def __init__(self): Options.__init__(self) self.android_package_name = 'com.opera.browser'
apache-2.0
dmonner/tweater
py/yaml/emitter.py
110
43159
# Emitter expects events obeying the following grammar: # stream ::= STREAM-START document* STREAM-END # document ::= DOCUMENT-START node DOCUMENT-END # node ::= SCALAR | sequence | mapping # sequence ::= SEQUENCE-START node* SEQUENCE-END # mapping ::= MAPPING-START (node node)* MAPPING-END __all__ = ['Emitter', 'EmitterError'] from error import YAMLError from events import * class EmitterError(YAMLError): pass class ScalarAnalysis(object): def __init__(self, scalar, empty, multiline, allow_flow_plain, allow_block_plain, allow_single_quoted, allow_double_quoted, allow_block): self.scalar = scalar self.empty = empty self.multiline = multiline self.allow_flow_plain = allow_flow_plain self.allow_block_plain = allow_block_plain self.allow_single_quoted = allow_single_quoted self.allow_double_quoted = allow_double_quoted self.allow_block = allow_block class Emitter(object): DEFAULT_TAG_PREFIXES = { u'!' : u'!', u'tag:yaml.org,2002:' : u'!!', } def __init__(self, stream, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None): # The stream should have the methods `write` and possibly `flush`. self.stream = stream # Encoding can be overriden by STREAM-START. self.encoding = None # Emitter is a state machine with a stack of states to handle nested # structures. self.states = [] self.state = self.expect_stream_start # Current event and the event queue. self.events = [] self.event = None # The current indentation level and the stack of previous indents. self.indents = [] self.indent = None # Flow level. self.flow_level = 0 # Contexts. self.root_context = False self.sequence_context = False self.mapping_context = False self.simple_key_context = False # Characteristics of the last emitted character: # - current position. # - is it a whitespace? # - is it an indention character # (indentation space, '-', '?', or ':')? self.line = 0 self.column = 0 self.whitespace = True self.indention = True # Whether the document requires an explicit document indicator self.open_ended = False # Formatting details. self.canonical = canonical self.allow_unicode = allow_unicode self.best_indent = 2 if indent and 1 < indent < 10: self.best_indent = indent self.best_width = 80 if width and width > self.best_indent*2: self.best_width = width self.best_line_break = u'\n' if line_break in [u'\r', u'\n', u'\r\n']: self.best_line_break = line_break # Tag prefixes. self.tag_prefixes = None # Prepared anchor and tag. self.prepared_anchor = None self.prepared_tag = None # Scalar analysis and style. self.analysis = None self.style = None def emit(self, event): self.events.append(event) while not self.need_more_events(): self.event = self.events.pop(0) self.state() self.event = None # In some cases, we wait for a few next events before emitting. def need_more_events(self): if not self.events: return True event = self.events[0] if isinstance(event, DocumentStartEvent): return self.need_events(1) elif isinstance(event, SequenceStartEvent): return self.need_events(2) elif isinstance(event, MappingStartEvent): return self.need_events(3) else: return False def need_events(self, count): level = 0 for event in self.events[1:]: if isinstance(event, (DocumentStartEvent, CollectionStartEvent)): level += 1 elif isinstance(event, (DocumentEndEvent, CollectionEndEvent)): level -= 1 elif isinstance(event, StreamEndEvent): level = -1 if level < 0: return False return (len(self.events) < count+1) def increase_indent(self, flow=False, indentless=False): self.indents.append(self.indent) if self.indent is None: if flow: self.indent = self.best_indent else: self.indent = 0 elif not indentless: self.indent += self.best_indent # States. # Stream handlers. def expect_stream_start(self): if isinstance(self.event, StreamStartEvent): if self.event.encoding and not getattr(self.stream, 'encoding', None): self.encoding = self.event.encoding self.write_stream_start() self.state = self.expect_first_document_start else: raise EmitterError("expected StreamStartEvent, but got %s" % self.event) def expect_nothing(self): raise EmitterError("expected nothing, but got %s" % self.event) # Document handlers. def expect_first_document_start(self): return self.expect_document_start(first=True) def expect_document_start(self, first=False): if isinstance(self.event, DocumentStartEvent): if (self.event.version or self.event.tags) and self.open_ended: self.write_indicator(u'...', True) self.write_indent() if self.event.version: version_text = self.prepare_version(self.event.version) self.write_version_directive(version_text) self.tag_prefixes = self.DEFAULT_TAG_PREFIXES.copy() if self.event.tags: handles = self.event.tags.keys() handles.sort() for handle in handles: prefix = self.event.tags[handle] self.tag_prefixes[prefix] = handle handle_text = self.prepare_tag_handle(handle) prefix_text = self.prepare_tag_prefix(prefix) self.write_tag_directive(handle_text, prefix_text) implicit = (first and not self.event.explicit and not self.canonical and not self.event.version and not self.event.tags and not self.check_empty_document()) if not implicit: self.write_indent() self.write_indicator(u'---', True) if self.canonical: self.write_indent() self.state = self.expect_document_root elif isinstance(self.event, StreamEndEvent): if self.open_ended: self.write_indicator(u'...', True) self.write_indent() self.write_stream_end() self.state = self.expect_nothing else: raise EmitterError("expected DocumentStartEvent, but got %s" % self.event) def expect_document_end(self): if isinstance(self.event, DocumentEndEvent): self.write_indent() if self.event.explicit: self.write_indicator(u'...', True) self.write_indent() self.flush_stream() self.state = self.expect_document_start else: raise EmitterError("expected DocumentEndEvent, but got %s" % self.event) def expect_document_root(self): self.states.append(self.expect_document_end) self.expect_node(root=True) # Node handlers. def expect_node(self, root=False, sequence=False, mapping=False, simple_key=False): self.root_context = root self.sequence_context = sequence self.mapping_context = mapping self.simple_key_context = simple_key if isinstance(self.event, AliasEvent): self.expect_alias() elif isinstance(self.event, (ScalarEvent, CollectionStartEvent)): self.process_anchor(u'&') self.process_tag() if isinstance(self.event, ScalarEvent): self.expect_scalar() elif isinstance(self.event, SequenceStartEvent): if self.flow_level or self.canonical or self.event.flow_style \ or self.check_empty_sequence(): self.expect_flow_sequence() else: self.expect_block_sequence() elif isinstance(self.event, MappingStartEvent): if self.flow_level or self.canonical or self.event.flow_style \ or self.check_empty_mapping(): self.expect_flow_mapping() else: self.expect_block_mapping() else: raise EmitterError("expected NodeEvent, but got %s" % self.event) def expect_alias(self): if self.event.anchor is None: raise EmitterError("anchor is not specified for alias") self.process_anchor(u'*') self.state = self.states.pop() def expect_scalar(self): self.increase_indent(flow=True) self.process_scalar() self.indent = self.indents.pop() self.state = self.states.pop() # Flow sequence handlers. def expect_flow_sequence(self): self.write_indicator(u'[', True, whitespace=True) self.flow_level += 1 self.increase_indent(flow=True) self.state = self.expect_first_flow_sequence_item def expect_first_flow_sequence_item(self): if isinstance(self.event, SequenceEndEvent): self.indent = self.indents.pop() self.flow_level -= 1 self.write_indicator(u']', False) self.state = self.states.pop() else: if self.canonical or self.column > self.best_width: self.write_indent() self.states.append(self.expect_flow_sequence_item) self.expect_node(sequence=True) def expect_flow_sequence_item(self): if isinstance(self.event, SequenceEndEvent): self.indent = self.indents.pop() self.flow_level -= 1 if self.canonical: self.write_indicator(u',', False) self.write_indent() self.write_indicator(u']', False) self.state = self.states.pop() else: self.write_indicator(u',', False) if self.canonical or self.column > self.best_width: self.write_indent() self.states.append(self.expect_flow_sequence_item) self.expect_node(sequence=True) # Flow mapping handlers. def expect_flow_mapping(self): self.write_indicator(u'{', True, whitespace=True) self.flow_level += 1 self.increase_indent(flow=True) self.state = self.expect_first_flow_mapping_key def expect_first_flow_mapping_key(self): if isinstance(self.event, MappingEndEvent): self.indent = self.indents.pop() self.flow_level -= 1 self.write_indicator(u'}', False) self.state = self.states.pop() else: if self.canonical or self.column > self.best_width: self.write_indent() if not self.canonical and self.check_simple_key(): self.states.append(self.expect_flow_mapping_simple_value) self.expect_node(mapping=True, simple_key=True) else: self.write_indicator(u'?', True) self.states.append(self.expect_flow_mapping_value) self.expect_node(mapping=True) def expect_flow_mapping_key(self): if isinstance(self.event, MappingEndEvent): self.indent = self.indents.pop() self.flow_level -= 1 if self.canonical: self.write_indicator(u',', False) self.write_indent() self.write_indicator(u'}', False) self.state = self.states.pop() else: self.write_indicator(u',', False) if self.canonical or self.column > self.best_width: self.write_indent() if not self.canonical and self.check_simple_key(): self.states.append(self.expect_flow_mapping_simple_value) self.expect_node(mapping=True, simple_key=True) else: self.write_indicator(u'?', True) self.states.append(self.expect_flow_mapping_value) self.expect_node(mapping=True) def expect_flow_mapping_simple_value(self): self.write_indicator(u':', False) self.states.append(self.expect_flow_mapping_key) self.expect_node(mapping=True) def expect_flow_mapping_value(self): if self.canonical or self.column > self.best_width: self.write_indent() self.write_indicator(u':', True) self.states.append(self.expect_flow_mapping_key) self.expect_node(mapping=True) # Block sequence handlers. def expect_block_sequence(self): indentless = (self.mapping_context and not self.indention) self.increase_indent(flow=False, indentless=indentless) self.state = self.expect_first_block_sequence_item def expect_first_block_sequence_item(self): return self.expect_block_sequence_item(first=True) def expect_block_sequence_item(self, first=False): if not first and isinstance(self.event, SequenceEndEvent): self.indent = self.indents.pop() self.state = self.states.pop() else: self.write_indent() self.write_indicator(u'-', True, indention=True) self.states.append(self.expect_block_sequence_item) self.expect_node(sequence=True) # Block mapping handlers. def expect_block_mapping(self): self.increase_indent(flow=False) self.state = self.expect_first_block_mapping_key def expect_first_block_mapping_key(self): return self.expect_block_mapping_key(first=True) def expect_block_mapping_key(self, first=False): if not first and isinstance(self.event, MappingEndEvent): self.indent = self.indents.pop() self.state = self.states.pop() else: self.write_indent() if self.check_simple_key(): self.states.append(self.expect_block_mapping_simple_value) self.expect_node(mapping=True, simple_key=True) else: self.write_indicator(u'?', True, indention=True) self.states.append(self.expect_block_mapping_value) self.expect_node(mapping=True) def expect_block_mapping_simple_value(self): self.write_indicator(u':', False) self.states.append(self.expect_block_mapping_key) self.expect_node(mapping=True) def expect_block_mapping_value(self): self.write_indent() self.write_indicator(u':', True, indention=True) self.states.append(self.expect_block_mapping_key) self.expect_node(mapping=True) # Checkers. def check_empty_sequence(self): return (isinstance(self.event, SequenceStartEvent) and self.events and isinstance(self.events[0], SequenceEndEvent)) def check_empty_mapping(self): return (isinstance(self.event, MappingStartEvent) and self.events and isinstance(self.events[0], MappingEndEvent)) def check_empty_document(self): if not isinstance(self.event, DocumentStartEvent) or not self.events: return False event = self.events[0] return (isinstance(event, ScalarEvent) and event.anchor is None and event.tag is None and event.implicit and event.value == u'') def check_simple_key(self): length = 0 if isinstance(self.event, NodeEvent) and self.event.anchor is not None: if self.prepared_anchor is None: self.prepared_anchor = self.prepare_anchor(self.event.anchor) length += len(self.prepared_anchor) if isinstance(self.event, (ScalarEvent, CollectionStartEvent)) \ and self.event.tag is not None: if self.prepared_tag is None: self.prepared_tag = self.prepare_tag(self.event.tag) length += len(self.prepared_tag) if isinstance(self.event, ScalarEvent): if self.analysis is None: self.analysis = self.analyze_scalar(self.event.value) length += len(self.analysis.scalar) return (length < 128 and (isinstance(self.event, AliasEvent) or (isinstance(self.event, ScalarEvent) and not self.analysis.empty and not self.analysis.multiline) or self.check_empty_sequence() or self.check_empty_mapping())) # Anchor, Tag, and Scalar processors. def process_anchor(self, indicator): if self.event.anchor is None: self.prepared_anchor = None return if self.prepared_anchor is None: self.prepared_anchor = self.prepare_anchor(self.event.anchor) if self.prepared_anchor: self.write_indicator(indicator+self.prepared_anchor, True) self.prepared_anchor = None def process_tag(self): tag = self.event.tag if isinstance(self.event, ScalarEvent): if self.style is None: self.style = self.choose_scalar_style() if ((not self.canonical or tag is None) and ((self.style == '' and self.event.implicit[0]) or (self.style != '' and self.event.implicit[1]))): self.prepared_tag = None return if self.event.implicit[0] and tag is None: tag = u'!' self.prepared_tag = None else: if (not self.canonical or tag is None) and self.event.implicit: self.prepared_tag = None return if tag is None: raise EmitterError("tag is not specified") if self.prepared_tag is None: self.prepared_tag = self.prepare_tag(tag) if self.prepared_tag: self.write_indicator(self.prepared_tag, True) self.prepared_tag = None def choose_scalar_style(self): if self.analysis is None: self.analysis = self.analyze_scalar(self.event.value) if self.event.style == '"' or self.canonical: return '"' if not self.event.style and self.event.implicit[0]: if (not (self.simple_key_context and (self.analysis.empty or self.analysis.multiline)) and (self.flow_level and self.analysis.allow_flow_plain or (not self.flow_level and self.analysis.allow_block_plain))): return '' if self.event.style and self.event.style in '|>': if (not self.flow_level and not self.simple_key_context and self.analysis.allow_block): return self.event.style if not self.event.style or self.event.style == '\'': if (self.analysis.allow_single_quoted and not (self.simple_key_context and self.analysis.multiline)): return '\'' return '"' def process_scalar(self): if self.analysis is None: self.analysis = self.analyze_scalar(self.event.value) if self.style is None: self.style = self.choose_scalar_style() split = (not self.simple_key_context) #if self.analysis.multiline and split \ # and (not self.style or self.style in '\'\"'): # self.write_indent() if self.style == '"': self.write_double_quoted(self.analysis.scalar, split) elif self.style == '\'': self.write_single_quoted(self.analysis.scalar, split) elif self.style == '>': self.write_folded(self.analysis.scalar) elif self.style == '|': self.write_literal(self.analysis.scalar) else: self.write_plain(self.analysis.scalar, split) self.analysis = None self.style = None # Analyzers. def prepare_version(self, version): major, minor = version if major != 1: raise EmitterError("unsupported YAML version: %d.%d" % (major, minor)) return u'%d.%d' % (major, minor) def prepare_tag_handle(self, handle): if not handle: raise EmitterError("tag handle must not be empty") if handle[0] != u'!' or handle[-1] != u'!': raise EmitterError("tag handle must start and end with '!': %r" % (handle.encode('utf-8'))) for ch in handle[1:-1]: if not (u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \ or ch in u'-_'): raise EmitterError("invalid character %r in the tag handle: %r" % (ch.encode('utf-8'), handle.encode('utf-8'))) return handle def prepare_tag_prefix(self, prefix): if not prefix: raise EmitterError("tag prefix must not be empty") chunks = [] start = end = 0 if prefix[0] == u'!': end = 1 while end < len(prefix): ch = prefix[end] if u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \ or ch in u'-;/?!:@&=+$,_.~*\'()[]': end += 1 else: if start < end: chunks.append(prefix[start:end]) start = end = end+1 data = ch.encode('utf-8') for ch in data: chunks.append(u'%%%02X' % ord(ch)) if start < end: chunks.append(prefix[start:end]) return u''.join(chunks) def prepare_tag(self, tag): if not tag: raise EmitterError("tag must not be empty") if tag == u'!': return tag handle = None suffix = tag prefixes = self.tag_prefixes.keys() prefixes.sort() for prefix in prefixes: if tag.startswith(prefix) \ and (prefix == u'!' or len(prefix) < len(tag)): handle = self.tag_prefixes[prefix] suffix = tag[len(prefix):] chunks = [] start = end = 0 while end < len(suffix): ch = suffix[end] if u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \ or ch in u'-;/?:@&=+$,_.~*\'()[]' \ or (ch == u'!' and handle != u'!'): end += 1 else: if start < end: chunks.append(suffix[start:end]) start = end = end+1 data = ch.encode('utf-8') for ch in data: chunks.append(u'%%%02X' % ord(ch)) if start < end: chunks.append(suffix[start:end]) suffix_text = u''.join(chunks) if handle: return u'%s%s' % (handle, suffix_text) else: return u'!<%s>' % suffix_text def prepare_anchor(self, anchor): if not anchor: raise EmitterError("anchor must not be empty") for ch in anchor: if not (u'0' <= ch <= u'9' or u'A' <= ch <= u'Z' or u'a' <= ch <= u'z' \ or ch in u'-_'): raise EmitterError("invalid character %r in the anchor: %r" % (ch.encode('utf-8'), anchor.encode('utf-8'))) return anchor def analyze_scalar(self, scalar): # Empty scalar is a special case. if not scalar: return ScalarAnalysis(scalar=scalar, empty=True, multiline=False, allow_flow_plain=False, allow_block_plain=True, allow_single_quoted=True, allow_double_quoted=True, allow_block=False) # Indicators and special characters. block_indicators = False flow_indicators = False line_breaks = False special_characters = False # Important whitespace combinations. leading_space = False leading_break = False trailing_space = False trailing_break = False break_space = False space_break = False # Check document indicators. if scalar.startswith(u'---') or scalar.startswith(u'...'): block_indicators = True flow_indicators = True # First character or preceded by a whitespace. preceeded_by_whitespace = True # Last character or followed by a whitespace. followed_by_whitespace = (len(scalar) == 1 or scalar[1] in u'\0 \t\r\n\x85\u2028\u2029') # The previous character is a space. previous_space = False # The previous character is a break. previous_break = False index = 0 while index < len(scalar): ch = scalar[index] # Check for indicators. if index == 0: # Leading indicators are special characters. if ch in u'#,[]{}&*!|>\'\"%@`': flow_indicators = True block_indicators = True if ch in u'?:': flow_indicators = True if followed_by_whitespace: block_indicators = True if ch == u'-' and followed_by_whitespace: flow_indicators = True block_indicators = True else: # Some indicators cannot appear within a scalar as well. if ch in u',?[]{}': flow_indicators = True if ch == u':': flow_indicators = True if followed_by_whitespace: block_indicators = True if ch == u'#' and preceeded_by_whitespace: flow_indicators = True block_indicators = True # Check for line breaks, special, and unicode characters. if ch in u'\n\x85\u2028\u2029': line_breaks = True if not (ch == u'\n' or u'\x20' <= ch <= u'\x7E'): if (ch == u'\x85' or u'\xA0' <= ch <= u'\uD7FF' or u'\uE000' <= ch <= u'\uFFFD') and ch != u'\uFEFF': unicode_characters = True if not self.allow_unicode: special_characters = True else: special_characters = True # Detect important whitespace combinations. if ch == u' ': if index == 0: leading_space = True if index == len(scalar)-1: trailing_space = True if previous_break: break_space = True previous_space = True previous_break = False elif ch in u'\n\x85\u2028\u2029': if index == 0: leading_break = True if index == len(scalar)-1: trailing_break = True if previous_space: space_break = True previous_space = False previous_break = True else: previous_space = False previous_break = False # Prepare for the next character. index += 1 preceeded_by_whitespace = (ch in u'\0 \t\r\n\x85\u2028\u2029') followed_by_whitespace = (index+1 >= len(scalar) or scalar[index+1] in u'\0 \t\r\n\x85\u2028\u2029') # Let's decide what styles are allowed. allow_flow_plain = True allow_block_plain = True allow_single_quoted = True allow_double_quoted = True allow_block = True # Leading and trailing whitespaces are bad for plain scalars. if (leading_space or leading_break or trailing_space or trailing_break): allow_flow_plain = allow_block_plain = False # We do not permit trailing spaces for block scalars. if trailing_space: allow_block = False # Spaces at the beginning of a new line are only acceptable for block # scalars. if break_space: allow_flow_plain = allow_block_plain = allow_single_quoted = False # Spaces followed by breaks, as well as special character are only # allowed for double quoted scalars. if space_break or special_characters: allow_flow_plain = allow_block_plain = \ allow_single_quoted = allow_block = False # Although the plain scalar writer supports breaks, we never emit # multiline plain scalars. if line_breaks: allow_flow_plain = allow_block_plain = False # Flow indicators are forbidden for flow plain scalars. if flow_indicators: allow_flow_plain = False # Block indicators are forbidden for block plain scalars. if block_indicators: allow_block_plain = False return ScalarAnalysis(scalar=scalar, empty=False, multiline=line_breaks, allow_flow_plain=allow_flow_plain, allow_block_plain=allow_block_plain, allow_single_quoted=allow_single_quoted, allow_double_quoted=allow_double_quoted, allow_block=allow_block) # Writers. def flush_stream(self): if hasattr(self.stream, 'flush'): self.stream.flush() def write_stream_start(self): # Write BOM if needed. if self.encoding and self.encoding.startswith('utf-16'): self.stream.write(u'\uFEFF'.encode(self.encoding)) def write_stream_end(self): self.flush_stream() def write_indicator(self, indicator, need_whitespace, whitespace=False, indention=False): if self.whitespace or not need_whitespace: data = indicator else: data = u' '+indicator self.whitespace = whitespace self.indention = self.indention and indention self.column += len(data) self.open_ended = False if self.encoding: data = data.encode(self.encoding) self.stream.write(data) def write_indent(self): indent = self.indent or 0 if not self.indention or self.column > indent \ or (self.column == indent and not self.whitespace): self.write_line_break() if self.column < indent: self.whitespace = True data = u' '*(indent-self.column) self.column = indent if self.encoding: data = data.encode(self.encoding) self.stream.write(data) def write_line_break(self, data=None): if data is None: data = self.best_line_break self.whitespace = True self.indention = True self.line += 1 self.column = 0 if self.encoding: data = data.encode(self.encoding) self.stream.write(data) def write_version_directive(self, version_text): data = u'%%YAML %s' % version_text if self.encoding: data = data.encode(self.encoding) self.stream.write(data) self.write_line_break() def write_tag_directive(self, handle_text, prefix_text): data = u'%%TAG %s %s' % (handle_text, prefix_text) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) self.write_line_break() # Scalar streams. def write_single_quoted(self, text, split=True): self.write_indicator(u'\'', True) spaces = False breaks = False start = end = 0 while end <= len(text): ch = None if end < len(text): ch = text[end] if spaces: if ch is None or ch != u' ': if start+1 == end and self.column > self.best_width and split \ and start != 0 and end != len(text): self.write_indent() else: data = text[start:end] self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end elif breaks: if ch is None or ch not in u'\n\x85\u2028\u2029': if text[start] == u'\n': self.write_line_break() for br in text[start:end]: if br == u'\n': self.write_line_break() else: self.write_line_break(br) self.write_indent() start = end else: if ch is None or ch in u' \n\x85\u2028\u2029' or ch == u'\'': if start < end: data = text[start:end] self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end if ch == u'\'': data = u'\'\'' self.column += 2 if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end + 1 if ch is not None: spaces = (ch == u' ') breaks = (ch in u'\n\x85\u2028\u2029') end += 1 self.write_indicator(u'\'', False) ESCAPE_REPLACEMENTS = { u'\0': u'0', u'\x07': u'a', u'\x08': u'b', u'\x09': u't', u'\x0A': u'n', u'\x0B': u'v', u'\x0C': u'f', u'\x0D': u'r', u'\x1B': u'e', u'\"': u'\"', u'\\': u'\\', u'\x85': u'N', u'\xA0': u'_', u'\u2028': u'L', u'\u2029': u'P', } def write_double_quoted(self, text, split=True): self.write_indicator(u'"', True) start = end = 0 while end <= len(text): ch = None if end < len(text): ch = text[end] if ch is None or ch in u'"\\\x85\u2028\u2029\uFEFF' \ or not (u'\x20' <= ch <= u'\x7E' or (self.allow_unicode and (u'\xA0' <= ch <= u'\uD7FF' or u'\uE000' <= ch <= u'\uFFFD'))): if start < end: data = text[start:end] self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end if ch is not None: if ch in self.ESCAPE_REPLACEMENTS: data = u'\\'+self.ESCAPE_REPLACEMENTS[ch] elif ch <= u'\xFF': data = u'\\x%02X' % ord(ch) elif ch <= u'\uFFFF': data = u'\\u%04X' % ord(ch) else: data = u'\\U%08X' % ord(ch) self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end+1 if 0 < end < len(text)-1 and (ch == u' ' or start >= end) \ and self.column+(end-start) > self.best_width and split: data = text[start:end]+u'\\' if start < end: start = end self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) self.write_indent() self.whitespace = False self.indention = False if text[start] == u' ': data = u'\\' self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) end += 1 self.write_indicator(u'"', False) def determine_block_hints(self, text): hints = u'' if text: if text[0] in u' \n\x85\u2028\u2029': hints += unicode(self.best_indent) if text[-1] not in u'\n\x85\u2028\u2029': hints += u'-' elif len(text) == 1 or text[-2] in u'\n\x85\u2028\u2029': hints += u'+' return hints def write_folded(self, text): hints = self.determine_block_hints(text) self.write_indicator(u'>'+hints, True) if hints[-1:] == u'+': self.open_ended = True self.write_line_break() leading_space = True spaces = False breaks = True start = end = 0 while end <= len(text): ch = None if end < len(text): ch = text[end] if breaks: if ch is None or ch not in u'\n\x85\u2028\u2029': if not leading_space and ch is not None and ch != u' ' \ and text[start] == u'\n': self.write_line_break() leading_space = (ch == u' ') for br in text[start:end]: if br == u'\n': self.write_line_break() else: self.write_line_break(br) if ch is not None: self.write_indent() start = end elif spaces: if ch != u' ': if start+1 == end and self.column > self.best_width: self.write_indent() else: data = text[start:end] self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end else: if ch is None or ch in u' \n\x85\u2028\u2029': data = text[start:end] self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) if ch is None: self.write_line_break() start = end if ch is not None: breaks = (ch in u'\n\x85\u2028\u2029') spaces = (ch == u' ') end += 1 def write_literal(self, text): hints = self.determine_block_hints(text) self.write_indicator(u'|'+hints, True) if hints[-1:] == u'+': self.open_ended = True self.write_line_break() breaks = True start = end = 0 while end <= len(text): ch = None if end < len(text): ch = text[end] if breaks: if ch is None or ch not in u'\n\x85\u2028\u2029': for br in text[start:end]: if br == u'\n': self.write_line_break() else: self.write_line_break(br) if ch is not None: self.write_indent() start = end else: if ch is None or ch in u'\n\x85\u2028\u2029': data = text[start:end] if self.encoding: data = data.encode(self.encoding) self.stream.write(data) if ch is None: self.write_line_break() start = end if ch is not None: breaks = (ch in u'\n\x85\u2028\u2029') end += 1 def write_plain(self, text, split=True): if self.root_context: self.open_ended = True if not text: return if not self.whitespace: data = u' ' self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) self.whitespace = False self.indention = False spaces = False breaks = False start = end = 0 while end <= len(text): ch = None if end < len(text): ch = text[end] if spaces: if ch != u' ': if start+1 == end and self.column > self.best_width and split: self.write_indent() self.whitespace = False self.indention = False else: data = text[start:end] self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end elif breaks: if ch not in u'\n\x85\u2028\u2029': if text[start] == u'\n': self.write_line_break() for br in text[start:end]: if br == u'\n': self.write_line_break() else: self.write_line_break(br) self.write_indent() self.whitespace = False self.indention = False start = end else: if ch is None or ch in u' \n\x85\u2028\u2029': data = text[start:end] self.column += len(data) if self.encoding: data = data.encode(self.encoding) self.stream.write(data) start = end if ch is not None: spaces = (ch == u' ') breaks = (ch in u'\n\x85\u2028\u2029') end += 1
gpl-3.0
JohnnyKing94/pootle
tests/forms/contact.py
5
9854
# -*- coding: utf-8 -*- # # Copyright (C) Pootle contributors. # # This file is a part of the Pootle project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. from __future__ import absolute_import import pytest from django.conf import settings from django.template.defaultfilters import escape from django.template.loader import render_to_string from contact.forms import ContactForm, ReportForm from pootle_store.models import Unit @pytest.mark.django_db def test_contact_form(admin, rf, mailoutbox): request = rf.request() request.user = admin request.META['REMOTE_ADDR'] = '127.0.0.1' recipient_email = settings.POOTLE_CONTACT_EMAIL specified_subject = "My subject" subject = "[%s] %s" % (settings.POOTLE_TITLE, specified_subject) data = { 'name': admin.full_name, 'email': admin.email, 'email_subject': specified_subject, 'body': "First paragraph of message\n\nSecond paragraph of message.", } form = ContactForm(request=request, data=data) assert form.is_valid() form.save() assert len(mailoutbox) == 1 message = mailoutbox[0] assert message.from_email == settings.DEFAULT_FROM_EMAIL reply_to = u'%s <%s>' % (data['name'], data['email']) assert reply_to == message.extra_headers['Reply-To'] assert [recipient_email] == message.recipients() assert subject == message.subject assert data['body'] in message.body assert "Your question or comment:" not in message.body @pytest.mark.django_db def test_contact_form_escaped_tags(admin, rf, mailoutbox): request = rf.request() request.user = admin request.META['REMOTE_ADDR'] = '127.0.0.1' recipient_email = settings.POOTLE_CONTACT_EMAIL specified_subject = "My <tag> subject" subject = "[%s] %s" % (settings.POOTLE_TITLE, specified_subject) data = { 'name': admin.full_name, 'email': admin.email, 'email_subject': specified_subject, 'body': "First <tag> of message.", } form = ContactForm(request=request, data=data) assert form.is_valid() form.save() assert len(mailoutbox) == 1 message = mailoutbox[0] assert message.from_email == settings.DEFAULT_FROM_EMAIL reply_to = u'%s <%s>' % (data['name'], data['email']) assert reply_to == message.extra_headers['Reply-To'] assert [recipient_email] == message.recipients() assert escape(subject) == message.subject assert escape(data['body']) in message.body assert "Your question or comment:" not in message.body @pytest.mark.django_db def test_contact_form_subject(admin, rf, mailoutbox): request = rf.request() request.user = admin request.META['REMOTE_ADDR'] = '127.0.0.1' data = { 'name': admin.full_name, 'email': admin.email, 'email_subject': "a" * 101, 'body': "Whatever", } form = ContactForm(request=request, data=data) assert not form.is_valid() data['email_subject'] = "a" * 100 form = ContactForm(request=request, data=data) assert form.is_valid() @pytest.mark.django_db def test_contact_form_required_fields(admin, rf, mailoutbox): request = rf.request() request.user = admin request.META['REMOTE_ADDR'] = '127.0.0.1' form = ContactForm(request=request, data={}) assert not form.is_valid() assert 'email' in form.errors assert form.errors['email'] == [u'This field is required.'] assert 'name' in form.errors assert form.errors['name'] == [u'This field is required.'] assert 'email_subject' in form.errors assert form.errors['email_subject'] == [u'This field is required.'] assert 'body' in form.errors assert form.errors['body'] == [u'This field is required.'] def _test_report_form(unit, recipient_email, user, rf, mailoutbox): request = rf.request() request.user = user request.META['REMOTE_ADDR'] = '127.0.0.1' # Get initial data for the form. subject_ctx = { 'server_name': settings.POOTLE_TITLE, 'unit': unit.pk, 'language': unit.store.translation_project.language.code, 'project': unit.store.translation_project.project.code, } subject = render_to_string('contact_form/report_form_subject.txt', context=subject_ctx) subject = subject.strip() context_ctx = { 'unit': unit, 'unit_absolute_url': request.build_absolute_uri(unit.get_translate_url()), } context = render_to_string('contact_form/report_form_context.txt', context=context_ctx) context = context.strip() translator_comment = "The string is wrong" data = { 'name': user.full_name, 'email': user.email, 'context': context, 'body': translator_comment, } email_body_ctx = { 'request': request, 'context': context, 'ip_address': '127.0.0.1', 'body': translator_comment, } email_body = render_to_string('contact_form/report_form.txt', context=email_body_ctx) # Instantiate form and test. form = ReportForm(request=request, initial=data, data=data, unit=unit) assert form.is_valid() form.save() assert len(mailoutbox) == 1 message = mailoutbox[0] assert message.from_email == settings.DEFAULT_FROM_EMAIL reply_to = u'%s <%s>' % (data['name'], data['email']) assert reply_to == message.extra_headers['Reply-To'] assert [recipient_email] == message.recipients() assert message.subject.startswith(u'[%s] ' % settings.POOTLE_TITLE) assert subject == message.subject assert email_body in message.body @pytest.mark.django_db def test_report_error_form_settings_email(admin, rf, mailoutbox): unit = Unit.objects.select_related( 'store__translation_project__project', 'store__translation_project__language', ).last() recipient_email = getattr(settings, 'POOTLE_CONTACT_REPORT_EMAIL', settings.POOTLE_CONTACT_EMAIL) _test_report_form(unit, recipient_email, admin, rf, mailoutbox) @pytest.mark.django_db def test_report_error_form_project_email(admin, rf, mailoutbox): unit = Unit.objects.select_related( 'store__translation_project__project', 'store__translation_project__language', ).last() project = unit.store.translation_project.project project.report_email = "errors@example.net" project.save() _test_report_form(unit, project.report_email, admin, rf, mailoutbox) @pytest.mark.django_db def test_report_error_form_context_cannot_be_altered(admin, rf, mailoutbox): request = rf.request() request.user = admin request.META['REMOTE_ADDR'] = '127.0.0.1' unit = Unit.objects.select_related( 'store__translation_project__project', 'store__translation_project__language', ).last() context_ctx = { 'unit': unit, 'unit_absolute_url': request.build_absolute_uri(unit.get_translate_url()), } context = render_to_string('contact_form/report_form_context.txt', context=context_ctx) context = context.strip() initial = { 'name': admin.full_name, 'email': admin.email, 'context': context, 'body': "The string is wrong", } data = initial.copy() sent_context = "Different context" data['context'] = sent_context # Instantiate form and test. form = ReportForm(request=request, initial=initial, data=data, unit=unit) assert form.is_valid() form.save() assert len(mailoutbox) == 1 message = mailoutbox[0] assert sent_context not in message.body @pytest.mark.django_db def test_report_error_form_escaped_tags(admin, rf, mailoutbox): request = rf.request() request.user = admin request.META['REMOTE_ADDR'] = '127.0.0.1' unit_target = "some <tag>" unit = Unit.objects.select_related( 'store__translation_project__project', 'store__translation_project__language', ).last() unit.target = unit_target unit.save() context_ctx = { 'unit': unit, 'unit_absolute_url': request.build_absolute_uri(unit.get_translate_url()), } context = render_to_string('contact_form/report_form_context.txt', context=context_ctx) context = context.strip() data = { 'name': admin.full_name, 'email': admin.email, 'context': context, 'body': "The string <tag> is wrong", } # Instantiate form and test. form = ReportForm(request=request, initial=data, data=data, unit=unit) assert form.is_valid() form.save() assert len(mailoutbox) == 1 message = mailoutbox[0] assert escape(unit_target) in message.body assert escape(data['body']) in message.body @pytest.mark.django_db def test_report_error_form_required_fields(admin, rf, mailoutbox): request = rf.request() request.user = admin request.META['REMOTE_ADDR'] = '127.0.0.1' unit = Unit.objects.select_related( 'store__translation_project__project', 'store__translation_project__language', ).last() # Instantiate form and test. form = ReportForm(request=request, initial={}, data={}, unit=unit) assert not form.is_valid() assert 'email' in form.errors assert form.errors['email'] == [u'This field is required.'] assert 'name' in form.errors assert form.errors['name'] == [u'This field is required.'] assert 'context' in form.errors assert form.errors['context'] == [u'This field is required.'] assert 'body' in form.errors assert form.errors['body'] == [u'This field is required.']
gpl-3.0
FNST-OpenStack/horizon
openstack_dashboard/api/vpn.py
27
14820
# Copyright 2013, Mirantis 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. from __future__ import absolute_import from collections import OrderedDict from horizon.utils.memoized import memoized # noqa from openstack_dashboard.api import neutron neutronclient = neutron.neutronclient class IKEPolicy(neutron.NeutronAPIDictWrapper): """Wrapper for neutron VPN IKEPolicy.""" def __init__(self, apiresource): super(IKEPolicy, self).__init__(apiresource) class IPSecPolicy(neutron.NeutronAPIDictWrapper): """Wrapper for neutron VPN IPSecPolicy.""" def __init__(self, apiresource): super(IPSecPolicy, self).__init__(apiresource) class IPSecSiteConnection(neutron.NeutronAPIDictWrapper): """Wrapper for neutron IPSecSiteConnection.""" def __init__(self, apiresource): super(IPSecSiteConnection, self).__init__(apiresource) class VPNService(neutron.NeutronAPIDictWrapper): """Wrapper for neutron VPNService.""" def __init__(self, apiresource): super(VPNService, self).__init__(apiresource) def vpnservice_create(request, **kwargs): """Create VPNService :param request: request context :param admin_state_up: admin state (default on) :param name: name for VPNService :param description: description for VPNService :param router_id: router id for router of VPNService :param subnet_id: subnet id for subnet of VPNService """ body = {'vpnservice': {'admin_state_up': kwargs['admin_state_up'], 'name': kwargs['name'], 'description': kwargs['description'], 'router_id': kwargs['router_id'], 'subnet_id': kwargs['subnet_id']} } vpnservice = neutronclient(request).create_vpnservice(body).get( 'vpnservice') return VPNService(vpnservice) def vpnservice_list(request, **kwargs): return _vpnservice_list(request, expand_subnet=True, expand_router=True, expand_conns=True, **kwargs) def _vpnservice_list(request, expand_subnet=False, expand_router=False, expand_conns=False, **kwargs): vpnservices = neutronclient(request).list_vpnservices( **kwargs).get('vpnservices') if expand_subnet: subnets = neutron.subnet_list(request) subnet_dict = OrderedDict((s.id, s) for s in subnets) for s in vpnservices: s['subnet_name'] = subnet_dict.get(s['subnet_id']).cidr if expand_router: routers = neutron.router_list(request) router_dict = OrderedDict((r.id, r) for r in routers) for s in vpnservices: s['router_name'] = router_dict.get(s['router_id']).name_or_id if expand_conns: ipsecsiteconns = _ipsecsiteconnection_list(request, **kwargs) for s in vpnservices: s['ipsecsiteconns'] = [c.id for c in ipsecsiteconns if c.vpnservice_id == s['id']] return [VPNService(v) for v in vpnservices] def vpnservice_get(request, vpnservice_id): return _vpnservice_get(request, vpnservice_id, expand_subnet=True, expand_router=True, expand_conns=True) def _vpnservice_get(request, vpnservice_id, expand_subnet=False, expand_router=False, expand_conns=False): vpnservice = neutronclient(request).show_vpnservice(vpnservice_id).get( 'vpnservice') if expand_subnet: vpnservice['subnet'] = neutron.subnet_get( request, vpnservice['subnet_id']) if expand_router: vpnservice['router'] = neutron.router_get( request, vpnservice['router_id']) if expand_conns: ipsecsiteconns = _ipsecsiteconnection_list(request) vpnservice['ipsecsiteconns'] = [c for c in ipsecsiteconns if c.vpnservice_id == vpnservice['id']] return VPNService(vpnservice) def vpnservice_update(request, vpnservice_id, **kwargs): vpnservice = neutronclient(request).update_vpnservice( vpnservice_id, kwargs).get('vpnservice') return VPNService(vpnservice) def vpnservice_delete(request, vpnservice_id): neutronclient(request).delete_vpnservice(vpnservice_id) def ikepolicy_create(request, **kwargs): """Create IKEPolicy :param request: request context :param name: name for IKEPolicy :param description: description for IKEPolicy :param auth_algorithm: authorization algorithm for IKEPolicy :param encryption_algorithm: encryption algorithm for IKEPolicy :param ike_version: IKE version for IKEPolicy :param lifetime: Lifetime Units and Value for IKEPolicy :param pfs: Perfect Forward Secrecy for IKEPolicy :param phase1_negotiation_mode: IKE Phase1 negotiation mode for IKEPolicy """ body = {'ikepolicy': {'name': kwargs['name'], 'description': kwargs['description'], 'auth_algorithm': kwargs['auth_algorithm'], 'encryption_algorithm': kwargs['encryption_algorithm'], 'ike_version': kwargs['ike_version'], 'lifetime': kwargs['lifetime'], 'pfs': kwargs['pfs'], 'phase1_negotiation_mode': kwargs['phase1_negotiation_mode']} } ikepolicy = neutronclient(request).create_ikepolicy(body).get( 'ikepolicy') return IKEPolicy(ikepolicy) def ikepolicy_list(request, **kwargs): return _ikepolicy_list(request, expand_conns=True, **kwargs) def _ikepolicy_list(request, expand_conns=False, **kwargs): ikepolicies = neutronclient(request).list_ikepolicies( **kwargs).get('ikepolicies') if expand_conns: ipsecsiteconns = _ipsecsiteconnection_list(request, **kwargs) for p in ikepolicies: p['ipsecsiteconns'] = [c.id for c in ipsecsiteconns if c.ikepolicy_id == p['id']] return [IKEPolicy(v) for v in ikepolicies] def ikepolicy_get(request, ikepolicy_id): return _ikepolicy_get(request, ikepolicy_id, expand_conns=True) def _ikepolicy_get(request, ikepolicy_id, expand_conns=False): ikepolicy = neutronclient(request).show_ikepolicy( ikepolicy_id).get('ikepolicy') if expand_conns: ipsecsiteconns = _ipsecsiteconnection_list(request) ikepolicy['ipsecsiteconns'] = [c for c in ipsecsiteconns if c.ikepolicy_id == ikepolicy['id']] return IKEPolicy(ikepolicy) def ikepolicy_update(request, ikepolicy_id, **kwargs): ikepolicy = neutronclient(request).update_ikepolicy( ikepolicy_id, kwargs).get('ikepolicy') return IKEPolicy(ikepolicy) def ikepolicy_delete(request, ikepolicy_id): neutronclient(request).delete_ikepolicy(ikepolicy_id) def ipsecpolicy_create(request, **kwargs): """Create IPSecPolicy :param request: request context :param name: name for IPSecPolicy :param description: description for IPSecPolicy :param auth_algorithm: authorization algorithm for IPSecPolicy :param encapsulation_mode: encapsulation mode for IPSecPolicy :param encryption_algorithm: encryption algorithm for IPSecPolicy :param lifetime: Lifetime Units and Value for IPSecPolicy :param pfs: Perfect Forward Secrecy for IPSecPolicy :param transform_protocol: Transform Protocol for IPSecPolicy """ body = {'ipsecpolicy': {'name': kwargs['name'], 'description': kwargs['description'], 'auth_algorithm': kwargs['auth_algorithm'], 'encapsulation_mode': kwargs['encapsulation_mode'], 'encryption_algorithm': kwargs['encryption_algorithm'], 'lifetime': kwargs['lifetime'], 'pfs': kwargs['pfs'], 'transform_protocol': kwargs['transform_protocol']} } ipsecpolicy = neutronclient(request).create_ipsecpolicy(body).get( 'ipsecpolicy') return IPSecPolicy(ipsecpolicy) def ipsecpolicy_list(request, **kwargs): return _ipsecpolicy_list(request, expand_conns=True, **kwargs) def _ipsecpolicy_list(request, expand_conns=False, **kwargs): ipsecpolicies = neutronclient(request).list_ipsecpolicies( **kwargs).get('ipsecpolicies') if expand_conns: ipsecsiteconns = _ipsecsiteconnection_list(request, **kwargs) for p in ipsecpolicies: p['ipsecsiteconns'] = [c.id for c in ipsecsiteconns if c.ipsecpolicy_id == p['id']] return [IPSecPolicy(v) for v in ipsecpolicies] def ipsecpolicy_get(request, ipsecpolicy_id): return _ipsecpolicy_get(request, ipsecpolicy_id, expand_conns=True) def _ipsecpolicy_get(request, ipsecpolicy_id, expand_conns=False): ipsecpolicy = neutronclient(request).show_ipsecpolicy( ipsecpolicy_id).get('ipsecpolicy') if expand_conns: ipsecsiteconns = _ipsecsiteconnection_list(request) ipsecpolicy['ipsecsiteconns'] = [c for c in ipsecsiteconns if (c.ipsecpolicy_id == ipsecpolicy['id'])] return IPSecPolicy(ipsecpolicy) def ipsecpolicy_update(request, ipsecpolicy_id, **kwargs): ipsecpolicy = neutronclient(request).update_ipsecpolicy( ipsecpolicy_id, kwargs).get('ipsecpolicy') return IPSecPolicy(ipsecpolicy) def ipsecpolicy_delete(request, ipsecpolicy_id): neutronclient(request).delete_ipsecpolicy(ipsecpolicy_id) def ipsecsiteconnection_create(request, **kwargs): """Create IPSecSiteConnection :param request: request context :param name: name for IPSecSiteConnection :param description: description for IPSecSiteConnection :param dpd: dead peer detection action, interval and timeout :param ikepolicy_id: IKEPolicy associated with this connection :param initiator: initiator state :param ipsecpolicy_id: IPsecPolicy associated with this connection :param mtu: MTU size for the connection :param peer_address: Peer gateway public address :param peer_cidrs: remote subnet(s) in CIDR format :param peer_id: Peer router identity for authentication" :param psk: Pre-Shared Key string :param vpnservice_id: VPNService associated with this connection :param admin_state_up: admin state (default on) """ body = {'ipsec_site_connection': {'name': kwargs['name'], 'description': kwargs['description'], 'dpd': kwargs['dpd'], 'ikepolicy_id': kwargs['ikepolicy_id'], 'initiator': kwargs['initiator'], 'ipsecpolicy_id': kwargs['ipsecpolicy_id'], 'mtu': kwargs['mtu'], 'peer_address': kwargs['peer_address'], 'peer_cidrs': kwargs['peer_cidrs'], 'peer_id': kwargs['peer_id'], 'psk': kwargs['psk'], 'vpnservice_id': kwargs['vpnservice_id'], 'admin_state_up': kwargs['admin_state_up']} } ipsecsiteconnection = neutronclient(request).create_ipsec_site_connection( body).get('ipsec_site_connection') return IPSecSiteConnection(ipsecsiteconnection) @memoized def ipsecsiteconnection_list(request, **kwargs): return _ipsecsiteconnection_list(request, expand_ikepolicies=True, expand_ipsecpolicies=True, expand_vpnservices=True, **kwargs) @memoized def _ipsecsiteconnection_list(request, expand_ikepolicies=False, expand_ipsecpolicies=False, expand_vpnservices=False, **kwargs): ipsecsiteconnections = neutronclient(request).list_ipsec_site_connections( **kwargs).get('ipsec_site_connections') if expand_ikepolicies: ikepolicies = _ikepolicy_list(request, **kwargs) policy_dict = OrderedDict((p.id, p) for p in ikepolicies) for c in ipsecsiteconnections: c['ikepolicy_name'] = policy_dict.get(c['ikepolicy_id']).name_or_id if expand_ipsecpolicies: ipsecpolicies = _ipsecpolicy_list(request, **kwargs) policy_dict = OrderedDict((p.id, p) for p in ipsecpolicies) for c in ipsecsiteconnections: c['ipsecpolicy_name'] = policy_dict.get(c['ipsecpolicy_id'] ).name_or_id if expand_vpnservices: vpnservices = _vpnservice_list(request, **kwargs) service_dict = OrderedDict((s.id, s) for s in vpnservices) for c in ipsecsiteconnections: c['vpnservice_name'] = service_dict.get(c['vpnservice_id'] ).name_or_id return [IPSecSiteConnection(v) for v in ipsecsiteconnections] def ipsecsiteconnection_get(request, ipsecsiteconnection_id): return _ipsecsiteconnection_get(request, ipsecsiteconnection_id, expand_ikepolicies=True, expand_ipsecpolicies=True, expand_vpnservices=True) def _ipsecsiteconnection_get(request, ipsecsiteconnection_id, expand_ikepolicies, expand_ipsecpolicies, expand_vpnservices): ipsecsiteconnection = neutronclient(request).show_ipsec_site_connection( ipsecsiteconnection_id).get('ipsec_site_connection') if expand_ikepolicies: ipsecsiteconnection['ikepolicy'] = _ikepolicy_get( request, ipsecsiteconnection['ikepolicy_id']) if expand_ipsecpolicies: ipsecsiteconnection['ipsecpolicy'] = _ipsecpolicy_get( request, ipsecsiteconnection['ipsecpolicy_id']) if expand_vpnservices: ipsecsiteconnection['vpnservice'] = _vpnservice_get( request, ipsecsiteconnection['vpnservice_id']) return IPSecSiteConnection(ipsecsiteconnection) def ipsecsiteconnection_update(request, ipsecsiteconnection_id, **kwargs): ipsecsiteconnection = neutronclient(request).update_ipsec_site_connection( ipsecsiteconnection_id, kwargs).get('ipsec_site_connection') return IPSecSiteConnection(ipsecsiteconnection) def ipsecsiteconnection_delete(request, ipsecsiteconnection_id): neutronclient(request).delete_ipsec_site_connection(ipsecsiteconnection_id)
apache-2.0
kmad1729/website
django/contrib/admin/widgets.py
156
12061
""" Form Widget classes specific to the Django admin site. """ import django.utils.copycompat as copy from django import forms from django.forms.widgets import RadioFieldRenderer from django.forms.util import flatatt from django.utils.html import escape from django.utils.text import truncate_words from django.utils.translation import ugettext as _ from django.utils.safestring import mark_safe from django.utils.encoding import force_unicode from django.conf import settings from django.core.urlresolvers import reverse, NoReverseMatch class FilteredSelectMultiple(forms.SelectMultiple): """ A SelectMultiple with a JavaScript filter interface. Note that the resulting JavaScript assumes that the jsi18n catalog has been loaded in the page """ class Media: js = (settings.ADMIN_MEDIA_PREFIX + "js/core.js", settings.ADMIN_MEDIA_PREFIX + "js/SelectBox.js", settings.ADMIN_MEDIA_PREFIX + "js/SelectFilter2.js") def __init__(self, verbose_name, is_stacked, attrs=None, choices=()): self.verbose_name = verbose_name self.is_stacked = is_stacked super(FilteredSelectMultiple, self).__init__(attrs, choices) def render(self, name, value, attrs=None, choices=()): if attrs is None: attrs = {} attrs['class'] = 'selectfilter' if self.is_stacked: attrs['class'] += 'stacked' output = [super(FilteredSelectMultiple, self).render(name, value, attrs, choices)] output.append(u'<script type="text/javascript">addEvent(window, "load", function(e) {') # TODO: "id_" is hard-coded here. This should instead use the correct # API to determine the ID dynamically. output.append(u'SelectFilter.init("id_%s", "%s", %s, "%s"); });</script>\n' % \ (name, self.verbose_name.replace('"', '\\"'), int(self.is_stacked), settings.ADMIN_MEDIA_PREFIX)) return mark_safe(u''.join(output)) class AdminDateWidget(forms.DateInput): class Media: js = (settings.ADMIN_MEDIA_PREFIX + "js/calendar.js", settings.ADMIN_MEDIA_PREFIX + "js/admin/DateTimeShortcuts.js") def __init__(self, attrs={}, format=None): super(AdminDateWidget, self).__init__(attrs={'class': 'vDateField', 'size': '10'}, format=format) class AdminTimeWidget(forms.TimeInput): class Media: js = (settings.ADMIN_MEDIA_PREFIX + "js/calendar.js", settings.ADMIN_MEDIA_PREFIX + "js/admin/DateTimeShortcuts.js") def __init__(self, attrs={}, format=None): super(AdminTimeWidget, self).__init__(attrs={'class': 'vTimeField', 'size': '8'}, format=format) class AdminSplitDateTime(forms.SplitDateTimeWidget): """ A SplitDateTime Widget that has some admin-specific styling. """ def __init__(self, attrs=None): widgets = [AdminDateWidget, AdminTimeWidget] # Note that we're calling MultiWidget, not SplitDateTimeWidget, because # we want to define widgets. forms.MultiWidget.__init__(self, widgets, attrs) def format_output(self, rendered_widgets): return mark_safe(u'<p class="datetime">%s %s<br />%s %s</p>' % \ (_('Date:'), rendered_widgets[0], _('Time:'), rendered_widgets[1])) class AdminRadioFieldRenderer(RadioFieldRenderer): def render(self): """Outputs a <ul> for this set of radio fields.""" return mark_safe(u'<ul%s>\n%s\n</ul>' % ( flatatt(self.attrs), u'\n'.join([u'<li>%s</li>' % force_unicode(w) for w in self])) ) class AdminRadioSelect(forms.RadioSelect): renderer = AdminRadioFieldRenderer class AdminFileWidget(forms.ClearableFileInput): template_with_initial = (u'<p class="file-upload">%s</p>' % forms.ClearableFileInput.template_with_initial) template_with_clear = (u'<span class="clearable-file-input">%s</span>' % forms.ClearableFileInput.template_with_clear) def url_params_from_lookup_dict(lookups): """ Converts the type of lookups specified in a ForeignKey limit_choices_to attribute to a dictionary of query parameters """ params = {} if lookups and hasattr(lookups, 'items'): items = [] for k, v in lookups.items(): if isinstance(v, list): v = u','.join([str(x) for x in v]) elif isinstance(v, bool): # See django.db.fields.BooleanField.get_prep_lookup v = ('0', '1')[v] else: v = unicode(v) items.append((k, v)) params.update(dict(items)) return params class ForeignKeyRawIdWidget(forms.TextInput): """ A Widget for displaying ForeignKeys in the "raw_id" interface rather than in a <select> box. """ def __init__(self, rel, attrs=None, using=None): self.rel = rel self.db = using super(ForeignKeyRawIdWidget, self).__init__(attrs) def render(self, name, value, attrs=None): if attrs is None: attrs = {} related_url = '../../../%s/%s/' % (self.rel.to._meta.app_label, self.rel.to._meta.object_name.lower()) params = self.url_parameters() if params: url = u'?' + u'&amp;'.join([u'%s=%s' % (k, v) for k, v in params.items()]) else: url = u'' if "class" not in attrs: attrs['class'] = 'vForeignKeyRawIdAdminField' # The JavaScript looks for this hook. output = [super(ForeignKeyRawIdWidget, self).render(name, value, attrs)] # TODO: "id_" is hard-coded here. This should instead use the correct # API to determine the ID dynamically. output.append(u'<a href="%s%s" class="related-lookup" id="lookup_id_%s" onclick="return showRelatedObjectLookupPopup(this);"> ' % \ (related_url, url, name)) output.append(u'<img src="%simg/admin/selector-search.gif" width="16" height="16" alt="%s" /></a>' % (settings.ADMIN_MEDIA_PREFIX, _('Lookup'))) if value: output.append(self.label_for_value(value)) return mark_safe(u''.join(output)) def base_url_parameters(self): return url_params_from_lookup_dict(self.rel.limit_choices_to) def url_parameters(self): from django.contrib.admin.views.main import TO_FIELD_VAR params = self.base_url_parameters() params.update({TO_FIELD_VAR: self.rel.get_related_field().name}) return params def label_for_value(self, value): key = self.rel.get_related_field().name try: obj = self.rel.to._default_manager.using(self.db).get(**{key: value}) return '&nbsp;<strong>%s</strong>' % escape(truncate_words(obj, 14)) except (ValueError, self.rel.to.DoesNotExist): return '' class ManyToManyRawIdWidget(ForeignKeyRawIdWidget): """ A Widget for displaying ManyToMany ids in the "raw_id" interface rather than in a <select multiple> box. """ def render(self, name, value, attrs=None): if attrs is None: attrs = {} attrs['class'] = 'vManyToManyRawIdAdminField' if value: value = ','.join([force_unicode(v) for v in value]) else: value = '' return super(ManyToManyRawIdWidget, self).render(name, value, attrs) def url_parameters(self): return self.base_url_parameters() def label_for_value(self, value): return '' def value_from_datadict(self, data, files, name): value = data.get(name) if value: return value.split(',') def _has_changed(self, initial, data): if initial is None: initial = [] if data is None: data = [] if len(initial) != len(data): return True for pk1, pk2 in zip(initial, data): if force_unicode(pk1) != force_unicode(pk2): return True return False class RelatedFieldWidgetWrapper(forms.Widget): """ This class is a wrapper to a given widget to add the add icon for the admin interface. """ def __init__(self, widget, rel, admin_site, can_add_related=None): self.is_hidden = widget.is_hidden self.needs_multipart_form = widget.needs_multipart_form self.attrs = widget.attrs self.choices = widget.choices self.widget = widget self.rel = rel # Backwards compatible check for whether a user can add related # objects. if can_add_related is None: can_add_related = rel.to in admin_site._registry self.can_add_related = can_add_related # so we can check if the related object is registered with this AdminSite self.admin_site = admin_site def __deepcopy__(self, memo): obj = copy.copy(self) obj.widget = copy.deepcopy(self.widget, memo) obj.attrs = self.widget.attrs memo[id(self)] = obj return obj def _media(self): return self.widget.media media = property(_media) def render(self, name, value, *args, **kwargs): rel_to = self.rel.to info = (rel_to._meta.app_label, rel_to._meta.object_name.lower()) try: related_url = reverse('admin:%s_%s_add' % info, current_app=self.admin_site.name) except NoReverseMatch: info = (self.admin_site.root_path, rel_to._meta.app_label, rel_to._meta.object_name.lower()) related_url = '%s%s/%s/add/' % info self.widget.choices = self.choices output = [self.widget.render(name, value, *args, **kwargs)] if self.can_add_related: # TODO: "id_" is hard-coded here. This should instead use the correct # API to determine the ID dynamically. output.append(u'<a href="%s" class="add-another" id="add_id_%s" onclick="return showAddAnotherPopup(this);"> ' % \ (related_url, name)) output.append(u'<img src="%simg/admin/icon_addlink.gif" width="10" height="10" alt="%s"/></a>' % (settings.ADMIN_MEDIA_PREFIX, _('Add Another'))) return mark_safe(u''.join(output)) def build_attrs(self, extra_attrs=None, **kwargs): "Helper function for building an attribute dictionary." self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs) return self.attrs def value_from_datadict(self, data, files, name): return self.widget.value_from_datadict(data, files, name) def _has_changed(self, initial, data): return self.widget._has_changed(initial, data) def id_for_label(self, id_): return self.widget.id_for_label(id_) class AdminTextareaWidget(forms.Textarea): def __init__(self, attrs=None): final_attrs = {'class': 'vLargeTextField'} if attrs is not None: final_attrs.update(attrs) super(AdminTextareaWidget, self).__init__(attrs=final_attrs) class AdminTextInputWidget(forms.TextInput): def __init__(self, attrs=None): final_attrs = {'class': 'vTextField'} if attrs is not None: final_attrs.update(attrs) super(AdminTextInputWidget, self).__init__(attrs=final_attrs) class AdminURLFieldWidget(forms.TextInput): def __init__(self, attrs=None): final_attrs = {'class': 'vURLField'} if attrs is not None: final_attrs.update(attrs) super(AdminURLFieldWidget, self).__init__(attrs=final_attrs) class AdminIntegerFieldWidget(forms.TextInput): def __init__(self, attrs=None): final_attrs = {'class': 'vIntegerField'} if attrs is not None: final_attrs.update(attrs) super(AdminIntegerFieldWidget, self).__init__(attrs=final_attrs) class AdminCommaSeparatedIntegerFieldWidget(forms.TextInput): def __init__(self, attrs=None): final_attrs = {'class': 'vCommaSeparatedIntegerField'} if attrs is not None: final_attrs.update(attrs) super(AdminCommaSeparatedIntegerFieldWidget, self).__init__(attrs=final_attrs)
bsd-3-clause
lulandco/SickRage
sickbeard/tv.py
3
117676
# coding=utf-8 # Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of SickRage. # # SickRage 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. # # SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>. # pylint: disable=too-many-lines from __future__ import unicode_literals import datetime import os.path import re import stat import threading import traceback try: import xml.etree.cElementTree as etree except ImportError: import xml.etree.ElementTree as etree try: from send2trash import send2trash except ImportError: pass from imdb import imdb import sickbeard from sickbeard import db from sickbeard import helpers, logger from sickbeard import image_cache from sickbeard import notifiers from sickbeard import postProcessor from sickbeard import subtitles from sickbeard.blackandwhitelist import BlackAndWhiteList from sickbeard import network_timezones from sickbeard.indexers.indexer_config import INDEXER_TVRAGE from sickbeard.name_parser.parser import NameParser, InvalidNameException, InvalidShowException from sickrage.helper import glob from sickrage.helper.common import dateTimeFormat, remove_extension, replace_extension, sanitize_filename, try_int, episode_num from sickrage.helper.encoding import ek from sickrage.helper.exceptions import EpisodeDeletedException, EpisodeNotFoundException, ex from sickrage.helper.exceptions import MultipleEpisodesInDatabaseException, MultipleShowsInDatabaseException from sickrage.helper.exceptions import MultipleShowObjectsException, NoNFOException, ShowDirectoryNotFoundException from sickrage.helper.exceptions import ShowNotFoundException from sickrage.show.Show import Show from sickbeard.common import Quality, Overview, statusStrings from sickbeard.common import DOWNLOADED, SNATCHED, SNATCHED_PROPER, ARCHIVED, IGNORED, UNAIRED, WANTED, SKIPPED, UNKNOWN from sickbeard.common import NAMING_DUPLICATE, NAMING_EXTEND, NAMING_LIMITED_EXTEND, NAMING_SEPARATED_REPEAT, \ NAMING_LIMITED_EXTEND_E_PREFIXED import shutil def dirty_setter(attr_name): def wrapper(self, val): if getattr(self, attr_name) != val: setattr(self, attr_name, val) self.dirty = True return wrapper class TVShow(object): # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, indexer, indexerid, lang=""): self._indexerid = int(indexerid) self._indexer = int(indexer) self._name = "" self._imdbid = "" self._network = "" self._genre = "" self._classification = "" self._runtime = 0 self._imdb_info = {} self._quality = int(sickbeard.QUALITY_DEFAULT) self._flatten_folders = int(sickbeard.FLATTEN_FOLDERS_DEFAULT) self._status = "Unknown" self._airs = "" self._startyear = 0 self._paused = 0 self._air_by_date = 0 self._subtitles = int(sickbeard.SUBTITLES_DEFAULT) self._subtitles_sr_metadata = 0 self._dvdorder = 0 self._lang = lang self._last_update_indexer = 1 self._sports = 0 self._anime = 0 self._scene = 0 self._rls_ignore_words = "" self._rls_require_words = "" self._default_ep_status = SKIPPED self.dirty = True self._location = "" self.lock = threading.Lock() self.episodes = {} self.nextaired = "" self.release_groups = None otherShow = Show.find(sickbeard.showList, self.indexerid) if otherShow is not None: raise MultipleShowObjectsException("Can't create a show if it already exists") self.loadFromDB() name = property(lambda self: self._name, dirty_setter("_name")) indexerid = property(lambda self: self._indexerid, dirty_setter("_indexerid")) indexer = property(lambda self: self._indexer, dirty_setter("_indexer")) # location = property(lambda self: self._location, dirty_setter("_location")) imdbid = property(lambda self: self._imdbid, dirty_setter("_imdbid")) network = property(lambda self: self._network, dirty_setter("_network")) genre = property(lambda self: self._genre, dirty_setter("_genre")) classification = property(lambda self: self._classification, dirty_setter("_classification")) runtime = property(lambda self: self._runtime, dirty_setter("_runtime")) imdb_info = property(lambda self: self._imdb_info, dirty_setter("_imdb_info")) quality = property(lambda self: self._quality, dirty_setter("_quality")) flatten_folders = property(lambda self: self._flatten_folders, dirty_setter("_flatten_folders")) status = property(lambda self: self._status, dirty_setter("_status")) airs = property(lambda self: self._airs, dirty_setter("_airs")) startyear = property(lambda self: self._startyear, dirty_setter("_startyear")) paused = property(lambda self: self._paused, dirty_setter("_paused")) air_by_date = property(lambda self: self._air_by_date, dirty_setter("_air_by_date")) subtitles = property(lambda self: self._subtitles, dirty_setter("_subtitles")) dvdorder = property(lambda self: self._dvdorder, dirty_setter("_dvdorder")) lang = property(lambda self: self._lang, dirty_setter("_lang")) last_update_indexer = property(lambda self: self._last_update_indexer, dirty_setter("_last_update_indexer")) sports = property(lambda self: self._sports, dirty_setter("_sports")) anime = property(lambda self: self._anime, dirty_setter("_anime")) scene = property(lambda self: self._scene, dirty_setter("_scene")) rls_ignore_words = property(lambda self: self._rls_ignore_words, dirty_setter("_rls_ignore_words")) rls_require_words = property(lambda self: self._rls_require_words, dirty_setter("_rls_require_words")) default_ep_status = property(lambda self: self._default_ep_status, dirty_setter("_default_ep_status")) subtitles_sr_metadata = property(lambda self: self._subtitles_sr_metadata, dirty_setter("_subtitles_sr_metadata")) @property def is_anime(self): return int(self.anime) > 0 @property def is_sports(self): return int(self.sports) > 0 @property def is_scene(self): return int(self.scene) > 0 @property def network_logo_name(self): return self.network.replace('\u00C9', 'e').replace('\u00E9', 'e').lower() def _getLocation(self): # no dir check needed if missing show dirs are created during post-processing if sickbeard.CREATE_MISSING_SHOW_DIRS or ek(os.path.isdir, self._location): return self._location raise ShowDirectoryNotFoundException("Show folder doesn't exist, you shouldn't be using it") def _setLocation(self, newLocation): logger.log("Setter sets location to " + newLocation, logger.DEBUG) # Don't validate dir if user wants to add shows without creating a dir if sickbeard.ADD_SHOWS_WO_DIR or ek(os.path.isdir, newLocation): dirty_setter("_location")(self, newLocation) else: raise NoNFOException("Invalid folder for the show!") location = property(_getLocation, _setLocation) # delete references to anything that's not in the internal lists def flushEpisodes(self): for curSeason in self.episodes: for curEp in self.episodes[curSeason]: myEp = self.episodes[curSeason][curEp] self.episodes[curSeason][curEp] = None del myEp def getAllEpisodes(self, season=None, has_location=False): sql_selection = 'SELECT season, episode, ' # subselection to detect multi-episodes early, share_location > 0 sql_selection += '(SELECT COUNT (*) FROM tv_episodes WHERE showid = tve.showid ' sql_selection += 'AND season = tve.season AND location != \'\' AND location = tve.location ' sql_selection += 'AND episode != tve.episode) AS share_location ' sql_selection += 'FROM tv_episodes tve WHERE showid = {0} '.format(self.indexerid) if season is not None: sql_selection += 'AND season = {0} '.format(season) if has_location: sql_selection += 'AND location != \'\' ' # need ORDER episode ASC to rename multi-episodes in order S01E01-02 sql_selection += 'ORDER BY season ASC, episode ASC ' main_db_con = db.DBConnection() results = main_db_con.select(sql_selection) ep_list = [] for cur_result in results: cur_ep = self.getEpisode(cur_result[b"season"], cur_result[b"episode"]) if not cur_ep: continue cur_ep.relatedEps = [] if cur_ep.location: # if there is a location, check if it's a multi-episode (share_location > 0) and put them in relatedEps if cur_result[b"share_location"] > 0: related_eps_result = main_db_con.select( "SELECT season, episode FROM tv_episodes WHERE showid = ? AND season = ? AND location = ? AND episode != ? ORDER BY episode ASC", [self.indexerid, cur_ep.season, cur_ep.location, cur_ep.episode]) for cur_related_ep in related_eps_result: related_ep = self.getEpisode(cur_related_ep[b"season"], cur_related_ep[b"episode"]) if related_ep and related_ep not in cur_ep.relatedEps: cur_ep.relatedEps.append(related_ep) ep_list.append(cur_ep) return ep_list def getEpisode(self, season=None, episode=None, ep_file=None, noCreate=False, absolute_number=None): # pylint: disable=too-many-arguments season = try_int(season, None) episode = try_int(episode, None) absolute_number = try_int(absolute_number, None) # if we get an anime get the real season and episode if self.is_anime and absolute_number and not season and not episode: main_db_con = db.DBConnection() sql = "SELECT season, episode FROM tv_episodes WHERE showid = ? AND absolute_number = ? AND season != 0" sql_results = main_db_con.select(sql, [self.indexerid, absolute_number]) if len(sql_results) == 1: episode = int(sql_results[0][b"episode"]) season = int(sql_results[0][b"season"]) logger.log("Found episode by absolute number {absolute} which is {ep}".format (absolute=absolute_number, ep=episode_num(season, episode)), logger.DEBUG) elif len(sql_results) > 1: logger.log("Multiple entries for absolute number: {absolute} in show: {name} found ".format (absolute=absolute_number, name=self.name), logger.ERROR) return None else: logger.log( "No entries for absolute number: " + str(absolute_number) + " in show: " + self.name + " found.", logger.DEBUG) return None if season not in self.episodes: self.episodes[season] = {} if episode not in self.episodes[season] or self.episodes[season][episode] is None: if noCreate: return None # logger.log("{id}: An object for episode {ep} didn't exist in the cache, trying to create it".format # (id=self.indexerid, ep=episode_num(season, episode)), logger.DEBUG) if ep_file: ep = TVEpisode(self, season, episode, ep_file) else: ep = TVEpisode(self, season, episode) if ep is not None: self.episodes[season][episode] = ep return self.episodes[season][episode] def should_update(self, update_date=datetime.date.today()): # if show is not 'Ended' always update (status 'Continuing') if self.status == 'Continuing': return True # run logic against the current show latest aired and next unaired data to see if we should bypass 'Ended' status graceperiod = datetime.timedelta(days=30) last_airdate = datetime.date.fromordinal(1) # get latest aired episode to compare against today - graceperiod and today + graceperiod main_db_con = db.DBConnection() sql_result = main_db_con.select( "SELECT IFNULL(MAX(airdate), 0) as last_aired FROM tv_episodes WHERE showid = ? AND season > 0 AND airdate > 1 AND status > 1", [self.indexerid]) if sql_result and sql_result[0][b'last_aired'] != 0: last_airdate = datetime.date.fromordinal(sql_result[0][b'last_aired']) if (update_date - graceperiod) <= last_airdate <= (update_date + graceperiod): return True # get next upcoming UNAIRED episode to compare against today + graceperiod sql_result = main_db_con.select( "SELECT IFNULL(MIN(airdate), 0) as airing_next FROM tv_episodes WHERE showid = ? AND season > 0 AND airdate > 1 AND status = 1", [self.indexerid]) if sql_result and sql_result[0][b'airing_next'] != 0: next_airdate = datetime.date.fromordinal(sql_result[0][b'airing_next']) if next_airdate <= (update_date + graceperiod): return True last_update_indexer = datetime.date.fromordinal(self.last_update_indexer) # in the first year after ended (last airdate), update every 30 days if (update_date - last_airdate) < datetime.timedelta(days=450) and (update_date - last_update_indexer) > datetime.timedelta(days=30): return True return False def writeShowNFO(self): result = False if not ek(os.path.isdir, self._location): logger.log(str(self.indexerid) + ": Show dir doesn't exist, skipping NFO generation") return False logger.log(str(self.indexerid) + ": Writing NFOs for show", logger.DEBUG) for cur_provider in sickbeard.metadata_provider_dict.values(): result = cur_provider.create_show_metadata(self) or result return result def writeMetadata(self, show_only=False): if not ek(os.path.isdir, self._location): logger.log(str(self.indexerid) + ": Show dir doesn't exist, skipping NFO generation") return self.getImages() self.writeShowNFO() if not show_only: self.writeEpisodeNFOs() def writeEpisodeNFOs(self): if not ek(os.path.isdir, self._location): logger.log(str(self.indexerid) + ": Show dir doesn't exist, skipping NFO generation") return logger.log(str(self.indexerid) + ": Writing NFOs for all episodes", logger.DEBUG) main_db_con = db.DBConnection() sql_results = main_db_con.select("SELECT season, episode FROM tv_episodes WHERE showid = ? AND location != ''", [self.indexerid]) for epResult in sql_results: logger.log("{id}: Retrieving/creating episode {ep}".format (id=self.indexerid, ep=episode_num(epResult[b"season"], epResult[b"episode"])), logger.DEBUG) curEp = self.getEpisode(epResult[b"season"], epResult[b"episode"]) if not curEp: continue curEp.createMetaFiles() def updateMetadata(self): if not ek(os.path.isdir, self._location): logger.log(str(self.indexerid) + ": Show dir doesn't exist, skipping NFO generation") return self.updateShowNFO() def updateShowNFO(self): result = False if not ek(os.path.isdir, self._location): logger.log(str(self.indexerid) + ": Show dir doesn't exist, skipping NFO generation") return False logger.log(str(self.indexerid) + ": Updating NFOs for show with new indexer info") for cur_provider in sickbeard.metadata_provider_dict.values(): result = cur_provider.update_show_indexer_metadata(self) or result return result # find all media files in the show folder and create episodes for as many as possible def loadEpisodesFromDir(self): if not ek(os.path.isdir, self._location): logger.log(str(self.indexerid) + ": Show dir doesn't exist, not loading episodes from disk", logger.DEBUG) return logger.log(str(self.indexerid) + ": Loading all episodes from the show directory " + self._location, logger.DEBUG) # get file list mediaFiles = helpers.listMediaFiles(self._location) logger.log("{0}: Found files: {1}".format(self.indexerid, mediaFiles), logger.DEBUG) # create TVEpisodes from each media file (if possible) sql_l = [] for mediaFile in mediaFiles: parse_result = None curEpisode = None logger.log(str(self.indexerid) + ": Creating episode from " + mediaFile, logger.DEBUG) try: curEpisode = self.makeEpFromFile(ek(os.path.join, self._location, mediaFile)) except (ShowNotFoundException, EpisodeNotFoundException) as error: logger.log("Episode " + mediaFile + " returned an exception: " + ex(error), logger.ERROR) continue except EpisodeDeletedException: logger.log("The episode deleted itself when I tried making an object for it", logger.DEBUG) if curEpisode is None: continue # see if we should save the release name in the db ep_file_name = ek(os.path.basename, curEpisode.location) ep_file_name = ek(os.path.splitext, ep_file_name)[0] try: parse_result = NameParser(False, showObj=self, tryIndexers=True).parse(ep_file_name) except (InvalidNameException, InvalidShowException): parse_result = None if ' ' not in ep_file_name and parse_result and parse_result.release_group: logger.log( "Name " + ep_file_name + " gave release group of " + parse_result.release_group + ", seems valid", logger.DEBUG) curEpisode.release_name = ep_file_name # store the reference in the show if curEpisode is not None: if self.subtitles: try: curEpisode.refreshSubtitles() except Exception: logger.log("{0}: Could not refresh subtitles".format(self.indexerid), logger.ERROR) logger.log(traceback.format_exc(), logger.DEBUG) sql_l.append(curEpisode.get_sql()) if sql_l: main_db_con = db.DBConnection() main_db_con.mass_action(sql_l) def loadEpisodesFromDB(self): # pylint: disable=too-many-locals logger.log("Loading all episodes from the DB", logger.DEBUG) scannedEps = {} try: main_db_con = db.DBConnection() sql = "SELECT season, episode, showid, show_name FROM tv_episodes JOIN tv_shows WHERE showid = indexer_id and showid = ?" sql_results = main_db_con.select(sql, [self.indexerid]) except Exception as error: logger.log("Could not load episodes from the DB. Error: {0}".format(error), logger.ERROR) return scannedEps lINDEXER_API_PARMS = sickbeard.indexerApi(self.indexer).api_params.copy() lINDEXER_API_PARMS['language'] = self.lang or sickbeard.INDEXER_DEFAULT_LANGUAGE logger.log("Using language: " + str(self.lang), logger.DEBUG) if self.dvdorder: lINDEXER_API_PARMS['dvdorder'] = True # logger.log("lINDEXER_API_PARMS: " + str(lINDEXER_API_PARMS), logger.DEBUG) # Spamming log t = sickbeard.indexerApi(self.indexer).indexer(**lINDEXER_API_PARMS) cachedShow = t[self.indexerid] cachedSeasons = {} curShowid = None curShowName = None for curResult in sql_results: curSeason = int(curResult[b"season"]) curEpisode = int(curResult[b"episode"]) curShowid = int(curResult[b'showid']) curShowName = str(curResult[b'show_name']) logger.log("{0}: Loading {1} episodes from DB".format(curShowid, curShowName), logger.DEBUG) deleteEp = False if curSeason not in cachedSeasons: try: cachedSeasons[curSeason] = cachedShow[curSeason] except sickbeard.indexer_seasonnotfound as error: logger.log("{0}: {1} (unaired/deleted) in the indexer {2} for {3}. Removing existing records from database".format (curShowid, error.message, sickbeard.indexerApi(self.indexer).name, curShowName), logger.DEBUG) deleteEp = True if curSeason not in scannedEps: logger.log("{id}: Not curSeason in scannedEps".format(id=curShowid), logger.DEBUG) scannedEps[curSeason] = {} logger.log("{id}: Loading {show} {ep} from the DB".format (id=curShowid, show=curShowName, ep=episode_num(curSeason, curEpisode)), logger.DEBUG) try: curEp = self.getEpisode(curSeason, curEpisode) if not curEp: raise EpisodeNotFoundException # if we found out that the ep is no longer on TVDB then delete it from our database too if deleteEp: curEp.deleteEpisode() curEp.loadFromDB(curSeason, curEpisode) curEp.loadFromIndexer(tvapi=t, cachedSeason=cachedSeasons[curSeason]) scannedEps[curSeason][curEpisode] = True except EpisodeDeletedException: logger.log("{id}: Tried loading {show} {ep} from the DB that should have been deleted, skipping it".format (id=curShowid, show=curShowName, ep=episode_num(curSeason, curEpisode)), logger.DEBUG) continue if curShowName and curShowid: logger.log("{id}: Finished loading all episodes for {show} from the DB".format (show=curShowName, id=curShowid), logger.DEBUG) return scannedEps def loadEpisodesFromIndexer(self, cache=True): lINDEXER_API_PARMS = sickbeard.indexerApi(self.indexer).api_params.copy() if not cache: lINDEXER_API_PARMS['cache'] = False lINDEXER_API_PARMS['language'] = self.lang or sickbeard.INDEXER_DEFAULT_LANGUAGE if self.dvdorder: lINDEXER_API_PARMS['dvdorder'] = True try: t = sickbeard.indexerApi(self.indexer).indexer(**lINDEXER_API_PARMS) showObj = t[self.indexerid] except sickbeard.indexer_error: logger.log("" + sickbeard.indexerApi(self.indexer).name + " timed out, unable to update episodes from " + sickbeard.indexerApi(self.indexer).name, logger.WARNING) return None logger.log( str(self.indexerid) + ": Loading all episodes from " + sickbeard.indexerApi(self.indexer).name + "..", logger.DEBUG) scannedEps = {} sql_l = [] for season in showObj: scannedEps[season] = {} for episode in showObj[season]: # need some examples of wtf episode 0 means to decide if we want it or not if episode == 0: continue try: ep = self.getEpisode(season, episode) if not ep: raise EpisodeNotFoundException except EpisodeNotFoundException: logger.log("{id}: {indexer} object for {ep} is incomplete, skipping this episode".format (id=self.indexerid, indexer=sickbeard.indexerApi(self.indexer).name, ep=episode_num(season, episode))) continue else: try: ep.loadFromIndexer(tvapi=t) except EpisodeDeletedException: logger.log("The episode was deleted, skipping the rest of the load") continue with ep.lock: # logger.log("{id}: Loading info from {indexer} for episode {ep}".format # (id=self.indexerid, indexer=sickbeard.indexerApi(self.indexer).name, # ep=episode_num(season, episode)), logger.DEBUG) ep.loadFromIndexer(season, episode, tvapi=t) sql_l.append(ep.get_sql()) scannedEps[season][episode] = True if sql_l: main_db_con = db.DBConnection() main_db_con.mass_action(sql_l) # Done updating save last update date self.last_update_indexer = datetime.datetime.now().toordinal() self.saveToDB() return scannedEps def getImages(self): fanart_result = poster_result = banner_result = False season_posters_result = season_banners_result = season_all_poster_result = season_all_banner_result = False for cur_provider in sickbeard.metadata_provider_dict.values(): # logger.log("Running metadata routines for " + cur_provider.name, logger.DEBUG) fanart_result = cur_provider.create_fanart(self) or fanart_result poster_result = cur_provider.create_poster(self) or poster_result banner_result = cur_provider.create_banner(self) or banner_result season_posters_result = cur_provider.create_season_posters(self) or season_posters_result season_banners_result = cur_provider.create_season_banners(self) or season_banners_result season_all_poster_result = cur_provider.create_season_all_poster(self) or season_all_poster_result season_all_banner_result = cur_provider.create_season_all_banner(self) or season_all_banner_result return fanart_result or poster_result or banner_result or season_posters_result or season_banners_result or season_all_poster_result or season_all_banner_result # make a TVEpisode object from a media file def makeEpFromFile(self, filepath): # pylint: disable=too-many-locals, too-many-branches, too-many-statements if not ek(os.path.isfile, filepath): logger.log("{0}: That isn't even a real file dude... {1}".format (self.indexerid, filepath)) return None logger.log("{0}: Creating episode object from {1}".format (self.indexerid, filepath), logger.DEBUG) try: parse_result = NameParser(showObj=self, tryIndexers=True, parse_method=('normal', 'anime')[self.is_anime]).parse(filepath) except (InvalidNameException, InvalidShowException) as error: logger.log("{0}: {1}".format(self.indexerid, error), logger.DEBUG) return None episodes = [ep for ep in parse_result.episode_numbers if ep is not None] if not episodes: logger.log("{0}: parse_result: {1}".format(self.indexerid, parse_result)) logger.log("{0}: No episode number found in {1}, ignoring it".format (self.indexerid, filepath), logger.WARNING) return None # for now lets assume that any episode in the show dir belongs to that show season = parse_result.season_number if parse_result.season_number is not None else 1 rootEp = None sql_l = [] for current_ep in episodes: logger.log("{0}: {1} parsed to {2} {3}".format (self.indexerid, filepath, self.name, episode_num(season, current_ep)), logger.DEBUG) checkQualityAgain = False same_file = False curEp = self.getEpisode(season, current_ep) if not curEp: try: curEp = self.getEpisode(season, current_ep, filepath) if not curEp: raise EpisodeNotFoundException except EpisodeNotFoundException: logger.log("{0}: Unable to figure out what this file is, skipping {1}".format (self.indexerid, filepath), logger.ERROR) continue else: # if there is a new file associated with this ep then re-check the quality if curEp.location and ek(os.path.normpath, curEp.location) != ek(os.path.normpath, filepath): logger.log( "{0}: The old episode had a different file associated with it, re-checking the quality using the new filename {1}".format (self.indexerid, filepath), logger.DEBUG) checkQualityAgain = True with curEp.lock: old_size = curEp.file_size curEp.location = filepath # if the sizes are the same then it's probably the same file same_file = old_size and curEp.file_size == old_size curEp.checkForMetaFiles() if rootEp is None: rootEp = curEp else: if curEp not in rootEp.relatedEps: with rootEp.lock: rootEp.relatedEps.append(curEp) # if it's a new file then if not same_file: with curEp.lock: curEp.release_name = '' # if they replace a file on me I'll make some attempt at re-checking the quality unless I know it's the same file if checkQualityAgain and not same_file: newQuality = Quality.nameQuality(filepath, self.is_anime) logger.log("{0}: Since this file has been renamed, I checked {1} and found quality {2}".format (self.indexerid, filepath, Quality.qualityStrings[newQuality]), logger.DEBUG) with curEp.lock: curEp.status = Quality.compositeStatus(DOWNLOADED, newQuality) # check for status/quality changes as long as it's a new file elif not same_file and sickbeard.helpers.isMediaFile(filepath) and curEp.status not in Quality.DOWNLOADED + Quality.ARCHIVED + [IGNORED]: oldStatus, oldQuality = Quality.splitCompositeStatus(curEp.status) newQuality = Quality.nameQuality(filepath, self.is_anime) newStatus = None # if it was snatched and now exists then set the status correctly if oldStatus == SNATCHED and oldQuality <= newQuality: logger.log("{0}: This ep used to be snatched with quality {1} but a file exists with quality {2} so I'm setting the status to DOWNLOADED".format (self.indexerid, Quality.qualityStrings[oldQuality], Quality.qualityStrings[newQuality]), logger.DEBUG) newStatus = DOWNLOADED # if it was snatched proper and we found a higher quality one then allow the status change elif oldStatus == SNATCHED_PROPER and oldQuality < newQuality: logger.log("{0}: This ep used to be snatched proper with quality {1} but a file exists with quality {2} so I'm setting the status to DOWNLOADED".format (self.indexerid, Quality.qualityStrings[oldQuality], Quality.qualityStrings[newQuality]), logger.DEBUG) newStatus = DOWNLOADED elif oldStatus not in (SNATCHED, SNATCHED_PROPER): newStatus = DOWNLOADED if newStatus is not None: with curEp.lock: logger.log("{0}: We have an associated file, so setting the status from {1} to DOWNLOADED/{2}".format (self.indexerid, curEp.status, Quality.statusFromName(filepath, anime=self.is_anime)), logger.DEBUG) curEp.status = Quality.compositeStatus(newStatus, newQuality) with curEp.lock: sql_l.append(curEp.get_sql()) if sql_l: main_db_con = db.DBConnection() main_db_con.mass_action(sql_l) # creating metafiles on the root should be good enough if rootEp: with rootEp.lock: rootEp.createMetaFiles() return rootEp def loadFromDB(self): # pylint: disable=too-many-branches, too-many-statements # logger.log(str(self.indexerid) + ": Loading show info from database", logger.DEBUG) main_db_con = db.DBConnection() sql_results = main_db_con.select("SELECT * FROM tv_shows WHERE indexer_id = ?", [self.indexerid]) if len(sql_results) > 1: raise MultipleShowsInDatabaseException() elif not sql_results: logger.log(str(self.indexerid) + ": Unable to find the show in the database") return else: self.indexer = int(sql_results[0][b"indexer"] or 0) if not self.name: self.name = sql_results[0][b"show_name"] if not self.network: self.network = sql_results[0][b"network"] if not self.genre: self.genre = sql_results[0][b"genre"] if not self.classification: self.classification = sql_results[0][b"classification"] self.runtime = sql_results[0][b"runtime"] self.status = sql_results[0][b"status"] if self.status is None: self.status = "Unknown" self.airs = sql_results[0][b"airs"] if self.airs is None: self.airs = "" self.startyear = int(sql_results[0][b"startyear"] or 0) self.air_by_date = int(sql_results[0][b"air_by_date"] or 0) self.anime = int(sql_results[0][b"anime"] or 0) self.sports = int(sql_results[0][b"sports"] or 0) self.scene = int(sql_results[0][b"scene"] or 0) self.subtitles = int(sql_results[0][b"subtitles"] or 0) self.dvdorder = int(sql_results[0][b"dvdorder"] or 0) self.quality = int(sql_results[0][b"quality"] or UNKNOWN) self.flatten_folders = int(sql_results[0][b"flatten_folders"] or 0) self.paused = int(sql_results[0][b"paused"] or 0) try: self._location = sql_results[0][b"location"] except Exception: dirty_setter("_location")(self, sql_results[0][b"location"]) if not self.lang: self.lang = sql_results[0][b"lang"] self.last_update_indexer = sql_results[0][b"last_update_indexer"] self.rls_ignore_words = sql_results[0][b"rls_ignore_words"] self.rls_require_words = sql_results[0][b"rls_require_words"] self.default_ep_status = int(sql_results[0][b"default_ep_status"] or SKIPPED) if not self.imdbid: self.imdbid = sql_results[0][b"imdb_id"] if self.is_anime: self.release_groups = BlackAndWhiteList(self.indexerid) self.subtitles_sr_metadata = int(sql_results[0][b"sub_use_sr_metadata"] or 0) # Get IMDb_info from database main_db_con = db.DBConnection() sql_results = main_db_con.select("SELECT * FROM imdb_info WHERE indexer_id = ?", [self.indexerid]) if not sql_results: logger.log(str(self.indexerid) + ": Unable to find IMDb show info in the database") return else: self.imdb_info = dict(zip(sql_results[0].keys(), sql_results[0])) self.dirty = False return True def loadFromIndexer(self, cache=True, tvapi=None): if self.indexer == INDEXER_TVRAGE: return logger.log(str(self.indexerid) + ": Loading show info from " + sickbeard.indexerApi(self.indexer).name, logger.DEBUG) # There's gotta be a better way of doing this but we don't wanna # change the cache value elsewhere if tvapi: t = tvapi else: lINDEXER_API_PARMS = sickbeard.indexerApi(self.indexer).api_params.copy() if not cache: lINDEXER_API_PARMS['cache'] = False lINDEXER_API_PARMS['language'] = self.lang or sickbeard.INDEXER_DEFAULT_LANGUAGE if self.dvdorder: lINDEXER_API_PARMS['dvdorder'] = True t = sickbeard.indexerApi(self.indexer).indexer(**lINDEXER_API_PARMS) myEp = t[self.indexerid] try: self.name = myEp[b'seriesname'].strip() except AttributeError: raise sickbeard.indexer_attributenotfound( "Found {0}, but attribute 'seriesname' was empty.".format(self.indexerid)) self.classification = getattr(myEp, 'classification', 'Scripted') self.genre = getattr(myEp, 'genre', '') self.network = getattr(myEp, 'network', '') self.runtime = getattr(myEp, 'runtime', '') self.imdbid = getattr(myEp, 'imdb_id', '') if getattr(myEp, 'airs_dayofweek', None) is not None and getattr(myEp, 'airs_time', None) is not None: self.airs = myEp[b"airs_dayofweek"] + " " + myEp[b"airs_time"] if self.airs is None: self.airs = '' if getattr(myEp, 'firstaired', None) is not None: self.startyear = int(str(myEp[b"firstaired"]).split('-')[0]) self.status = getattr(myEp, 'status', 'Unknown') def loadIMDbInfo(self): # pylint: disable=too-many-branches imdb_info = { 'imdb_id': self.imdbid, 'title': '', 'year': '', 'akas': [], 'runtimes': '', 'genres': [], 'countries': '', 'country_codes': [], 'certificates': [], 'rating': '', 'votes': '', 'last_update': '' } i = imdb.IMDb() if not self.imdbid: self.imdbid = i.title2imdbID(self.name, kind='tv series') if not self.imdbid: logger.log(str(self.indexerid) + ": Not loading show info from IMDb, because we don't know the imdbid", logger.DEBUG) return logger.log(str(self.indexerid) + ": Loading show info from IMDb", logger.DEBUG) imdbTv = i.get_movie(str(re.sub(r"[^0-9]", "", self.imdbid))) for key in [x for x in imdb_info.keys() if x.replace('_', ' ') in imdbTv.keys()]: # Store only the first value for string type if isinstance(imdb_info[key], basestring) and isinstance(imdbTv.get(key.replace('_', ' ')), list): imdb_info[key] = imdbTv.get(key.replace('_', ' '))[0] else: imdb_info[key] = imdbTv.get(key.replace('_', ' ')) # Filter only the value if imdb_info[b'runtimes']: imdb_info[b'runtimes'] = re.search(r'\d+', imdb_info[b'runtimes']).group(0) else: imdb_info[b'runtimes'] = self.runtime if imdb_info[b'akas']: imdb_info[b'akas'] = '|'.join(imdb_info[b'akas']) else: imdb_info[b'akas'] = '' # Join all genres in a string if imdb_info[b'genres']: imdb_info[b'genres'] = '|'.join(imdb_info[b'genres']) else: imdb_info[b'genres'] = '' # Get only the production country certificate if any if imdb_info[b'certificates'] and imdb_info[b'countries']: dct = {} try: for item in imdb_info[b'certificates']: dct[item.split(':')[0]] = item.split(':')[1] imdb_info[b'certificates'] = dct[imdb_info[b'countries']] except Exception: imdb_info[b'certificates'] = '' else: imdb_info[b'certificates'] = '' if imdb_info[b'country_codes']: imdb_info[b'country_codes'] = '|'.join(imdb_info[b'country_codes']) else: imdb_info[b'country_codes'] = '' imdb_info[b'last_update'] = datetime.date.today().toordinal() # Rename dict keys without spaces for DB upsert self.imdb_info = dict( (k.replace(' ', '_'), k(v) if hasattr(v, 'keys') else v) for k, v in imdb_info.iteritems()) logger.log(str(self.indexerid) + ": Obtained info from IMDb ->" + str(self.imdb_info), logger.DEBUG) def nextEpisode(self): curDate = datetime.date.today().toordinal() if not self.nextaired or self.nextaired and curDate > self.nextaired: main_db_con = db.DBConnection() sql_results = main_db_con.select( "SELECT airdate, season, episode FROM tv_episodes WHERE showid = ? AND airdate >= ? AND status IN (?,?) ORDER BY airdate ASC LIMIT 1", [self.indexerid, datetime.date.today().toordinal(), UNAIRED, WANTED]) self.nextaired = sql_results[0][b'airdate'] if sql_results else '' return self.nextaired def deleteShow(self, full=False): sql_l = [["DELETE FROM tv_episodes WHERE showid = ?", [self.indexerid]], ["DELETE FROM tv_shows WHERE indexer_id = ?", [self.indexerid]], ["DELETE FROM imdb_info WHERE indexer_id = ?", [self.indexerid]], ["DELETE FROM xem_refresh WHERE indexer_id = ?", [self.indexerid]], ["DELETE FROM scene_numbering WHERE indexer_id = ?", [self.indexerid]]] main_db_con = db.DBConnection() main_db_con.mass_action(sql_l) action = ('delete', 'trash')[sickbeard.TRASH_REMOVE_SHOW] # remove self from show list sickbeard.showList = [x for x in sickbeard.showList if int(x.indexerid) != self.indexerid] # clear the cache image_cache_dir = ek(os.path.join, sickbeard.CACHE_DIR, 'images') for cache_file in ek(glob.glob, ek(os.path.join, glob.escape(image_cache_dir), str(self.indexerid) + '.*')): logger.log('Attempt to {0} cache file {1}'.format(action, cache_file)) try: if sickbeard.TRASH_REMOVE_SHOW: send2trash(cache_file) else: ek(os.remove, cache_file) except OSError as error: logger.log('Unable to {0} {1}: {2}'.format(action, cache_file, error), logger.WARNING) # remove entire show folder if full: try: logger.log('Attempt to {0} show folder {1}'.format(action, self._location)) # check first the read-only attribute file_attribute = ek(os.stat, self.location)[0] if not file_attribute & stat.S_IWRITE: # File is read-only, so make it writeable logger.log('Attempting to make writeable the read only folder {0}'.format(self._location), logger.DEBUG) try: ek(os.chmod, self.location, stat.S_IWRITE) except Exception as error: logger.log('Unable to change permissions of {0}: {1}'.format(self._location, error), logger.WARNING) if sickbeard.TRASH_REMOVE_SHOW: send2trash(self.location) else: ek(shutil.rmtree, self.location) logger.log('{0} show folder {1}'.format (('Deleted', 'Trashed')[sickbeard.TRASH_REMOVE_SHOW], self._location)) except ShowDirectoryNotFoundException: logger.log("Show folder does not exist, no need to {0} {1}".format(action, self._location), logger.WARNING) except OSError as error: logger.log('Unable to {0} {1}: {2}'.format(action, self._location, error), logger.WARNING) if sickbeard.USE_TRAKT and sickbeard.TRAKT_SYNC_WATCHLIST: logger.log("Removing show: indexerid " + str(self.indexerid) + ", Title " + str(self.name) + " from Watchlist", logger.DEBUG) notifiers.trakt_notifier.update_watchlist(self, update="remove") def populateCache(self): cache_inst = image_cache.ImageCache() logger.log("Checking & filling cache for show " + self.name, logger.DEBUG) cache_inst.fill_cache(self) def refreshDir(self): # make sure the show dir is where we think it is unless dirs are created on the fly if not ek(os.path.isdir, self._location) and not sickbeard.CREATE_MISSING_SHOW_DIRS: return False # load from dir self.loadEpisodesFromDir() # run through all locations from DB, check that they exist logger.log(str(self.indexerid) + ": Loading all episodes with a location from the database", logger.DEBUG) main_db_con = db.DBConnection() sql_results = main_db_con.select("SELECT season, episode, location FROM tv_episodes WHERE showid = ? AND location != ''", [self.indexerid]) sql_l = [] for ep in sql_results: curLoc = ek(os.path.normpath, ep[b"location"]) season = int(ep[b"season"]) episode = int(ep[b"episode"]) try: curEp = self.getEpisode(season, episode) if not curEp: raise EpisodeDeletedException except EpisodeDeletedException: logger.log("The episode was deleted while we were refreshing it, moving on to the next one", logger.DEBUG) continue # if the path doesn't exist or if it's not in our show dir if not ek(os.path.isfile, curLoc) or not ek(os.path.normpath, curLoc).startswith( ek(os.path.normpath, self.location)): # check if downloaded files still exist, update our data if this has changed if not sickbeard.SKIP_REMOVED_FILES: with curEp.lock: # if it used to have a file associated with it and it doesn't anymore then set it to sickbeard.EP_DEFAULT_DELETED_STATUS if curEp.location and curEp.status in Quality.DOWNLOADED: if sickbeard.EP_DEFAULT_DELETED_STATUS == ARCHIVED: oldStatus_, oldQuality = Quality.splitCompositeStatus(curEp.status) new_status = Quality.compositeStatus(ARCHIVED, oldQuality) else: new_status = sickbeard.EP_DEFAULT_DELETED_STATUS logger.log("{id}: Location for {ep} doesn't exist, removing it and changing our status to {status}".format (id=self.indexerid, ep=episode_num(season, episode), status=statusStrings[new_status]), logger.DEBUG) curEp.status = new_status curEp.subtitles = list() curEp.subtitles_searchcount = 0 curEp.subtitles_lastsearch = str(datetime.datetime.min) curEp.location = '' curEp.hasnfo = False curEp.hastbn = False curEp.release_name = '' sql_l.append(curEp.get_sql()) if sql_l: main_db_con = db.DBConnection() main_db_con.mass_action(sql_l) def download_subtitles(self, force=False): if not ek(os.path.isdir, self._location): logger.log(str(self.indexerid) + ": Show dir doesn't exist, can't download subtitles", logger.DEBUG) return logger.log("{0}: Downloading subtitles".format(self.indexerid), logger.DEBUG) try: episodes = self.getAllEpisodes(has_location=True) if not episodes: logger.log("{0}: No episodes to download subtitles for {1}".format(self.indexerid, self.name), logger.DEBUG) return for episode in episodes: episode.download_subtitles(force=force) except Exception: logger.log("{0}: Error occurred when downloading subtitles for {1}".format(self.indexerid, self.name), logger.DEBUG) logger.log(traceback.format_exc(), logger.ERROR) def saveToDB(self, forceSave=False): if not self.dirty and not forceSave: # logger.log(str(self.indexerid) + ": Not saving show to db - record is not dirty", logger.DEBUG) return logger.log("{0:d}: Saving to database: {1}".format(self.indexerid, self.name), logger.DEBUG) controlValueDict = {"indexer_id": self.indexerid} newValueDict = {"indexer": self.indexer, "show_name": self.name, "location": self._location, "network": self.network, "genre": self.genre, "classification": self.classification, "runtime": self.runtime, "quality": self.quality, "airs": self.airs, "status": self.status, "flatten_folders": self.flatten_folders, "paused": self.paused, "air_by_date": self.air_by_date, "anime": self.anime, "scene": self.scene, "sports": self.sports, "subtitles": self.subtitles, "dvdorder": self.dvdorder, "startyear": self.startyear, "lang": self.lang, "imdb_id": self.imdbid, "last_update_indexer": self.last_update_indexer, "rls_ignore_words": self.rls_ignore_words, "rls_require_words": self.rls_require_words, "default_ep_status": self.default_ep_status, "sub_use_sr_metadata": self.subtitles_sr_metadata} main_db_con = db.DBConnection() main_db_con.upsert("tv_shows", newValueDict, controlValueDict) helpers.update_anime_support() if self.imdbid: controlValueDict = {"indexer_id": self.indexerid} newValueDict = self.imdb_info main_db_con = db.DBConnection() main_db_con.upsert("imdb_info", newValueDict, controlValueDict) def __str__(self): toReturn = "" toReturn += "indexerid: " + str(self.indexerid) + "\n" toReturn += "indexer: " + str(self.indexer) + "\n" toReturn += "name: " + self.name + "\n" toReturn += "location: " + self._location + "\n" if self.network: toReturn += "network: " + self.network + "\n" if self.airs: toReturn += "airs: " + self.airs + "\n" toReturn += "status: " + self.status + "\n" toReturn += "startyear: " + str(self.startyear) + "\n" if self.genre: toReturn += "genre: " + self.genre + "\n" toReturn += "classification: " + self.classification + "\n" toReturn += "runtime: " + str(self.runtime) + "\n" toReturn += "quality: " + str(self.quality) + "\n" toReturn += "scene: " + str(self.is_scene) + "\n" toReturn += "sports: " + str(self.is_sports) + "\n" toReturn += "anime: " + str(self.is_anime) + "\n" return toReturn @staticmethod def qualitiesToString(qualities=None): return ', '.join([Quality.qualityStrings[quality] for quality in qualities or [] if quality and quality in Quality.qualityStrings]) or 'None' def wantEpisode(self, season, episode, quality, manualSearch=False, downCurQuality=False): # pylint: disable=too-many-return-statements, too-many-arguments # if the quality isn't one we want under any circumstances then just say no allowed_qualities, preferred_qualities = Quality.splitQuality(self.quality) logger.log("Any,Best = [ {0} ] [ {1} ] Found = [ {2} ]".format (self.qualitiesToString(allowed_qualities), self.qualitiesToString(preferred_qualities), self.qualitiesToString([quality])), logger.DEBUG) if quality not in allowed_qualities + preferred_qualities or quality is UNKNOWN: logger.log("Don't want this quality, ignoring found result for {name} {ep} with quality {quality}".format (name=self.name, ep=episode_num(season, episode), quality=Quality.qualityStrings[quality]), logger.DEBUG) return False main_db_con = db.DBConnection() sql_results = main_db_con.select("SELECT status FROM tv_episodes WHERE showid = ? AND season = ? AND episode = ?", [self.indexerid, season, episode]) if not sql_results or not len(sql_results): logger.log("Unable to find a matching episode in database, ignoring found result for {name} {ep} with quality {quality}".format (name=self.name, ep=episode_num(season, episode), quality=Quality.qualityStrings[quality]), logger.DEBUG) return False epStatus = int(sql_results[0][b"status"]) epStatus_text = statusStrings[epStatus] # if we know we don't want it then just say no if epStatus in Quality.ARCHIVED + [UNAIRED, SKIPPED, IGNORED] and not manualSearch: logger.log("Existing episode status is '{status}', ignoring found result for {name} {ep} with quality {quality}".format (status=epStatus_text, name=self.name, ep=episode_num(season, episode), quality=Quality.qualityStrings[quality]), logger.DEBUG) return False curStatus_, curQuality = Quality.splitCompositeStatus(epStatus) # if it's one of these then we want it as long as it's in our allowed initial qualities if epStatus in (WANTED, SKIPPED, UNKNOWN): logger.log("Existing episode status is '{status}', getting found result for {name} {ep} with quality {quality}".format (status=epStatus_text, name=self.name, ep=episode_num(season, episode), quality=Quality.qualityStrings[quality]), logger.DEBUG) return True elif manualSearch: if (downCurQuality and quality >= curQuality) or (not downCurQuality and quality > curQuality): logger.log("Usually ignoring found result, but forced search allows the quality," " getting found result for {name} {ep} with quality {quality}".format (name=self.name, ep=episode_num(season, episode), quality=Quality.qualityStrings[quality]), logger.DEBUG) return True # if we are re-downloading then we only want it if it's in our preferred_qualities list and better than what we have, or we only have one bestQuality and we do not have that quality yet if epStatus in Quality.DOWNLOADED + Quality.SNATCHED + Quality.SNATCHED_PROPER and quality in preferred_qualities and (quality > curQuality or curQuality not in preferred_qualities): logger.log("Episode already exists with quality {existing_quality} but the found result" " quality {new_quality} is wanted more, getting found result for {name} {ep}".format (existing_quality=Quality.qualityStrings[curQuality], new_quality=Quality.qualityStrings[quality], name=self.name, ep=episode_num(season, episode)), logger.DEBUG) return True elif curQuality == Quality.UNKNOWN and manualSearch: logger.log("Episode already exists but quality is Unknown, getting found result for {name} {ep} with quality {quality}".format (name=self.name, ep=episode_num(season, episode), quality=Quality.qualityStrings[quality]), logger.DEBUG) return True else: logger.log("Episode already exists with quality {existing_quality} and the found result has same/lower quality," " ignoring found result for {name} {ep} with quality {new_quality}".format (existing_quality=Quality.qualityStrings[curQuality], name=self.name, ep=episode_num(season, episode), new_quality=Quality.qualityStrings[quality]), logger.DEBUG) return False def getOverview(self, epStatus): # pylint: disable=too-many-return-statements, too-many-branches """ Get the Overview status from the Episode status :param epStatus: an Episode status :return: an Overview status """ ep_status = try_int(epStatus) or UNKNOWN if ep_status == WANTED: return Overview.WANTED elif ep_status in (UNAIRED, UNKNOWN): return Overview.UNAIRED elif ep_status in (SKIPPED, IGNORED): return Overview.SKIPPED elif ep_status in Quality.ARCHIVED: return Overview.GOOD elif ep_status in Quality.FAILED: return Overview.WANTED elif ep_status in Quality.SNATCHED: return Overview.SNATCHED elif ep_status in Quality.SNATCHED_PROPER: return Overview.SNATCHED_PROPER elif ep_status in Quality.SNATCHED_BEST: return Overview.SNATCHED_BEST elif ep_status in Quality.DOWNLOADED: allowed_qualities, preferred_qualities = Quality.splitQuality(self.quality) ep_status, cur_quality = Quality.splitCompositeStatus(ep_status) if cur_quality not in allowed_qualities + preferred_qualities: return Overview.QUAL elif preferred_qualities and cur_quality not in preferred_qualities: return Overview.QUAL else: return Overview.GOOD else: logger.log('Could not parse episode status into a valid overview status: {0}'.format(epStatus), logger.ERROR) def __getstate__(self): d = dict(self.__dict__) del d[b'lock'] return d def __setstate__(self, d): d[b'lock'] = threading.Lock() self.__dict__.update(d) class TVEpisode(object): # pylint: disable=too-many-instance-attributes, too-many-public-methods def __init__(self, show, season, episode, ep_file=""): self._name = "" self._season = season self._episode = episode self._absolute_number = 0 self._description = "" self._subtitles = list() self._subtitles_searchcount = 0 self._subtitles_lastsearch = str(datetime.datetime.min) self._airdate = datetime.date.fromordinal(1) self._hasnfo = False self._hastbn = False self._status = UNKNOWN self._indexerid = 0 self._file_size = 0 self._release_name = '' self._is_proper = False self._version = 0 self._release_group = '' # setting any of the above sets the dirty flag self.dirty = True self.show = show self.scene_season = 0 self.scene_episode = 0 self.scene_absolute_number = 0 self._location = ep_file self._indexer = int(self.show.indexer) self.lock = threading.Lock() self.specifyEpisode(self.season, self.episode) self.relatedEps = [] self.checkForMetaFiles() self.wantedQuality = [] name = property(lambda self: self._name, dirty_setter("_name")) season = property(lambda self: self._season, dirty_setter("_season")) episode = property(lambda self: self._episode, dirty_setter("_episode")) absolute_number = property(lambda self: self._absolute_number, dirty_setter("_absolute_number")) description = property(lambda self: self._description, dirty_setter("_description")) subtitles = property(lambda self: self._subtitles, dirty_setter("_subtitles")) subtitles_searchcount = property(lambda self: self._subtitles_searchcount, dirty_setter("_subtitles_searchcount")) subtitles_lastsearch = property(lambda self: self._subtitles_lastsearch, dirty_setter("_subtitles_lastsearch")) airdate = property(lambda self: self._airdate, dirty_setter("_airdate")) hasnfo = property(lambda self: self._hasnfo, dirty_setter("_hasnfo")) hastbn = property(lambda self: self._hastbn, dirty_setter("_hastbn")) status = property(lambda self: self._status, dirty_setter("_status")) indexer = property(lambda self: self._indexer, dirty_setter("_indexer")) indexerid = property(lambda self: self._indexerid, dirty_setter("_indexerid")) # location = property(lambda self: self._location, dirty_setter("_location")) file_size = property(lambda self: self._file_size, dirty_setter("_file_size")) release_name = property(lambda self: self._release_name, dirty_setter("_release_name")) is_proper = property(lambda self: self._is_proper, dirty_setter("_is_proper")) version = property(lambda self: self._version, dirty_setter("_version")) release_group = property(lambda self: self._release_group, dirty_setter("_release_group")) def _set_location(self, new_location): logger.log("Setter sets location to " + new_location, logger.DEBUG) # self._location = newLocation dirty_setter("_location")(self, new_location) if new_location and ek(os.path.isfile, new_location): self.file_size = ek(os.path.getsize, new_location) else: self.file_size = 0 location = property(lambda self: self._location, _set_location) def refreshSubtitles(self): """Look for subtitles files and refresh the subtitles property""" self.subtitles, save_subtitles = subtitles.refresh_subtitles(self) if save_subtitles: self.saveToDB() def download_subtitles(self, force=False, force_lang=None): force_ = force if not ek(os.path.isfile, self.location): logger.log("{id}: Episode file doesn't exist, can't download subtitles for {ep}".format (id=self.show.indexerid, ep=episode_num(self.season, self.episode)), logger.DEBUG) return if not subtitles.needs_subtitles(self.subtitles, force_lang): logger.log('Episode already has all needed subtitles, skipping episode {ep} of show {show}'.format (ep=episode_num(self.season, self.episode), show=self.show.name), logger.DEBUG) return logger.log("Checking subtitle candidates for {show} {ep} ({location})".format (show=self.show.name, ep=episode_num(self.season, self.episode), location=os.path.basename(self.location)), logger.DEBUG) self.subtitles, new_subtitles = subtitles.download_subtitles(self, force_lang) self.subtitles_searchcount += 1 if self.subtitles_searchcount else 1 self.subtitles_lastsearch = datetime.datetime.now().strftime(dateTimeFormat) self.saveToDB() if new_subtitles: subtitle_list = ", ".join([subtitles.name_from_code(code) for code in new_subtitles]) logger.log("{id}: Downloaded {subtitles} subtitles for {show} {ep}".format (id=self.show.indexerid, subtitles=subtitle_list, show=self.show.name, ep=episode_num(self.season, self.episode)), logger.DEBUG) notifiers.notify_subtitle_download(self.prettyName(), subtitle_list) else: logger.log("{id}: No subtitles downloaded for {show} {ep}".format (id=self.show.indexerid, show=self.show.name, ep=episode_num(self.season, self.episode)), logger.DEBUG) return new_subtitles def checkForMetaFiles(self): oldhasnfo = self.hasnfo oldhastbn = self.hastbn cur_nfo = False cur_tbn = False # check for nfo and tbn if ek(os.path.isfile, self.location): for cur_provider in sickbeard.metadata_provider_dict.values(): if cur_provider.episode_metadata: new_result = cur_provider._has_episode_metadata(self) # pylint: disable=protected-access else: new_result = False cur_nfo = new_result or cur_nfo if cur_provider.episode_thumbnails: new_result = cur_provider._has_episode_thumb(self) # pylint: disable=protected-access else: new_result = False cur_tbn = new_result or cur_tbn self.hasnfo = cur_nfo self.hastbn = cur_tbn # if either setting has changed return true, if not return false return oldhasnfo != self.hasnfo or oldhastbn != self.hastbn def specifyEpisode(self, season, episode): sql_results = self.loadFromDB(season, episode) if not sql_results: # only load from NFO if we didn't load from DB if ek(os.path.isfile, self.location): try: self.loadFromNFO(self.location) except NoNFOException: logger.log("{id}: There was an error loading the NFO for episode {ep}".format (id=self.show.indexerid, ep=episode_num(season, episode)), logger.ERROR) # if we tried loading it from NFO and didn't find the NFO, try the Indexers if not self.hasnfo: try: result = self.loadFromIndexer(season, episode) except EpisodeDeletedException: result = False # if we failed SQL *and* NFO, Indexers then fail if not result: raise EpisodeNotFoundException("Couldn't find episode {ep}".format(ep=episode_num(season, episode))) def loadFromDB(self, season, episode): # pylint: disable=too-many-branches # logger.log("{id}: Loading episode details for {name} {ep} from DB".format # (id=self.show.indexerid, name=self.show.name, # ep=episode_num(season, episode)), logger.DEBUG) main_db_con = db.DBConnection() sql_results = main_db_con.select("SELECT * FROM tv_episodes WHERE showid = ? AND season = ? AND episode = ?", [self.show.indexerid, season, episode]) if len(sql_results) > 1: raise MultipleEpisodesInDatabaseException("Your DB has two records for the same show somehow.") elif not sql_results: logger.log("{id}: Episode {ep} not found in the database".format (id=self.show.indexerid, ep=episode_num(season, episode)), logger.DEBUG) return False else: if sql_results[0][b"name"]: self.name = sql_results[0][b"name"] self.season = season self.episode = episode self.absolute_number = sql_results[0][b"absolute_number"] self.description = sql_results[0][b"description"] if not self.description: self.description = "" if sql_results[0][b"subtitles"] and sql_results[0][b"subtitles"]: self.subtitles = sql_results[0][b"subtitles"].split(",") self.subtitles_searchcount = sql_results[0][b"subtitles_searchcount"] self.subtitles_lastsearch = sql_results[0][b"subtitles_lastsearch"] self.airdate = datetime.date.fromordinal(long(sql_results[0][b"airdate"])) # logger.log("1 Status changes from " + str(self.status) + " to " + str(sql_results[0][b"status"]), logger.DEBUG) self.status = int(sql_results[0][b"status"] or -1) # don't overwrite my location if sql_results[0][b"location"] and sql_results[0][b"location"]: self.location = ek(os.path.normpath, sql_results[0][b"location"]) if sql_results[0][b"file_size"]: self.file_size = int(sql_results[0][b"file_size"]) else: self.file_size = 0 self.indexerid = int(sql_results[0][b"indexerid"]) self.indexer = int(sql_results[0][b"indexer"]) sickbeard.scene_numbering.xem_refresh(self.show.indexerid, self.show.indexer) self.scene_season = try_int(sql_results[0][b"scene_season"], 0) self.scene_episode = try_int(sql_results[0][b"scene_episode"], 0) self.scene_absolute_number = try_int(sql_results[0][b"scene_absolute_number"], 0) if self.scene_absolute_number == 0: self.scene_absolute_number = sickbeard.scene_numbering.get_scene_absolute_numbering( self.show.indexerid, self.show.indexer, self.absolute_number ) if self.scene_season == 0 or self.scene_episode == 0: self.scene_season, self.scene_episode = sickbeard.scene_numbering.get_scene_numbering( self.show.indexerid, self.show.indexer, self.season, self.episode ) if sql_results[0][b"release_name"] is not None: self.release_name = sql_results[0][b"release_name"] if sql_results[0][b"is_proper"]: self.is_proper = int(sql_results[0][b"is_proper"]) if sql_results[0][b"version"]: self.version = int(sql_results[0][b"version"]) if sql_results[0][b"release_group"] is not None: self.release_group = sql_results[0][b"release_group"] self.dirty = False return True def loadFromIndexer(self, season=None, episode=None, cache=True, tvapi=None, cachedSeason=None): # pylint: disable=too-many-arguments, too-many-branches, too-many-statements if season is None: season = self.season if episode is None: episode = self.episode # logger.log("{id}: Loading episode details for {show} {ep} from {indexer}".format # (id=self.show.indexerid, show=self.show.name, ep=episode_num(season, episode), # indexer=sickbeard.indexerApi(self.show.indexer).name), logger.DEBUG) indexer_lang = self.show.lang try: if cachedSeason: myEp = cachedSeason[episode] else: if tvapi: t = tvapi else: lINDEXER_API_PARMS = sickbeard.indexerApi(self.indexer).api_params.copy() if not cache: lINDEXER_API_PARMS['cache'] = False lINDEXER_API_PARMS['language'] = indexer_lang or sickbeard.INDEXER_DEFAULT_LANGUAGE if self.show.dvdorder: lINDEXER_API_PARMS['dvdorder'] = True t = sickbeard.indexerApi(self.indexer).indexer(**lINDEXER_API_PARMS) myEp = t[self.show.indexerid][season][episode] except (sickbeard.indexer_error, IOError) as error: logger.log("" + sickbeard.indexerApi(self.indexer).name + " threw up an error: " + ex(error), logger.DEBUG) # if the episode is already valid just log it, if not throw it up if self.name: logger.log("" + sickbeard.indexerApi(self.indexer).name + " timed out but we have enough info from other sources, allowing the error", logger.DEBUG) return else: logger.log("" + sickbeard.indexerApi(self.indexer).name + " timed out, unable to create the episode", logger.ERROR) return False except (sickbeard.indexer_episodenotfound, sickbeard.indexer_seasonnotfound): logger.log("Unable to find the episode on " + sickbeard.indexerApi( self.indexer).name + "... has it been removed? Should I delete from db?", logger.DEBUG) # if I'm no longer on the Indexers but I once was then delete myself from the DB if self.indexerid != -1: self.deleteEpisode() return if getattr(myEp, 'episodename', None) is None: logger.log("This episode {show} - {ep} has no name on {indexer}. Setting to an empty string".format (show=self.show.name, ep=episode_num(season, episode), indexer=sickbeard.indexerApi(self.indexer).name)) setattr(myEp, 'episodename', '') if getattr(myEp, 'absolute_number', None) is None: logger.log("{id}: This episode {show} - {ep} has no absolute number on {indexer}".format (id=self.show.indexerid, show=self.show.name, ep=episode_num(season, episode), indexer=sickbeard.indexerApi(self.indexer).name), logger.DEBUG) else: logger.log("{id}: The absolute number for {ep} is: {absolute} ".format (id=self.show.indexerid, ep=episode_num(season, episode), absolute=myEp[b"absolute_number"]), logger.DEBUG) self.absolute_number = int(myEp[b"absolute_number"]) self.name = getattr(myEp, 'episodename', "") self.season = season self.episode = episode sickbeard.scene_numbering.xem_refresh(self.show.indexerid, self.show.indexer) self.scene_absolute_number = sickbeard.scene_numbering.get_scene_absolute_numbering( self.show.indexerid, self.show.indexer, self.absolute_number ) self.scene_season, self.scene_episode = sickbeard.scene_numbering.get_scene_numbering( self.show.indexerid, self.show.indexer, self.season, self.episode ) self.description = getattr(myEp, 'overview', "") firstaired = getattr(myEp, 'firstaired', None) if not firstaired or firstaired == "0000-00-00": firstaired = str(datetime.date.fromordinal(1)) rawAirdate = [int(x) for x in firstaired.split("-")] try: self.airdate = datetime.date(rawAirdate[0], rawAirdate[1], rawAirdate[2]) except (ValueError, IndexError): logger.log("Malformed air date of {aired} retrieved from {indexer} for ({show} - {ep})".format (aired=firstaired, indexer=sickbeard.indexerApi(self.indexer).name, show=self.show.name, ep=episode_num(season, episode)), logger.WARNING) # if I'm incomplete on the indexer but I once was complete then just delete myself from the DB for now if self.indexerid != -1: self.deleteEpisode() return False # early conversion to int so that episode doesn't get marked dirty self.indexerid = getattr(myEp, 'id', None) if self.indexerid is None: logger.log("Failed to retrieve ID from {indexer}".format (indexer=sickbeard.indexerApi(self.indexer).name), logger.ERROR) if self.indexerid != -1: self.deleteEpisode() return False # don't update show status if show dir is missing, unless it's missing on purpose if not ek(os.path.isdir, self.show._location) and not sickbeard.CREATE_MISSING_SHOW_DIRS and not sickbeard.ADD_SHOWS_WO_DIR: # pylint: disable=protected-access logger.log("The show dir {0} is missing, not bothering to change the episode statuses since it'd probably be invalid".format(self.show._location)) # pylint: disable=protected-access return if self.location: logger.log("{id}: Setting status for {ep} based on status {status} and location {location}".format (id=self.show.indexerid, ep=episode_num(season, episode), status=statusStrings[self.status], location=self.location), logger.DEBUG) if not ek(os.path.isfile, self.location): if self.airdate >= datetime.date.today() or self.airdate == datetime.date.fromordinal(1): logger.log("{0}: Episode airs in the future or has no airdate, marking it {1}".format(self.show.indexerid, statusStrings[UNAIRED]), logger.DEBUG) self.status = UNAIRED elif self.status in [UNAIRED, UNKNOWN]: # Only do UNAIRED/UNKNOWN, it could already be snatched/ignored/skipped, or downloaded/archived to disconnected media logger.log("Episode has already aired, marking it {0}".format(statusStrings[self.show.default_ep_status]), logger.DEBUG) self.status = self.show.default_ep_status if self.season > 0 else SKIPPED # auto-skip specials else: logger.log("Not touching status [ {0} ] It could be skipped/ignored/snatched/archived".format(statusStrings[self.status]), logger.DEBUG) # if we have a media file then it's downloaded elif sickbeard.helpers.isMediaFile(self.location): # leave propers alone, you have to either post-process them or manually change them back if self.status not in Quality.SNATCHED_PROPER + Quality.DOWNLOADED + Quality.SNATCHED + Quality.ARCHIVED: logger.log( "5 Status changes from " + str(self.status) + " to " + str(Quality.statusFromName(self.location)), logger.DEBUG) self.status = Quality.statusFromName(self.location, anime=self.show.is_anime) # shouldn't get here probably else: logger.log("6 Status changes from " + str(self.status) + " to " + str(UNKNOWN), logger.DEBUG) self.status = UNKNOWN def loadFromNFO(self, location): # pylint: disable=too-many-branches if not ek(os.path.isdir, self.show._location): # pylint: disable=protected-access logger.log( str(self.show.indexerid) + ": The show dir is missing, not bothering to try loading the episode NFO") return logger.log( str(self.show.indexerid) + ": Loading episode details from the NFO file associated with " + location, logger.DEBUG) self.location = location if self.location != "": if self.status == UNKNOWN and sickbeard.helpers.isMediaFile(self.location): logger.log("7 Status changes from " + str(self.status) + " to " + str( Quality.statusFromName(self.location, anime=self.show.is_anime)), logger.DEBUG) self.status = Quality.statusFromName(self.location, anime=self.show.is_anime) nfoFile = replace_extension(self.location, "nfo") logger.log(str(self.show.indexerid) + ": Using NFO name " + nfoFile, logger.DEBUG) if ek(os.path.isfile, nfoFile): try: showXML = etree.ElementTree(file=nfoFile) except (SyntaxError, ValueError) as error: logger.log("Error loading the NFO, backing up the NFO and skipping for now: " + ex(error), logger.ERROR) try: ek(os.rename, nfoFile, nfoFile + ".old") except Exception as error: logger.log( "Failed to rename your episode's NFO file - you need to delete it or fix it: " + ex(error), logger.ERROR) raise NoNFOException("Error in NFO format") for epDetails in showXML.getiterator('episodedetails'): if epDetails.findtext('season') is None or int(epDetails.findtext('season')) != self.season or \ epDetails.findtext('episode') is None or int(epDetails.findtext('episode')) != self.episode: logger.log("{id}: NFO has an <episodedetails> block for a different episode - wanted {ep_wanted} but got {ep_found}".format (id=self.show.indexerid, ep_wanted=episode_num(self.season, self.episode), ep_found=episode_num(epDetails.findtext('season'), epDetails.findtext('episode'))), logger.DEBUG) continue if epDetails.findtext('title') is None or epDetails.findtext('aired') is None: raise NoNFOException("Error in NFO format (missing episode title or airdate)") self.name = epDetails.findtext('title') self.episode = int(epDetails.findtext('episode')) self.season = int(epDetails.findtext('season')) sickbeard.scene_numbering.xem_refresh(self.show.indexerid, self.show.indexer) self.scene_absolute_number = sickbeard.scene_numbering.get_scene_absolute_numbering( self.show.indexerid, self.show.indexer, self.absolute_number ) self.scene_season, self.scene_episode = sickbeard.scene_numbering.get_scene_numbering( self.show.indexerid, self.show.indexer, self.season, self.episode ) self.description = epDetails.findtext('plot') if self.description is None: self.description = "" if epDetails.findtext('aired'): rawAirdate = [int(x) for x in epDetails.findtext('aired').split("-")] self.airdate = datetime.date(rawAirdate[0], rawAirdate[1], rawAirdate[2]) else: self.airdate = datetime.date.fromordinal(1) self.hasnfo = True else: self.hasnfo = False if ek(os.path.isfile, replace_extension(nfoFile, "tbn")): self.hastbn = True else: self.hastbn = False def __str__(self): toReturn = "" toReturn += "{0!r} - S{1!r}E{2!r} - {3!r}\n".format(self.show.name, self.season, self.episode, self.name) toReturn += "location: {0!r}\n".format(self.location) toReturn += "description: {0!r}\n".format(self.description) toReturn += "subtitles: {0!r}\n".format(",".join(self.subtitles)) toReturn += "subtitles_searchcount: {0!r}\n".format(self.subtitles_searchcount) toReturn += "subtitles_lastsearch: {0!r}\n".format(self.subtitles_lastsearch) toReturn += "airdate: {0!r} ({1!r})\n".format(self.airdate.toordinal(), self.airdate) toReturn += "hasnfo: {0!r}\n".format(self.hasnfo) toReturn += "hastbn: {0!r}\n".format(self.hastbn) toReturn += "status: {0!r}\n".format(self.status) return toReturn def createMetaFiles(self): if not ek(os.path.isdir, self.show._location): # pylint: disable=protected-access logger.log(str(self.show.indexerid) + ": The show dir is missing, not bothering to try to create metadata") return self.createNFO() self.createThumbnail() if self.checkForMetaFiles(): self.saveToDB() def createNFO(self): result = False for cur_provider in sickbeard.metadata_provider_dict.values(): result = cur_provider.create_episode_metadata(self) or result return result def createThumbnail(self): result = False for cur_provider in sickbeard.metadata_provider_dict.values(): result = cur_provider.create_episode_thumb(self) or result return result def deleteEpisode(self): logger.log("Deleting {show} {ep} from the DB".format (show=self.show.name, ep=episode_num(self.season, self.episode)), logger.DEBUG) # remove myself from the show dictionary if self.show.getEpisode(self.season, self.episode, noCreate=True) == self: logger.log("Removing myself from my show's list", logger.DEBUG) del self.show.episodes[self.season][self.episode] # delete myself from the DB logger.log("Deleting myself from the database", logger.DEBUG) main_db_con = db.DBConnection() sql = "DELETE FROM tv_episodes WHERE showid=" + str(self.show.indexerid) + " AND season=" + str( self.season) + " AND episode=" + str(self.episode) main_db_con.action(sql) raise EpisodeDeletedException() def get_sql(self, forceSave=False): """ Creates SQL queue for this episode if any of its data has been changed since the last save. forceSave: If True it will create SQL queue even if no data has been changed since the last save (aka if the record is not dirty). """ try: if not self.dirty and not forceSave: logger.log(str(self.show.indexerid) + ": Not creating SQL queue - record is not dirty", logger.DEBUG) return main_db_con = db.DBConnection() rows = main_db_con.select( 'SELECT episode_id, subtitles FROM tv_episodes WHERE showid = ? AND season = ? AND episode = ?', [self.show.indexerid, self.season, self.episode]) epID = None if rows: epID = int(rows[0][b'episode_id']) if epID: # use a custom update method to get the data into the DB for existing records. # Multi or added subtitle or removed subtitles if sickbeard.SUBTITLES_MULTI or not rows[0][b'subtitles'] or not self.subtitles: return [ "UPDATE tv_episodes SET indexerid = ?, indexer = ?, name = ?, description = ?, subtitles = ?, " "subtitles_searchcount = ?, subtitles_lastsearch = ?, airdate = ?, hasnfo = ?, hastbn = ?, status = ?, " "location = ?, file_size = ?, release_name = ?, is_proper = ?, showid = ?, season = ?, episode = ?, " "absolute_number = ?, version = ?, release_group = ? WHERE episode_id = ?", [self.indexerid, self.indexer, self.name, self.description, ",".join(self.subtitles), self.subtitles_searchcount, self.subtitles_lastsearch, self.airdate.toordinal(), self.hasnfo, self.hastbn, self.status, self.location, self.file_size, self.release_name, self.is_proper, self.show.indexerid, self.season, self.episode, self.absolute_number, self.version, self.release_group, epID]] else: # Don't update the subtitle language when the srt file doesn't contain the alpha2 code, keep value from subliminal return [ "UPDATE tv_episodes SET indexerid = ?, indexer = ?, name = ?, description = ?, " "subtitles_searchcount = ?, subtitles_lastsearch = ?, airdate = ?, hasnfo = ?, hastbn = ?, status = ?, " "location = ?, file_size = ?, release_name = ?, is_proper = ?, showid = ?, season = ?, episode = ?, " "absolute_number = ?, version = ?, release_group = ? WHERE episode_id = ?", [self.indexerid, self.indexer, self.name, self.description, self.subtitles_searchcount, self.subtitles_lastsearch, self.airdate.toordinal(), self.hasnfo, self.hastbn, self.status, self.location, self.file_size, self.release_name, self.is_proper, self.show.indexerid, self.season, self.episode, self.absolute_number, self.version, self.release_group, epID]] else: # use a custom insert method to get the data into the DB. return [ "INSERT OR IGNORE INTO tv_episodes (episode_id, indexerid, indexer, name, description, subtitles, " "subtitles_searchcount, subtitles_lastsearch, airdate, hasnfo, hastbn, status, location, file_size, " "release_name, is_proper, showid, season, episode, absolute_number, version, release_group) VALUES " "((SELECT episode_id FROM tv_episodes WHERE showid = ? AND season = ? AND episode = ?)" ",?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);", [self.show.indexerid, self.season, self.episode, self.indexerid, self.indexer, self.name, self.description, ",".join(self.subtitles), self.subtitles_searchcount, self.subtitles_lastsearch, self.airdate.toordinal(), self.hasnfo, self.hastbn, self.status, self.location, self.file_size, self.release_name, self.is_proper, self.show.indexerid, self.season, self.episode, self.absolute_number, self.version, self.release_group]] except Exception as error: logger.log("Error while updating database: {0}".format(error), logger.ERROR) def saveToDB(self, forceSave=False): """ Saves this episode to the database if any of its data has been changed since the last save. forceSave: If True it will save to the database even if no data has been changed since the last save (aka if the record is not dirty). """ if not self.dirty and not forceSave: # logger.log(str(self.show.indexerid) + ": Not saving episode to db - record is not dirty", logger.DEBUG) return newValueDict = {"indexerid": self.indexerid, "indexer": self.indexer, "name": self.name, "description": self.description, "subtitles": ",".join(self.subtitles), "subtitles_searchcount": self.subtitles_searchcount, "subtitles_lastsearch": self.subtitles_lastsearch, "airdate": self.airdate.toordinal(), "hasnfo": self.hasnfo, "hastbn": self.hastbn, "status": self.status, "location": self.location, "file_size": self.file_size, "release_name": self.release_name, "is_proper": self.is_proper, "absolute_number": self.absolute_number, "version": self.version, "release_group": self.release_group} controlValueDict = {"showid": self.show.indexerid, "season": self.season, "episode": self.episode} # logger.log("%s: Saving episode details to database %rx%r: %s" % # (self.show.indexerid, self.season, self.episode, statusStrings[self.status]), logger.DEBUG) # use a custom update/insert method to get the data into the DB main_db_con = db.DBConnection() main_db_con.upsert("tv_episodes", newValueDict, controlValueDict) def fullPath(self): if self.location is None or self.location == "": return None else: return ek(os.path.join, self.show.location, self.location) def createStrings(self, pattern=None): patterns = [ '%S.N.S%SE%0E', '%S.N.S%0SE%E', '%S.N.S%SE%E', '%S.N.S%0SE%0E', '%SN S%SE%0E', '%SN S%0SE%E', '%SN S%SE%E', '%SN S%0SE%0E' ] strings = [] if not pattern: for p in patterns: strings += [self._format_pattern(p)] return strings return self._format_pattern(pattern) def prettyName(self): """ Returns the name of this episode in a "pretty" human-readable format. Used for logging and notifications and such. Returns: A string representing the episode's name and season/ep numbers """ if self.show.anime and not self.show.scene: return self._format_pattern('%SN - %AB - %EN') elif self.show.air_by_date: return self._format_pattern('%SN - %AD - %EN') return self._format_pattern('%SN - S%0SE%0E - %EN') def _ep_name(self): """ Returns the name of the episode to use during renaming. Combines the names of related episodes. Eg. "Ep Name (1)" and "Ep Name (2)" becomes "Ep Name" "Ep Name" and "Other Ep Name" becomes "Ep Name & Other Ep Name" """ multiNameRegex = r"(.*) \(\d{1,2}\)" self.relatedEps = sorted(self.relatedEps, key=lambda x: x.episode) if not self.relatedEps: goodName = self.name else: goodName = '' singleName = True curGoodName = None for curName in [self.name] + [x.name for x in self.relatedEps]: match = re.match(multiNameRegex, curName) if not match: singleName = False break if curGoodName is None: curGoodName = match.group(1) elif curGoodName != match.group(1): singleName = False break if singleName: goodName = curGoodName else: goodName = self.name for relEp in self.relatedEps: goodName += " & " + relEp.name return goodName def _replace_map(self): # pylint: disable=too-many-branches """ Generates a replacement map for this episode which maps all possible custom naming patterns to the correct value for this episode. Returns: A dict with patterns as the keys and their replacement values as the values. """ ep_name = self._ep_name() def dot(name): # assert isinstance(name, unicode), name + ' is not unicode' return helpers.sanitizeSceneName(name) def us(name): return re.sub('[ -]', '_', name) def release_name(name): if name: name = helpers.remove_non_release_groups(remove_extension(name)) return name def release_group(show, name): if name: name = helpers.remove_non_release_groups(remove_extension(name)) else: return '' try: parse_result = NameParser(name, showObj=show, naming_pattern=True).parse(name) except (InvalidNameException, InvalidShowException) as error: logger.log("Unable to get parse release_group: {0}".format(error), logger.DEBUG) return '' if not parse_result.release_group: return '' return parse_result.release_group.strip('.- []{}') epStatus_, epQual = Quality.splitCompositeStatus(self.status) # @UnusedVariable if sickbeard.NAMING_STRIP_YEAR: show_name = re.sub(r"\(\d+\)$", "", self.show.name).strip() else: show_name = self.show.name # try to get the release group rel_grp = { "SickRage": 'SickRage' } if hasattr(self, 'location'): # from the location name rel_grp[b'location'] = release_group(self.show, self.location) if not rel_grp[b'location']: del rel_grp[b'location'] if hasattr(self, '_release_group'): # from the release group field in db rel_grp[b'database'] = self._release_group.strip('.- []{}') if not rel_grp[b'database']: del rel_grp[b'database'] if hasattr(self, 'release_name'): # from the release name field in db rel_grp[b'release_name'] = release_group(self.show, self.release_name) if not rel_grp[b'release_name']: del rel_grp[b'release_name'] # use release_group, release_name, location in that order if 'database' in rel_grp: relgrp = 'database' elif 'release_name' in rel_grp: relgrp = 'release_name' elif 'location' in rel_grp: relgrp = 'location' else: relgrp = 'SickRage' # try to get the release encoder to comply with scene naming standards encoder = Quality.sceneQualityFromName(self.release_name.replace(rel_grp[relgrp], ""), epQual) if encoder: logger.log("Found codec for '" + show_name + ": " + ep_name + "'.", logger.DEBUG) return { '%SN': show_name, '%S.N': dot(show_name), '%S_N': us(show_name), '%EN': ep_name, '%E.N': dot(ep_name), '%E_N': us(ep_name), '%QN': Quality.qualityStrings[epQual], '%Q.N': dot(Quality.qualityStrings[epQual]), '%Q_N': us(Quality.qualityStrings[epQual]), '%SQN': Quality.sceneQualityStrings[epQual] + encoder, '%SQ.N': dot(Quality.sceneQualityStrings[epQual] + encoder), '%SQ_N': us(Quality.sceneQualityStrings[epQual] + encoder), '%S': str(self.season), '%0S': '{0:02d}'.format(int(self.season)), '%E': str(self.episode), '%0E': '{0:02d}'.format(int(self.episode)), '%XS': str(self.scene_season), '%0XS': '{0:02d}'.format(int(self.scene_season)), '%XE': str(self.scene_episode), '%0XE': '{0:02d}'.format(int(self.scene_episode)), '%AB': '{0:03d}'.format(int(self.absolute_number)), '%XAB': '{0:03d}'.format(int(self.scene_absolute_number)), '%RN': release_name(self.release_name), '%RG': rel_grp[relgrp], '%CRG': rel_grp[relgrp].upper(), '%AD': str(self.airdate).replace('-', ' '), '%A.D': str(self.airdate).replace('-', '.'), '%A_D': us(str(self.airdate)), '%A-D': str(self.airdate), '%Y': str(self.airdate.year), '%M': str(self.airdate.month), '%D': str(self.airdate.day), '%CY': str(datetime.date.today().year), '%CM': str(datetime.date.today().month), '%CD': str(datetime.date.today().day), '%0M': '{0:02d}'.format(int(self.airdate.month)), '%0D': '{0:02d}'.format(int(self.airdate.day)), '%RT': "PROPER" if self.is_proper else "", } @staticmethod def _format_string(pattern, replace_map): """ Replaces all template strings with the correct value """ result_name = pattern # do the replacements for cur_replacement in sorted(replace_map.keys(), reverse=True): result_name = result_name.replace(cur_replacement, sanitize_filename(replace_map[cur_replacement])) result_name = result_name.replace(cur_replacement.lower(), sanitize_filename(replace_map[cur_replacement].lower())) return result_name def _format_pattern(self, pattern=None, multi=None, anime_type=None): # pylint: disable=too-many-branches, too-many-statements, too-many-locals """ Manipulates an episode naming pattern and then fills the template in """ if pattern is None: pattern = sickbeard.NAMING_PATTERN if multi is None: multi = sickbeard.NAMING_MULTI_EP if sickbeard.NAMING_CUSTOM_ANIME: if anime_type is None: anime_type = sickbeard.NAMING_ANIME else: anime_type = 3 replace_map = self._replace_map() result_name = pattern # if there's no release group in the db, let the user know we replaced it if replace_map[b'%RG'] and replace_map[b'%RG'] != 'SickRage': if not hasattr(self, '_release_group'): logger.log("Episode has no release group, replacing it with '" + replace_map[b'%RG'] + "'", logger.DEBUG) self._release_group = replace_map[b'%RG'] # if release_group is not in the db, put it there elif not self._release_group: logger.log("Episode has no release group, replacing it with '" + replace_map[b'%RG'] + "'", logger.DEBUG) self._release_group = replace_map[b'%RG'] # if release_group is not in the db, put it there # if there's no release name then replace it with a reasonable facsimile if not replace_map[b'%RN']: if self.show.air_by_date or self.show.sports: result_name = result_name.replace('%RN', '%S.N.%A.D.%E.N-' + replace_map[b'%RG']) result_name = result_name.replace('%rn', '%s.n.%A.D.%e.n-' + replace_map[b'%RG'].lower()) elif anime_type != 3: result_name = result_name.replace('%RN', '%S.N.%AB.%E.N-' + replace_map[b'%RG']) result_name = result_name.replace('%rn', '%s.n.%ab.%e.n-' + replace_map[b'%RG'].lower()) else: result_name = result_name.replace('%RN', '%S.N.S%0SE%0E.%E.N-' + replace_map[b'%RG']) result_name = result_name.replace('%rn', '%s.n.s%0se%0e.%e.n-' + replace_map[b'%RG'].lower()) # logger.log("Episode has no release name, replacing it with a generic one: " + result_name, logger.DEBUG) if not replace_map[b'%RT']: result_name = re.sub('([ _.-]*)%RT([ _.-]*)', r'\2', result_name) # split off ep name part only name_groups = re.split(r'[\\/]', result_name) # figure out the double-ep numbering style for each group, if applicable for cur_name_group in name_groups: season_format = sep = ep_sep = ep_format = None season_ep_regex = r''' (?P<pre_sep>[ _.-]*) ((?:s(?:eason|eries)?\s*)?%0?S(?![._]?N)) (.*?) (%0?E(?![._]?N)) (?P<post_sep>[ _.-]*) ''' ep_only_regex = r'(E?%0?E(?![._]?N))' # try the normal way season_ep_match = re.search(season_ep_regex, cur_name_group, re.I | re.X) ep_only_match = re.search(ep_only_regex, cur_name_group, re.I | re.X) # if we have a season and episode then collect the necessary data if season_ep_match: season_format = season_ep_match.group(2) ep_sep = season_ep_match.group(3) ep_format = season_ep_match.group(4) sep = season_ep_match.group('pre_sep') if not sep: sep = season_ep_match.group('post_sep') if not sep: sep = ' ' # force 2-3-4 format if they chose to extend if multi in (NAMING_EXTEND, NAMING_LIMITED_EXTEND, NAMING_LIMITED_EXTEND_E_PREFIXED): ep_sep = '-' regex_used = season_ep_regex # if there's no season then there's not much choice so we'll just force them to use 03-04-05 style elif ep_only_match: season_format = '' ep_sep = '-' ep_format = ep_only_match.group(1) sep = '' regex_used = ep_only_regex else: continue # we need at least this much info to continue if not ep_sep or not ep_format: continue # start with the ep string, eg. E03 ep_string = self._format_string(ep_format.upper(), replace_map) for other_ep in self.relatedEps: # for limited extend we only append the last ep if multi in (NAMING_LIMITED_EXTEND, NAMING_LIMITED_EXTEND_E_PREFIXED) and other_ep != self.relatedEps[-1]: continue elif multi == NAMING_DUPLICATE: # add " - S01" ep_string += sep + season_format elif multi == NAMING_SEPARATED_REPEAT: ep_string += sep # add "E04" ep_string += ep_sep if multi == NAMING_LIMITED_EXTEND_E_PREFIXED: ep_string += 'E' ep_string += other_ep._format_string(ep_format.upper(), other_ep._replace_map()) # pylint: disable=protected-access if anime_type != 3: if self.absolute_number == 0: curAbsolute_number = self.episode else: curAbsolute_number = self.absolute_number if self.season != 0: # dont set absolute numbers if we are on specials ! if anime_type == 1: # this crazy person wants both ! (note: +=) ep_string += sep + "{#:03d}".format(**{ "#": curAbsolute_number}) elif anime_type == 2: # total anime freak only need the absolute number ! (note: =) ep_string = "{#:03d}".format(**{"#": curAbsolute_number}) for relEp in self.relatedEps: if relEp.absolute_number != 0: ep_string += '-' + "{#:03d}".format(**{"#": relEp.absolute_number}) else: ep_string += '-' + "{#:03d}".format(**{"#": relEp.episode}) regex_replacement = None if anime_type == 2: regex_replacement = r'\g<pre_sep>' + ep_string + r'\g<post_sep>' elif season_ep_match: regex_replacement = r'\g<pre_sep>\g<2>\g<3>' + ep_string + r'\g<post_sep>' elif ep_only_match: regex_replacement = ep_string if regex_replacement: # fill out the template for this piece and then insert this piece into the actual pattern cur_name_group_result = re.sub('(?i)(?x)' + regex_used, regex_replacement, cur_name_group) # cur_name_group_result = cur_name_group.replace(ep_format, ep_string) result_name = result_name.replace(cur_name_group, cur_name_group_result) result_name = self._format_string(result_name, replace_map) logger.log("formatting pattern: " + pattern + " -> " + result_name, logger.DEBUG) return result_name def proper_path(self): """ Figures out the path where this episode SHOULD live according to the renaming rules, relative from the show dir """ anime_type = sickbeard.NAMING_ANIME if not self.show.is_anime: anime_type = 3 result = self.formatted_filename(anime_type=anime_type) # if they want us to flatten it and we're allowed to flatten it then we will if self.show.flatten_folders and not sickbeard.NAMING_FORCE_FOLDERS: return result # if not we append the folder on and use that else: result = ek(os.path.join, self.formatted_dir(), result) return result def formatted_dir(self, pattern=None, multi=None): """ Just the folder name of the episode """ if pattern is None: # we only use ABD if it's enabled, this is an ABD show, AND this is not a multi-ep if self.show.air_by_date and sickbeard.NAMING_CUSTOM_ABD and not self.relatedEps: pattern = sickbeard.NAMING_ABD_PATTERN elif self.show.sports and sickbeard.NAMING_CUSTOM_SPORTS and not self.relatedEps: pattern = sickbeard.NAMING_SPORTS_PATTERN elif self.show.anime and sickbeard.NAMING_CUSTOM_ANIME: pattern = sickbeard.NAMING_ANIME_PATTERN else: pattern = sickbeard.NAMING_PATTERN # split off the dirs only, if they exist name_groups = re.split(r'[\\/]', pattern) if len(name_groups) == 1: return '' else: return self._format_pattern(os.sep.join(name_groups[:-1]), multi) def formatted_filename(self, pattern=None, multi=None, anime_type=None): """ Just the filename of the episode, formatted based on the naming settings """ if pattern is None: # we only use ABD if it's enabled, this is an ABD show, AND this is not a multi-ep if self.show.air_by_date and sickbeard.NAMING_CUSTOM_ABD and not self.relatedEps: pattern = sickbeard.NAMING_ABD_PATTERN elif self.show.sports and sickbeard.NAMING_CUSTOM_SPORTS and not self.relatedEps: pattern = sickbeard.NAMING_SPORTS_PATTERN elif self.show.anime and sickbeard.NAMING_CUSTOM_ANIME: pattern = sickbeard.NAMING_ANIME_PATTERN else: pattern = sickbeard.NAMING_PATTERN # split off the dirs only, if they exist name_groups = re.split(r'[\\/]', pattern) return sanitize_filename(self._format_pattern(name_groups[-1], multi, anime_type)) def rename(self): # pylint: disable=too-many-locals, too-many-branches """ Renames an episode file and all related files to the location and filename as specified in the naming settings. """ if not ek(os.path.isfile, self.location): logger.log("Can't perform rename on " + self.location + " when it doesn't exist, skipping", logger.WARNING) return proper_path = self.proper_path() absolute_proper_path = ek(os.path.join, self.show.location, proper_path) absolute_current_path_no_ext, file_ext = ek(os.path.splitext, self.location) absolute_current_path_no_ext_length = len(absolute_current_path_no_ext) related_subs = [] current_path = absolute_current_path_no_ext if absolute_current_path_no_ext.startswith(self.show.location): current_path = absolute_current_path_no_ext[len(self.show.location):] logger.log("Renaming/moving episode from the base path " + self.location + " to " + absolute_proper_path, logger.DEBUG) # if it's already named correctly then don't do anything if proper_path == current_path: logger.log(str(self.indexerid) + ": File " + self.location + " is already named correctly, skipping", logger.DEBUG) return related_files = postProcessor.PostProcessor(self.location).list_associated_files( self.location, subfolders=True) # This is wrong. Cause of pp not moving subs. if self.show.subtitles and sickbeard.SUBTITLES_DIR != '': related_subs = postProcessor.PostProcessor(self.location).list_associated_files( sickbeard.SUBTITLES_DIR, subtitles_only=True, subfolders=True) absolute_proper_subs_path = ek(os.path.join, sickbeard.SUBTITLES_DIR, self.formatted_filename()) logger.log("Files associated to " + self.location + ": " + str(related_files), logger.DEBUG) # move the ep file result = helpers.rename_ep_file(self.location, absolute_proper_path, absolute_current_path_no_ext_length) # move related files for cur_related_file in related_files: # We need to fix something here because related files can be in subfolders and the original code doesn't handle this (at all) cur_related_dir = ek(os.path.dirname, ek(os.path.abspath, cur_related_file)) subfolder = cur_related_dir.replace(ek(os.path.dirname, ek(os.path.abspath, self.location)), '') # We now have a subfolder. We need to add that to the absolute_proper_path. # First get the absolute proper-path dir proper_related_dir = ek(os.path.dirname, ek(os.path.abspath, absolute_proper_path + file_ext)) proper_related_path = absolute_proper_path.replace(proper_related_dir, proper_related_dir + subfolder) cur_result = helpers.rename_ep_file(cur_related_file, proper_related_path, absolute_current_path_no_ext_length + len(subfolder)) if not cur_result: logger.log(str(self.indexerid) + ": Unable to rename file " + cur_related_file, logger.ERROR) for cur_related_sub in related_subs: absolute_proper_subs_path = ek(os.path.join, sickbeard.SUBTITLES_DIR, self.formatted_filename()) cur_result = helpers.rename_ep_file(cur_related_sub, absolute_proper_subs_path, absolute_current_path_no_ext_length) if not cur_result: logger.log(str(self.indexerid) + ": Unable to rename file " + cur_related_sub, logger.ERROR) # save the ep with self.lock: if result: self.location = absolute_proper_path + file_ext for relEp in self.relatedEps: relEp.location = absolute_proper_path + file_ext # in case something changed with the metadata just do a quick check for curEp in [self] + self.relatedEps: curEp.checkForMetaFiles() # save any changes to the databas sql_l = [] with self.lock: for relEp in [self] + self.relatedEps: sql_l.append(relEp.get_sql()) if sql_l: main_db_con = db.DBConnection() main_db_con.mass_action(sql_l) def airdateModifyStamp(self): """ Make the modify date and time of a file reflect the show air date and time. Note: Also called from postProcessor """ if not all([sickbeard.AIRDATE_EPISODES, self.airdate, self.location, self.show, self.show.airs, self.show.network]): return try: airdate_ordinal = self.airdate.toordinal() if airdate_ordinal < 1: return airdatetime = network_timezones.parse_date_time(airdate_ordinal, self.show.airs, self.show.network) if sickbeard.FILE_TIMESTAMP_TIMEZONE == 'local': airdatetime = airdatetime.astimezone(network_timezones.sb_timezone) filemtime = datetime.datetime.fromtimestamp(ek(os.path.getmtime, self.location)).replace(tzinfo=network_timezones.sb_timezone) if filemtime != airdatetime: import time airdatetime = airdatetime.timetuple() logger.log("{0}: About to modify date of '{1}' to show air date {2}".format (self.show.indexerid, self.location, time.strftime("%b %d,%Y (%H:%M)", airdatetime)), logger.DEBUG) try: if helpers.touchFile(self.location, time.mktime(airdatetime)): logger.log("{0}: Changed modify date of '{1}' to show air date {2}".format (self.show.indexerid, ek(os.path.basename, self.location), time.strftime("%b %d,%Y (%H:%M)", airdatetime))) else: logger.log("{0}: Unable to modify date of '{1}' to show air date {2}".format (self.show.indexerid, ek(os.path.basename, self.location), time.strftime("%b %d,%Y (%H:%M)", airdatetime)), logger.WARNING) except Exception: logger.log("{0}: Failed to modify date of '{1}' to show air date {2}".format (self.show.indexerid, ek(os.path.basename, self.location), time.strftime("%b %d,%Y (%H:%M)", airdatetime)), logger.WARNING) except Exception: logger.log("{0}: Failed to modify date of '{1}'".format (self.show.indexerid, ek(os.path.basename, self.location)), logger.WARNING) def __getstate__(self): d = dict(self.__dict__) del d[b'lock'] return d def __setstate__(self, d): d[b'lock'] = threading.Lock() self.__dict__.update(d)
gpl-3.0
makinacorpus/odoo
addons/mrp/product.py
180
4590
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv class product_template(osv.osv): _inherit = "product.template" def _bom_orders_count(self, cr, uid, ids, field_name, arg, context=None): Bom = self.pool('mrp.bom') res = {} for product_tmpl_id in ids: nb = Bom.search_count(cr, uid, [('product_tmpl_id', '=', product_tmpl_id)], context=context) res[product_tmpl_id] = { 'bom_count': nb, } return res def _bom_orders_count_mo(self, cr, uid, ids, name, arg, context=None): res = {} for product_tmpl_id in self.browse(cr, uid, ids): res[product_tmpl_id.id] = sum([p.mo_count for p in product_tmpl_id.product_variant_ids]) return res _columns = { 'bom_ids': fields.one2many('mrp.bom', 'product_tmpl_id','Bill of Materials'), 'bom_count': fields.function(_bom_orders_count, string='# Bill of Material', type='integer', multi="_bom_order_count"), 'mo_count': fields.function(_bom_orders_count_mo, string='# Manufacturing Orders', type='integer'), 'produce_delay': fields.float('Manufacturing Lead Time', help="Average delay in days to produce this product. In the case of multi-level BOM, the manufacturing lead times of the components will be added."), 'track_production': fields.boolean('Track Manufacturing Lots', help="Forces to specify a Serial Number for all moves containing this product and generated by a Manufacturing Order"), } _defaults = { 'produce_delay': 1, } def action_view_mos(self, cr, uid, ids, context=None): products = self._get_products(cr, uid, ids, context=context) result = self._get_act_window_dict(cr, uid, 'mrp.act_product_mrp_production', context=context) if len(ids) == 1 and len(products) == 1: result['context'] = "{'default_product_id': " + str(products[0]) + ", 'search_default_product_id': " + str(products[0]) + "}" else: result['domain'] = "[('product_id','in',[" + ','.join(map(str, products)) + "])]" result['context'] = "{}" return result class product_product(osv.osv): _inherit = "product.product" def _bom_orders_count(self, cr, uid, ids, field_name, arg, context=None): Production = self.pool('mrp.production') res = {} for product_id in ids: res[product_id] = Production.search_count(cr,uid, [('product_id', '=', product_id)], context=context) return res _columns = { 'mo_count': fields.function(_bom_orders_count, string='# Manufacturing Orders', type='integer'), } def action_view_bom(self, cr, uid, ids, context=None): tmpl_obj = self.pool.get("product.template") products = set() for product in self.browse(cr, uid, ids, context=context): products.add(product.product_tmpl_id.id) result = tmpl_obj._get_act_window_dict(cr, uid, 'mrp.product_open_bom', context=context) # bom specific to this variant or global to template domain = [ '|', ('product_id', 'in', ids), '&', ('product_id', '=', False), ('product_tmpl_id', 'in', list(products)), ] result['context'] = "{'default_product_id': active_id, 'search_default_product_id': active_id, 'default_product_tmpl_id': %s}" % (len(products) and products.pop() or 'False') result['domain'] = str(domain) return result # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
pabloborrego93/edx-platform
pavelib/paver_tests/test_servers.py
15
11645
"""Unit tests for the Paver server tasks.""" import ddt from paver.easy import call_task from .utils import PaverTestCase EXPECTED_COFFEE_COMMAND = ( u"node_modules/.bin/coffee --compile `find {platform_root}/lms " u"{platform_root}/cms {platform_root}/common -type f -name \"*.coffee\"`" ) EXPECTED_SASS_COMMAND = ( u"libsass {sass_directory}" ) EXPECTED_COMMON_SASS_DIRECTORIES = [ u"common/static/sass", ] EXPECTED_LMS_SASS_DIRECTORIES = [ u"lms/static/sass", u"lms/static/certificates/sass", ] EXPECTED_CMS_SASS_DIRECTORIES = [ u"cms/static/sass", ] EXPECTED_LMS_SASS_COMMAND = [ u"python manage.py lms --settings={asset_settings} compile_sass lms ", ] EXPECTED_CMS_SASS_COMMAND = [ u"python manage.py cms --settings={asset_settings} compile_sass cms ", ] EXPECTED_COLLECT_STATIC_COMMAND = ( u"python manage.py {system} --settings={asset_settings} collectstatic --noinput {log_string}" ) EXPECTED_CELERY_COMMAND = ( u"python manage.py lms --settings={settings} celery worker --beat --loglevel=INFO --pythonpath=." ) EXPECTED_RUN_SERVER_COMMAND = ( u"python manage.py {system} --settings={settings} runserver --traceback --pythonpath=. 0.0.0.0:{port}" ) EXPECTED_INDEX_COURSE_COMMAND = ( u"python manage.py {system} --settings={settings} reindex_course --setup" ) @ddt.ddt class TestPaverServerTasks(PaverTestCase): """ Test the Paver server tasks. """ @ddt.data( [{}], [{"settings": "aws"}], [{"asset-settings": "test_static_optimized"}], [{"settings": "devstack_optimized", "asset-settings": "test_static_optimized"}], [{"fast": True}], [{"port": 8030}], ) @ddt.unpack def test_lms(self, options): """ Test the "devstack" task. """ self.verify_server_task("lms", options) @ddt.data( [{}], [{"settings": "aws"}], [{"asset-settings": "test_static_optimized"}], [{"settings": "devstack_optimized", "asset-settings": "test_static_optimized"}], [{"fast": True}], [{"port": 8031}], ) @ddt.unpack def test_studio(self, options): """ Test the "devstack" task. """ self.verify_server_task("studio", options) @ddt.data( [{}], [{"settings": "aws"}], [{"asset-settings": "test_static_optimized"}], [{"settings": "devstack_optimized", "asset-settings": "test_static_optimized"}], [{"fast": True}], [{"optimized": True}], [{"optimized": True, "fast": True}], [{"no-contracts": True}], ) @ddt.unpack def test_devstack(self, server_options): """ Test the "devstack" task. """ options = server_options.copy() is_optimized = options.get("optimized", False) expected_settings = "devstack_optimized" if is_optimized else options.get("settings", "devstack") # First test with LMS options["system"] = "lms" options["expected_messages"] = [ EXPECTED_INDEX_COURSE_COMMAND.format( system="cms", settings=expected_settings, ) ] self.verify_server_task("devstack", options, contracts_default=True) # Then test with Studio options["system"] = "cms" options["expected_messages"] = [ EXPECTED_INDEX_COURSE_COMMAND.format( system="cms", settings=expected_settings, ) ] self.verify_server_task("devstack", options, contracts_default=True) @ddt.data( [{}], [{"settings": "aws"}], [{"asset_settings": "test_static_optimized"}], [{"settings": "devstack_optimized", "asset-settings": "test_static_optimized"}], [{"fast": True}], [{"optimized": True}], [{"optimized": True, "fast": True}], ) @ddt.unpack def test_run_all_servers(self, options): """ Test the "run_all_servers" task. """ self.verify_run_all_servers_task(options) @ddt.data( [{}], [{"settings": "aws"}], ) @ddt.unpack def test_celery(self, options): """ Test the "celery" task. """ settings = options.get("settings", "dev_with_worker") call_task("pavelib.servers.celery", options=options) self.assertEquals(self.task_messages, [EXPECTED_CELERY_COMMAND.format(settings=settings)]) @ddt.data( [{}], [{"settings": "aws"}], ) @ddt.unpack def test_update_db(self, options): """ Test the "update_db" task. """ settings = options.get("settings", "devstack") call_task("pavelib.servers.update_db", options=options) # pylint: disable=line-too-long db_command = "NO_EDXAPP_SUDO=1 EDX_PLATFORM_SETTINGS_OVERRIDE={settings} /edx/bin/edxapp-migrate-{server} --traceback --pythonpath=. " self.assertEquals( self.task_messages, [ db_command.format(server="lms", settings=settings), db_command.format(server="cms", settings=settings), ] ) @ddt.data( ["lms", {}], ["lms", {"settings": "aws"}], ["cms", {}], ["cms", {"settings": "aws"}], ) @ddt.unpack def test_check_settings(self, system, options): """ Test the "check_settings" task. """ settings = options.get("settings", "devstack") call_task("pavelib.servers.check_settings", args=[system, settings]) self.assertEquals( self.task_messages, [ "echo 'import {system}.envs.{settings}' " "| python manage.py {system} --settings={settings} shell --plain --pythonpath=.".format( system=system, settings=settings ), ] ) def verify_server_task(self, task_name, options, contracts_default=False): """ Verify the output of a server task. """ log_string = options.get("log_string", "> /dev/null") settings = options.get("settings", None) asset_settings = options.get("asset-settings", None) is_optimized = options.get("optimized", False) is_fast = options.get("fast", False) no_contracts = options.get("no-contracts", not contracts_default) if task_name == "devstack": system = options.get("system") elif task_name == "studio": system = "cms" else: system = "lms" port = options.get("port", "8000" if system == "lms" else "8001") self.reset_task_messages() if task_name == "devstack": args = ["studio" if system == "cms" else system] if settings: args.append("--settings={settings}".format(settings=settings)) if asset_settings: args.append("--asset-settings={asset_settings}".format(asset_settings=asset_settings)) if is_optimized: args.append("--optimized") if is_fast: args.append("--fast") if no_contracts: args.append("--no-contracts") call_task("pavelib.servers.devstack", args=args) else: call_task("pavelib.servers.{task_name}".format(task_name=task_name), options=options) expected_messages = options.get("expected_messages", []) expected_settings = settings if settings else "devstack" expected_asset_settings = asset_settings if asset_settings else expected_settings if is_optimized: expected_settings = "devstack_optimized" expected_asset_settings = "test_static_optimized" expected_collect_static = not is_fast and expected_settings != "devstack" if not is_fast: expected_messages.append(u"xmodule_assets common/static/xmodule") expected_messages.append(u"install npm_assets") expected_messages.append(EXPECTED_COFFEE_COMMAND.format(platform_root=self.platform_root)) expected_messages.extend(self.expected_sass_commands(system=system, asset_settings=expected_asset_settings)) if expected_collect_static: expected_messages.append(EXPECTED_COLLECT_STATIC_COMMAND.format( system=system, asset_settings=expected_asset_settings, log_string=log_string )) expected_run_server_command = EXPECTED_RUN_SERVER_COMMAND.format( system=system, settings=expected_settings, port=port, ) if not no_contracts: expected_run_server_command += " --contracts" expected_messages.append(expected_run_server_command) self.assertEquals(self.task_messages, expected_messages) def verify_run_all_servers_task(self, options): """ Verify the output of a server task. """ log_string = options.get("log_string", "> /dev/null") settings = options.get("settings", None) asset_settings = options.get("asset_settings", None) is_optimized = options.get("optimized", False) is_fast = options.get("fast", False) self.reset_task_messages() call_task("pavelib.servers.run_all_servers", options=options) expected_settings = settings if settings else "devstack" expected_asset_settings = asset_settings if asset_settings else expected_settings if is_optimized: expected_settings = "devstack_optimized" expected_asset_settings = "test_static_optimized" expected_collect_static = not is_fast and expected_settings != "devstack" expected_messages = [] if not is_fast: expected_messages.append(u"xmodule_assets common/static/xmodule") expected_messages.append(u"install npm_assets") expected_messages.append(EXPECTED_COFFEE_COMMAND.format(platform_root=self.platform_root)) expected_messages.extend(self.expected_sass_commands(asset_settings=expected_asset_settings)) if expected_collect_static: expected_messages.append(EXPECTED_COLLECT_STATIC_COMMAND.format( system="lms", asset_settings=expected_asset_settings, log_string=log_string )) expected_messages.append(EXPECTED_COLLECT_STATIC_COMMAND.format( system="cms", asset_settings=expected_asset_settings, log_string=log_string )) expected_messages.append( EXPECTED_RUN_SERVER_COMMAND.format( system="lms", settings=expected_settings, port=8000, ) ) expected_messages.append( EXPECTED_RUN_SERVER_COMMAND.format( system="cms", settings=expected_settings, port=8001, ) ) expected_messages.append(EXPECTED_CELERY_COMMAND.format(settings="dev_with_worker")) self.assertEquals(self.task_messages, expected_messages) def expected_sass_commands(self, system=None, asset_settings=u"test_static_optimized"): """ Returns the expected SASS commands for the specified system. """ expected_sass_commands = [] if system != 'cms': expected_sass_commands.extend(EXPECTED_LMS_SASS_COMMAND) if system != 'lms': expected_sass_commands.extend(EXPECTED_CMS_SASS_COMMAND) return [command.format(asset_settings=asset_settings) for command in expected_sass_commands]
agpl-3.0
giver/m101p
week3/hw3-2and3-3/validate.py
20
13708
import base64 code="CmltcG9ydCBweW1vbmdvCmltcG9ydCB1cmxsaWIyCmltcG9ydCB1cmxsaWIKaW1wb3J0IGNvb2tpZWxpYgppbXBvcnQgcmFuZG9tCmltcG9ydCByZQppbXBvcnQgc3RyaW5nCmltcG9ydCBzeXMKaW1wb3J0IGdldG9wdAoKIyB0aGlzIGlzIGEgdmFsaWRhdGlvbiBwcm9ncmFtIHRvIG1ha2Ugc3VyZSB0aGF0IHRoZSBibG9nIHdvcmtzIGNvcnJlY3RseS4KIyBJZiB5b3UgYXJlIHJlYWRpbmcgdGhpcyBpbiBjbGVhciB0ZXh0LCB5b3UgYXJlIHByb2JhYmx5IHZpb2xhdGluZyB0aGUgaG9ub3IgY29kZQoKIyBpbml0IHRoZSBnbG9iYWwgY29va2llIGphcgpjaiA9IGNvb2tpZWxpYi5Db29raWVKYXIoKQojIGRlY2xhcmUgdGhlIHZhcmlhYmxlcyB0byBjb25uZWN0IHRvIGRiCmNvbm5lY3Rpb24gPSBOb25lCmRiID0gTm9uZQp3ZWJob3N0ID0gImxvY2FsaG9zdDo4MDgyIgptb25nb3N0ciA9ICJtb25nb2RiOi8vbG9jYWxob3N0OjI3MDE3IgpkYl9uYW1lID0gImJsb2ciCgojIHRoaXMgc2NyaXB0IHdpbGwgY2hlY2sgdGhhdCBob21ld29yayAzLjIgaXMgY29ycmVjdAoKIyBtYWtlcyBhIGxpdHRsZSBzYWx0CmRlZiBtYWtlX3NhbHQobik6CiAgICBzYWx0ID0gIiIKICAgIGZvciBpIGluIHJhbmdlKG4pOgogICAgICAgIHNhbHQgPSBzYWx0ICsgcmFuZG9tLmNob2ljZShzdHJpbmcuYXNjaWlfbGV0dGVycykKICAgIHJldHVybiBzYWx0CgoKIyB0aGlzIGlzIGEgdmFsaWRhdGlvbiBwcm9ncmFtIHRvIG1ha2Ugc3VyZSB0aGF0IHRoZSBibG9nIHdvcmtzIGNvcnJlY3RseS4KCmRlZiBjcmVhdGVfdXNlcih1c2VybmFtZSwgcGFzc3dvcmQpOgogICAgCiAgICBnbG9iYWwgY2oKCiAgICB0cnk6CiAgICAgICAgcHJpbnQgIlRyeWluZyB0byBjcmVhdGUgYSB0ZXN0IHVzZXIgIiwgdXNlcm5hbWUKICAgICAgICB1cmwgPSAiaHR0cDovL3swfS9zaWdudXAiLmZvcm1hdCh3ZWJob3N0KQoKICAgICAgICBkYXRhID0gdXJsbGliLnVybGVuY29kZShbKCJlbWFpbCIsIiIpLCgidXNlcm5hbWUiLHVzZXJuYW1lKSwgKCJwYXNzd29yZCIscGFzc3dvcmQpLCAoInZlcmlmeSIscGFzc3dvcmQpXSkKICAgICAgICByZXF1ZXN0ID0gdXJsbGliMi5SZXF1ZXN0KHVybD11cmwsIGRhdGE9ZGF0YSkKICAgICAgICBvcGVuZXIgPSB1cmxsaWIyLmJ1aWxkX29wZW5lcih1cmxsaWIyLkhUVFBDb29raWVQcm9jZXNzb3IoY2opKQogICAgICAgIGYgPSBvcGVuZXIub3BlbihyZXF1ZXN0KQoKICAgICAgICB1c2VycyA9IGRiLnVzZXJzCiAgICAgICAgIyBjaGVjayB0aGF0IHRoZSB1c2VyIGlzIGluIHVzZXJzIGNvbGxlY3Rpb24KICAgICAgICB1c2VyID0gdXNlcnMuZmluZF9vbmUoeydfaWQnOnVzZXJuYW1lfSkKICAgICAgICBpZiAodXNlciA9PSBOb25lKToKICAgICAgICAgICAgcHJpbnQgIkNvdWxkIG5vdCBmaW5kIHRoZSB0ZXN0IHVzZXIgIiwgdXNlcm5hbWUsICJpbiB0aGUgdXNlcnMgY29sbGVjdGlvbi4iCiAgICAgICAgICAgIHJldHVybiBGYWxzZQogICAgICAgIHByaW50ICJGb3VuZCB0aGUgdGVzdCB1c2VyICIsIHVzZXJuYW1lLCAiIGluIHRoZSB1c2VycyBjb2xsZWN0aW9uIgoKICAgICAgICAjIGNoZWNrIHRoYXQgdGhlIHVzZXIgaGFzIGJlZW4gYnVpbHQKICAgICAgICByZXN1bHQgPSBmLnJlYWQoKQogICAgICAgIGV4cHIgPSByZS5jb21waWxlKCJXZWxjb21lXHMrIisgdXNlcm5hbWUpCiAgICAgICAgaWYgZXhwci5zZWFyY2gocmVzdWx0KToKICAgICAgICAgICAgcmV0dXJuIFRydWUKICAgICAgICAKICAgICAgICBwcmludCAiV2hlbiB3ZSB0cmllZCB0byBjcmVhdGUgYSB1c2VyLCBoZXJlIGlzIHRoZSBvdXRwdXQgd2UgZ290XG4iCiAgICAgICAgcHJpbnQgcmVzdWx0CiAgICAgICAgCiAgICAgICAgcmV0dXJuIEZhbHNlCiAgICBleGNlcHQ6CiAgICAgICAgcHJpbnQgInRoZSByZXF1ZXN0IHRvICIsIHVybCwgIiBmYWlsZWQsIHNvIHlvdXIgYmxvZyBtYXkgbm90IGJlIHJ1bm5pbmcuIgogICAgICAgIHJhaXNlCiAgICAgICAgcmV0dXJuIEZhbHNlCgoKZGVmIHRyeV90b19sb2dpbih1c2VybmFtZSwgcGFzc3dvcmQpOgoKICAgIHRyeToKICAgICAgICBwcmludCAiVHJ5aW5nIHRvIGxvZ2luIGZvciB0ZXN0IHVzZXIgIiwgdXNlcm5hbWUKICAgICAgICB1cmwgPSAiaHR0cDovL3swfS9sb2dpbiIuZm9ybWF0KHdlYmhvc3QpCgogICAgICAgIGRhdGEgPSB1cmxsaWIudXJsZW5jb2RlKFsoInVzZXJuYW1lIix1c2VybmFtZSksICgicGFzc3dvcmQiLHBhc3N3b3JkKV0pCiAgICAgICAgcmVxdWVzdCA9IHVybGxpYjIuUmVxdWVzdCh1cmw9dXJsLCBkYXRhPWRhdGEpCiAgICAgICAgb3BlbmVyID0gdXJsbGliMi5idWlsZF9vcGVuZXIodXJsbGliMi5IVFRQQ29va2llUHJvY2Vzc29yKGNqKSkKICAgICAgICBmID0gb3BlbmVyLm9wZW4ocmVxdWVzdCkKCiAgICAgICAgIyBjaGVjayBmb3Igc3VjY2Vzc2Z1bCBsb2dpbgogICAgICAgIHJlc3VsdCA9IGYucmVhZCgpCiAgICAgICAgZXhwciA9IHJlLmNvbXBpbGUoIldlbGNvbWVccysiKyB1c2VybmFtZSkKICAgICAgICBpZiBleHByLnNlYXJjaChyZXN1bHQpOgogICAgICAgICAgICByZXR1cm4gVHJ1ZQoKICAgICAgICBwcmludCAiV2hlbiB3ZSB0cmllZCB0byBsb2dpbiwgaGVyZSBpcyB0aGUgb3V0cHV0IHdlIGdvdFxuIgogICAgICAgIHByaW50IHJlc3VsdAogICAgICAgIHJldHVybiBGYWxzZQogICAgZXhjZXB0OgogICAgICAgIHByaW50ICJ0aGUgcmVxdWVzdCB0byAiLCB1cmwsICIgZmFpbGVkLCBzbyB5b3VyIGJsb2cgbWF5IG5vdCBiZSBydW5uaW5nLiIKICAgICAgICByZXR1cm4gRmFsc2UKCgpkZWYgYWRkX2Jsb2dfcG9zdCh0aXRsZSxwb3N0LHRhZ3MpOgoKICAgIHRyeToKICAgICAgICBwcmludCAiVHJ5aW5nIHRvIHN1Ym1pdCBhIHBvc3Qgd2l0aCB0aXRsZSAiLCB0aXRsZQogICAgICAgIGRhdGEgPSB1cmxsaWIudXJsZW5jb2RlKFsoImJvZHkiLHBvc3QpLCAoInN1YmplY3QiLHRpdGxlKSwgKCJ0YWdzIix0YWdzKV0pCiAgICAgICAgdXJsID0gImh0dHA6Ly97MH0vbmV3cG9zdCIuZm9ybWF0KHdlYmhvc3QpCiAgICAgICAgcmVxdWVzdCA9IHVybGxpYjIuUmVxdWVzdCh1cmw9dXJsLCBkYXRhPWRhdGEpCiAgICAgICAgY2ouYWRkX2Nvb2tpZV9oZWFkZXIocmVxdWVzdCkKICAgICAgICBvcGVuZXIgPSB1cmxsaWIyLmJ1aWxkX29wZW5lcigpCiAgICAgICAgZiA9IG9wZW5lci5vcGVuKHJlcXVlc3QpCgogICAgICAgICMgY2hlY2sgZm9yIHN1Y2Nlc3NmdWwgbG9naW4KICAgICAgICByZXN1bHQgPSBmLnJlYWQoKQogICAgICAgIGV4cHIgPSByZS5jb21waWxlKHRpdGxlICsgIi4rIiArIHBvc3QsIHJlLkRPVEFMTCkKCiAgICAgICAgaWYgZXhwci5zZWFyY2gocmVzdWx0KToKICAgICAgICAgICAgcmV0dXJuIFRydWUKCiAgICAgICAgcHJpbnQgIldoZW4gd2UgdHJpZWQgdG8gcG9zdCwgaGVyZSBpcyB0aGUgb3V0cHV0IHdlIGdvdFxuIgogICAgICAgIHByaW50IHJlc3VsdAogICAgICAgIHJldHVybiBGYWxzZQoKICAgIGV4Y2VwdDoKICAgICAgICBwcmludCAidGhlIHJlcXVlc3QgdG8gIiwgdXJsLCAiIGZhaWxlZCwgc28geW91ciBibG9nIG1heSBub3QgYmUgcnVubmluZy4iCiAgICAgICAgcmFpc2UKCiAgICAgICAgcmV0dXJuIEZhbHNlCgpkZWYgYWRkX2Jsb2dfY29tbWVudCh0aXRsZSxwb3N0KToKCiAgICB0cnk6CiAgICAgICAgcHJpbnQgIlRyeWluZyB0byBzdWJtaXQgYSBibG9nIGNvbW1lbnQgZm9yIHBvc3Qgd2l0aCB0aXRsZSIsIHRpdGxlCiAgICAgICAgdXJsID0gImh0dHA6Ly97MH0vbmV3Y29tbWVudCIuZm9ybWF0KHdlYmhvc3QpCiAgICAgICAgCiAgICAgICAgZG9jID0ge30KICAgICAgICBjaGVja19tb25nb19mb3JfcG9zdCh0aXRsZSwgcG9zdCwgZG9jKQoKICAgICAgICBwZXJtYWxpbmsgPSBkb2NbJ2RvYyddWydwZXJtYWxpbmsnXQoKICAgICAgICBjb21tZW50X25hbWUgPSBtYWtlX3NhbHQoMTIpCiAgICAgICAgY29tbWVudF9ib2R5ID0gbWFrZV9zYWx0KDEyKQoKICAgICAgICBkYXRhID0gdXJsbGliLnVybGVuY29kZShbKCJjb21tZW50TmFtZSIsY29tbWVudF9uYW1lKSwgKCJjb21tZW50Qm9keSIsY29tbWVudF9ib2R5KSwgKCJwZXJtYWxpbmsiLHBlcm1hbGluayldKQogICAgICAgIHJlcXVlc3QgPSB1cmxsaWIyLlJlcXVlc3QodXJsPXVybCwgZGF0YT1kYXRhKQogICAgICAgIGNqLmFkZF9jb29raWVfaGVhZGVyKHJlcXVlc3QpCiAgICAgICAgb3BlbmVyID0gdXJsbGliMi5idWlsZF9vcGVuZXIoKQogICAgICAgIGYgPSBvcGVuZXIub3BlbihyZXF1ZXN0KQoKICAgICAgICAjIGNoZWNrIGZvciBzdWNjZXNzZnVsIGFkZGl0aW9uIG9mIGNvbW1lbnQgb24gcGFnZQogICAgICAgIHJlc3VsdCA9IGYucmVhZCgpCiAgICAgICAgZXhwciA9IHJlLmNvbXBpbGUodGl0bGUgKyAiLisiICsgcG9zdCwgcmUuRE9UQUxMKQoKICAgICAgICBpZiBub3QgZXhwci5zZWFyY2gocmVzdWx0KToKICAgICAgICAgICAgcHJpbnQgIldoZW4gd2UgdHJpZWQgdG8gZmluZCB0aGUgY29tbWVudCB3ZSBwb3N0ZWQgYXQgdGhlICAiLCB1cmwsICIgaGVyZSBpcyB3aGF0IHdlIGdvdCIKICAgICAgICAgICAgcHJpbnQgcmVzdWx0CiAgICAgICAgICAgIHJldHVybiBGYWxzZQoKCiAgICAgICAgIyBjaGVjayBmb3Igc3VjY2Vzc2Z1bCBhZGRpdGlvbiBvZiBjb21tZW50Li5yZXRyaWV2ZSB0aGUgZG9jIGFnYWluCiAgICAgICAgaWYobm90IGNoZWNrX21vbmdvX2Zvcl9wb3N0KHRpdGxlLCBwb3N0LCBkb2MpKToKICAgICAgICAgICAgcHJpbnQgIkNvdWxkIG5vdCBmaW5kIGNvbW1lbnQgaW4gZGF0YWJhc2UiCiAgICAgICAgICAgIHJldHVybiBGYWxzZQogICAgICAgIAogICAgICAgIGZvdW5kID0gRmFsc2UKICAgICAgICBpZiAoJ2NvbW1lbnRzJyBpbiBkb2NbJ2RvYyddKToKICAgICAgICAgICAgZm9yIGNvbW1lbnQgaW4gZG9jWydkb2MnXVsnY29tbWVudHMnXToKICAgICAgICAgICAgICAgIGlmIChjb21tZW50Wydib2R5J10gPT0gY29tbWVudF9ib2R5IGFuZCBjb21tZW50WydhdXRob3InXSA9PSBjb21tZW50X25hbWUpOgogICAgICAgICAgICAgICAgICAgIGZvdW5kID0gVHJ1ZQoKICAgICAgICByZXR1cm4gZm91bmQKCiAgICBleGNlcHQ6CiAgICAgICAgcHJpbnQgInRoZSByZXF1ZXN0IHRvICIsIHVybCwgIiBmYWlsZWQsIHNvIHlvdXIgYmxvZyBtYXkgbm90IGJlIHJ1bm5pbmcuIgogICAgICAgIHJhaXNlCgogICAgICAgIHJldHVybiBGYWxzZQoKCiMgZ3JhYnMgdGhlIGJsb2cgaW5kZXggYW5kIGNoZWNrcyB0aGF0IHRoZSBwb3N0cyBhcHBlYXIgaW4gdGhlIHJpZ2h0IG9yZGVyCmRlZiBjaGVja19ibG9nX2luZGV4KHRpdGxlMSwgdGl0bGUyKToKCiAgICB0cnk6CiAgICAgICAgdXJsID0gImh0dHA6Ly97MH0vIi5mb3JtYXQod2ViaG9zdCkKICAgICAgICBwcmludCAiVHJ5aW5nIHRvIGdyYWIgdGhlIGJsb2cgaG9tZSBwYWdlIGF0IHVybCAiLCB1cmwKICAgICAgICByZXF1ZXN0ID0gdXJsbGliMi5SZXF1ZXN0KHVybD11cmwpCiAgICAgICAgY2ouYWRkX2Nvb2tpZV9oZWFkZXIocmVxdWVzdCkKICAgICAgICBvcGVuZXIgPSB1cmxsaWIyLmJ1aWxkX29wZW5lcigpCiAgICAgICAgZiA9IG9wZW5lci5vcGVuKHJlcXVlc3QpCgogICAgICAgICMgY2hlY2sgZm9yIHN1Y2Nlc3NmdWwgbG9naW4KICAgICAgICByZXN1bHQgPSBmLnJlYWQoKQogICAgICAgIGV4cHIgPSByZS5jb21waWxlKHRpdGxlMiArICIuKyIgKyB0aXRsZTIsIHJlLkRPVEFMTCkKCiAgICAgICAgaWYgZXhwci5zZWFyY2gocmVzdWx0KToKICAgICAgICAgICAgcmV0dXJuIFRydWUKCiAgICAgICAgcHJpbnQgIldoZW4gd2UgdHJpZWQgdG8gcmVhZCB0aGUgYmxvZyBpbmRleCBhdCAiLCB1cmwsICIgaGVyZSBpcyB3aGF0IHdlIGdvdCIKICAgICAgICBwcmludCByZXN1bHQKICAgICAgICByZXR1cm4gRmFsc2UKCiAgICBleGNlcHQ6CiAgICAgICAgcHJpbnQgInRoZSByZXF1ZXN0IHRvICIsIHVybCwgIiBmYWlsZWQsIHNvIHlvdXIgYmxvZyBtYXkgbm90IGJlIHJ1bm5pbmcuIgogICAgICAgIHJhaXNlCgogICAgICAgIHJldHVybiBGYWxzZQoKIyBjaGVjayB0aGF0IGEgcGFydGljdWxhciBibG9nIHBvc3QgaXMgaW4gdGhlIGNvbGxlY3Rpb24KZGVmIGNoZWNrX21vbmdvX2Zvcl9wb3N0KHRpdGxlLCBib2R5LCBkb2N1bWVudCk6CiAgICAKICAgIHBvc3RzID0gZGIucG9zdHMKICAgIHRyeToKICAgICAgICBwb3N0ID0gcG9zdHMuZmluZF9vbmUoeyd0aXRsZSc6dGl0bGUsICdib2R5Jzpib2R5fSkKICAgICAgICBpZiAocG9zdCBpcyBOb25lKToKICAgICAgICAgICAgcHJpbnQgIkNhbid0IGZpbmQgcG9zdCB3aXRoIHRpdGxlICIsIHRpdGxlLCAiIGluIGNvbGxlY3Rpb24iCiAgICAgICAgICAgIHJldHVybiBGYWxzZQogICAgICAgIGRvY3VtZW50Wydkb2MnXSA9IHBvc3QKICAgICAgICByZXR1cm4gVHJ1ZQogICAgZXhjZXB0OgogICAgICAgIHByaW50ICJjYW4nIHF1ZXJ5IE1vbmdvREIuLmlzIGl0IHJ1bm5pbmc/IgogICAgICAgIHJhaXNlCgogICAgICAgIHJldHVybiBGYWxzZQoKIyBjb21tYW5kIGxpbmUgYXJnIHBhcnNpbmcgdG8gbWFrZSBmb2xrcyBoYXBweSB3aG8gd2FudCB0byBydW4gYXQgbW9uZ29sYWJzIG9yIG1vbmdvaHEKIyB0aGlzIGZ1bmN0aW9ucyB1c2VzIGdsb2JhbCB2YXJzIHRvIGNvbW11bmljYXRlLiBmb3JnaXZlIG1lLgpkZWYgYXJnX3BhcnNpbmcoYXJndik6CgogICAgZ2xvYmFsIHdlYmhvc3QKICAgIGdsb2JhbCBtb25nb3N0cgogICAgZ2xvYmFsIGRiX25hbWUKCiAgICB0cnk6CiAgICAgICAgb3B0cywgYXJncyA9IGdldG9wdC5nZXRvcHQoYXJndiwgIi1wOi1tOi1kOiIpCiAgICBleGNlcHQgZ2V0b3B0LkdldG9wdEVycm9yOgogICAgICAgIHByaW50ICJ1c2FnZSB2YWxpZGF0ZS5weSAtcCB3ZWJob3N0IC1tIG1vbmdvQ29ubmVjdFN0cmluZyAtZCBkYXRhYmFzZU5hbWUiCiAgICAgICAgcHJpbnQgIlx0d2ViaG9zdCBkZWZhdWx0cyB0byB7MH0iLmZvcm1hdCh3ZWJob3N0KQogICAgICAgIHByaW50ICJcdG1vbmdvQ29ubmVjdGlvblN0cmluZyBkZWZhdWx0IHRvIHswfSIuZm9ybWF0KG1vbmdvc3RyKQogICAgICAgIHByaW50ICJcdGRhdGFiYXNlTmFtZSBkZWZhdWx0cyB0byB7MH0iLmZvcm1hdChkYl9uYW1lKQogICAgICAgIHN5cy5leGl0KDIpCiAgICBmb3Igb3B0LCBhcmcgaW4gb3B0czoKICAgICAgICBpZiAob3B0ID09ICctaCcpOgogICAgICAgICAgICBwcmludCAidXNhZ2UgdmFsaWRhdGUucHkgLXAgd2ViaG9zdCAtbSBtb25nb0Nvbm5lY3RTdHJpbmcgLWQgZGF0YWJhc2VOYW1lIgogICAgICAgICAgICBzeXMuZXhpdCgyKQogICAgICAgIGVsaWYgb3B0IGluICgiLXAiKToKICAgICAgICAgICAgd2ViaG9zdCA9IGFyZwogICAgICAgICAgICBwcmludCAiT3ZlcnJpZGluZyBIVFRQIGhvc3QgdG8gYmUgIiwgd2ViaG9zdAogICAgICAgIGVsaWYgb3B0IGluICgiLW0iKToKICAgICAgICAgICAgbW9uZ29zdHIgPSBhcmcKICAgICAgICAgICAgcHJpbnQgIk92ZXJyaWRpbmcgTW9uZ29EQiBjb25uZWN0aW9uIHN0cmluZyB0byBiZSAiLCBtb25nb3N0cgogICAgICAgIGVsaWYgb3B0IGluICgiLWQiKToKICAgICAgICAgICAgZGJfbmFtZSA9IGFyZwogICAgICAgICAgICBwcmludCAiT3ZlcnJpZGluZyBNb25nb0RCIGRhdGFiYXNlIHRvIGJlICIsIGRiX25hbWUKICAgICAgICAgICAgCgoKIyBtYWluIHNlY3Rpb24gb2YgdGhlIGNvZGUKZGVmIG1haW4oYXJndik6CiAgICAgICAgICAgIAogICAgYXJnX3BhcnNpbmcoYXJndikKICAgIGdsb2JhbCBjb25uZWN0aW9uCiAgICBnbG9iYWwgZGIKCiAgICBwcmludCAiV2VsY29tZSB0byB0aGUgSFcgMy4yIGFuZCBIVyAzLjMgdmFsaWRhdGlvbiB0ZXN0ZXIiCgogICAgIyBjb25uZWN0IHRvIHRoZSBkYiAobW9uZ29zdHIgd2FzIHNldCBpbiBhcmdfcGFyc2luZykKICAgIGNvbm5lY3Rpb24gPSBweW1vbmdvLk1vbmdvQ2xpZW50KG1vbmdvc3RyKQogICAgZGIgPSBjb25uZWN0aW9uW2RiX25hbWVdCiAgICAgICAgCiAgICB1c2VybmFtZSA9IG1ha2Vfc2FsdCg3KQogICAgcGFzc3dvcmQgPSBtYWtlX3NhbHQoOCkKCiAgICAgIyB0cnkgdG8gY3JlYXRlIHVzZXIKCiAgICBpZiAoY3JlYXRlX3VzZXIodXNlcm5hbWUsIHBhc3N3b3JkKSk6CiAgICAgICAgcHJpbnQgIlVzZXIgY3JlYXRpb24gc3VjY2Vzc2Z1bC4gIgogICAgICAgICAjIHRyeSB0byBsb2dpbgogICAgICAgIGlmICh0cnlfdG9fbG9naW4odXNlcm5hbWUsIHBhc3N3b3JkKSk6CiAgICAgICAgICAgIHByaW50ICJVc2VyIGxvZ2luIHN1Y2Nlc3NmdWwuIgogICAgICAgIGVsc2U6CiAgICAgICAgICAgIHByaW50ICJVc2VyIGxvZ2luIGZhaWxlZCIKICAgICAgICAgICAgcHJpbnQgIk9kZCwgdGhpcyB3ZWVrcydzIGNvZGUgc2hvdWxkIGRvIHRoYXQgYXMgZ2l2ZW4iCiAgICAgICAgICAgIHN5cy5leGl0KDEpCgogICAgZWxzZToKICAgICAgICBwcmludCAiU29ycnksIHlvdSBoYXZlIG5vdCBzb2x2ZWQgaXQgeWV0LiIKICAgICAgICBzeXMuZXhpdCgxKQoKCiAgICAjIHRyeSB0byBjcmVhdGUgYSBibG9nIHBvc3QKICAgIHBvc3QxID0gbWFrZV9zYWx0KDMwKQogICAgdGl0bGUxID0gbWFrZV9zYWx0KDMwKQogICAgdGFnczEgPSBtYWtlX3NhbHQoNSkgKyAiLCAiICsgbWFrZV9zYWx0KDUpICsgIiwgIiArIG1ha2Vfc2FsdCg1KQoKCiAgICBpZiAoYWRkX2Jsb2dfcG9zdCh0aXRsZTEsIHBvc3QxLHRhZ3MxKSk6CiAgICAgICAgcHJpbnQgIlN1Ym1pc3Npb24gb2Ygc2luZ2xlIHBvc3Qgc3VjY2Vzc2Z1bCIKICAgIGVsc2U6CiAgICAgICAgcHJpbnQgIlVuYWJsZSB0byBjcmVhdGUgYSBwb3N0IgogICAgICAgIHN5cy5leGl0KDEpCgoKICAgICMgdHJ5IHRvIGNyZWF0ZSBhIHNlY29uZCBibG9nIHBvc3QKICAgIHBvc3QyID0gbWFrZV9zYWx0KDMwKQogICAgdGl0bGUyID0gbWFrZV9zYWx0KDMwKQogICAgdGFnczIgPSBtYWtlX3NhbHQoNSkgKyAiLCAiICsgbWFrZV9zYWx0KDUpICsgIiwgIiArIG1ha2Vfc2FsdCg1KQoKICAgIGlmIChhZGRfYmxvZ19wb3N0KHRpdGxlMiwgcG9zdDIsdGFnczIpKToKICAgICAgICBwcmludCAiU3VibWlzc2lvbiBvZiBzZWNvbmQgcG9zdCBzdWNjZXNzZnVsIgogICAgZWxzZToKICAgICAgICBwcmludCAiVW5hYmxlIHRvIGNyZWF0ZSBzZWNvbmQgcG9zdCIKICAgICAgICBzeXMuZXhpdCgxKQoKICAgICMgbm93IGxldCdzIG1ha2Ugc3VyZSB0aGF0IGJvdGggcG9zdHMgYXBwZWFyIG9uIHRoZSBob21lIHBhZ2Ugb2YgdGhlIGJsb2csIGluIHRoZSBjb3JyZWN0IG9yZGVyCgogICAgaWYgKGNoZWNrX2Jsb2dfaW5kZXgodGl0bGUxLCB0aXRsZTIpKToKICAgICAgICBwcmludCAiQmxvY2sgaW5kZXggbG9va3MgZ29vZC4iCiAgICBlbHNlOgogICAgICAgIHByaW50ICJCbG9nIGluZGV4IGRvZXMgbm90IGhhdmUgdGhlIHBvc3RzIHByZXNlbnQsIG9yZGVyZWQgY29ycmVjdGx5IgogICAgICAgIHN5cy5leGl0KDEpCgoKICAgICMgY2hlY2sgZm9yIERCIGRhdGEgaW50ZWdyaXR5CiAgICBpZiAobm90IGNoZWNrX21vbmdvX2Zvcl9wb3N0KHRpdGxlMSwgcG9zdDEsIHt9KSk6CiAgICAgICAgcHJpbnQgIkNhbid0IGZpbmQgYmxvZyBwb3N0IGluIGJsb2cgZGIsIHBvc3RzIGNvbGxlY3Rpb24gd2l0aCB0aXRsZSAiLCB0aXRsZQogICAgICAgIHN5cy5leGl0KDEpCiAgICBlbHNlOgogICAgICAgIHByaW50ICJGb3VuZCBibG9nIHBvc3QgaW4gcG9zdHMgY29sbGVjdGlvbiIKCgogICAgcHJpbnQgIlRlc3RzIFBhc3NlZCBmb3IgSFcgMy4yLiBZb3VyIEhXIDMuMiB2YWxpZGF0aW9uIGNvZGUgaXMgODlqa2xmc2pybGsyMDlqZmtzMmoyZWsiCgogICAgIyBub3cgY2hlY2sgdGhhdCB5b3UgY2FuIHBvc3QgYSBjb21tZW50CiAgICBpZiAobm90IGFkZF9ibG9nX2NvbW1lbnQodGl0bGUxLHBvc3QxKSk6CiAgICAgICAgcHJpbnQgIkNhbid0IGFkZCBibG9nIGNvbW1lbnRzIChzbyBIVyAzLjMgbm90IHlldCBjb21wbGV0ZSkiCiAgICAgICAgc3lzLmV4aXQoMSkKICAgIGVsc2U6CiAgICAgICAgcHJpbnQgIlN1Y2Nlc3NmdWxseSBhZGRlZCBibG9nIGNvbW1lbnRzIgoKCiAgICBwcmludCAiVGVzdHMgUGFzc2VkIGZvciBIVyAzLjMuIFlvdXIgSFcgMy4zIHZhbGlkYXRpb24gY29kZSBpcyBqazEzMTB2bjJsa3YwajJrZjBqa2ZzIgogICAgCgoKCmlmIF9fbmFtZV9fID09ICJfX21haW5fXyI6CiAgICBtYWluKHN5cy5hcmd2WzE6XSkKCgoKCgoKCg==" eval(compile(base64.b64decode(code), "<string>", 'exec'))
unlicense
RPG-18/qtawss3
3rdparty/gtest-1.7.0/test/gtest_shuffle_test.py
3023
12549
#!/usr/bin/env python # # Copyright 2009 Google Inc. All Rights Reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Verifies that test shuffling works.""" __author__ = 'wan@google.com (Zhanyong Wan)' import os import gtest_test_utils # Command to run the gtest_shuffle_test_ program. COMMAND = gtest_test_utils.GetTestExecutablePath('gtest_shuffle_test_') # The environment variables for test sharding. TOTAL_SHARDS_ENV_VAR = 'GTEST_TOTAL_SHARDS' SHARD_INDEX_ENV_VAR = 'GTEST_SHARD_INDEX' TEST_FILTER = 'A*.A:A*.B:C*' ALL_TESTS = [] ACTIVE_TESTS = [] FILTERED_TESTS = [] SHARDED_TESTS = [] SHUFFLED_ALL_TESTS = [] SHUFFLED_ACTIVE_TESTS = [] SHUFFLED_FILTERED_TESTS = [] SHUFFLED_SHARDED_TESTS = [] def AlsoRunDisabledTestsFlag(): return '--gtest_also_run_disabled_tests' def FilterFlag(test_filter): return '--gtest_filter=%s' % (test_filter,) def RepeatFlag(n): return '--gtest_repeat=%s' % (n,) def ShuffleFlag(): return '--gtest_shuffle' def RandomSeedFlag(n): return '--gtest_random_seed=%s' % (n,) def RunAndReturnOutput(extra_env, args): """Runs the test program and returns its output.""" environ_copy = os.environ.copy() environ_copy.update(extra_env) return gtest_test_utils.Subprocess([COMMAND] + args, env=environ_copy).output def GetTestsForAllIterations(extra_env, args): """Runs the test program and returns a list of test lists. Args: extra_env: a map from environment variables to their values args: command line flags to pass to gtest_shuffle_test_ Returns: A list where the i-th element is the list of tests run in the i-th test iteration. """ test_iterations = [] for line in RunAndReturnOutput(extra_env, args).split('\n'): if line.startswith('----'): tests = [] test_iterations.append(tests) elif line.strip(): tests.append(line.strip()) # 'TestCaseName.TestName' return test_iterations def GetTestCases(tests): """Returns a list of test cases in the given full test names. Args: tests: a list of full test names Returns: A list of test cases from 'tests', in their original order. Consecutive duplicates are removed. """ test_cases = [] for test in tests: test_case = test.split('.')[0] if not test_case in test_cases: test_cases.append(test_case) return test_cases def CalculateTestLists(): """Calculates the list of tests run under different flags.""" if not ALL_TESTS: ALL_TESTS.extend( GetTestsForAllIterations({}, [AlsoRunDisabledTestsFlag()])[0]) if not ACTIVE_TESTS: ACTIVE_TESTS.extend(GetTestsForAllIterations({}, [])[0]) if not FILTERED_TESTS: FILTERED_TESTS.extend( GetTestsForAllIterations({}, [FilterFlag(TEST_FILTER)])[0]) if not SHARDED_TESTS: SHARDED_TESTS.extend( GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '1'}, [])[0]) if not SHUFFLED_ALL_TESTS: SHUFFLED_ALL_TESTS.extend(GetTestsForAllIterations( {}, [AlsoRunDisabledTestsFlag(), ShuffleFlag(), RandomSeedFlag(1)])[0]) if not SHUFFLED_ACTIVE_TESTS: SHUFFLED_ACTIVE_TESTS.extend(GetTestsForAllIterations( {}, [ShuffleFlag(), RandomSeedFlag(1)])[0]) if not SHUFFLED_FILTERED_TESTS: SHUFFLED_FILTERED_TESTS.extend(GetTestsForAllIterations( {}, [ShuffleFlag(), RandomSeedFlag(1), FilterFlag(TEST_FILTER)])[0]) if not SHUFFLED_SHARDED_TESTS: SHUFFLED_SHARDED_TESTS.extend( GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '1'}, [ShuffleFlag(), RandomSeedFlag(1)])[0]) class GTestShuffleUnitTest(gtest_test_utils.TestCase): """Tests test shuffling.""" def setUp(self): CalculateTestLists() def testShufflePreservesNumberOfTests(self): self.assertEqual(len(ALL_TESTS), len(SHUFFLED_ALL_TESTS)) self.assertEqual(len(ACTIVE_TESTS), len(SHUFFLED_ACTIVE_TESTS)) self.assertEqual(len(FILTERED_TESTS), len(SHUFFLED_FILTERED_TESTS)) self.assertEqual(len(SHARDED_TESTS), len(SHUFFLED_SHARDED_TESTS)) def testShuffleChangesTestOrder(self): self.assert_(SHUFFLED_ALL_TESTS != ALL_TESTS, SHUFFLED_ALL_TESTS) self.assert_(SHUFFLED_ACTIVE_TESTS != ACTIVE_TESTS, SHUFFLED_ACTIVE_TESTS) self.assert_(SHUFFLED_FILTERED_TESTS != FILTERED_TESTS, SHUFFLED_FILTERED_TESTS) self.assert_(SHUFFLED_SHARDED_TESTS != SHARDED_TESTS, SHUFFLED_SHARDED_TESTS) def testShuffleChangesTestCaseOrder(self): self.assert_(GetTestCases(SHUFFLED_ALL_TESTS) != GetTestCases(ALL_TESTS), GetTestCases(SHUFFLED_ALL_TESTS)) self.assert_( GetTestCases(SHUFFLED_ACTIVE_TESTS) != GetTestCases(ACTIVE_TESTS), GetTestCases(SHUFFLED_ACTIVE_TESTS)) self.assert_( GetTestCases(SHUFFLED_FILTERED_TESTS) != GetTestCases(FILTERED_TESTS), GetTestCases(SHUFFLED_FILTERED_TESTS)) self.assert_( GetTestCases(SHUFFLED_SHARDED_TESTS) != GetTestCases(SHARDED_TESTS), GetTestCases(SHUFFLED_SHARDED_TESTS)) def testShuffleDoesNotRepeatTest(self): for test in SHUFFLED_ALL_TESTS: self.assertEqual(1, SHUFFLED_ALL_TESTS.count(test), '%s appears more than once' % (test,)) for test in SHUFFLED_ACTIVE_TESTS: self.assertEqual(1, SHUFFLED_ACTIVE_TESTS.count(test), '%s appears more than once' % (test,)) for test in SHUFFLED_FILTERED_TESTS: self.assertEqual(1, SHUFFLED_FILTERED_TESTS.count(test), '%s appears more than once' % (test,)) for test in SHUFFLED_SHARDED_TESTS: self.assertEqual(1, SHUFFLED_SHARDED_TESTS.count(test), '%s appears more than once' % (test,)) def testShuffleDoesNotCreateNewTest(self): for test in SHUFFLED_ALL_TESTS: self.assert_(test in ALL_TESTS, '%s is an invalid test' % (test,)) for test in SHUFFLED_ACTIVE_TESTS: self.assert_(test in ACTIVE_TESTS, '%s is an invalid test' % (test,)) for test in SHUFFLED_FILTERED_TESTS: self.assert_(test in FILTERED_TESTS, '%s is an invalid test' % (test,)) for test in SHUFFLED_SHARDED_TESTS: self.assert_(test in SHARDED_TESTS, '%s is an invalid test' % (test,)) def testShuffleIncludesAllTests(self): for test in ALL_TESTS: self.assert_(test in SHUFFLED_ALL_TESTS, '%s is missing' % (test,)) for test in ACTIVE_TESTS: self.assert_(test in SHUFFLED_ACTIVE_TESTS, '%s is missing' % (test,)) for test in FILTERED_TESTS: self.assert_(test in SHUFFLED_FILTERED_TESTS, '%s is missing' % (test,)) for test in SHARDED_TESTS: self.assert_(test in SHUFFLED_SHARDED_TESTS, '%s is missing' % (test,)) def testShuffleLeavesDeathTestsAtFront(self): non_death_test_found = False for test in SHUFFLED_ACTIVE_TESTS: if 'DeathTest.' in test: self.assert_(not non_death_test_found, '%s appears after a non-death test' % (test,)) else: non_death_test_found = True def _VerifyTestCasesDoNotInterleave(self, tests): test_cases = [] for test in tests: [test_case, _] = test.split('.') if test_cases and test_cases[-1] != test_case: test_cases.append(test_case) self.assertEqual(1, test_cases.count(test_case), 'Test case %s is not grouped together in %s' % (test_case, tests)) def testShuffleDoesNotInterleaveTestCases(self): self._VerifyTestCasesDoNotInterleave(SHUFFLED_ALL_TESTS) self._VerifyTestCasesDoNotInterleave(SHUFFLED_ACTIVE_TESTS) self._VerifyTestCasesDoNotInterleave(SHUFFLED_FILTERED_TESTS) self._VerifyTestCasesDoNotInterleave(SHUFFLED_SHARDED_TESTS) def testShuffleRestoresOrderAfterEachIteration(self): # Get the test lists in all 3 iterations, using random seed 1, 2, # and 3 respectively. Google Test picks a different seed in each # iteration, and this test depends on the current implementation # picking successive numbers. This dependency is not ideal, but # makes the test much easier to write. [tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = ( GetTestsForAllIterations( {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)])) # Make sure running the tests with random seed 1 gets the same # order as in iteration 1 above. [tests_with_seed1] = GetTestsForAllIterations( {}, [ShuffleFlag(), RandomSeedFlag(1)]) self.assertEqual(tests_in_iteration1, tests_with_seed1) # Make sure running the tests with random seed 2 gets the same # order as in iteration 2 above. Success means that Google Test # correctly restores the test order before re-shuffling at the # beginning of iteration 2. [tests_with_seed2] = GetTestsForAllIterations( {}, [ShuffleFlag(), RandomSeedFlag(2)]) self.assertEqual(tests_in_iteration2, tests_with_seed2) # Make sure running the tests with random seed 3 gets the same # order as in iteration 3 above. Success means that Google Test # correctly restores the test order before re-shuffling at the # beginning of iteration 3. [tests_with_seed3] = GetTestsForAllIterations( {}, [ShuffleFlag(), RandomSeedFlag(3)]) self.assertEqual(tests_in_iteration3, tests_with_seed3) def testShuffleGeneratesNewOrderInEachIteration(self): [tests_in_iteration1, tests_in_iteration2, tests_in_iteration3] = ( GetTestsForAllIterations( {}, [ShuffleFlag(), RandomSeedFlag(1), RepeatFlag(3)])) self.assert_(tests_in_iteration1 != tests_in_iteration2, tests_in_iteration1) self.assert_(tests_in_iteration1 != tests_in_iteration3, tests_in_iteration1) self.assert_(tests_in_iteration2 != tests_in_iteration3, tests_in_iteration2) def testShuffleShardedTestsPreservesPartition(self): # If we run M tests on N shards, the same M tests should be run in # total, regardless of the random seeds used by the shards. [tests1] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '0'}, [ShuffleFlag(), RandomSeedFlag(1)]) [tests2] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '1'}, [ShuffleFlag(), RandomSeedFlag(20)]) [tests3] = GetTestsForAllIterations({TOTAL_SHARDS_ENV_VAR: '3', SHARD_INDEX_ENV_VAR: '2'}, [ShuffleFlag(), RandomSeedFlag(25)]) sorted_sharded_tests = tests1 + tests2 + tests3 sorted_sharded_tests.sort() sorted_active_tests = [] sorted_active_tests.extend(ACTIVE_TESTS) sorted_active_tests.sort() self.assertEqual(sorted_active_tests, sorted_sharded_tests) if __name__ == '__main__': gtest_test_utils.Main()
apache-2.0
guolivar/totus-niwa
service/thirdparty/featureserver/FeatureServer/DataSource/Flickr.py
1
4910
from FeatureServer.DataSource import DataSource from vectorformats.Feature import Feature from FeatureServer.Exceptions.NoGeometryException import NoGeometryException import md5 import urllib from lxml import etree from StringIO import StringIO class Flickr (DataSource): def __init__(self, name, api_key, api_secret, attributes = "*", srid_out = 4326, **args): DataSource.__init__(self, name, **args) self.api_key = api_key self.api_secret = api_secret self.srid_out = srid_out self.attributes = attributes self.api = FlickrAPI(self.api_key, self.api_secret) def select (self, action): features = [] if action.id is not None: data = self.api.request({'method':'flickr.photos.getInfo','photo_id':action.id}) doc = etree.parse(StringIO(data)).getroot() photo = doc.xpath('/rsp/photo')[0] try: features.append(self.convert_photo(photo)) except Exception as e: ''' ''' else: params = {'method' : 'flickr.photos.search','extras':'description,owner_name,geo,tags,license'} if action.bbox: params['bbox'] = "%f,%f,%f,%f" % tuple(action.bbox) if hasattr(self, 'user_id'): params['user_id'] = self.user_id if hasattr(self, 'tags'): params['tags'] = self.tags if hasattr(self, 'tag_mode'): params['tag_mode'] = self.tag_mode else: params['tag_mode'] = "any" data = self.api.request(params) doc = etree.parse(StringIO(data)).getroot() photos = [ photo for photo in doc.xpath('/rsp/photos')[0] ] for photo in photos: try: features.append(self.convert_photo(photo)) except Exception as e: continue return features def convert_photo (self, xml): node_names = self.get_node_names(xml) props = {'img_url' : self.get_url(xml)} owners = xml.xpath('./owner') if len(owners) > 0: props['owner'] = owners[0].attrib['nsid'] props['username'] = owners[0].attrib['username'] for i in node_names: if i == "tags": tags = [ tag.text for tag in xml.xpath('./%s' % str(i))[0] ] props[i] = ",".join(tags) else: nodes = xml.xpath('./%s' % str(i)) if len(nodes) > 0: if len(list(nodes[0])) == 0: if nodes[0].text is None: props[i] = "" else: props[i] = nodes[0].text try: coordinates = self.get_coordinates(xml) except: raise return Feature(id=xml.attrib["id"], geometry={'type':"Point", 'coordinates':coordinates}, geometry_attr="geometry", srs=self.srid_out, props=props) def get_node_names(self, xml): if self.attributes == "*": props = [ child.tag for child in xml ] props.remove("location") props.remove("owner") else: props = self.attributes.split(',') return props def get_coordinates(self, xml): location = xml.xpath('./location') if len(location) > 0: loc = location[0] return [float(loc.attrib['longitude']), float(loc.attrib['latitude'])] if "longitude" in xml.attrib and "latitude" in xml.attrib: return [float(xml.attrib['longitude']), float(xml.attrib['latitude'])] raise NoGeometryException("Twitter", self.name) def get_url(self, xml): return "http://farm%s.static.flickr.com/%s/%s_%s_b.jpg" % (xml.attrib['farm'], xml.attrib['server'], xml.attrib['id'], xml.attrib['secret']) class FlickrAPI: urls = { 'xml' : 'http://api.flickr.com/services/rest/' } def __init__(self, api_key, api_secret): self.api_key = api_key self.api_secret = api_secret def request(self, params = {}, format = "rest"): params['api_key'] = self.api_key params['format'] = format params['api_sig'] = self.signature(params) return urllib.urlopen(self.urls["xml"], urllib.urlencode(params)).read() def signature(self, params): items = [] keys = params.keys() keys.sort() for key in keys: items.append("%s%s" % (key,params[key])) sign_string = "%s%s" % (self.api_secret, "".join(items)) return md5.md5(sign_string).hexdigest()
gpl-3.0
cloudbase/nova
nova/policies/agents.py
5
1061
# Copyright 2016 Cloudbase Solutions Srl # 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. from oslo_policy import policy from nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-agents' POLICY_ROOT = 'os_compute_api:os-agents:%s' agents_policies = [ policy.RuleDefault( name=BASE_POLICY_NAME, check_str=base.RULE_ADMIN_API), policy.RuleDefault( name=POLICY_ROOT % 'discoverable', check_str=base.RULE_ANY), ] def list_rules(): return agents_policies
apache-2.0
DNSS4503/android_kernel_msm
tools/perf/scripts/python/netdev-times.py
11271
15048
# Display a process of packets and processed time. # It helps us to investigate networking or network device. # # options # tx: show only tx chart # rx: show only rx chart # dev=: show only thing related to specified device # debug: work with debug mode. It shows buffer status. import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * all_event_list = []; # insert all tracepoint event related with this script irq_dic = {}; # key is cpu and value is a list which stacks irqs # which raise NET_RX softirq net_rx_dic = {}; # key is cpu and value include time of NET_RX softirq-entry # and a list which stacks receive receive_hunk_list = []; # a list which include a sequence of receive events rx_skb_list = []; # received packet list for matching # skb_copy_datagram_iovec buffer_budget = 65536; # the budget of rx_skb_list, tx_queue_list and # tx_xmit_list of_count_rx_skb_list = 0; # overflow count tx_queue_list = []; # list of packets which pass through dev_queue_xmit of_count_tx_queue_list = 0; # overflow count tx_xmit_list = []; # list of packets which pass through dev_hard_start_xmit of_count_tx_xmit_list = 0; # overflow count tx_free_list = []; # list of packets which is freed # options show_tx = 0; show_rx = 0; dev = 0; # store a name of device specified by option "dev=" debug = 0; # indices of event_info tuple EINFO_IDX_NAME= 0 EINFO_IDX_CONTEXT=1 EINFO_IDX_CPU= 2 EINFO_IDX_TIME= 3 EINFO_IDX_PID= 4 EINFO_IDX_COMM= 5 # Calculate a time interval(msec) from src(nsec) to dst(nsec) def diff_msec(src, dst): return (dst - src) / 1000000.0 # Display a process of transmitting a packet def print_transmit(hunk): if dev != 0 and hunk['dev'].find(dev) < 0: return print "%7s %5d %6d.%06dsec %12.3fmsec %12.3fmsec" % \ (hunk['dev'], hunk['len'], nsecs_secs(hunk['queue_t']), nsecs_nsecs(hunk['queue_t'])/1000, diff_msec(hunk['queue_t'], hunk['xmit_t']), diff_msec(hunk['xmit_t'], hunk['free_t'])) # Format for displaying rx packet processing PF_IRQ_ENTRY= " irq_entry(+%.3fmsec irq=%d:%s)" PF_SOFT_ENTRY=" softirq_entry(+%.3fmsec)" PF_NAPI_POLL= " napi_poll_exit(+%.3fmsec %s)" PF_JOINT= " |" PF_WJOINT= " | |" PF_NET_RECV= " |---netif_receive_skb(+%.3fmsec skb=%x len=%d)" PF_NET_RX= " |---netif_rx(+%.3fmsec skb=%x)" PF_CPY_DGRAM= " | skb_copy_datagram_iovec(+%.3fmsec %d:%s)" PF_KFREE_SKB= " | kfree_skb(+%.3fmsec location=%x)" PF_CONS_SKB= " | consume_skb(+%.3fmsec)" # Display a process of received packets and interrputs associated with # a NET_RX softirq def print_receive(hunk): show_hunk = 0 irq_list = hunk['irq_list'] cpu = irq_list[0]['cpu'] base_t = irq_list[0]['irq_ent_t'] # check if this hunk should be showed if dev != 0: for i in range(len(irq_list)): if irq_list[i]['name'].find(dev) >= 0: show_hunk = 1 break else: show_hunk = 1 if show_hunk == 0: return print "%d.%06dsec cpu=%d" % \ (nsecs_secs(base_t), nsecs_nsecs(base_t)/1000, cpu) for i in range(len(irq_list)): print PF_IRQ_ENTRY % \ (diff_msec(base_t, irq_list[i]['irq_ent_t']), irq_list[i]['irq'], irq_list[i]['name']) print PF_JOINT irq_event_list = irq_list[i]['event_list'] for j in range(len(irq_event_list)): irq_event = irq_event_list[j] if irq_event['event'] == 'netif_rx': print PF_NET_RX % \ (diff_msec(base_t, irq_event['time']), irq_event['skbaddr']) print PF_JOINT print PF_SOFT_ENTRY % \ diff_msec(base_t, hunk['sirq_ent_t']) print PF_JOINT event_list = hunk['event_list'] for i in range(len(event_list)): event = event_list[i] if event['event_name'] == 'napi_poll': print PF_NAPI_POLL % \ (diff_msec(base_t, event['event_t']), event['dev']) if i == len(event_list) - 1: print "" else: print PF_JOINT else: print PF_NET_RECV % \ (diff_msec(base_t, event['event_t']), event['skbaddr'], event['len']) if 'comm' in event.keys(): print PF_WJOINT print PF_CPY_DGRAM % \ (diff_msec(base_t, event['comm_t']), event['pid'], event['comm']) elif 'handle' in event.keys(): print PF_WJOINT if event['handle'] == "kfree_skb": print PF_KFREE_SKB % \ (diff_msec(base_t, event['comm_t']), event['location']) elif event['handle'] == "consume_skb": print PF_CONS_SKB % \ diff_msec(base_t, event['comm_t']) print PF_JOINT def trace_begin(): global show_tx global show_rx global dev global debug for i in range(len(sys.argv)): if i == 0: continue arg = sys.argv[i] if arg == 'tx': show_tx = 1 elif arg =='rx': show_rx = 1 elif arg.find('dev=',0, 4) >= 0: dev = arg[4:] elif arg == 'debug': debug = 1 if show_tx == 0 and show_rx == 0: show_tx = 1 show_rx = 1 def trace_end(): # order all events in time all_event_list.sort(lambda a,b :cmp(a[EINFO_IDX_TIME], b[EINFO_IDX_TIME])) # process all events for i in range(len(all_event_list)): event_info = all_event_list[i] name = event_info[EINFO_IDX_NAME] if name == 'irq__softirq_exit': handle_irq_softirq_exit(event_info) elif name == 'irq__softirq_entry': handle_irq_softirq_entry(event_info) elif name == 'irq__softirq_raise': handle_irq_softirq_raise(event_info) elif name == 'irq__irq_handler_entry': handle_irq_handler_entry(event_info) elif name == 'irq__irq_handler_exit': handle_irq_handler_exit(event_info) elif name == 'napi__napi_poll': handle_napi_poll(event_info) elif name == 'net__netif_receive_skb': handle_netif_receive_skb(event_info) elif name == 'net__netif_rx': handle_netif_rx(event_info) elif name == 'skb__skb_copy_datagram_iovec': handle_skb_copy_datagram_iovec(event_info) elif name == 'net__net_dev_queue': handle_net_dev_queue(event_info) elif name == 'net__net_dev_xmit': handle_net_dev_xmit(event_info) elif name == 'skb__kfree_skb': handle_kfree_skb(event_info) elif name == 'skb__consume_skb': handle_consume_skb(event_info) # display receive hunks if show_rx: for i in range(len(receive_hunk_list)): print_receive(receive_hunk_list[i]) # display transmit hunks if show_tx: print " dev len Qdisc " \ " netdevice free" for i in range(len(tx_free_list)): print_transmit(tx_free_list[i]) if debug: print "debug buffer status" print "----------------------------" print "xmit Qdisc:remain:%d overflow:%d" % \ (len(tx_queue_list), of_count_tx_queue_list) print "xmit netdevice:remain:%d overflow:%d" % \ (len(tx_xmit_list), of_count_tx_xmit_list) print "receive:remain:%d overflow:%d" % \ (len(rx_skb_list), of_count_rx_skb_list) # called from perf, when it finds a correspoinding event def irq__softirq_entry(name, context, cpu, sec, nsec, pid, comm, vec): if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX": return event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec) all_event_list.append(event_info) def irq__softirq_exit(name, context, cpu, sec, nsec, pid, comm, vec): if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX": return event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec) all_event_list.append(event_info) def irq__softirq_raise(name, context, cpu, sec, nsec, pid, comm, vec): if symbol_str("irq__softirq_entry", "vec", vec) != "NET_RX": return event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, vec) all_event_list.append(event_info) def irq__irq_handler_entry(name, context, cpu, sec, nsec, pid, comm, irq, irq_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, irq, irq_name) all_event_list.append(event_info) def irq__irq_handler_exit(name, context, cpu, sec, nsec, pid, comm, irq, ret): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, irq, ret) all_event_list.append(event_info) def napi__napi_poll(name, context, cpu, sec, nsec, pid, comm, napi, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, napi, dev_name) all_event_list.append(event_info) def net__netif_receive_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr, skblen, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, dev_name) all_event_list.append(event_info) def net__netif_rx(name, context, cpu, sec, nsec, pid, comm, skbaddr, skblen, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, dev_name) all_event_list.append(event_info) def net__net_dev_queue(name, context, cpu, sec, nsec, pid, comm, skbaddr, skblen, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, dev_name) all_event_list.append(event_info) def net__net_dev_xmit(name, context, cpu, sec, nsec, pid, comm, skbaddr, skblen, rc, dev_name): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen, rc ,dev_name) all_event_list.append(event_info) def skb__kfree_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr, protocol, location): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, protocol, location) all_event_list.append(event_info) def skb__consume_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr) all_event_list.append(event_info) def skb__skb_copy_datagram_iovec(name, context, cpu, sec, nsec, pid, comm, skbaddr, skblen): event_info = (name, context, cpu, nsecs(sec, nsec), pid, comm, skbaddr, skblen) all_event_list.append(event_info) def handle_irq_handler_entry(event_info): (name, context, cpu, time, pid, comm, irq, irq_name) = event_info if cpu not in irq_dic.keys(): irq_dic[cpu] = [] irq_record = {'irq':irq, 'name':irq_name, 'cpu':cpu, 'irq_ent_t':time} irq_dic[cpu].append(irq_record) def handle_irq_handler_exit(event_info): (name, context, cpu, time, pid, comm, irq, ret) = event_info if cpu not in irq_dic.keys(): return irq_record = irq_dic[cpu].pop() if irq != irq_record['irq']: return irq_record.update({'irq_ext_t':time}) # if an irq doesn't include NET_RX softirq, drop. if 'event_list' in irq_record.keys(): irq_dic[cpu].append(irq_record) def handle_irq_softirq_raise(event_info): (name, context, cpu, time, pid, comm, vec) = event_info if cpu not in irq_dic.keys() \ or len(irq_dic[cpu]) == 0: return irq_record = irq_dic[cpu].pop() if 'event_list' in irq_record.keys(): irq_event_list = irq_record['event_list'] else: irq_event_list = [] irq_event_list.append({'time':time, 'event':'sirq_raise'}) irq_record.update({'event_list':irq_event_list}) irq_dic[cpu].append(irq_record) def handle_irq_softirq_entry(event_info): (name, context, cpu, time, pid, comm, vec) = event_info net_rx_dic[cpu] = {'sirq_ent_t':time, 'event_list':[]} def handle_irq_softirq_exit(event_info): (name, context, cpu, time, pid, comm, vec) = event_info irq_list = [] event_list = 0 if cpu in irq_dic.keys(): irq_list = irq_dic[cpu] del irq_dic[cpu] if cpu in net_rx_dic.keys(): sirq_ent_t = net_rx_dic[cpu]['sirq_ent_t'] event_list = net_rx_dic[cpu]['event_list'] del net_rx_dic[cpu] if irq_list == [] or event_list == 0: return rec_data = {'sirq_ent_t':sirq_ent_t, 'sirq_ext_t':time, 'irq_list':irq_list, 'event_list':event_list} # merge information realted to a NET_RX softirq receive_hunk_list.append(rec_data) def handle_napi_poll(event_info): (name, context, cpu, time, pid, comm, napi, dev_name) = event_info if cpu in net_rx_dic.keys(): event_list = net_rx_dic[cpu]['event_list'] rec_data = {'event_name':'napi_poll', 'dev':dev_name, 'event_t':time} event_list.append(rec_data) def handle_netif_rx(event_info): (name, context, cpu, time, pid, comm, skbaddr, skblen, dev_name) = event_info if cpu not in irq_dic.keys() \ or len(irq_dic[cpu]) == 0: return irq_record = irq_dic[cpu].pop() if 'event_list' in irq_record.keys(): irq_event_list = irq_record['event_list'] else: irq_event_list = [] irq_event_list.append({'time':time, 'event':'netif_rx', 'skbaddr':skbaddr, 'skblen':skblen, 'dev_name':dev_name}) irq_record.update({'event_list':irq_event_list}) irq_dic[cpu].append(irq_record) def handle_netif_receive_skb(event_info): global of_count_rx_skb_list (name, context, cpu, time, pid, comm, skbaddr, skblen, dev_name) = event_info if cpu in net_rx_dic.keys(): rec_data = {'event_name':'netif_receive_skb', 'event_t':time, 'skbaddr':skbaddr, 'len':skblen} event_list = net_rx_dic[cpu]['event_list'] event_list.append(rec_data) rx_skb_list.insert(0, rec_data) if len(rx_skb_list) > buffer_budget: rx_skb_list.pop() of_count_rx_skb_list += 1 def handle_net_dev_queue(event_info): global of_count_tx_queue_list (name, context, cpu, time, pid, comm, skbaddr, skblen, dev_name) = event_info skb = {'dev':dev_name, 'skbaddr':skbaddr, 'len':skblen, 'queue_t':time} tx_queue_list.insert(0, skb) if len(tx_queue_list) > buffer_budget: tx_queue_list.pop() of_count_tx_queue_list += 1 def handle_net_dev_xmit(event_info): global of_count_tx_xmit_list (name, context, cpu, time, pid, comm, skbaddr, skblen, rc, dev_name) = event_info if rc == 0: # NETDEV_TX_OK for i in range(len(tx_queue_list)): skb = tx_queue_list[i] if skb['skbaddr'] == skbaddr: skb['xmit_t'] = time tx_xmit_list.insert(0, skb) del tx_queue_list[i] if len(tx_xmit_list) > buffer_budget: tx_xmit_list.pop() of_count_tx_xmit_list += 1 return def handle_kfree_skb(event_info): (name, context, cpu, time, pid, comm, skbaddr, protocol, location) = event_info for i in range(len(tx_queue_list)): skb = tx_queue_list[i] if skb['skbaddr'] == skbaddr: del tx_queue_list[i] return for i in range(len(tx_xmit_list)): skb = tx_xmit_list[i] if skb['skbaddr'] == skbaddr: skb['free_t'] = time tx_free_list.append(skb) del tx_xmit_list[i] return for i in range(len(rx_skb_list)): rec_data = rx_skb_list[i] if rec_data['skbaddr'] == skbaddr: rec_data.update({'handle':"kfree_skb", 'comm':comm, 'pid':pid, 'comm_t':time}) del rx_skb_list[i] return def handle_consume_skb(event_info): (name, context, cpu, time, pid, comm, skbaddr) = event_info for i in range(len(tx_xmit_list)): skb = tx_xmit_list[i] if skb['skbaddr'] == skbaddr: skb['free_t'] = time tx_free_list.append(skb) del tx_xmit_list[i] return def handle_skb_copy_datagram_iovec(event_info): (name, context, cpu, time, pid, comm, skbaddr, skblen) = event_info for i in range(len(rx_skb_list)): rec_data = rx_skb_list[i] if skbaddr == rec_data['skbaddr']: rec_data.update({'handle':"skb_copy_datagram_iovec", 'comm':comm, 'pid':pid, 'comm_t':time}) del rx_skb_list[i] return
gpl-2.0
ulope/django
tests/utils_tests/test_datastructures.py
16
10835
""" Tests for stuff in django.utils.datastructures. """ import copy import pickle from django.test import SimpleTestCase from django.test.utils import IgnoreDeprecationWarningsMixin from django.utils.datastructures import (DictWrapper, ImmutableList, MultiValueDict, MultiValueDictKeyError, MergeDict, OrderedSet, SortedDict) from django.utils import six class SortedDictTests(IgnoreDeprecationWarningsMixin, SimpleTestCase): def setUp(self): super(SortedDictTests, self).setUp() self.d1 = SortedDict() self.d1[7] = 'seven' self.d1[1] = 'one' self.d1[9] = 'nine' self.d2 = SortedDict() self.d2[1] = 'one' self.d2[9] = 'nine' self.d2[0] = 'nil' self.d2[7] = 'seven' def test_basic_methods(self): self.assertEqual(list(six.iterkeys(self.d1)), [7, 1, 9]) self.assertEqual(list(six.itervalues(self.d1)), ['seven', 'one', 'nine']) self.assertEqual(list(six.iteritems(self.d1)), [(7, 'seven'), (1, 'one'), (9, 'nine')]) def test_overwrite_ordering(self): """ Overwriting an item keeps its place. """ self.d1[1] = 'ONE' self.assertEqual(list(six.itervalues(self.d1)), ['seven', 'ONE', 'nine']) def test_append_items(self): """ New items go to the end. """ self.d1[0] = 'nil' self.assertEqual(list(six.iterkeys(self.d1)), [7, 1, 9, 0]) def test_delete_and_insert(self): """ Deleting an item, then inserting the same key again will place it at the end. """ del self.d2[7] self.assertEqual(list(six.iterkeys(self.d2)), [1, 9, 0]) self.d2[7] = 'lucky number 7' self.assertEqual(list(six.iterkeys(self.d2)), [1, 9, 0, 7]) if six.PY2: def test_change_keys(self): """ Changing the keys won't do anything, it's only a copy of the keys dict. This test doesn't make sense under Python 3 because keys is an iterator. """ k = self.d2.keys() k.remove(9) self.assertEqual(self.d2.keys(), [1, 9, 0, 7]) def test_init_keys(self): """ Initialising a SortedDict with two keys will just take the first one. A real dict will actually take the second value so we will too, but we'll keep the ordering from the first key found. """ tuples = ((2, 'two'), (1, 'one'), (2, 'second-two')) d = SortedDict(tuples) self.assertEqual(list(six.iterkeys(d)), [2, 1]) real_dict = dict(tuples) self.assertEqual(sorted(six.itervalues(real_dict)), ['one', 'second-two']) # Here the order of SortedDict values *is* what we are testing self.assertEqual(list(six.itervalues(d)), ['second-two', 'one']) def test_overwrite(self): self.d1[1] = 'not one' self.assertEqual(self.d1[1], 'not one') self.assertEqual(list(six.iterkeys(self.d1)), list(six.iterkeys(self.d1.copy()))) def test_append(self): self.d1[13] = 'thirteen' self.assertEqual( repr(self.d1), "{7: 'seven', 1: 'one', 9: 'nine', 13: 'thirteen'}" ) def test_pop(self): self.assertEqual(self.d1.pop(1, 'missing'), 'one') self.assertEqual(self.d1.pop(1, 'missing'), 'missing') # We don't know which item will be popped in popitem(), so we'll # just check that the number of keys has decreased. l = len(self.d1) self.d1.popitem() self.assertEqual(l - len(self.d1), 1) def test_dict_equality(self): d = SortedDict((i, i) for i in range(3)) self.assertEqual(d, {0: 0, 1: 1, 2: 2}) def test_tuple_init(self): d = SortedDict(((1, "one"), (0, "zero"), (2, "two"))) self.assertEqual(repr(d), "{1: 'one', 0: 'zero', 2: 'two'}") def test_pickle(self): self.assertEqual( pickle.loads(pickle.dumps(self.d1, 2)), {7: 'seven', 1: 'one', 9: 'nine'} ) def test_copy(self): orig = SortedDict(((1, "one"), (0, "zero"), (2, "two"))) copied = copy.copy(orig) self.assertEqual(list(six.iterkeys(orig)), [1, 0, 2]) self.assertEqual(list(six.iterkeys(copied)), [1, 0, 2]) def test_clear(self): self.d1.clear() self.assertEqual(self.d1, {}) self.assertEqual(self.d1.keyOrder, []) def test_reversed(self): self.assertEqual(list(self.d1), [7, 1, 9]) self.assertEqual(list(self.d2), [1, 9, 0, 7]) self.assertEqual(list(reversed(self.d1)), [9, 1, 7]) self.assertEqual(list(reversed(self.d2)), [7, 0, 9, 1]) class MergeDictTests(IgnoreDeprecationWarningsMixin, SimpleTestCase): def test_simple_mergedict(self): d1 = {'chris': 'cool', 'camri': 'cute', 'cotton': 'adorable', 'tulip': 'snuggable', 'twoofme': 'firstone'} d2 = {'chris2': 'cool2', 'camri2': 'cute2', 'cotton2': 'adorable2', 'tulip2': 'snuggable2'} d3 = {'chris3': 'cool3', 'camri3': 'cute3', 'cotton3': 'adorable3', 'tulip3': 'snuggable3'} md = MergeDict(d1, d2, d3) self.assertEqual(md['chris'], 'cool') self.assertEqual(md['camri'], 'cute') self.assertEqual(md['twoofme'], 'firstone') md2 = md.copy() self.assertEqual(md2['chris'], 'cool') def test_mergedict_merges_multivaluedict(self): """ MergeDict can merge MultiValueDicts """ multi1 = MultiValueDict({'key1': ['value1'], 'key2': ['value2', 'value3']}) multi2 = MultiValueDict({'key2': ['value4'], 'key4': ['value5', 'value6']}) mm = MergeDict(multi1, multi2) # Although 'key2' appears in both dictionaries, # only the first value is used. self.assertEqual(mm.getlist('key2'), ['value2', 'value3']) self.assertEqual(mm.getlist('key4'), ['value5', 'value6']) self.assertEqual(mm.getlist('undefined'), []) self.assertEqual(sorted(six.iterkeys(mm)), ['key1', 'key2', 'key4']) self.assertEqual(len(list(six.itervalues(mm))), 3) self.assertIn('value1', six.itervalues(mm)) self.assertEqual( sorted(six.iteritems(mm), key=lambda k: k[0]), [('key1', 'value1'), ('key2', 'value3'), ('key4', 'value6')] ) self.assertEqual( [(k, mm.getlist(k)) for k in sorted(mm)], [('key1', ['value1']), ('key2', ['value2', 'value3']), ('key4', ['value5', 'value6'])] ) def test_bool_casting(self): empty = MergeDict({}, {}, {}) not_empty = MergeDict({}, {}, {"key": "value"}) self.assertFalse(empty) self.assertTrue(not_empty) def test_key_error(self): """ Test that the message of KeyError contains the missing key name. """ d1 = MergeDict({'key1': 42}) with six.assertRaisesRegex(self, KeyError, 'key2'): d1['key2'] class OrderedSetTests(SimpleTestCase): def test_bool(self): # Refs #23664 s = OrderedSet() self.assertFalse(s) s.add(1) self.assertTrue(s) class MultiValueDictTests(SimpleTestCase): def test_multivaluedict(self): d = MultiValueDict({'name': ['Adrian', 'Simon'], 'position': ['Developer']}) self.assertEqual(d['name'], 'Simon') self.assertEqual(d.get('name'), 'Simon') self.assertEqual(d.getlist('name'), ['Adrian', 'Simon']) self.assertEqual( sorted(list(six.iteritems(d))), [('name', 'Simon'), ('position', 'Developer')] ) self.assertEqual( sorted(list(six.iterlists(d))), [('name', ['Adrian', 'Simon']), ('position', ['Developer'])] ) six.assertRaisesRegex(self, MultiValueDictKeyError, 'lastname', d.__getitem__, 'lastname') self.assertEqual(d.get('lastname'), None) self.assertEqual(d.get('lastname', 'nonexistent'), 'nonexistent') self.assertEqual(d.getlist('lastname'), []) self.assertEqual(d.getlist('doesnotexist', ['Adrian', 'Simon']), ['Adrian', 'Simon']) d.setlist('lastname', ['Holovaty', 'Willison']) self.assertEqual(d.getlist('lastname'), ['Holovaty', 'Willison']) self.assertEqual(sorted(list(six.itervalues(d))), ['Developer', 'Simon', 'Willison']) def test_appendlist(self): d = MultiValueDict() d.appendlist('name', 'Adrian') d.appendlist('name', 'Simon') self.assertEqual(d.getlist('name'), ['Adrian', 'Simon']) def test_copy(self): for copy_func in [copy.copy, lambda d: d.copy()]: d1 = MultiValueDict({ "developers": ["Carl", "Fred"] }) self.assertEqual(d1["developers"], "Fred") d2 = copy_func(d1) d2.update({"developers": "Groucho"}) self.assertEqual(d2["developers"], "Groucho") self.assertEqual(d1["developers"], "Fred") d1 = MultiValueDict({ "key": [[]] }) self.assertEqual(d1["key"], []) d2 = copy_func(d1) d2["key"].append("Penguin") self.assertEqual(d1["key"], ["Penguin"]) self.assertEqual(d2["key"], ["Penguin"]) def test_dict_translation(self): mvd = MultiValueDict({ 'devs': ['Bob', 'Joe'], 'pm': ['Rory'], }) d = mvd.dict() self.assertEqual(sorted(six.iterkeys(d)), sorted(six.iterkeys(mvd))) for key in six.iterkeys(mvd): self.assertEqual(d[key], mvd[key]) self.assertEqual({}, MultiValueDict().dict()) class ImmutableListTests(SimpleTestCase): def test_sort(self): d = ImmutableList(range(10)) # AttributeError: ImmutableList object is immutable. self.assertRaisesMessage(AttributeError, 'ImmutableList object is immutable.', d.sort) self.assertEqual(repr(d), '(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)') def test_custom_warning(self): d = ImmutableList(range(10), warning="Object is immutable!") self.assertEqual(d[1], 1) # AttributeError: Object is immutable! self.assertRaisesMessage(AttributeError, 'Object is immutable!', d.__setitem__, 1, 'test') class DictWrapperTests(SimpleTestCase): def test_dictwrapper(self): f = lambda x: "*%s" % x d = DictWrapper({'a': 'a'}, f, 'xx_') self.assertEqual( "Normal: %(a)s. Modified: %(xx_a)s" % d, 'Normal: a. Modified: *a' )
bsd-3-clause
flyser/AutobahnPython
examples/websocket/streaming/message_based_server.py
27
1622
############################################################################### ## ## Copyright 2011 Tavendo GmbH ## ## 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 hashlib from twisted.internet import reactor from autobahn.websocket import WebSocketServerFactory, \ WebSocketServerProtocol, \ listenWS class MessageBasedHashServerProtocol(WebSocketServerProtocol): """ Message-based WebSockets server that computes a SHA-256 for every message it receives and sends back the computed digest. """ def onMessage(self, message, binary): sha256 = hashlib.sha256() sha256.update(message) digest = sha256.hexdigest() self.sendMessage(digest) print "Sent digest for message: %s" % digest if __name__ == '__main__': factory = WebSocketServerFactory("ws://localhost:9000") factory.protocol = MessageBasedHashServerProtocol listenWS(factory) reactor.run()
apache-2.0
bwbeach/ansible
test/integration/cleanup_gce.py
163
2589
''' Find and delete GCE resources matching the provided --match string. Unless --yes|-y is provided, the prompt for confirmation prior to deleting resources. Please use caution, you can easily delete your *ENTIRE* GCE infrastructure. ''' import os import re import sys import optparse import yaml try: from libcloud.compute.types import Provider from libcloud.compute.providers import get_driver from libcloud.common.google import GoogleBaseError, QuotaExceededError, \ ResourceExistsError, ResourceInUseError, ResourceNotFoundError _ = Provider.GCE except ImportError: print("failed=True " + \ "msg='libcloud with GCE support (0.13.3+) required for this module'") sys.exit(1) import gce_credentials def delete_gce_resources(get_func, attr, opts): for item in get_func(): val = getattr(item, attr) if re.search(opts.match_re, val, re.IGNORECASE): prompt_and_delete(item, "Delete matching %s? [y/n]: " % (item,), opts.assumeyes) def prompt_and_delete(item, prompt, assumeyes): if not assumeyes: assumeyes = raw_input(prompt).lower() == 'y' assert hasattr(item, 'destroy'), "Class <%s> has no delete attribute" % item.__class__ if assumeyes: item.destroy() print ("Deleted %s" % item) def parse_args(): parser = optparse.OptionParser(usage="%s [options]" % (sys.argv[0],), description=__doc__) gce_credentials.add_credentials_options(parser) parser.add_option("--yes", "-y", action="store_true", dest="assumeyes", default=False, help="Don't prompt for confirmation") parser.add_option("--match", action="store", dest="match_re", default="^ansible-testing-", help="Regular expression used to find GCE resources (default: %default)") (opts, args) = parser.parse_args() gce_credentials.check_required(opts, parser) return (opts, args) if __name__ == '__main__': (opts, args) = parse_args() # Connect to GCE gce = gce_credentials.get_gce_driver(opts) try: # Delete matching instances delete_gce_resources(gce.list_nodes, 'name', opts) # Delete matching snapshots def get_snapshots(): for volume in gce.list_volumes(): for snapshot in gce.list_volume_snapshots(volume): yield snapshot delete_gce_resources(get_snapshots, 'name', opts) # Delete matching disks delete_gce_resources(gce.list_volumes, 'name', opts) except KeyboardInterrupt as e: print("\nExiting on user command.")
gpl-3.0
zzicewind/nova
nova/virt/xenapi/fake.py
47
38557
# Copyright (c) 2010 Citrix Systems, 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. # # Parts of this file are based upon xmlrpclib.py, the XML-RPC client # interface included in the Python distribution. # # Copyright (c) 1999-2002 by Secret Labs AB # Copyright (c) 1999-2002 by Fredrik Lundh # # By obtaining, using, and/or copying this software and/or its # associated documentation, you agree that you have read, understood, # and will comply with the following terms and conditions: # # Permission to use, copy, modify, and distribute this software and # its associated documentation for any purpose and without fee is # hereby granted, provided that the above copyright notice appears in # all copies, and that both that copyright notice and this permission # notice appear in supporting documentation, and that the name of # Secret Labs AB or the author not be used in advertising or publicity # pertaining to distribution of the software without specific, written # prior permission. # # SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD # TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT- # ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR # BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY # DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, # WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS # ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE # OF THIS SOFTWARE. # -------------------------------------------------------------------- """ A fake XenAPI SDK. """ import base64 import pickle import random import uuid from xml.sax import saxutils import zlib from oslo_log import log as logging from oslo_serialization import jsonutils from oslo_utils import timeutils from oslo_utils import units import six from nova import exception from nova.i18n import _ from nova.virt.xenapi.client import session as xenapi_session _CLASSES = ['host', 'network', 'session', 'pool', 'SR', 'VBD', 'PBD', 'VDI', 'VIF', 'PIF', 'VM', 'VLAN', 'task'] _db_content = {} LOG = logging.getLogger(__name__) def reset(): for c in _CLASSES: _db_content[c] = {} host = create_host('fake') create_vm('fake dom 0', 'Running', is_a_template=False, is_control_domain=True, resident_on=host) def reset_table(table): if table not in _CLASSES: return _db_content[table] = {} def _create_pool(name_label): return _create_object('pool', {'name_label': name_label}) def create_host(name_label, hostname='fake_name', address='fake_addr'): host_ref = _create_object('host', {'name_label': name_label, 'hostname': hostname, 'address': address}) host_default_sr_ref = _create_local_srs(host_ref) _create_local_pif(host_ref) # Create a pool if we don't have one already if len(_db_content['pool']) == 0: pool_ref = _create_pool('') _db_content['pool'][pool_ref]['master'] = host_ref _db_content['pool'][pool_ref]['default-SR'] = host_default_sr_ref _db_content['pool'][pool_ref]['suspend-image-SR'] = host_default_sr_ref def create_network(name_label, bridge): return _create_object('network', {'name_label': name_label, 'bridge': bridge}) def create_vm(name_label, status, **kwargs): if status == 'Running': domid = random.randrange(1, 1 << 16) resident_on = _db_content['host'].keys()[0] else: domid = -1 resident_on = '' vm_rec = kwargs.copy() vm_rec.update({'name_label': name_label, 'domid': domid, 'power_state': status, 'blocked_operations': {}, 'resident_on': resident_on}) vm_ref = _create_object('VM', vm_rec) after_VM_create(vm_ref, vm_rec) return vm_ref def destroy_vm(vm_ref): vm_rec = _db_content['VM'][vm_ref] vbd_refs = vm_rec['VBDs'] # NOTE(johannes): Shallow copy since destroy_vbd will remove itself # from the list for vbd_ref in vbd_refs[:]: destroy_vbd(vbd_ref) del _db_content['VM'][vm_ref] def destroy_vbd(vbd_ref): vbd_rec = _db_content['VBD'][vbd_ref] vm_ref = vbd_rec['VM'] vm_rec = _db_content['VM'][vm_ref] vm_rec['VBDs'].remove(vbd_ref) vdi_ref = vbd_rec['VDI'] vdi_rec = _db_content['VDI'][vdi_ref] vdi_rec['VBDs'].remove(vbd_ref) del _db_content['VBD'][vbd_ref] def destroy_vdi(vdi_ref): vdi_rec = _db_content['VDI'][vdi_ref] vbd_refs = vdi_rec['VBDs'] # NOTE(johannes): Shallow copy since destroy_vbd will remove itself # from the list for vbd_ref in vbd_refs[:]: destroy_vbd(vbd_ref) del _db_content['VDI'][vdi_ref] def create_vdi(name_label, sr_ref, **kwargs): vdi_rec = { 'SR': sr_ref, 'read_only': False, 'type': '', 'name_label': name_label, 'name_description': '', 'sharable': False, 'other_config': {}, 'location': '', 'xenstore_data': {}, 'sm_config': {'vhd-parent': None}, 'physical_utilisation': '123', 'managed': True, } vdi_rec.update(kwargs) vdi_ref = _create_object('VDI', vdi_rec) after_VDI_create(vdi_ref, vdi_rec) return vdi_ref def after_VDI_create(vdi_ref, vdi_rec): vdi_rec.setdefault('VBDs', []) def create_vbd(vm_ref, vdi_ref, userdevice=0, other_config=None): if other_config is None: other_config = {} vbd_rec = {'VM': vm_ref, 'VDI': vdi_ref, 'userdevice': str(userdevice), 'currently_attached': False, 'other_config': other_config} vbd_ref = _create_object('VBD', vbd_rec) after_VBD_create(vbd_ref, vbd_rec) return vbd_ref def after_VBD_create(vbd_ref, vbd_rec): """Create read-only fields and backref from VM and VDI to VBD when VBD is created. """ vbd_rec['currently_attached'] = False vbd_rec['device'] = '' vbd_rec.setdefault('other_config', {}) vm_ref = vbd_rec['VM'] vm_rec = _db_content['VM'][vm_ref] vm_rec['VBDs'].append(vbd_ref) vm_name_label = _db_content['VM'][vm_ref]['name_label'] vbd_rec['vm_name_label'] = vm_name_label vdi_ref = vbd_rec['VDI'] if vdi_ref and vdi_ref != "OpaqueRef:NULL": vdi_rec = _db_content['VDI'][vdi_ref] vdi_rec['VBDs'].append(vbd_ref) def after_VIF_create(vif_ref, vif_rec): """Create backref from VM to VIF when VIF is created. """ vm_ref = vif_rec['VM'] vm_rec = _db_content['VM'][vm_ref] vm_rec['VIFs'].append(vif_ref) def after_VM_create(vm_ref, vm_rec): """Create read-only fields in the VM record.""" vm_rec.setdefault('domid', -1) vm_rec.setdefault('is_control_domain', False) vm_rec.setdefault('is_a_template', False) vm_rec.setdefault('memory_static_max', str(8 * units.Gi)) vm_rec.setdefault('memory_dynamic_max', str(8 * units.Gi)) vm_rec.setdefault('VCPUs_max', str(4)) vm_rec.setdefault('VBDs', []) vm_rec.setdefault('VIFs', []) vm_rec.setdefault('resident_on', '') def create_pbd(host_ref, sr_ref, attached): config = {'path': '/var/run/sr-mount/%s' % sr_ref} return _create_object('PBD', {'device_config': config, 'host': host_ref, 'SR': sr_ref, 'currently_attached': attached}) def create_task(name_label): return _create_object('task', {'name_label': name_label, 'status': 'pending'}) def _create_local_srs(host_ref): """Create an SR that looks like the one created on the local disk by default by the XenServer installer. Also, fake the installation of an ISO SR. """ create_sr(name_label='Local storage ISO', type='iso', other_config={'i18n-original-value-name_label': 'Local storage ISO', 'i18n-key': 'local-storage-iso'}, physical_size=80000, physical_utilisation=40000, virtual_allocation=80000, host_ref=host_ref) return create_sr(name_label='Local storage', type='ext', other_config={'i18n-original-value-name_label': 'Local storage', 'i18n-key': 'local-storage'}, physical_size=40000, physical_utilisation=20000, virtual_allocation=10000, host_ref=host_ref) def create_sr(**kwargs): sr_ref = _create_object( 'SR', {'name_label': kwargs.get('name_label'), 'type': kwargs.get('type'), 'content_type': kwargs.get('type', 'user'), 'shared': kwargs.get('shared', False), 'physical_size': kwargs.get('physical_size', str(1 << 30)), 'physical_utilisation': str( kwargs.get('physical_utilisation', 0)), 'virtual_allocation': str(kwargs.get('virtual_allocation', 0)), 'other_config': kwargs.get('other_config', {}), 'VDIs': kwargs.get('VDIs', [])}) pbd_ref = create_pbd(kwargs.get('host_ref'), sr_ref, True) _db_content['SR'][sr_ref]['PBDs'] = [pbd_ref] return sr_ref def _create_local_pif(host_ref): pif_ref = _create_object('PIF', {'name-label': 'Fake PIF', 'MAC': '00:11:22:33:44:55', 'physical': True, 'VLAN': -1, 'device': 'fake0', 'host_uuid': host_ref, 'network': '', 'IP': '10.1.1.1', 'IPv6': '', 'uuid': '', 'management': 'true'}) _db_content['PIF'][pif_ref]['uuid'] = pif_ref return pif_ref def _create_object(table, obj): ref = str(uuid.uuid4()) obj['uuid'] = str(uuid.uuid4()) _db_content[table][ref] = obj return ref def _create_sr(table, obj): sr_type = obj[6] # Forces fake to support iscsi only if sr_type != 'iscsi' and sr_type != 'nfs': raise Failure(['SR_UNKNOWN_DRIVER', sr_type]) host_ref = _db_content['host'].keys()[0] sr_ref = _create_object(table, obj[2]) if sr_type == 'iscsi': vdi_ref = create_vdi('', sr_ref) pbd_ref = create_pbd(host_ref, sr_ref, True) _db_content['SR'][sr_ref]['VDIs'] = [vdi_ref] _db_content['SR'][sr_ref]['PBDs'] = [pbd_ref] _db_content['VDI'][vdi_ref]['SR'] = sr_ref _db_content['PBD'][pbd_ref]['SR'] = sr_ref return sr_ref def _create_vlan(pif_ref, vlan_num, network_ref): pif_rec = get_record('PIF', pif_ref) vlan_pif_ref = _create_object('PIF', {'name-label': 'Fake VLAN PIF', 'MAC': '00:11:22:33:44:55', 'physical': True, 'VLAN': vlan_num, 'device': pif_rec['device'], 'host_uuid': pif_rec['host_uuid']}) return _create_object('VLAN', {'tagged-pif': pif_ref, 'untagged-pif': vlan_pif_ref, 'tag': vlan_num}) def get_all(table): return _db_content[table].keys() def get_all_records(table): return _db_content[table] def _query_matches(record, query): # Simple support for the XenServer query language: # 'field "host"="<uuid>" and field "SR"="<sr uuid>"' # Tested through existing tests (e.g. calls to find_network_with_bridge) and_clauses = query.split(" and ") if len(and_clauses) > 1: matches = True for clause in and_clauses: matches = matches and _query_matches(record, clause) return matches or_clauses = query.split(" or ") if len(or_clauses) > 1: matches = False for clause in or_clauses: matches = matches or _query_matches(record, clause) return matches if query[:4] == 'not ': return not _query_matches(record, query[4:]) # Now it must be a single field - bad queries never match if query[:5] != 'field': return False (field, value) = query[6:].split('=', 1) # Some fields (e.g. name_label, memory_overhead) have double # underscores in the DB, but only single underscores when querying field = field.replace("__", "_").strip(" \"'") value = value.strip(" \"'") # Strings should be directly compared if isinstance(record[field], str): return record[field] == value # But for all other value-checks, convert to a string first # (Notably used for booleans - which can be lower or camel # case and are interpreted/sanitised by XAPI) return str(record[field]).lower() == value.lower() def get_all_records_where(table_name, query): matching_records = {} table = _db_content[table_name] for record in table: if _query_matches(table[record], query): matching_records[record] = table[record] return matching_records def get_record(table, ref): if ref in _db_content[table]: return _db_content[table].get(ref) else: raise Failure(['HANDLE_INVALID', table, ref]) def check_for_session_leaks(): if len(_db_content['session']) > 0: raise exception.NovaException('Sessions have leaked: %s' % _db_content['session']) def as_value(s): """Helper function for simulating XenAPI plugin responses. It escapes and wraps the given argument. """ return '<value>%s</value>' % saxutils.escape(s) def as_json(*args, **kwargs): """Helper function for simulating XenAPI plugin responses for those that are returning JSON. If this function is given plain arguments, then these are rendered as a JSON list. If it's given keyword arguments then these are rendered as a JSON dict. """ arg = args or kwargs return jsonutils.dumps(arg) class Failure(Exception): def __init__(self, details): self.details = details def __str__(self): try: return str(self.details) except Exception: return "XenAPI Fake Failure: %s" % str(self.details) def _details_map(self): return {str(i): self.details[i] for i in range(len(self.details))} class SessionBase(object): """Base class for Fake Sessions.""" def __init__(self, uri): self._session = None xenapi_session.apply_session_helpers(self) def pool_get_default_SR(self, _1, pool_ref): return _db_content['pool'].values()[0]['default-SR'] def VBD_insert(self, _1, vbd_ref, vdi_ref): vbd_rec = get_record('VBD', vbd_ref) get_record('VDI', vdi_ref) vbd_rec['empty'] = False vbd_rec['VDI'] = vdi_ref def VBD_plug(self, _1, ref): rec = get_record('VBD', ref) if rec['currently_attached']: raise Failure(['DEVICE_ALREADY_ATTACHED', ref]) rec['currently_attached'] = True rec['device'] = rec['userdevice'] def VBD_unplug(self, _1, ref): rec = get_record('VBD', ref) if not rec['currently_attached']: raise Failure(['DEVICE_ALREADY_DETACHED', ref]) rec['currently_attached'] = False rec['device'] = '' def VBD_add_to_other_config(self, _1, vbd_ref, key, value): db_ref = _db_content['VBD'][vbd_ref] if 'other_config' not in db_ref: db_ref['other_config'] = {} if key in db_ref['other_config']: raise Failure(['MAP_DUPLICATE_KEY', 'VBD', 'other_config', vbd_ref, key]) db_ref['other_config'][key] = value def VBD_get_other_config(self, _1, vbd_ref): db_ref = _db_content['VBD'][vbd_ref] if 'other_config' not in db_ref: return {} return db_ref['other_config'] def PBD_create(self, _1, pbd_rec): pbd_ref = _create_object('PBD', pbd_rec) _db_content['PBD'][pbd_ref]['currently_attached'] = False return pbd_ref def PBD_plug(self, _1, pbd_ref): rec = get_record('PBD', pbd_ref) if rec['currently_attached']: raise Failure(['DEVICE_ALREADY_ATTACHED', rec]) rec['currently_attached'] = True sr_ref = rec['SR'] _db_content['SR'][sr_ref]['PBDs'] = [pbd_ref] def PBD_unplug(self, _1, pbd_ref): rec = get_record('PBD', pbd_ref) if not rec['currently_attached']: raise Failure(['DEVICE_ALREADY_DETACHED', rec]) rec['currently_attached'] = False sr_ref = rec['SR'] _db_content['SR'][sr_ref]['PBDs'].remove(pbd_ref) def SR_introduce(self, _1, sr_uuid, label, desc, type, content_type, shared, sm_config): for ref, rec in six.iteritems(_db_content['SR']): if rec.get('uuid') == sr_uuid: # make forgotten = 0 and return ref _db_content['SR'][ref]['forgotten'] = 0 return ref # SR not found in db, so we create one params = {'sr_uuid': sr_uuid, 'label': label, 'desc': desc, 'type': type, 'content_type': content_type, 'shared': shared, 'sm_config': sm_config} sr_ref = _create_object('SR', params) _db_content['SR'][sr_ref]['uuid'] = sr_uuid _db_content['SR'][sr_ref]['forgotten'] = 0 vdi_per_lun = False if type == 'iscsi': # Just to be clear vdi_per_lun = True if vdi_per_lun: # we need to create a vdi because this introduce # is likely meant for a single vdi vdi_ref = create_vdi('', sr_ref) _db_content['SR'][sr_ref]['VDIs'] = [vdi_ref] _db_content['VDI'][vdi_ref]['SR'] = sr_ref return sr_ref def SR_forget(self, _1, sr_ref): _db_content['SR'][sr_ref]['forgotten'] = 1 def SR_scan(self, _1, sr_ref): return def VM_get_xenstore_data(self, _1, vm_ref): return _db_content['VM'][vm_ref].get('xenstore_data', {}) def VM_remove_from_xenstore_data(self, _1, vm_ref, key): db_ref = _db_content['VM'][vm_ref] if 'xenstore_data' not in db_ref: return if key in db_ref['xenstore_data']: del db_ref['xenstore_data'][key] def VM_add_to_xenstore_data(self, _1, vm_ref, key, value): db_ref = _db_content['VM'][vm_ref] if 'xenstore_data' not in db_ref: db_ref['xenstore_data'] = {} db_ref['xenstore_data'][key] = value def VM_pool_migrate(self, _1, vm_ref, host_ref, options): pass def VDI_remove_from_other_config(self, _1, vdi_ref, key): db_ref = _db_content['VDI'][vdi_ref] if 'other_config' not in db_ref: return if key in db_ref['other_config']: del db_ref['other_config'][key] def VDI_add_to_other_config(self, _1, vdi_ref, key, value): db_ref = _db_content['VDI'][vdi_ref] if 'other_config' not in db_ref: db_ref['other_config'] = {} if key in db_ref['other_config']: raise Failure(['MAP_DUPLICATE_KEY', 'VDI', 'other_config', vdi_ref, key]) db_ref['other_config'][key] = value def VDI_copy(self, _1, vdi_to_copy_ref, sr_ref): db_ref = _db_content['VDI'][vdi_to_copy_ref] name_label = db_ref['name_label'] read_only = db_ref['read_only'] sharable = db_ref['sharable'] other_config = db_ref['other_config'].copy() return create_vdi(name_label, sr_ref, sharable=sharable, read_only=read_only, other_config=other_config) def VDI_clone(self, _1, vdi_to_clone_ref): db_ref = _db_content['VDI'][vdi_to_clone_ref] sr_ref = db_ref['SR'] return self.VDI_copy(_1, vdi_to_clone_ref, sr_ref) def host_compute_free_memory(self, _1, ref): # Always return 12GB available return 12 * units.Gi def _plugin_agent_version(self, method, args): return as_json(returncode='0', message='1.0\\r\\n') def _plugin_agent_key_init(self, method, args): return as_json(returncode='D0', message='1') def _plugin_agent_password(self, method, args): return as_json(returncode='0', message='success') def _plugin_agent_inject_file(self, method, args): return as_json(returncode='0', message='success') def _plugin_agent_resetnetwork(self, method, args): return as_json(returncode='0', message='success') def _plugin_agent_agentupdate(self, method, args): url = args["url"] md5 = args["md5sum"] message = "success with %(url)s and hash:%(md5)s" % dict(url=url, md5=md5) return as_json(returncode='0', message=message) def _plugin_noop(self, method, args): return '' def _plugin_pickle_noop(self, method, args): return pickle.dumps(None) def _plugin_migration_transfer_vhd(self, method, args): kwargs = pickle.loads(args['params'])['kwargs'] vdi_ref = self.xenapi_request('VDI.get_by_uuid', (kwargs['vdi_uuid'], )) assert vdi_ref return pickle.dumps(None) _plugin_glance_upload_vhd = _plugin_pickle_noop _plugin_kernel_copy_vdi = _plugin_noop _plugin_kernel_create_kernel_ramdisk = _plugin_noop _plugin_kernel_remove_kernel_ramdisk = _plugin_noop _plugin_migration_move_vhds_into_sr = _plugin_noop def _plugin_xenhost_host_data(self, method, args): return jsonutils.dumps({ 'host_memory': {'total': 10, 'overhead': 20, 'free': 30, 'free-computed': 40}, 'host_uuid': 'fb97583b-baa1-452d-850e-819d95285def', 'host_name-label': 'fake-xenhost', 'host_name-description': 'Default install of XenServer', 'host_hostname': 'fake-xenhost', 'host_ip_address': '10.219.10.24', 'enabled': 'true', 'host_capabilities': ['xen-3.0-x86_64', 'xen-3.0-x86_32p', 'hvm-3.0-x86_32', 'hvm-3.0-x86_32p', 'hvm-3.0-x86_64'], 'host_other-config': { 'agent_start_time': '1412774967.', 'iscsi_iqn': 'iqn.2014-10.org.example:39fa9ee3', 'boot_time': '1412774885.', }, 'host_cpu_info': { 'physical_features': '0098e3fd-bfebfbff-00000001-28100800', 'modelname': 'Intel(R) Xeon(R) CPU X3430 @ 2.40GHz', 'vendor': 'GenuineIntel', 'features': '0098e3fd-bfebfbff-00000001-28100800', 'family': 6, 'maskable': 'full', 'cpu_count': 4, 'socket_count': '1', 'flags': 'fpu de tsc msr pae mce cx8 apic sep mtrr mca ' 'cmov pat clflush acpi mmx fxsr sse sse2 ss ht ' 'nx constant_tsc nonstop_tsc aperfmperf pni vmx ' 'est ssse3 sse4_1 sse4_2 popcnt hypervisor ida ' 'tpr_shadow vnmi flexpriority ept vpid', 'stepping': 5, 'model': 30, 'features_after_reboot': '0098e3fd-bfebfbff-00000001-28100800', 'speed': '2394.086' }, }) def _plugin_poweraction(self, method, args): return jsonutils.dumps({"power_action": method[5:]}) _plugin_xenhost_host_reboot = _plugin_poweraction _plugin_xenhost_host_startup = _plugin_poweraction _plugin_xenhost_host_shutdown = _plugin_poweraction def _plugin_xenhost_set_host_enabled(self, method, args): enabled = 'enabled' if args.get('enabled') == 'true' else 'disabled' return jsonutils.dumps({"status": enabled}) def _plugin_xenhost_host_uptime(self, method, args): return jsonutils.dumps({"uptime": "fake uptime"}) def _plugin_xenhost_get_pci_device_details(self, method, args): """Simulate the ouput of three pci devices. Both of those devices are available for pci passtrough but only one will match with the pci whitelist used in the method test_pci_passthrough_devices_*(). Return a single list. """ # Driver is not pciback dev_bad1 = ["Slot:\t0000:86:10.0", "Class:\t0604", "Vendor:\t10b5", "Device:\t8747", "Rev:\tba", "Driver:\tpcieport", "\n"] # Driver is pciback but vendor and device are bad dev_bad2 = ["Slot:\t0000:88:00.0", "Class:\t0300", "Vendor:\t0bad", "Device:\tcafe", "SVendor:\t10de", "SDevice:\t100d", "Rev:\ta1", "Driver:\tpciback", "\n"] # Driver is pciback and vendor, device are used for matching dev_good = ["Slot:\t0000:87:00.0", "Class:\t0300", "Vendor:\t10de", "Device:\t11bf", "SVendor:\t10de", "SDevice:\t100d", "Rev:\ta1", "Driver:\tpciback", "\n"] lspci_output = "\n".join(dev_bad1 + dev_bad2 + dev_good) return pickle.dumps(lspci_output) def _plugin_xenhost_get_pci_type(self, method, args): return pickle.dumps("type-PCI") def _plugin_console_get_console_log(self, method, args): dom_id = args["dom_id"] if dom_id == 0: raise Failure('Guest does not have a console') return base64.b64encode(zlib.compress("dom_id: %s" % dom_id)) def _plugin_nova_plugin_version_get_version(self, method, args): return pickle.dumps("1.2") def _plugin_xenhost_query_gc(self, method, args): return pickle.dumps("False") def host_call_plugin(self, _1, _2, plugin, method, args): func = getattr(self, '_plugin_%s_%s' % (plugin, method), None) if not func: raise Exception('No simulation in host_call_plugin for %s,%s' % (plugin, method)) return func(method, args) def VDI_get_virtual_size(self, *args): return 1 * units.Gi def VDI_resize_online(self, *args): return 'derp' VDI_resize = VDI_resize_online def _VM_reboot(self, session, vm_ref): db_ref = _db_content['VM'][vm_ref] if db_ref['power_state'] != 'Running': raise Failure(['VM_BAD_POWER_STATE', 'fake-opaque-ref', db_ref['power_state'].lower(), 'halted']) db_ref['power_state'] = 'Running' db_ref['domid'] = random.randrange(1, 1 << 16) def VM_clean_reboot(self, session, vm_ref): return self._VM_reboot(session, vm_ref) def VM_hard_reboot(self, session, vm_ref): return self._VM_reboot(session, vm_ref) def VM_hard_shutdown(self, session, vm_ref): db_ref = _db_content['VM'][vm_ref] db_ref['power_state'] = 'Halted' db_ref['domid'] = -1 VM_clean_shutdown = VM_hard_shutdown def VM_suspend(self, session, vm_ref): db_ref = _db_content['VM'][vm_ref] db_ref['power_state'] = 'Suspended' def VM_pause(self, session, vm_ref): db_ref = _db_content['VM'][vm_ref] db_ref['power_state'] = 'Paused' def pool_eject(self, session, host_ref): pass def pool_join(self, session, hostname, username, password): pass def pool_set_name_label(self, session, pool_ref, name): pass def host_migrate_receive(self, session, destref, nwref, options): return "fake_migrate_data" def VM_assert_can_migrate(self, session, vmref, migrate_data, live, vdi_map, vif_map, options): pass def VM_migrate_send(self, session, mref, migrate_data, live, vdi_map, vif_map, options): pass def VM_remove_from_blocked_operations(self, session, vm_ref, key): # operation is idempotent, XenServer doesn't care if the key exists _db_content['VM'][vm_ref]['blocked_operations'].pop(key, None) def xenapi_request(self, methodname, params): if methodname.startswith('login'): self._login(methodname, params) return None elif methodname == 'logout' or methodname == 'session.logout': self._logout() return None else: full_params = (self._session,) + params meth = getattr(self, methodname, None) if meth is None: LOG.debug('Raising NotImplemented') raise NotImplementedError( _('xenapi.fake does not have an implementation for %s') % methodname) return meth(*full_params) def _login(self, method, params): self._session = str(uuid.uuid4()) _session_info = {'uuid': str(uuid.uuid4()), 'this_host': _db_content['host'].keys()[0]} _db_content['session'][self._session] = _session_info def _logout(self): s = self._session self._session = None if s not in _db_content['session']: raise exception.NovaException( "Logging out a session that is invalid or already logged " "out: %s" % s) del _db_content['session'][s] def __getattr__(self, name): if name == 'handle': return self._session elif name == 'xenapi': return _Dispatcher(self.xenapi_request, None) elif name.startswith('login') or name.startswith('slave_local'): return lambda *params: self._login(name, params) elif name.startswith('Async'): return lambda *params: self._async(name, params) elif '.' in name: impl = getattr(self, name.replace('.', '_')) if impl is not None: def callit(*params): LOG.debug('Calling %(name)s %(impl)s', {'name': name, 'impl': impl}) self._check_session(params) return impl(*params) return callit if self._is_gettersetter(name, True): LOG.debug('Calling getter %s', name) return lambda *params: self._getter(name, params) elif self._is_gettersetter(name, False): LOG.debug('Calling setter %s', name) return lambda *params: self._setter(name, params) elif self._is_create(name): return lambda *params: self._create(name, params) elif self._is_destroy(name): return lambda *params: self._destroy(name, params) elif name == 'XenAPI': return FakeXenAPI() else: return None def _is_gettersetter(self, name, getter): bits = name.split('.') return (len(bits) == 2 and bits[0] in _CLASSES and bits[1].startswith(getter and 'get_' or 'set_')) def _is_create(self, name): return self._is_method(name, 'create') def _is_destroy(self, name): return self._is_method(name, 'destroy') def _is_method(self, name, meth): bits = name.split('.') return (len(bits) == 2 and bits[0] in _CLASSES and bits[1] == meth) def _getter(self, name, params): self._check_session(params) (cls, func) = name.split('.') if func == 'get_all': self._check_arg_count(params, 1) return get_all(cls) if func == 'get_all_records': self._check_arg_count(params, 1) return get_all_records(cls) if func == 'get_all_records_where': self._check_arg_count(params, 2) return get_all_records_where(cls, params[1]) if func == 'get_record': self._check_arg_count(params, 2) return get_record(cls, params[1]) if func in ('get_by_name_label', 'get_by_uuid'): self._check_arg_count(params, 2) return_singleton = (func == 'get_by_uuid') return self._get_by_field( _db_content[cls], func[len('get_by_'):], params[1], return_singleton=return_singleton) if len(params) == 2: field = func[len('get_'):] ref = params[1] if (ref in _db_content[cls]): if (field in _db_content[cls][ref]): return _db_content[cls][ref][field] else: raise Failure(['HANDLE_INVALID', cls, ref]) LOG.debug('Raising NotImplemented') raise NotImplementedError( _('xenapi.fake does not have an implementation for %s or it has ' 'been called with the wrong number of arguments') % name) def _setter(self, name, params): self._check_session(params) (cls, func) = name.split('.') if len(params) == 3: field = func[len('set_'):] ref = params[1] val = params[2] if (ref in _db_content[cls] and field in _db_content[cls][ref]): _db_content[cls][ref][field] = val return LOG.debug('Raising NotImplemented') raise NotImplementedError( 'xenapi.fake does not have an implementation for %s or it has ' 'been called with the wrong number of arguments or the database ' 'is missing that field' % name) def _create(self, name, params): self._check_session(params) is_sr_create = name == 'SR.create' is_vlan_create = name == 'VLAN.create' # Storage Repositories have a different API expected = is_sr_create and 10 or is_vlan_create and 4 or 2 self._check_arg_count(params, expected) (cls, _) = name.split('.') ref = (is_sr_create and _create_sr(cls, params) or is_vlan_create and _create_vlan(params[1], params[2], params[3]) or _create_object(cls, params[1])) # Call hook to provide any fixups needed (ex. creating backrefs) after_hook = 'after_%s_create' % cls if after_hook in globals(): globals()[after_hook](ref, params[1]) obj = get_record(cls, ref) # Add RO fields if cls == 'VM': obj['power_state'] = 'Halted' return ref def _destroy(self, name, params): self._check_session(params) self._check_arg_count(params, 2) table = name.split('.')[0] ref = params[1] if ref not in _db_content[table]: raise Failure(['HANDLE_INVALID', table, ref]) # Call destroy function (if exists) destroy_func = globals().get('destroy_%s' % table.lower()) if destroy_func: destroy_func(ref) else: del _db_content[table][ref] def _async(self, name, params): task_ref = create_task(name) task = _db_content['task'][task_ref] func = name[len('Async.'):] try: result = self.xenapi_request(func, params[1:]) if result: result = as_value(result) task['result'] = result task['status'] = 'success' except Failure as exc: task['error_info'] = exc.details task['status'] = 'failed' task['finished'] = timeutils.utcnow() return task_ref def _check_session(self, params): if (self._session is None or self._session not in _db_content['session']): raise Failure(['HANDLE_INVALID', 'session', self._session]) if len(params) == 0 or params[0] != self._session: LOG.debug('Raising NotImplemented') raise NotImplementedError('Call to XenAPI without using .xenapi') def _check_arg_count(self, params, expected): actual = len(params) if actual != expected: raise Failure(['MESSAGE_PARAMETER_COUNT_MISMATCH', expected, actual]) def _get_by_field(self, recs, k, v, return_singleton): result = [] for ref, rec in six.iteritems(recs): if rec.get(k) == v: result.append(ref) if return_singleton: try: return result[0] except IndexError: raise Failure(['UUID_INVALID', v, result, recs, k]) return result class FakeXenAPI(object): def __init__(self): self.Failure = Failure # Based upon _Method from xmlrpclib. class _Dispatcher(object): def __init__(self, send, name): self.__send = send self.__name = name def __repr__(self): if self.__name: return '<xenapi.fake._Dispatcher for %s>' % self.__name else: return '<xenapi.fake._Dispatcher>' def __getattr__(self, name): if self.__name is None: return _Dispatcher(self.__send, name) else: return _Dispatcher(self.__send, "%s.%s" % (self.__name, name)) def __call__(self, *args): return self.__send(self.__name, args)
apache-2.0
Simdiva/DSL-Task
evaluate.py
3
3037
# -*- coding: utf-8 -*- import io import sys from collections import Counter red = '\033[01;31m' native = '\033[m' def err_msg(txt): return red + txt + native def language_groups(version=2.0): varieties = {'Portugese': ['pt-BR', 'pt-PT'], 'Spanish': ['es-ES', 'es-AR'], 'English':['en-UK', 'en-US']} similar_languages = {'Malay, Indo':['my', 'id'], 'Czech, Slovak':['cz', 'sk'], 'Bosnian, Croatian, Serbian':['bs', 'hr', 'sr'], 'Bulgarian, Macedonian':['bg','mk'], 'Others':['xx']} if version == 1: similar_languages.pop('Bulgarian, Macedonian') similar_languages.pop('Others') elif version == 2: varieties.pop('English') groups = varieties; groups.update(similar_languages) return groups def breakdown_evaluation(results, goldtags, version=2.0, human_readable=True, overall_only=False): positives = Counter([y for x,y in zip(results,goldtags) if x.lower().replace('_', '-')==y.lower()]) golds = Counter(goldtags) groups = language_groups(version) sum_positives = sum(positives.values()) sum_gold = sum(golds.values()) accuracy = sum_positives / float(sum_gold) if overall_only: output_line = map(str, ['Overall', 'Accuracy', sum_positives, sum_gold, accuracy]) return accuracy bygroup_output = [] if human_readable: print "=== Results === " for g in groups: print print g for l in groups[g]: p = positives[l] gl = golds[l] print "{}: {} / {} = {}".format(l, p, gl, p/float(gl)) print print "Overall:", "{} / {} = {}".format(sum_positives, sum_gold, accuracy) print else: for g in groups: for l in groups[g]: p, gl = positives[l], golds[l] if not overall_only: result_line = '\t'.join(map(str,[g, l, p, gl, p/float(gl)])) bygroup_output.append(result_line) # print '\t'.join(output_line) return bygroup_output def main(system_output, goldfile): results = [i.strip().split('\t')[-1] for i in io.open(system_output, 'r')] goldtags = [i.strip().split('\t')[-1] for i in io.open(goldfile, 'r')] breakdown_evaluation(results, goldtags, version=2.0, human_readable=True) if __name__ == '__main__': if len(sys.argv) != 3: usage_msg = err_msg('Usage: python3 %s system_output goldfile\n' % sys.argv[0]) example_msg = err_msg('Example: python3 %s ~/usaar-dislang-run1-test.txt ' '~/DSLCC-v2.0/gold/test-gold.txt \n' % sys.argv[0]) sys.stderr.write(usage_msg) sys.stderr.write(example_msg) sys.exit(1) main(*sys.argv[1:])
cc0-1.0
rmsk2/Das-grosse-Quiz
client/playingfield.py
1
19375
################################################################################ # Copyright 2016 Martin Grap # # 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 playingfield Contains a class that implements the playing field of "Das grosse Quiz" # # \file playingfield.py # \brief Contains a class that implements the playing field of "Das grosse Quiz". import pickle import questions import displayclient ERR_OK = 0 ERR_ERROR = 42 ## \brief An excpetion class that is used for constructing exception objects in this module. # class PlayingFieldException(Exception): ## \brief An excpetion class that is used for constructing exception objects in this module. # # \param [error_message] Is a string. It has to contain an error message that is to be conveyed to # receiver of the corresponding exception. # def __init__(self, error_message): Exception.__init__(self, 'PlayingField error:' + error_message) ## \brief This class implements the playing field of "Das grosse Quiz". # # The central data structure is a multi level dictionary which is referenced through the self._field member. # The outmost dictionary has the category names as its keys. The values of each of these categories is another # dictionary that has the keys 20, 40, 60, 80, 100. The value of these keys is a third dictionary that has the # keys 'answeredby' and 'wronganswersby'. The value for the 'answeredby' key is either None (when the question has # not been answered yet) or a string which specifies the name of the team that answered the question. The key # 'wronganswersby' has a set() as its value which contains the names of the team(s) that have given a wrong answer # to the question. # class PlayingField: ## \brief Constructor. # # \param [question_repo] An object of type questions.QuestionRepository which holds information about questions, teams # and network configuration. # def __init__(self, question_repo): ## \brief An object of type questions.QuestionRepository. self._repo = question_repo ## \brief A list of strings. Each list element denotes a category. self._categories = self._repo.categories ## \brief A multi level dictionary that holds the playing field information. self._field = {} ## \brief A multi level dictionary that holds the question for each cell in the playing field. self._questions = {} ## \brief A list of strings. Each list element denotes a name of a team. self._teams = self._repo.teams ## \brief An object of type displayclient.SignClient which is used to talk to the displayserver. self._sign_client = displayclient.SignClient(self._repo.config['host'], self._repo.config['port']) ## \brief An object of type questions.Question. It holds the question which is currently displayed by the displayserver. self._current_question = None field_column = {20:None, 40:None, 60:None, 80:None, 100:None} # Initialize the self._field and self._questions dictionaries for i in self._categories: self._field[i] = field_column.copy() self._questions[i] = field_column.copy() # Retrieve all questions the the repository for i in self._categories: for j in [20, 40, 60, 80, 100]: self._questions[i][j] = self._repo.get_question(i, j) self._field[i][j] = {'answeredby':None, 'wronganswersby':set()} ## \brief Returns a reference to the playing field dictionary. # # \returns A dictionary as described in the class documentation. # @property def playing_field(self): return self._field ## \brief Returns a reference to displayserver client object which is in use in this PlayingField instance. # # \returns An object of type displayclient.SignClient. # @property def raspi(self): return self._sign_client ## \brief Returns a string describing the hostname and port which have been specified in the question repository that is used # by this PlayingField instance. # # \returns A string. # @property def server_info(self): return '{}:{}'.format(self._repo.config['host'], self._repo.config['port']) ## \brief Returns a reference to the questions.Question object which represents the question currently displayed by the displaserver. # # \returns An object of type questions.Question or None. # @property def current_question(self): return self._current_question ## \brief This method allows to deserialize the current state of the playing field from a file. # # \param [file_name] A string. Has to contain the name of the file which contains a serialized state. # # \returns A boolean. A return value of True means that reconstructing the state was successfull. # def load_state(self, file_name): result = ERR_OK dumped_playing_field = None try: with open(file_name, 'rb') as f: dumped_playing_field = f.read() restored_playing_field = pickle.loads(dumped_playing_field) for i in self._categories: for j in [20, 40, 60, 80, 100]: for t in restored_playing_field[i][j]['wronganswersby']: if not (t in self.current_teams): raise PlayingFieldException('Loaded state contains unknown team names') # NB: If restored_playing_field[i][j]['answeredby'] contains an unknown team name the question is regarded as # answered by noone. self._field = restored_playing_field self._current_question = None except: result = ERR_ERROR return result ## \brief This method allows to serialize the current state of the playing field into a file. # # \param [file_name] A string. Has to contain the name of the file into which the serialized state should be stored. # # \returns A boolean. A return value of True means that saving the state was successfull. # def save_state(self, file_name): result = ERR_OK try: dumped_playing_field = pickle.dumps(self._field) with open(file_name, 'wb') as f: f.write(dumped_playing_field) except: result = ERR_ERROR return result ## \brief This method clears the state of playing field, i.e. sets all cells to the default value which # means that no question has been answered either right or wrong yet. # # \returns Nothing. # def clear(self): for i in self._categories: for j in [20, 40, 60, 80, 100]: self._field[i][j] = {'answeredby':None, 'wronganswersby':set()} ## \brief This method evaluates the current state of the playing field. It iterates over all cells and sums up the # points earned by each team. A correct answer adds the value of the question to the team result. In case of # a wrong answer the question value is substracted from the team result. # # \returns A dictionary. It maps a string key to an int value. Each key is the name of a team and its value # is the number of points earned by the corresponding team. # def calc_result(self): result = {} for i in self._teams: result[i] = 0 for i in self._categories: for j in [20, 40, 60, 80, 100]: if self._field[i][j]['answeredby'] in self._teams: result[self._field[i][j]['answeredby']] += j for k in self._field[i][j]['wronganswersby']: if k in self._teams: result[k] -= j return result ## \brief This method evaluates the current state of the playing field. It iterates over all cells and counts the # questions which have already been answered. # # \returns An int. # def num_questions_answered(self): result = 0 for i in self._categories: for j in [20, 40, 60, 80, 100]: if self._field[i][j]['answeredby'] != None: result += 1 return result ## \brief Instructs the displayserver to display the intro message and resets the value of self._current_question to None. # # \returns An int. A return value of 0 indicates a successfull execution. # def show_intro(self): self._current_question = None return self._sign_client.show_intro() ## \brief Instructs the displayserver to display the "Thank you" message and resets the value of self._current_question to None. # # \returns An int. A return value of 0 indicates a successfull execution. # def show_thanks(self): self._current_question = None return self._sign_client.show_thanks() ## \brief Instructs the displayserver to display final result message and resets the value of self._current_question to None. # # \returns An int. A return value of 0 indicates a successfull execution. # def show_result(self): self._current_question = None res = self.calc_result() return self._sign_client.show_result(res) ## \brief Instructs the displayserver to display the playing field and resets the value of self._current_question to None. # # \returns An int. A return value of 0 indicates a successfull execution. # def show(self): self._current_question = None return self._sign_client.show_playing_field(self._field) ## \brief Records that a team has answered a question correctly. If the question has already been answered this method # does nothing. # # \param [category] A string. Denotes the category of the question that has been answered correctly. # # \param [value] An int. Denotes the value of the question that has been answered correctly. # # \param [who_answered] A string. Specifies the name of the team which has answered the question correctly. # # \returns Nothing. # def answer_question(self, category, value, who_answered): if (self._field[category][value]['answeredby'] == None) and (who_answered not in self._field[category][value]['wronganswersby']): self._field[category][value]['answeredby'] = who_answered self._current_question = None ## \brief Resets the state of a question to its default value (no correct and no wrong answers). # # \param [category] A string. Denotes the category of the question that has been answered correctly. # # \param [value] An int. Denotes the value of the question that has been answered correctly. # # \returns Nothing. # def clear_question(self, category, value): self._field[category][value]['answeredby'] = None self._field[category][value]['wronganswersby'] = set() self._current_question = None ## \brief Records that a team has given a wrong answer to a question. If the question has already been answered this method # does nothing. # # \param [category] A string. Denotes the category of the question that has been answered wrongly. # # \param [value] An int. Denotes the value of the question that has been answered wrongly. # # \param [who_answered] A string. Specifies the name of the team which has answered the question wrongly. # # \returns Nothing. # def wrong_answer_question(self, category, value, who_answered): if self._field[category][value]['answeredby'] == None: self._field[category][value]['wronganswersby'].add(who_answered) ## \brief Records that a team has answered the current question correctly. If the question has already been answered this method # does nothing. Additionaly this method instructs the displayserver to show the playing field again. The current question # is also reset to None. # # \param [who_answered] A string. Specifies the name of the team which has answered the question correctly. # # \returns An int. A value of 0 indicates that displaying the playing field was successfull. # def answer_current_question(self, who_answered): result = ERR_OK if self._current_question != None: c = self._current_question.category v = self._current_question.value if (self._field[c][v]['answeredby'] == None) and (who_answered not in self._field[c][v]['wronganswersby']): self.answer_question(c, v, who_answered) result = self.show() return result ## \brief Resets the state of the current question to its default value (no correct and no wrong answers). Additionaly this method instructs # the displayserver to show the playing field again. The current question is also reset to None. # # \returns An int. A value of 0 indicates that displaying the playing field was successfull. # def clear_current_question(self): result = ERR_OK if self._current_question != None: self.clear_question(self._current_question.category, self._current_question.value) result = self.show() return result ## \brief Records that a team has answered the current question wrongly. If the question has already been answered this method # does nothing. # # \param [who_answered] A string. Specifies the name of the team which has given a wrong answer. # # \returns Nothing. # def wrong_answer_current_question(self, who_answered): if self._current_question != None: self.wrong_answer_question(self._current_question.category, self._current_question.value, who_answered) ## \brief Returns the category names in use in this PlayingField instance. # # \returns A list of strings. The strings denote the category names and the list is sorted. # @property def current_categories(self): result = self._categories[:] result.sort() return result ## \brief Returns the names of the three teams names in use in this PlayingField instance. # # \returns A list of strings. The strings denote the team names and the list is sorted. # @property def current_teams(self): result = self._teams[:] result.sort() return result ## \brief Returns the name of the team that has answered the specified question correctly. # # \param [category] A string. Denotes the category of the question for which the answer information is to be retrieved. # # \param [value] An int. Denotes the value of the question for which the answer information is to be retrieved. # # \returns A string. The name of the team which has given a correct answer or None in case the question # has not been answered yet. # def question_answered_by(self, category, value): return self._field[category][value]['answeredby'] ## \brief Returns the names of the teams that have given a wrong answer to the specified question. # # \param [category] A string. Denotes the category of the question for which the answer information is to be retrieved. # # \param [value] An int. Denotes the value of the question for which the answer information is to be retrieved. # # \returns A set of strings. The set contains the names of the teams which have given a wrong answer. # def question_answered_wrong_by(self, category, value): return self._field[category][value]['wronganswersby'] ## \brief This method instructs the display server to show a certain question. This question then becomes the current question # and the time value which specifies how many seconds remain to answer the question is set to its start value. # # \param [category] A string. Denotes the category of the question which is to become the current question. # # \param [value] An int. Denotes the value of the question which is to become the current question. # # \returns An int. A value of 0 indicates that displaying the question was successfull. # def ask_question(self, category, value): question = self._questions[category][value] time = question.time_allowance if not question.show_time: time = -1 self._current_question = question self._current_question.reset() return self._sign_client.show_question(question.text, time) ## \brief This method decrements the number of seconds that remain to answer the current question and updates the display to # reflect the changed timer value. # # \returns An int. A value of 0 indicates that displaying the question was successfull. # def decrement_question_time(self): result = ERR_OK # Check if there is a valid current question, that its timer value is positive and that a time value should be displayed if (self._current_question != None) and (self._current_question.current_time > 0) and (self._current_question.show_time): self._current_question.current_time -= 1 result = self._sign_client.show_question(self._current_question.text, self._current_question.current_time) return result
apache-2.0
samfpetersen/gnuradio
gr-qtgui/python/qtgui/__init__.py
15
1183
# # Copyright 2011 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio 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, or (at your option) # any later version. # # GNU Radio 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 GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # ''' Provides a GUI interface using the QT backend. ''' # The presence of this file turns this directory into a Python package import os try: from qtgui_swig import * except ImportError: dirname, filename = os.path.split(os.path.abspath(__file__)) __path__.append(os.path.join(dirname, "..", "..", "swig")) from qtgui_swig import * from range import Range, RangeWidget import util
gpl-3.0
GabrielNicolasAvellaneda/dd-agent
checks.d/pgbouncer.py
14
6682
"""Pgbouncer check Collects metrics from the pgbouncer database. """ # 3p import psycopg2 as pg # project from checks import AgentCheck, CheckException class ShouldRestartException(Exception): pass class PgBouncer(AgentCheck): """Collects metrics from pgbouncer """ RATE = AgentCheck.rate GAUGE = AgentCheck.gauge DB_NAME = 'pgbouncer' SERVICE_CHECK_NAME = 'pgbouncer.can_connect' STATS_METRICS = { 'descriptors': [ ('database', 'db'), ], 'metrics': { 'total_requests': ('pgbouncer.stats.requests_per_second', RATE), 'total_received': ('pgbouncer.stats.bytes_received_per_second', RATE), 'total_sent': ('pgbouncer.stats.bytes_sent_per_second', RATE), 'total_query_time': ('pgbouncer.stats.total_query_time', GAUGE), 'avg_req': ('pgbouncer.stats.avg_req', GAUGE), 'avg_recv': ('pgbouncer.stats.avg_recv', GAUGE), 'avg_sent': ('pgbouncer.stats.avg_sent', GAUGE), 'avg_query': ('pgbouncer.stats.avg_query', GAUGE), }, 'query': """SHOW STATS""", } POOLS_METRICS = { 'descriptors': [ ('database', 'db'), ('user', 'user'), ], 'metrics': { 'cl_active': ('pgbouncer.pools.cl_active', GAUGE), 'cl_waiting': ('pgbouncer.pools.cl_waiting', GAUGE), 'sv_active': ('pgbouncer.pools.sv_active', GAUGE), 'sv_idle': ('pgbouncer.pools.sv_idle', GAUGE), 'sv_used': ('pgbouncer.pools.sv_used', GAUGE), 'sv_tested': ('pgbouncer.pools.sv_tested', GAUGE), 'sv_login': ('pgbouncer.pools.sv_login', GAUGE), 'maxwait': ('pgbouncer.pools.maxwait', GAUGE), }, 'query': """SHOW POOLS""", } def __init__(self, name, init_config, agentConfig, instances=None): AgentCheck.__init__(self, name, init_config, agentConfig, instances) self.dbs = {} def _get_service_checks_tags(self, host, port): service_checks_tags = [ "host:%s" % host, "port:%s" % port, "db:%s" % self.DB_NAME ] return service_checks_tags def _collect_stats(self, db, instance_tags): """Query pgbouncer for various metrics """ metric_scope = [self.STATS_METRICS, self.POOLS_METRICS] try: cursor = db.cursor() for scope in metric_scope: cols = scope['metrics'].keys() try: query = scope['query'] self.log.debug("Running query: %s" % query) cursor.execute(query) results = cursor.fetchall() except pg.Error, e: self.log.warning("Not all metrics may be available: %s" % str(e)) continue for row in results: if row[0] == self.DB_NAME: continue desc = scope['descriptors'] assert len(row) == len(cols) + len(desc) tags = instance_tags[:] tags += ["%s:%s" % (d[0][1], d[1]) for d in zip(desc, row[:len(desc)])] values = zip([scope['metrics'][c] for c in cols], row[len(desc):]) [v[0][1](self, v[0][0], v[1], tags=tags) for v in values] if not results: self.warning('No results were found for query: "%s"' % query) cursor.close() except pg.Error, e: self.log.error("Connection error: %s" % str(e)) raise ShouldRestartException def _get_connection(self, key, host, port, user, password, use_cached=True): "Get and memoize connections to instances" if key in self.dbs and use_cached: return self.dbs[key] elif host != "" and user != "": try: if host == 'localhost' and password == '': # Use ident method connection = pg.connect("user=%s dbname=%s" % (user, self.DB_NAME)) elif port != '': connection = pg.connect(host=host, port=port, user=user, password=password, database=self.DB_NAME) else: connection = pg.connect(host=host, user=user, password=password, database=self.DB_NAME) connection.set_isolation_level(pg.extensions.ISOLATION_LEVEL_AUTOCOMMIT) self.log.debug('pgbouncer status: %s' % AgentCheck.OK) except Exception: message = u'Cannot establish connection to pgbouncer://%s:%s/%s' % (host, port, self.DB_NAME) self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL, tags=self._get_service_checks_tags(host, port), message=message) self.log.debug('pgbouncer status: %s' % AgentCheck.CRITICAL) raise else: if not host: raise CheckException("Please specify a PgBouncer host to connect to.") elif not user: raise CheckException("Please specify a user to connect to PgBouncer as.") self.dbs[key] = connection return connection def check(self, instance): host = instance.get('host', '') port = instance.get('port', '') user = instance.get('username', '') password = instance.get('password', '') tags = instance.get('tags', []) key = '%s:%s' % (host, port) if tags is None: tags = [] else: tags = list(set(tags)) try: db = self._get_connection(key, host, port, user, password) self._collect_stats(db, tags) except ShouldRestartException: self.log.info("Resetting the connection") db = self._get_connection(key, host, port, user, password, use_cached=False) self._collect_stats(db, tags) message = u'Established connection to pgbouncer://%s:%s/%s' % (host, port, self.DB_NAME) self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.OK, tags=self._get_service_checks_tags(host, port), message=message) self.log.debug('pgbouncer status: %s' % AgentCheck.OK)
bsd-3-clause
trabacus-softapps/openerp-8.0-cc
openerp/addons/hw_escpos/escpos/printer.py
71
3770
#!/usr/bin/python ''' @author: Manuel F Martinez <manpaz@bashlinux.com> @organization: Bashlinux @copyright: Copyright (c) 2012 Bashlinux @license: GPL ''' import usb.core import usb.util import serial import socket from escpos import * from constants import * from exceptions import * class Usb(Escpos): """ Define USB printer """ def __init__(self, idVendor, idProduct, interface=0, in_ep=0x82, out_ep=0x01): """ @param idVendor : Vendor ID @param idProduct : Product ID @param interface : USB device interface @param in_ep : Input end point @param out_ep : Output end point """ self.idVendor = idVendor self.idProduct = idProduct self.interface = interface self.in_ep = in_ep self.out_ep = out_ep self.open() def open(self): """ Search device on USB tree and set is as escpos device """ self.device = usb.core.find(idVendor=self.idVendor, idProduct=self.idProduct) if self.device is None: print "Cable isn't plugged in" if self.device.is_kernel_driver_active(0): try: self.device.detach_kernel_driver(0) except usb.core.USBError as e: print "Could not detatch kernel driver: %s" % str(e) try: self.device.set_configuration() self.device.reset() except usb.core.USBError as e: print "Could not set configuration: %s" % str(e) def _raw(self, msg): """ Print any command sent in raw format """ self.device.write(self.out_ep, msg, self.interface) def __del__(self): """ Release USB interface """ if self.device: usb.util.dispose_resources(self.device) self.device = None class Serial(Escpos): """ Define Serial printer """ def __init__(self, devfile="/dev/ttyS0", baudrate=9600, bytesize=8, timeout=1): """ @param devfile : Device file under dev filesystem @param baudrate : Baud rate for serial transmission @param bytesize : Serial buffer size @param timeout : Read/Write timeout """ self.devfile = devfile self.baudrate = baudrate self.bytesize = bytesize self.timeout = timeout self.open() def open(self): """ Setup serial port and set is as escpos device """ self.device = serial.Serial(port=self.devfile, baudrate=self.baudrate, bytesize=self.bytesize, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=self.timeout, dsrdtr=True) if self.device is not None: print "Serial printer enabled" else: print "Unable to open serial printer on: %s" % self.devfile def _raw(self, msg): """ Print any command sent in raw format """ self.device.write(msg) def __del__(self): """ Close Serial interface """ if self.device is not None: self.device.close() class Network(Escpos): """ Define Network printer """ def __init__(self,host,port=9100): """ @param host : Printer's hostname or IP address @param port : Port to write to """ self.host = host self.port = port self.open() def open(self): """ Open TCP socket and set it as escpos device """ self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.device.connect((self.host, self.port)) if self.device is None: print "Could not open socket for %s" % self.host def _raw(self, msg): self.device.send(msg) def __del__(self): """ Close TCP connection """ self.device.close()
agpl-3.0
mozilla/verbatim
vendor/lib/python/django/forms/util.py
83
3358
from django.conf import settings from django.utils.html import conditional_escape from django.utils.encoding import StrAndUnicode, force_unicode from django.utils.safestring import mark_safe from django.utils import timezone from django.utils.translation import ugettext_lazy as _ # Import ValidationError so that it can be imported from this # module to maintain backwards compatibility. from django.core.exceptions import ValidationError def flatatt(attrs): """ Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. """ return u''.join([u' %s="%s"' % (k, conditional_escape(v)) for k, v in attrs.items()]) class ErrorDict(dict, StrAndUnicode): """ A collection of errors that knows how to display itself in various formats. The dictionary keys are the field names, and the values are the errors. """ def __unicode__(self): return self.as_ul() def as_ul(self): if not self: return u'' return mark_safe(u'<ul class="errorlist">%s</ul>' % ''.join([u'<li>%s%s</li>' % (k, conditional_escape(force_unicode(v))) for k, v in self.items()])) def as_text(self): return u'\n'.join([u'* %s\n%s' % (k, u'\n'.join([u' * %s' % force_unicode(i) for i in v])) for k, v in self.items()]) class ErrorList(list, StrAndUnicode): """ A collection of errors that knows how to display itself in various formats. """ def __unicode__(self): return self.as_ul() def as_ul(self): if not self: return u'' return mark_safe(u'<ul class="errorlist">%s</ul>' % ''.join([u'<li>%s</li>' % conditional_escape(force_unicode(e)) for e in self])) def as_text(self): if not self: return u'' return u'\n'.join([u'* %s' % force_unicode(e) for e in self]) def __repr__(self): return repr([force_unicode(e) for e in self]) # Utilities for time zone support in DateTimeField et al. def from_current_timezone(value): """ When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes. """ if settings.USE_TZ and value is not None and timezone.is_naive(value): current_timezone = timezone.get_current_timezone() try: return timezone.make_aware(value, current_timezone) except Exception, e: raise ValidationError(_('%(datetime)s couldn\'t be interpreted ' 'in time zone %(current_timezone)s; it ' 'may be ambiguous or it may not exist.') % {'datetime': value, 'current_timezone': current_timezone}) return value def to_current_timezone(value): """ When time zone support is enabled, convert aware datetimes to naive dateimes in the current time zone for display. """ if settings.USE_TZ and value is not None and timezone.is_aware(value): current_timezone = timezone.get_current_timezone() return timezone.make_naive(value, current_timezone) return value
gpl-2.0
tcstewar/embodied_benchmarks
control.py
1
3938
import numpy as np class Signal(object): def __init__(self, D, L, dt, max_freq, seed=None): rng = np.random.RandomState(seed=seed) steps = int(max_freq * L) self.w = 2 * np.pi * np.arange(steps) / L self.A = rng.randn(D, steps) + 1.0j * rng.randn(D, steps) power = np.sqrt(np.sum(self.A * self.A.conj())) self.A /= power def value(self, t): s = np.sin(self.w * t) * self.A return np.sum(s, axis=1).real def dvalue(self, t): s = np.cos(self.w * t) * self.w * self.A return np.sum(s, axis=1).real class Environment(object): def __init__(self, seed=None): self.rng = np.random.RandomState(seed=seed) class LinearSystem(Environment): def __init__(self, d_controlled, d_motor, dt=0.001, seed=None, scale_mult=10, scale_add=10, diagonal=False, max_sense_noise=0.1, max_motor_noise=0.1, period=5.0, max_freq=1.0): super(LinearSystem, self).__init__(seed=seed) self.d_motor = d_motor self.d_controlled = d_controlled self.dt = dt self.state = self.rng.randn(d_controlled) if diagonal: assert d_controlled == d_motor self.J = np.abs(np.diag(self.rng.randn(d_motor))) * scale_mult else: self.J = self.rng.randn(d_motor, d_controlled) * scale_mult self.sense_noise = self.rng.uniform(0, max_sense_noise) self.motor_noise = self.rng.uniform(0, max_motor_noise) self.additive = self.rng.rand(d_controlled) * scale_add def step(self, motor): motor = motor + self.rng.randn(self.d_motor) * self.motor_noise dstate = (np.dot(motor, self.J) + self.additive) * self.dt self.state = self.state + dstate return self.state + self.rng.randn(self.d_controlled) * self.sense_noise class Controller(object): pass class PID(Controller): def __init__(self, Kp, Kd=0, Ki=0, J=None, tau_d=0.1, dt=0.001): self.Kp = Kp self.Kd = Kd self.Ki = Ki if J is not None: x = np.dot(J.T, J) scale = np.linalg.det(x) ** (1.0 / x.shape[0]) self.JT = J.T / scale else: self.JT = None self.prev_state = None self.dstate = None self.istate = None self.scale = np.exp(-dt / tau_d) self.dt = dt def step(self, state, desired_state): if self.prev_state is None: self.prev_state = None self.dstate = np.zeros_like(state) self.istate = np.zeros_like(state) else: d = state - self.prev_state self.dstate = self.dstate * self.scale + d * (1.0 - self.scale) self.istate += self.dt * (desired_state - state) v = (self.Kp * (desired_state - state) + self.Kd * (-self.dstate) + self.Ki * self.istate) if self.JT is not None: v = np.dot(v, self.JT) return v if __name__ == '__main__': D_state = 3 D_motor = 5 dt = 0.001 env = LinearSystem(d_controlled=D_state, d_motor=D_motor, diagonal=False, scale_add=5) ctrl = PID(100, 10, 1000, J=env.J) desired_state = Signal(D_state, L=3.0, dt=dt, max_freq=2.0) T = 6.0 steps = int(T / dt) t = np.arange(steps) * dt state = np.zeros((D_state, steps), dtype=float) desired = np.zeros((D_state, steps), dtype=float) sense = np.zeros((D_state, steps), dtype=float) m = np.zeros(D_motor, dtype=float) for i in range(steps): desired[:,i] = desired_state.value(t[i]) s = env.step(m) m = ctrl.step(s, desired[:,i]) state[:,i] = env.state sense[:,i] = s import pylab pylab.plot(t, state.T, label='state') pylab.plot(t, desired.T, label='desired') #pylab.plot(sense.T, label='sense') #pylab.legend(loc='best') pylab.show()
gpl-2.0
wemanuel/smry
smry/Crypto/Hash/CMAC.py
5
11991
# -*- coding: utf-8 -*- # # Hash/CMAC.py - Implements the CMAC algorithm # # =================================================================== # The contents of this file are dedicated to the public domain. To # the extent that dedication to the public domain is not available, # everyone is granted a worldwide, perpetual, royalty-free, # non-exclusive license to exercise all rights associated with the # contents of this file for any purpose whatsoever. # No rights are reserved. # # 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. # =================================================================== """CMAC (Cipher-based Message Authentication Code) algorithm CMAC is a MAC defined in `NIST SP 800-38B`_ and in RFC4493_ (for AES only) and constructed using a block cipher. It was originally known as `OMAC1`_. The algorithm is sometimes named *X-CMAC* where *X* is the name of the cipher (e.g. AES-CMAC). This is an example showing how to *create* an AES-CMAC: >>> from Crypto.Hash import CMAC >>> from Crypto.Cipher import AES >>> >>> secret = b'Sixteen byte key' >>> cobj = CMAC.new(secret, ciphermod=AES) >>> cobj.update(b'Hello') >>> print cobj.hexdigest() And this is an example showing how to *check* an AES-CMAC: >>> from Crypto.Hash import CMAC >>> from Crypto.Cipher import AES >>> >>> # We have received a message 'msg' together >>> # with its MAC 'mac' >>> >>> secret = b'Sixteen byte key' >>> cobj = CMAC.new(secret, ciphermod=AES) >>> cobj.update(msg) >>> try: >>> cobj.verify(mac) >>> print "The message '%s' is authentic" % msg >>> except ValueError: >>> print "The message or the key is wrong" .. _`NIST SP 800-38B`: http://csrc.nist.gov/publications/nistpubs/800-38B/SP_800-38B.pdf .. _RFC4493: http://www.ietf.org/rfc/rfc4493.txt .. _OMAC1: http://www.nuee.nagoya-u.ac.jp/labs/tiwata/omac/omac.html """ __all__ = ['new', 'digest_size', 'CMAC' ] import sys if sys.version_info[0] == 2 and sys.version_info[1] == 1: from Crypto.Util.py21compat import * from Crypto.Util.py3compat import * from binascii import unhexlify from Crypto.Util.strxor import strxor from Crypto.Util.number import long_to_bytes, bytes_to_long #: The size of the authentication tag produced by the MAC. digest_size = None def _shift_bytes(bs, xor_lsb=0): num = (bytes_to_long(bs)<<1) ^ xor_lsb return long_to_bytes(num, len(bs))[-len(bs):] class _SmoothMAC(object): """Turn a MAC that only operates on aligned blocks of data into a MAC with granularity of 1 byte.""" def __init__(self, block_size, msg=b(""), min_digest=0): self._bs = block_size #: Data waiting to be MAC-ed self._buffer = [] self._buffer_len = 0 #: Data received via update() self._total_len = 0 #: Minimum amount of bytes required by the final digest step self._min_digest = min_digest #: Block MAC object self._mac = None #: Cached digest self._tag = None if msg: self.update(msg) def can_reduce(self): return (self._mac is not None) def get_len(self): return self._total_len def zero_pad(self): if self._buffer_len & (self._bs-1): npad = self._bs - self._buffer_len & (self._bs-1) self._buffer.append(bchr(0)*npad) self._buffer_len += npad def update(self, data): # Optimization (try not to copy data if possible) if self._buffer_len==0 and self.can_reduce() and\ self._min_digest==0 and len(data)%self._bs==0: self._update(data) self._total_len += len(data) return self._buffer.append(data) self._buffer_len += len(data) self._total_len += len(data) # Feed data into MAC blocks, rem = divmod(self._buffer_len, self._bs) if rem<self._min_digest: blocks -= 1 if blocks>0 and self.can_reduce(): aligned_data = blocks*self._bs buf = b("").join(self._buffer) self._update(buf[:aligned_data]) self._buffer = [ buf[aligned_data:] ] self._buffer_len -= aligned_data def _deep_copy(self, target): # Copy everything by self._mac, since we don't know how to target._buffer = self._buffer[:] for m in [ '_bs', '_buffer_len', '_total_len', '_min_digest', '_tag' ]: setattr(target, m, getattr(self, m)) def _update(self, data_block): """Delegate to the implementation the update of the MAC state given some new *block aligned* data.""" raise NotImplementedError("_update() must be still implemented") def _digest(self, left_data): """Delegate to the implementation the computation of the final MAC given the current MAC state and the last piece of data (not block aligned).""" raise NotImplementedError("_digest() must be still implemented") def digest(self): if self._tag: return self._tag if self._buffer_len>0: self.update(b("")) left_data = b("").join(self._buffer) self._tag = self._digest(left_data) return self._tag class CMAC(_SmoothMAC): """Class that implements CMAC""" #: The size of the authentication tag produced by the MAC. digest_size = None def __init__(self, key, msg = None, ciphermod = None): """Create a new CMAC object. :Parameters: key : byte string secret key for the CMAC object. The key must be valid for the underlying cipher algorithm. For instance, it must be 16 bytes long for AES-128. msg : byte string The very first chunk of the message to authenticate. It is equivalent to an early call to `update`. Optional. ciphermod : module A cipher module from `Crypto.Cipher`. The cipher's block size must be 64 or 128 bits. It is recommended to use `Crypto.Cipher.AES`. """ if ciphermod is None: raise TypeError("ciphermod must be specified (try AES)") _SmoothMAC.__init__(self, ciphermod.block_size, msg, 1) self._key = key self._factory = ciphermod # Section 5.3 of NIST SP 800 38B if ciphermod.block_size==8: const_Rb = 0x1B elif ciphermod.block_size==16: const_Rb = 0x87 else: raise TypeError("CMAC requires a cipher with a block size of 8 or 16 bytes, not %d" % (ciphermod.block_size,)) self.digest_size = ciphermod.block_size # Compute sub-keys cipher = ciphermod.new(key, ciphermod.MODE_ECB) l = cipher.encrypt(bchr(0)*ciphermod.block_size) if bord(l[0]) & 0x80: self._k1 = _shift_bytes(l, const_Rb) else: self._k1 = _shift_bytes(l) if bord(self._k1[0]) & 0x80: self._k2 = _shift_bytes(self._k1, const_Rb) else: self._k2 = _shift_bytes(self._k1) # Initialize CBC cipher with zero IV self._IV = bchr(0)*ciphermod.block_size self._mac = ciphermod.new(key, ciphermod.MODE_CBC, self._IV) def update(self, msg): """Continue authentication of a message by consuming the next chunk of data. Repeated calls are equivalent to a single call with the concatenation of all the arguments. In other words: >>> m.update(a); m.update(b) is equivalent to: >>> m.update(a+b) :Parameters: msg : byte string The next chunk of the message being authenticated """ _SmoothMAC.update(self, msg) def _update(self, data_block): self._IV = self._mac.encrypt(data_block)[-self._mac.block_size:] def copy(self): """Return a copy ("clone") of the MAC object. The copy will have the same internal state as the original MAC object. This can be used to efficiently compute the MAC of strings that share a common initial substring. :Returns: A `CMAC` object """ obj = CMAC(self._key, ciphermod=self._factory) _SmoothMAC._deep_copy(self, obj) obj._mac = self._factory.new(self._key, self._factory.MODE_CBC, self._IV) for m in [ '_tag', '_k1', '_k2', '_IV']: setattr(obj, m, getattr(self, m)) return obj def digest(self): """Return the **binary** (non-printable) MAC of the message that has been authenticated so far. This method does not change the state of the MAC object. You can continue updating the object after calling this function. :Return: A byte string of `digest_size` bytes. It may contain non-ASCII characters, including null bytes. """ return _SmoothMAC.digest(self) def _digest(self, last_data): if len(last_data)==self._bs: last_block = strxor(last_data, self._k1) else: last_block = strxor(last_data+bchr(128)+ bchr(0)*(self._bs-1-len(last_data)), self._k2) tag = self._mac.encrypt(last_block) return tag def hexdigest(self): """Return the **printable** MAC of the message that has been authenticated so far. This method does not change the state of the MAC object. :Return: A string of 2* `digest_size` bytes. It contains only hexadecimal ASCII digits. """ return "".join(["%02x" % bord(x) for x in tuple(self.digest())]) def verify(self, mac_tag): """Verify that a given **binary** MAC (computed by another party) is valid. :Parameters: mac_tag : byte string The expected MAC of the message. :Raises ValueError: if the MAC does not match. It means that the message has been tampered with or that the MAC key is incorrect. """ mac = self.digest() res = 0 # Constant-time comparison for x,y in zip(mac, mac_tag): res |= bord(x) ^ bord(y) if res or len(mac_tag)!=self.digest_size: raise ValueError("MAC check failed") def hexverify(self, hex_mac_tag): """Verify that a given **printable** MAC (computed by another party) is valid. :Parameters: hex_mac_tag : string The expected MAC of the message, as a hexadecimal string. :Raises ValueError: if the MAC does not match. It means that the message has been tampered with or that the MAC key is incorrect. """ self.verify(unhexlify(tobytes(hex_mac_tag))) def new(key, msg = None, ciphermod = None): """Create a new CMAC object. :Parameters: key : byte string secret key for the CMAC object. The key must be valid for the underlying cipher algorithm. For instance, it must be 16 bytes long for AES-128. msg : byte string The very first chunk of the message to authenticate. It is equivalent to an early call to `CMAC.update`. Optional. ciphermod : module A cipher module from `Crypto.Cipher`. The cipher's block size must be 64 or 128 bits. Default is `Crypto.Cipher.AES`. :Returns: A `CMAC` object """ return CMAC(key, msg, ciphermod)
apache-2.0
gbrmachado/treeherder
treeherder/model/error_summary.py
9
8253
import json import logging import re from django.conf import settings from django.core.urlresolvers import reverse logger = logging.getLogger(__name__) LEAK_RE = re.compile(r'\d+ bytes leaked \((.+)\)$') CRASH_RE = re.compile(r'.+ application crashed \[@ (.+)\]$') MOZHARNESS_RE = re.compile( r'^\d+:\d+:\d+[ ]+(?:DEBUG|INFO|WARNING|ERROR|CRITICAL|FATAL) - [ ]?' ) def get_error_summary(all_errors): """ Transform the error lines into the artifact format. Add bug suggestions if they are found. """ error_summary = [] bugscache_uri = '{0}{1}'.format( settings.API_HOSTNAME, reverse("bugscache-list") ) terms_requested = {} for err in all_errors: # remove the mozharness prefix clean_line = get_mozharness_substring(err['line']) search_terms = [] # get a meaningful search term out of the error line search_term = get_error_search_term(clean_line) bugs = dict(open_recent=[], all_others=[]) # collect open recent and all other bugs suggestions if search_term: search_terms.append(search_term) if search_term not in terms_requested: # retrieve the list of suggestions from the api bugs = get_bugs_for_search_term( search_term, bugscache_uri ) terms_requested[search_term] = bugs else: bugs = terms_requested[search_term] if not bugs or not (bugs['open_recent'] or bugs['all_others']): # no suggestions, try to use # the crash signature as search term crash_signature = get_crash_signature(clean_line) if crash_signature: search_terms.append(crash_signature) if crash_signature not in terms_requested: bugs = get_bugs_for_search_term( crash_signature, bugscache_uri ) terms_requested[crash_signature] = bugs else: bugs = terms_requested[crash_signature] # TODO: Rename 'search' to 'error_text' or similar, since that's # closer to what it actually represents (bug 1091060). error_summary.append({ "search": clean_line, "search_terms": search_terms, "bugs": bugs }) return error_summary def get_mozharness_substring(line): return MOZHARNESS_RE.sub('', line).strip() def get_error_search_term(error_line): """ retrieves bug suggestions from bugscache using search_term in a full_text search. """ if not error_line: return None # This is strongly inspired by # https://hg.mozilla.org/webtools/tbpl/file/tip/php/inc/AnnotatedSummaryGenerator.php#l73 tokens = error_line.split(" | ") search_term = None if len(tokens) >= 3: # it's in the "FAILURE-TYPE | testNameOrFilePath | message" type format. test_name_or_path = tokens[1] message = tokens[2] # Leak failure messages are of the form: # leakcheck | .*\d+ bytes leaked (Object-1, Object-2, Object-3, ...) match = LEAK_RE.search(message) if match: search_term = match.group(1) else: for splitter in ("/", "\\"): # if this is a path, we are interested in the last part test_name_or_path = test_name_or_path.split(splitter)[-1] search_term = test_name_or_path # If the failure line was not in the pipe symbol delimited format or the search term # will likely return too many (or irrelevant) results (eg: too short or matches terms # on the blacklist), then we fall back to searching for the entire failure line if # it is suitable. if not (search_term and is_helpful_search_term(search_term)): if is_helpful_search_term(error_line): search_term = error_line else: search_term = None # Searching for extremely long search terms is undesirable, since: # a) Bugzilla's max summary length is 256 characters, and once "Intermittent " # and platform/suite information is prefixed, there are even fewer characters # left for us to use for the failure string against which we need to match. # b) For long search terms, the additional length does little to prevent against # false positives, but means we're more susceptible to false negatives due to # run-to-run variances in the error messages (eg paths, process IDs). if search_term: search_term = search_term[:100] return search_term def get_crash_signature(error_line): """ Detect if the error_line contains a crash signature and return it if it's a helpful search term """ search_term = None match = CRASH_RE.match(error_line) if match and is_helpful_search_term(match.group(1)): search_term = match.group(1) return search_term def is_helpful_search_term(search_term): # Search terms that will match too many bug summaries # and so not result in useful suggestions. search_term = search_term.strip() blacklist = [ 'automation.py', 'remoteautomation.py', 'Shutdown', 'undefined', 'Main app process exited normally', 'Traceback (most recent call last):', 'Return code: 0', 'Return code: 1', 'Return code: 2', 'Return code: 9', 'Return code: 10', 'Exiting 1', 'Exiting 9', 'CrashingThread(void *)', 'libSystem.B.dylib + 0xd7a', 'linux-gate.so + 0x424', 'TypeError: content is null', 'leakcheck' ] return len(search_term) > 4 and not (search_term in blacklist) def get_bugs_for_search_term(search, base_uri): """ Fetch the base_uri endpoint filtering on search and status. Status must be either 'open' or 'closed' """ from treeherder.etl.common import get_remote_content params = { 'search': search } return get_remote_content(base_uri, params=params) def get_artifacts_that_need_bug_suggestions(artifact_list): """ Return a list of ``text_log_summary`` that don't have ``Bug suggestions`` """ bs_guid_list = [x['job_guid'] for x in artifact_list if x['name'] == 'Bug suggestions'] tls_list = [x for x in artifact_list if x['name'] == 'text_log_summary' and x['job_guid'] not in bs_guid_list] return tls_list def get_error_summary_artifacts(artifact_list): """ Create bug suggestions artifact(s) for any text_log_summary artifacts. ``artifact_list`` here is a list of artifacts that may contain one or more ``text_log_artifact`` objects. If it does, we extract the error lines from it. If there ARE error lines, then we generate the ``bug suggestions`` artifacts and return them. """ bug_suggestion_artifacts = [] for artifact in artifact_list: # this is the only artifact name eligible to trigger generation of bug # suggestions. if artifact['name'] != 'text_log_summary': continue all_errors = get_all_errors(artifact) bug_suggestion_artifacts.append({ "job_guid": artifact['job_guid'], "name": 'Bug suggestions', "type": 'json', "blob": json.dumps(get_error_summary(all_errors)) }) return bug_suggestion_artifacts def get_all_errors(artifact): """Extract the error lines from an artifact's blob field""" artifact_blob = json.loads(artifact['blob']) if isinstance(artifact_blob, dict): return artifact_blob.get('step_data', {}).get('all_errors', []) def load_error_summary(project, artifacts, job_id_lookup): """Load new bug suggestions artifacts if we generate them.""" from treeherder.model.derived import ArtifactsModel bsa = get_error_summary_artifacts(artifacts) if bsa: with ArtifactsModel(project) as artifacts_model: artifacts_model.load_job_artifacts(bsa, job_id_lookup)
mpl-2.0
odoousers2014/LibrERP
product_catalog_extend/report/__init__.py
5
1119
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2011 DeneroTeam. (<http://www.deneroteam.com>) # Copyright (C) 2011 Didotech Inc. (<http://www.didotech.com>) # All Rights Reserved # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import product_catalog_report # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
cloudstax/openmanage
vendor/lambda-python-requests/chardet/eucjpprober.py
289
3749
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is mozilla.org code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library 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; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### from .enums import ProbingState, MachineState from .mbcharsetprober import MultiByteCharSetProber from .codingstatemachine import CodingStateMachine from .chardistribution import EUCJPDistributionAnalysis from .jpcntx import EUCJPContextAnalysis from .mbcssm import EUCJP_SM_MODEL class EUCJPProber(MultiByteCharSetProber): def __init__(self): super(EUCJPProber, self).__init__() self.coding_sm = CodingStateMachine(EUCJP_SM_MODEL) self.distribution_analyzer = EUCJPDistributionAnalysis() self.context_analyzer = EUCJPContextAnalysis() self.reset() def reset(self): super(EUCJPProber, self).reset() self.context_analyzer.reset() @property def charset_name(self): return "EUC-JP" @property def language(self): return "Japanese" def feed(self, byte_str): for i in range(len(byte_str)): # PY3K: byte_str is a byte array, so byte_str[i] is an int, not a byte coding_state = self.coding_sm.next_state(byte_str[i]) if coding_state == MachineState.ERROR: self.logger.debug('%s %s prober hit error at byte %s', self.charset_name, self.language, i) self._state = ProbingState.NOT_ME break elif coding_state == MachineState.ITS_ME: self._state = ProbingState.FOUND_IT break elif coding_state == MachineState.START: char_len = self.coding_sm.get_current_charlen() if i == 0: self._last_char[1] = byte_str[0] self.context_analyzer.feed(self._last_char, char_len) self.distribution_analyzer.feed(self._last_char, char_len) else: self.context_analyzer.feed(byte_str[i - 1:i + 1], char_len) self.distribution_analyzer.feed(byte_str[i - 1:i + 1], char_len) self._last_char[0] = byte_str[-1] if self.state == ProbingState.DETECTING: if (self.context_analyzer.got_enough_data() and (self.get_confidence() > self.SHORTCUT_THRESHOLD)): self._state = ProbingState.FOUND_IT return self.state def get_confidence(self): context_conf = self.context_analyzer.get_confidence() distrib_conf = self.distribution_analyzer.get_confidence() return max(context_conf, distrib_conf)
apache-2.0
mariodebian/jclic-browser
python-examples/demo.py
1
3681
# This is an example for demonstrating use of the GtkTreeView widget. # The code in this example is not particularly good: it is written to # concentrate on widget usage demonstration, not for maintainability. import pygtk pygtk.require("2.0") import gtk import gobject view = None choose_parent_view = None dialog = None def move(old_iter, new_parent, model): if old_iter: folder = model.get_value(old_iter, 0) model.remove(old_iter) new_iter = model.insert_before(new_parent, None) model.set_value(new_iter, 0, folder) model.set_value(new_iter, 1, folder["name"]) def dialog_ok(*args): dialog.hide() model, parent_iter = choose_parent_view.get_selection().get_selected() model, old_iter = view.get_selection().get_selected() if parent_iter and old_iter: move(old_iter, parent_iter, model) def dialog_cancel(*args): dialog.hide() def choose_parent(*args): dialog.show() def move_to_top(*args): model, old_iter = view.get_selection().get_selected() if old_iter: move(old_iter, None, model) def quit(*args): gtk.main_quit() def make_view(model): # Create the view itself. view = gtk.TreeView(model) renderer = gtk.CellRendererText() column = gtk.TreeViewColumn("Folder", renderer, text=1) view.append_column(column) view.show() # Create scrollbars around the view. scrolled = gtk.ScrolledWindow() scrolled.add(view) scrolled.show() return view, scrolled def make_buttons(list): buttonbox = gtk.HBox() for label, func in list: button = gtk.Button() button.set_label(label) button.connect("clicked", func) button.show() buttonbox.pack_start(button, expand=gtk.FALSE, fill=gtk.FALSE) buttonbox.show() return buttonbox def main(): # Create the model. model = gtk.TreeStore(gobject.TYPE_PYOBJECT, gobject.TYPE_STRING) # Populate the model with data. We represent folders with Python # dicts (hash tables or hashmaps in other languages), for simplicity. # In a real program, they would be programmer defined classes. for i in range(100): folder = { "name": "folder %d" % i, "files": ["foo", "bar"] } iter = model.insert_before(None, None) model.set_value(iter, 0, folder) model.set_value(iter, 1, folder["name"]) # Create the main view. global view view, scrolled = make_view(model) view.set_reorderable(gtk.TRUE) # Create some command buttons. buttonbox = make_buttons([("Quit", quit), ("Choose parent", choose_parent), ("Move to top", move_to_top)]) # Create a vertical box to hold the above stuff. vbox = gtk.VBox() vbox.pack_start(buttonbox, expand=gtk.FALSE, fill=gtk.FALSE) vbox.pack_start(scrolled, expand=gtk.TRUE, fill=gtk.TRUE) vbox.show() # Create toplevel window to show it all. win = gtk.Window(gtk.WINDOW_TOPLEVEL) win.connect("delete_event", quit) win.add(vbox) win.show() win.resize(300, 500) # Create the GtkTreeView for choosing a parent. global choose_parent_view choose_parent_view, scrolled = make_view(model) buttonbox = make_buttons([("OK", dialog_ok), ("Cancel", dialog_cancel)]) vbox = gtk.VBox() vbox.pack_start(scrolled, expand=gtk.TRUE, fill=gtk.TRUE) vbox.pack_start(buttonbox, expand=gtk.FALSE, fill=gtk.FALSE) vbox.show() global dialog dialog = gtk.Window(gtk.WINDOW_TOPLEVEL) dialog.set_default_size(200, 400) dialog.add(vbox) # Run the Gtk+ main loop. gtk.main() if __name__ == "__main__": main()
gpl-2.0
mixturemodel-flow/tensorflow
tensorflow/python/saved_model/saved_model.py
102
1626
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Convenience functions to save a model. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import from tensorflow.python.saved_model import builder from tensorflow.python.saved_model import constants from tensorflow.python.saved_model import loader from tensorflow.python.saved_model import main_op from tensorflow.python.saved_model import signature_constants from tensorflow.python.saved_model import signature_def_utils from tensorflow.python.saved_model import tag_constants from tensorflow.python.saved_model import utils # pylint: enable=unused-import from tensorflow.python.util.all_util import remove_undocumented _allowed_symbols = [ "builder", "constants", "loader", "main_op", "signature_constants", "signature_def_utils", "tag_constants", "utils", ] remove_undocumented(__name__, _allowed_symbols)
apache-2.0
riteshshrv/django
tests/utils_tests/test_jslex.py
169
9708
# -*- coding: utf-8 -*- """Tests for jslex.""" # originally from https://bitbucket.org/ned/jslex from __future__ import unicode_literals from django.test import SimpleTestCase from django.utils.jslex import JsLexer, prepare_js_for_gettext class JsTokensTest(SimpleTestCase): LEX_CASES = [ # ids ("a ABC $ _ a123", ["id a", "id ABC", "id $", "id _", "id a123"]), ("\\u1234 abc\\u0020 \\u0065_\\u0067", ["id \\u1234", "id abc\\u0020", "id \\u0065_\\u0067"]), # numbers ("123 1.234 0.123e-3 0 1E+40 1e1 .123", ["dnum 123", "dnum 1.234", "dnum 0.123e-3", "dnum 0", "dnum 1E+40", "dnum 1e1", "dnum .123"]), ("0x1 0xabCD 0XABcd", ["hnum 0x1", "hnum 0xabCD", "hnum 0XABcd"]), ("010 0377 090", ["onum 010", "onum 0377", "dnum 0", "dnum 90"]), ("0xa123ghi", ["hnum 0xa123", "id ghi"]), # keywords ("function Function FUNCTION", ["keyword function", "id Function", "id FUNCTION"]), ("const constructor in inherits", ["keyword const", "id constructor", "keyword in", "id inherits"]), ("true true_enough", ["reserved true", "id true_enough"]), # strings (''' 'hello' "hello" ''', ["string 'hello'", 'string "hello"']), (r""" 'don\'t' "don\"t" '"' "'" '\'' "\"" """, [r"""string 'don\'t'""", r'''string "don\"t"''', r"""string '"'""", r'''string "'"''', r"""string '\''""", r'''string "\""''']), (r'"ƃuıxǝ⅂ ʇdıɹɔsɐʌɐſ\""', [r'string "ƃuıxǝ⅂ ʇdıɹɔsɐʌɐſ\""']), # comments ("a//b", ["id a", "linecomment //b"]), ("/****/a/=2//hello", ["comment /****/", "id a", "punct /=", "dnum 2", "linecomment //hello"]), ("/*\n * Header\n */\na=1;", ["comment /*\n * Header\n */", "id a", "punct =", "dnum 1", "punct ;"]), # punctuation ("a+++b", ["id a", "punct ++", "punct +", "id b"]), # regex (r"a=/a*/,1", ["id a", "punct =", "regex /a*/", "punct ,", "dnum 1"]), (r"a=/a*[^/]+/,1", ["id a", "punct =", "regex /a*[^/]+/", "punct ,", "dnum 1"]), (r"a=/a*\[^/,1", ["id a", "punct =", r"regex /a*\[^/", "punct ,", "dnum 1"]), (r"a=/\//,1", ["id a", "punct =", r"regex /\//", "punct ,", "dnum 1"]), # next two are from http://www.mozilla.org/js/language/js20-2002-04/rationale/syntax.html#regular-expressions ("""for (var x = a in foo && "</x>" || mot ? z:/x:3;x<5;y</g/i) {xyz(x++);}""", ["keyword for", "punct (", "keyword var", "id x", "punct =", "id a", "keyword in", "id foo", "punct &&", 'string "</x>"', "punct ||", "id mot", "punct ?", "id z", "punct :", "regex /x:3;x<5;y</g", "punct /", "id i", "punct )", "punct {", "id xyz", "punct (", "id x", "punct ++", "punct )", "punct ;", "punct }"]), ("""for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y</g/i) {xyz(x++);}""", ["keyword for", "punct (", "keyword var", "id x", "punct =", "id a", "keyword in", "id foo", "punct &&", 'string "</x>"', "punct ||", "id mot", "punct ?", "id z", "punct /", "id x", "punct :", "dnum 3", "punct ;", "id x", "punct <", "dnum 5", "punct ;", "id y", "punct <", "regex /g/i", "punct )", "punct {", "id xyz", "punct (", "id x", "punct ++", "punct )", "punct ;", "punct }"]), # Various "illegal" regexes that are valid according to the std. (r"""/????/, /++++/, /[----]/ """, ["regex /????/", "punct ,", "regex /++++/", "punct ,", "regex /[----]/"]), # Stress cases from http://stackoverflow.com/questions/5533925/what-javascript-constructs-does-jslex-incorrectly-lex/5573409#5573409 (r"""/\[/""", [r"""regex /\[/"""]), (r"""/[i]/""", [r"""regex /[i]/"""]), (r"""/[\]]/""", [r"""regex /[\]]/"""]), (r"""/a[\]]/""", [r"""regex /a[\]]/"""]), (r"""/a[\]]b/""", [r"""regex /a[\]]b/"""]), (r"""/[\]/]/gi""", [r"""regex /[\]/]/gi"""]), (r"""/\[[^\]]+\]/gi""", [r"""regex /\[[^\]]+\]/gi"""]), (""" rexl.re = { NAME: /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/, UNQUOTED_LITERAL: /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/, QUOTED_LITERAL: /^'(?:[^']|'')*'/, NUMERIC_LITERAL: /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/, SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/ }; """, ["id rexl", "punct .", "id re", "punct =", "punct {", "id NAME", "punct :", r"""regex /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/""", "punct ,", "id UNQUOTED_LITERAL", "punct :", r"""regex /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""", "punct ,", "id QUOTED_LITERAL", "punct :", r"""regex /^'(?:[^']|'')*'/""", "punct ,", "id NUMERIC_LITERAL", "punct :", r"""regex /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "punct ,", "id SYMBOL", "punct :", r"""regex /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""", "punct }", "punct ;" ]), (""" rexl.re = { NAME: /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/, UNQUOTED_LITERAL: /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/, QUOTED_LITERAL: /^'(?:[^']|'')*'/, NUMERIC_LITERAL: /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/, SYMBOL: /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/ }; str = '"'; """, ["id rexl", "punct .", "id re", "punct =", "punct {", "id NAME", "punct :", r"""regex /^(?![0-9])(?:\w)+|^"(?:[^"]|"")+"/""", "punct ,", "id UNQUOTED_LITERAL", "punct :", r"""regex /^@(?:(?![0-9])(?:\w|\:)+|^"(?:[^"]|"")+")\[[^\]]+\]/""", "punct ,", "id QUOTED_LITERAL", "punct :", r"""regex /^'(?:[^']|'')*'/""", "punct ,", "id NUMERIC_LITERAL", "punct :", r"""regex /^[0-9]+(?:\.[0-9]*(?:[eE][-+][0-9]+)?)?/""", "punct ,", "id SYMBOL", "punct :", r"""regex /^(?:==|=|<>|<=|<|>=|>|!~~|!~|~~|~|!==|!=|!~=|!~|!|&|\||\.|\:|,|\(|\)|\[|\]|\{|\}|\?|\:|;|@|\^|\/\+|\/|\*|\+|-)/""", "punct }", "punct ;", "id str", "punct =", """string '"'""", "punct ;", ]), (r""" this._js = "e.str(\"" + this.value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"") + "\")"; """, ["keyword this", "punct .", "id _js", "punct =", r'''string "e.str(\""''', "punct +", "keyword this", "punct .", "id value", "punct .", "id replace", "punct (", r"regex /\\/g", "punct ,", r'string "\\\\"', "punct )", "punct .", "id replace", "punct (", r'regex /"/g', "punct ,", r'string "\\\""', "punct )", "punct +", r'string "\")"', "punct ;"]), ] def make_function(input, toks): def test_func(self): lexer = JsLexer() result = ["%s %s" % (name, tok) for name, tok in lexer.lex(input) if name != 'ws'] self.assertListEqual(result, toks) return test_func for i, (input, toks) in enumerate(JsTokensTest.LEX_CASES): setattr(JsTokensTest, "test_case_%d" % i, make_function(input, toks)) GETTEXT_CASES = ( ( r""" a = 1; /* /[0-9]+/ */ b = 0x2a0b / 1; // /[0-9]+/ c = 3; """, r""" a = 1; /* /[0-9]+/ */ b = 0x2a0b / 1; // /[0-9]+/ c = 3; """ ), ( r""" a = 1.234e-5; /* * /[0-9+/ */ b = .0123; """, r""" a = 1.234e-5; /* * /[0-9+/ */ b = .0123; """ ), ( r""" x = y / z; alert(gettext("hello")); x /= 3; """, r""" x = y / z; alert(gettext("hello")); x /= 3; """ ), ( r""" s = "Hello \"th/foo/ere\""; s = 'He\x23llo \'th/foo/ere\''; s = 'slash quote \", just quote "'; """, r""" s = "Hello \"th/foo/ere\""; s = "He\x23llo \'th/foo/ere\'"; s = "slash quote \", just quote \""; """ ), ( r""" s = "Line continuation\ continued /hello/ still the string";/hello/; """, r""" s = "Line continuation\ continued /hello/ still the string";"REGEX"; """ ), ( r""" var regex = /pattern/; var regex2 = /matter/gm; var regex3 = /[*/]+/gm.foo("hey"); """, r""" var regex = "REGEX"; var regex2 = "REGEX"; var regex3 = "REGEX".foo("hey"); """ ), ( r""" for (var x = a in foo && "</x>" || mot ? z:/x:3;x<5;y</g/i) {xyz(x++);} for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y</g/i) {xyz(x++);} """, r""" for (var x = a in foo && "</x>" || mot ? z:"REGEX"/i) {xyz(x++);} for (var x = a in foo && "</x>" || mot ? z/x:3;x<5;y<"REGEX") {xyz(x++);} """ ), ( """ \\u1234xyz = gettext('Hello there'); """, r""" Uu1234xyz = gettext("Hello there"); """ ) ) class JsToCForGettextTest(SimpleTestCase): pass def make_function(js, c): def test_func(self): self.assertMultiLineEqual(prepare_js_for_gettext(js), c) return test_func for i, pair in enumerate(GETTEXT_CASES): setattr(JsToCForGettextTest, "test_case_%d" % i, make_function(*pair))
bsd-3-clause
wallyqs/asyncio-nats-streaming
stan/pb/protocol_pb2.py
1
27111
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: protocol.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='protocol.proto', package='pb', syntax='proto3', serialized_pb=_b('\n\x0eprotocol.proto\x12\x02pb\"f\n\x06PubMsg\x12\x10\n\x08\x63lientID\x18\x01 \x01(\t\x12\x0c\n\x04guid\x18\x02 \x01(\t\x12\x0f\n\x07subject\x18\x03 \x01(\t\x12\r\n\x05reply\x18\x04 \x01(\t\x12\x0c\n\x04\x64\x61ta\x18\x05 \x01(\x0c\x12\x0e\n\x06sha256\x18\n \x01(\x0c\"%\n\x06PubAck\x12\x0c\n\x04guid\x18\x01 \x01(\t\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"\x81\x01\n\x08MsgProto\x12\x10\n\x08sequence\x18\x01 \x01(\x04\x12\x0f\n\x07subject\x18\x02 \x01(\t\x12\r\n\x05reply\x18\x03 \x01(\t\x12\x0c\n\x04\x64\x61ta\x18\x04 \x01(\x0c\x12\x11\n\ttimestamp\x18\x05 \x01(\x03\x12\x13\n\x0bredelivered\x18\x06 \x01(\x08\x12\r\n\x05\x43RC32\x18\n \x01(\r\"(\n\x03\x41\x63k\x12\x0f\n\x07subject\x18\x01 \x01(\t\x12\x10\n\x08sequence\x18\x02 \x01(\x04\":\n\x0e\x43onnectRequest\x12\x10\n\x08\x63lientID\x18\x01 \x01(\t\x12\x16\n\x0eheartbeatInbox\x18\x02 \x01(\t\"\xa3\x01\n\x0f\x43onnectResponse\x12\x11\n\tpubPrefix\x18\x01 \x01(\t\x12\x13\n\x0bsubRequests\x18\x02 \x01(\t\x12\x15\n\runsubRequests\x18\x03 \x01(\t\x12\x15\n\rcloseRequests\x18\x04 \x01(\t\x12\r\n\x05\x65rror\x18\x05 \x01(\t\x12\x18\n\x10subCloseRequests\x18\x06 \x01(\t\x12\x11\n\tpublicKey\x18\x64 \x01(\t\"\xf1\x01\n\x13SubscriptionRequest\x12\x10\n\x08\x63lientID\x18\x01 \x01(\t\x12\x0f\n\x07subject\x18\x02 \x01(\t\x12\x0e\n\x06qGroup\x18\x03 \x01(\t\x12\r\n\x05inbox\x18\x04 \x01(\t\x12\x13\n\x0bmaxInFlight\x18\x05 \x01(\x05\x12\x15\n\rackWaitInSecs\x18\x06 \x01(\x05\x12\x13\n\x0b\x64urableName\x18\x07 \x01(\t\x12(\n\rstartPosition\x18\n \x01(\x0e\x32\x11.pb.StartPosition\x12\x15\n\rstartSequence\x18\x0b \x01(\x04\x12\x16\n\x0estartTimeDelta\x18\x0c \x01(\x03\"7\n\x14SubscriptionResponse\x12\x10\n\x08\x61\x63kInbox\x18\x02 \x01(\t\x12\r\n\x05\x65rror\x18\x03 \x01(\t\"[\n\x12UnsubscribeRequest\x12\x10\n\x08\x63lientID\x18\x01 \x01(\t\x12\x0f\n\x07subject\x18\x02 \x01(\t\x12\r\n\x05inbox\x18\x03 \x01(\t\x12\x13\n\x0b\x64urableName\x18\x04 \x01(\t\" \n\x0c\x43loseRequest\x12\x10\n\x08\x63lientID\x18\x01 \x01(\t\"\x1e\n\rCloseResponse\x12\r\n\x05\x65rror\x18\x01 \x01(\t*`\n\rStartPosition\x12\x0b\n\x07NewOnly\x10\x00\x12\x10\n\x0cLastReceived\x10\x01\x12\x12\n\x0eTimeDeltaStart\x10\x02\x12\x11\n\rSequenceStart\x10\x03\x12\t\n\x05\x46irst\x10\x04\x62\x06proto3') ) _sym_db.RegisterFileDescriptor(DESCRIPTOR) _STARTPOSITION = _descriptor.EnumDescriptor( name='StartPosition', full_name='pb.StartPosition', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='NewOnly', index=0, number=0, options=None, type=None), _descriptor.EnumValueDescriptor( name='LastReceived', index=1, number=1, options=None, type=None), _descriptor.EnumValueDescriptor( name='TimeDeltaStart', index=2, number=2, options=None, type=None), _descriptor.EnumValueDescriptor( name='SequenceStart', index=3, number=3, options=None, type=None), _descriptor.EnumValueDescriptor( name='First', index=4, number=4, options=None, type=None), ], containing_type=None, options=None, serialized_start=1025, serialized_end=1121, ) _sym_db.RegisterEnumDescriptor(_STARTPOSITION) StartPosition = enum_type_wrapper.EnumTypeWrapper(_STARTPOSITION) NewOnly = 0 LastReceived = 1 TimeDeltaStart = 2 SequenceStart = 3 First = 4 _PUBMSG = _descriptor.Descriptor( name='PubMsg', full_name='pb.PubMsg', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='clientID', full_name='pb.PubMsg.clientID', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='guid', full_name='pb.PubMsg.guid', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='subject', full_name='pb.PubMsg.subject', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='reply', full_name='pb.PubMsg.reply', index=3, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='data', full_name='pb.PubMsg.data', index=4, number=5, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='sha256', full_name='pb.PubMsg.sha256', index=5, number=10, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=22, serialized_end=124, ) _PUBACK = _descriptor.Descriptor( name='PubAck', full_name='pb.PubAck', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='guid', full_name='pb.PubAck.guid', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='error', full_name='pb.PubAck.error', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=126, serialized_end=163, ) _MSGPROTO = _descriptor.Descriptor( name='MsgProto', full_name='pb.MsgProto', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='sequence', full_name='pb.MsgProto.sequence', index=0, number=1, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='subject', full_name='pb.MsgProto.subject', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='reply', full_name='pb.MsgProto.reply', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='data', full_name='pb.MsgProto.data', index=3, number=4, type=12, cpp_type=9, label=1, has_default_value=False, default_value=_b(""), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='timestamp', full_name='pb.MsgProto.timestamp', index=4, number=5, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='redelivered', full_name='pb.MsgProto.redelivered', index=5, number=6, type=8, cpp_type=7, label=1, has_default_value=False, default_value=False, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='CRC32', full_name='pb.MsgProto.CRC32', index=6, number=10, type=13, cpp_type=3, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=166, serialized_end=295, ) _ACK = _descriptor.Descriptor( name='Ack', full_name='pb.Ack', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='subject', full_name='pb.Ack.subject', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='sequence', full_name='pb.Ack.sequence', index=1, number=2, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=297, serialized_end=337, ) _CONNECTREQUEST = _descriptor.Descriptor( name='ConnectRequest', full_name='pb.ConnectRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='clientID', full_name='pb.ConnectRequest.clientID', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='heartbeatInbox', full_name='pb.ConnectRequest.heartbeatInbox', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=339, serialized_end=397, ) _CONNECTRESPONSE = _descriptor.Descriptor( name='ConnectResponse', full_name='pb.ConnectResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='pubPrefix', full_name='pb.ConnectResponse.pubPrefix', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='subRequests', full_name='pb.ConnectResponse.subRequests', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='unsubRequests', full_name='pb.ConnectResponse.unsubRequests', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='closeRequests', full_name='pb.ConnectResponse.closeRequests', index=3, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='error', full_name='pb.ConnectResponse.error', index=4, number=5, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='subCloseRequests', full_name='pb.ConnectResponse.subCloseRequests', index=5, number=6, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='publicKey', full_name='pb.ConnectResponse.publicKey', index=6, number=100, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=400, serialized_end=563, ) _SUBSCRIPTIONREQUEST = _descriptor.Descriptor( name='SubscriptionRequest', full_name='pb.SubscriptionRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='clientID', full_name='pb.SubscriptionRequest.clientID', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='subject', full_name='pb.SubscriptionRequest.subject', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='qGroup', full_name='pb.SubscriptionRequest.qGroup', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='inbox', full_name='pb.SubscriptionRequest.inbox', index=3, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='maxInFlight', full_name='pb.SubscriptionRequest.maxInFlight', index=4, number=5, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='ackWaitInSecs', full_name='pb.SubscriptionRequest.ackWaitInSecs', index=5, number=6, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='durableName', full_name='pb.SubscriptionRequest.durableName', index=6, number=7, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='startPosition', full_name='pb.SubscriptionRequest.startPosition', index=7, number=10, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='startSequence', full_name='pb.SubscriptionRequest.startSequence', index=8, number=11, type=4, cpp_type=4, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='startTimeDelta', full_name='pb.SubscriptionRequest.startTimeDelta', index=9, number=12, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=566, serialized_end=807, ) _SUBSCRIPTIONRESPONSE = _descriptor.Descriptor( name='SubscriptionResponse', full_name='pb.SubscriptionResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='ackInbox', full_name='pb.SubscriptionResponse.ackInbox', index=0, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='error', full_name='pb.SubscriptionResponse.error', index=1, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=809, serialized_end=864, ) _UNSUBSCRIBEREQUEST = _descriptor.Descriptor( name='UnsubscribeRequest', full_name='pb.UnsubscribeRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='clientID', full_name='pb.UnsubscribeRequest.clientID', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='subject', full_name='pb.UnsubscribeRequest.subject', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='inbox', full_name='pb.UnsubscribeRequest.inbox', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), _descriptor.FieldDescriptor( name='durableName', full_name='pb.UnsubscribeRequest.durableName', index=3, number=4, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=866, serialized_end=957, ) _CLOSEREQUEST = _descriptor.Descriptor( name='CloseRequest', full_name='pb.CloseRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='clientID', full_name='pb.CloseRequest.clientID', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=959, serialized_end=991, ) _CLOSERESPONSE = _descriptor.Descriptor( name='CloseResponse', full_name='pb.CloseResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='error', full_name='pb.CloseResponse.error', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, options=None), ], extensions=[ ], nested_types=[], enum_types=[ ], options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=993, serialized_end=1023, ) _SUBSCRIPTIONREQUEST.fields_by_name['startPosition'].enum_type = _STARTPOSITION DESCRIPTOR.message_types_by_name['PubMsg'] = _PUBMSG DESCRIPTOR.message_types_by_name['PubAck'] = _PUBACK DESCRIPTOR.message_types_by_name['MsgProto'] = _MSGPROTO DESCRIPTOR.message_types_by_name['Ack'] = _ACK DESCRIPTOR.message_types_by_name['ConnectRequest'] = _CONNECTREQUEST DESCRIPTOR.message_types_by_name['ConnectResponse'] = _CONNECTRESPONSE DESCRIPTOR.message_types_by_name['SubscriptionRequest'] = _SUBSCRIPTIONREQUEST DESCRIPTOR.message_types_by_name['SubscriptionResponse'] = _SUBSCRIPTIONRESPONSE DESCRIPTOR.message_types_by_name['UnsubscribeRequest'] = _UNSUBSCRIBEREQUEST DESCRIPTOR.message_types_by_name['CloseRequest'] = _CLOSEREQUEST DESCRIPTOR.message_types_by_name['CloseResponse'] = _CLOSERESPONSE DESCRIPTOR.enum_types_by_name['StartPosition'] = _STARTPOSITION PubMsg = _reflection.GeneratedProtocolMessageType('PubMsg', (_message.Message,), dict( DESCRIPTOR = _PUBMSG, __module__ = 'protocol_pb2' # @@protoc_insertion_point(class_scope:pb.PubMsg) )) _sym_db.RegisterMessage(PubMsg) PubAck = _reflection.GeneratedProtocolMessageType('PubAck', (_message.Message,), dict( DESCRIPTOR = _PUBACK, __module__ = 'protocol_pb2' # @@protoc_insertion_point(class_scope:pb.PubAck) )) _sym_db.RegisterMessage(PubAck) MsgProto = _reflection.GeneratedProtocolMessageType('MsgProto', (_message.Message,), dict( DESCRIPTOR = _MSGPROTO, __module__ = 'protocol_pb2' # @@protoc_insertion_point(class_scope:pb.MsgProto) )) _sym_db.RegisterMessage(MsgProto) Ack = _reflection.GeneratedProtocolMessageType('Ack', (_message.Message,), dict( DESCRIPTOR = _ACK, __module__ = 'protocol_pb2' # @@protoc_insertion_point(class_scope:pb.Ack) )) _sym_db.RegisterMessage(Ack) ConnectRequest = _reflection.GeneratedProtocolMessageType('ConnectRequest', (_message.Message,), dict( DESCRIPTOR = _CONNECTREQUEST, __module__ = 'protocol_pb2' # @@protoc_insertion_point(class_scope:pb.ConnectRequest) )) _sym_db.RegisterMessage(ConnectRequest) ConnectResponse = _reflection.GeneratedProtocolMessageType('ConnectResponse', (_message.Message,), dict( DESCRIPTOR = _CONNECTRESPONSE, __module__ = 'protocol_pb2' # @@protoc_insertion_point(class_scope:pb.ConnectResponse) )) _sym_db.RegisterMessage(ConnectResponse) SubscriptionRequest = _reflection.GeneratedProtocolMessageType('SubscriptionRequest', (_message.Message,), dict( DESCRIPTOR = _SUBSCRIPTIONREQUEST, __module__ = 'protocol_pb2' # @@protoc_insertion_point(class_scope:pb.SubscriptionRequest) )) _sym_db.RegisterMessage(SubscriptionRequest) SubscriptionResponse = _reflection.GeneratedProtocolMessageType('SubscriptionResponse', (_message.Message,), dict( DESCRIPTOR = _SUBSCRIPTIONRESPONSE, __module__ = 'protocol_pb2' # @@protoc_insertion_point(class_scope:pb.SubscriptionResponse) )) _sym_db.RegisterMessage(SubscriptionResponse) UnsubscribeRequest = _reflection.GeneratedProtocolMessageType('UnsubscribeRequest', (_message.Message,), dict( DESCRIPTOR = _UNSUBSCRIBEREQUEST, __module__ = 'protocol_pb2' # @@protoc_insertion_point(class_scope:pb.UnsubscribeRequest) )) _sym_db.RegisterMessage(UnsubscribeRequest) CloseRequest = _reflection.GeneratedProtocolMessageType('CloseRequest', (_message.Message,), dict( DESCRIPTOR = _CLOSEREQUEST, __module__ = 'protocol_pb2' # @@protoc_insertion_point(class_scope:pb.CloseRequest) )) _sym_db.RegisterMessage(CloseRequest) CloseResponse = _reflection.GeneratedProtocolMessageType('CloseResponse', (_message.Message,), dict( DESCRIPTOR = _CLOSERESPONSE, __module__ = 'protocol_pb2' # @@protoc_insertion_point(class_scope:pb.CloseResponse) )) _sym_db.RegisterMessage(CloseResponse) # @@protoc_insertion_point(module_scope)
apache-2.0
40223112/w16test
static/Brython3.1.1-20150328-091302/Lib/site-packages/pygame/version.py
607
1334
## pygame - Python Game Library ## Copyright (C) 2000-2003 Pete Shinners ## ## This library is free software; you can redistribute it and/or ## modify it under the terms of the GNU Library General Public ## License as published by the Free Software Foundation; either ## version 2 of the License, or (at your option) any later version. ## ## This library 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 ## Library General Public License for more details. ## ## You should have received a copy of the GNU Library General Public ## License along with this library; if not, write to the Free ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ## ## Pete Shinners ## pete@shinners.org """Simply the current installed pygame version. The version information is stored in the regular pygame module as 'pygame.ver'. Keeping the version information also available in a separate module allows you to test the pygame version without importing the main pygame module. The python version information should always compare greater than any previous releases. (hmm, until we get to versions > 10) """ ver = '1.8.0pre' vernum = 1,8,0
agpl-3.0
kyoungrok0517/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers
ExamplesFromChapters/Chapter3/ClusteringWithGaussians.py
90
1034
import numpy as np import pymc as pm data = np.loadtxt("../../Chapter3_MCMC/data/mixture_data.csv", delimiter=",") p = pm.Uniform("p", 0, 1) assignment = pm.Categorical("assignment", [p, 1 - p], size=data.shape[0]) taus = 1.0 / pm.Uniform("stds", 0, 100, size=2) ** 2 # notice the size! centers = pm.Normal("centers", [150, 150], [0.001, 0.001], size=2) """ The below deterministic functions map a assingment, in this case 0 or 1, to a set of parameters, located in the (1,2) arrays `taus` and `centers.` """ @pm.deterministic def center_i(assignment=assignment, centers=centers): return centers[assignment] @pm.deterministic def tau_i(assignment=assignment, taus=taus): return taus[assignment] # and to combine it with the observations: observations = pm.Normal("obs", center_i, tau_i, value=data, observed=True) # below we create a model class model = pm.Model([p, assignment, taus, centers]) map_ = pm.MAP(model) map_.fit() mcmc = pm.MCMC(model) mcmc.sample(100000, 50000)
mit
liyitest/rr
openstack_dashboard/dashboards/identity/roles/urls.py
64
1070
# Copyright 2013 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.conf.urls import patterns from django.conf.urls import url from openstack_dashboard.dashboards.identity.roles import views urlpatterns = patterns( 'openstack_dashboard.dashboards.identity.roles.views', url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<role_id>[^/]+)/update/$', views.UpdateView.as_view(), name='update'), url(r'^create/$', views.CreateView.as_view(), name='create'))
apache-2.0
saadbinakhlaq/django-oscar
sites/demo/apps/shipping/migrations/0002_auto__add_field_weightbased_default_weight.py
15
2912
# encoding: utf-8 import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'WeightBased.default_weight' db.add_column('shipping_weightbased', 'default_weight', self.gf('django.db.models.fields.DecimalField')(default='0.00', max_digits=12, decimal_places=2), keep_default=False) def backwards(self, orm): # Deleting field 'WeightBased.default_weight' db.delete_column('shipping_weightbased', 'default_weight') models = { 'shipping.orderanditemcharges': { 'Meta': {'object_name': 'OrderAndItemCharges'}, 'code': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '128', 'db_index': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'free_shipping_threshold': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '12', 'decimal_places': '2', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}), 'price_per_item': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'max_digits': '12', 'decimal_places': '2'}), 'price_per_order': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'max_digits': '12', 'decimal_places': '2'}) }, 'shipping.weightband': { 'Meta': {'ordering': "['upper_limit']", 'object_name': 'WeightBand'}, 'charge': ('django.db.models.fields.DecimalField', [], {'max_digits': '12', 'decimal_places': '2'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'method': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'bands'", 'to': "orm['shipping.WeightBased']"}), 'upper_limit': ('django.db.models.fields.FloatField', [], {}) }, 'shipping.weightbased': { 'Meta': {'object_name': 'WeightBased'}, 'code': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '128', 'db_index': 'True'}), 'default_weight': ('django.db.models.fields.DecimalField', [], {'default': "'0.00'", 'max_digits': '12', 'decimal_places': '2'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '128'}), 'upper_charge': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '12', 'decimal_places': '2'}) } } complete_apps = ['shipping']
bsd-3-clause
djnugent/Precland
Precland/Simulator.py
2
7761
#!/usr/bin/python #SYSTEM IMPORTS import sys from os.path import expanduser import math import time import cv2 import numpy as np from cv_utils.position_vector import PositionVector from cv_utils.helpers import * from cv_utils.transforms import * from droneapi.lib import VehicleMode, Location, Attitude ''' TODO fix warped aspect ratios ''' class PrecisionLandSimulator(): def __init__(self,config): self.targetLocation = PositionVector() self.vehicleLocation = PositionVector() self.backgroundColor = (209,209,209) #define camera self.camera_width = config.get_integer('simulator','width',640) self.camera_height = config.get_integer('simulator','height',480) self.camera_hfov = config.get_float('camera','hfov',72.3) self.camera_vfov = config.get_float('camera','vfov',46) self.has_gimbal = config.get_boolean('camera','has_gimbal',False) #define environment self.simulator_framerate = config.get_integer('simulator','frame_rate',30) self.target_size = config.get_float('simulator','target_size',0.75) self.target_location = config.get_string('simulator','target_location','~/precland/Targets/mat_v1.jpg') self.camera_fov = math.sqrt(self.camera_vfov**2 + self.camera_hfov**2) self.last_update_time = 0 self.load_target() #load_target- load an image to simulate the target. Enter the actaul target size in meters(assuming the target is square) def load_target(self): self.target = cv2.imread(expanduser(self.target_location)) if self.target is None: print "Unable to load target image!" sys.exit(0) self.target_width = self.target.shape[1] self.target_height = self.target.shape[0] #scaling factor for real dimensions to simultor pixels self.pixels_per_meter = (self.target_height + self.target_width) / (2.0 * self.target_size) #set_target_location- give the target a gps location def set_target_location(self, location): self.targetLocation.set_from_location(location) #refresh_simulator - update vehicle position info necessary to simulate an image def refresh_simulator(self, vehicleLocation, vehicleAttitude): #get gps location of vehicle self.vehicleLocation.set_from_location(vehicleLocation) self.vehicleAttitude = vehicleAttitude #main - code used to test the simulator. Must be run from sitl. Control vehicle in guided mode using arrow keys,r,t,q,e def main(self): veh_control.connect(local_connect()) self.set_target_location(veh_control.get_location()) while(veh_control.is_connected()): location = veh_control.get_location() attitude = veh_control.get_attitude() self.refresh_simulator(location,attitude) ret,frame = self.get_image() cv2.imshow('frame',frame) key = cv2.waitKey(1) print key if key ==1113938: veh_control.set_velocity(2,0,0) #forward elif key == 1113940: veh_control.set_velocity(-2,0,0) #backward elif key == 1113937: veh_control.set_velocity(0,-2,0) #left elif key ==1113939: veh_control.set_velocity(0,2,0) #right elif(key == 1048690): yaw = math.degrees(attitude.yaw) #yaw left veh_control.set_yaw(yaw - 5) elif(key == 1048692): yaw = math.degrees(attitude.yaw) #yaw right veh_control.set_yaw(yaw + 5) elif(key == 1048677): veh_control.set_velocity(0,0,-2) #down elif(key == 1048689): veh_control.set_velocity(0,0,2) #up else: veh_control.set_velocity(0,0,0) #still #project_3D_to_2D - project a 3d point onto a 2d plane. Covert from world perspective to camera perspective def project_3D_to_2D(self,thetaX,thetaY,thetaZ, aX, aY,aZ, cX, cY, cZ, height, width, fov): dX = math.cos(-thetaY) * (math.sin(-thetaZ)*(cY-aY) + math.cos(-thetaZ)*(cX-aX)) - math.sin(-thetaY)*(aZ-cZ) dY = math.sin(-thetaX) * (math.cos(-thetaY)*(aZ-cZ) + math.sin(-thetaY)*(math.sin(-thetaZ)*(cY-aY) + math.cos(-thetaZ)*(cX-aX))) + math.cos(-thetaX)*(math.cos(-thetaZ)*(cY-aY) - math.sin(-thetaZ) * (cX-aX)) dZ = math.cos(-thetaX) * (math.cos(-thetaY)*(aZ-cZ) + math.sin(-thetaY)*(math.sin(-thetaZ)*(cY-aY) + math.cos(-thetaZ)*(cX-aX))) - math.sin(-thetaX)*(math.cos(-thetaZ)*(cY-aY) - math.sin(-thetaZ) * (cX-aX)) #veiwer position eX = 0 eY = 0 eZ = 1.0/math.tan(math.radians(fov)/2.0) #2D point bX = (dX - eX)*(eZ/dZ) bY = (dY - eY)*(eZ/dZ) #scaled to resolution sX = bX * width sY = bY * height return (sX,sY) #simulate_target - simulate an image given the target position[aX,aY,aZ](pixels)and camera position[cX,cY,cZ](pixels) and camera orientation def simulate_target(self,thetaX,thetaY,thetaZ, aX, aY, aZ, cX, cY, cZ, camera_height, camera_width, fov): img_width = self.target_width img_height = self.target_height #point maps corners = np.float32([[-img_width/2,img_height/2],[img_width/2 ,img_height/2],[-img_width/2,-img_height/2],[img_width/2, -img_height/2]]) newCorners = np.float32([[0,0],[0,0],[0,0],[0,0]]) #calculate projection for four corners of image for i in range(0,len(corners)): #shift to world x = corners[i][0] + cX - img_width/2.0 y = corners[i][1] + cY - img_height/2.0 #calculate perspective and position x , y = self.project_3D_to_2D(thetaX,thetaY,thetaZ, aY, aX, aZ, y, x, cZ,camera_height,camera_width,fov) #shift to camera x , y = shift_to_image((x,y),camera_width,camera_height) newCorners[i] = x,y #project image M = cv2.getPerspectiveTransform(corners,newCorners) sim = cv2.warpPerspective(self.target,M,(self.camera_width,self.camera_height),borderValue=self.backgroundColor) return sim #get_image - retreive a simulated camera image def get_image(self): start = int(time.time() * 1000) #distance bewteen camera and target in meters aX,aY,aZ = self.targetLocation.x, self.targetLocation.y, self.targetLocation.z cX,cY,cZ = self.vehicleLocation.x, self.vehicleLocation.y, self.vehicleLocation.z #camera angle thetaX = self.vehicleAttitude.pitch thetaY = self.vehicleAttitude.roll thetaZ = self.vehicleAttitude.yaw if self.has_gimbal: thetaX, thetaY = 0,0 #convert distance bewtween camera and target in pixels aX = aX * self.pixels_per_meter aY = aY * self.pixels_per_meter aZ = aZ * self.pixels_per_meter cX = cX * self.pixels_per_meter cY = cY * self.pixels_per_meter cZ = cZ * self.pixels_per_meter #render image sim = self.simulate_target(thetaX,thetaY,thetaZ, aX, aY, aZ, cX, cY, cZ, self.camera_height, self.camera_width, self.camera_fov) #simulate framerate #constrain framerate while self.simulator_framerate != 0 and (time.time() - self.last_update_time < (1.0 / self.simulator_framerate )): pass self.last_update_time = time.time() return True,cv2.cvtColor(sim,cv2.COLOR_BGR2GRAY) if __name__ == "__builtin__": #load config file config = Config("precland","~/precland_default.cnf") sim = PrecisionLandSimulator(config) sim.main()
gpl-3.0
CartoDB/cartodb-python
examples/sql_batch_api_jobs.py
2
3070
import argparse import logging import os import warnings from carto.auth import APIKeyAuthClient from carto.sql import BatchSQLClient warnings.filterwarnings('ignore') # Logger (better than print) logging.basicConfig( level=logging.INFO, format=' %(asctime)s - %(levelname)s - %(message)s', datefmt='%I:%M:%S %p') logger = logging.getLogger() # set input arguments parser = argparse.ArgumentParser( description='Create a Batch SQL API job') parser.add_argument('operation', type=str, default=None, choices=['create', 'read', 'update', 'cancel'], help='Set the batch operation that you want to apply') parser.add_argument('--query', type=str, dest='query', help='Set the query that you want to apply') parser.add_argument('--job_id', type=str, dest='job_id', help='Set the id of the job to check') parser.add_argument('--organization', type=str, dest='organization', default=os.environ['CARTO_ORG'] if 'CARTO_ORG' in os.environ else '', help='Set the name of the organization' + ' account (defaults to env variable CARTO_ORG)') parser.add_argument('--base_url', type=str, dest='CARTO_BASE_URL', default=os.environ['CARTO_API_URL'] if 'CARTO_API_URL' in os.environ else '', help='Set the base URL. For example:' + ' https://username.carto.com/ ' + '(defaults to env variable CARTO_API_URL)') parser.add_argument('--api_key', dest='CARTO_API_KEY', default=os.environ['CARTO_API_KEY'] if 'CARTO_API_KEY' in os.environ else '', help='Api key of the account' + ' (defaults to env variable CARTO_API_KEY)') args = parser.parse_args() # Set authentification to CARTO if args.CARTO_BASE_URL and args.CARTO_API_KEY and args.organization: auth_client = APIKeyAuthClient( args.CARTO_BASE_URL, args.CARTO_API_KEY, args.organization) batchSQLClient = BatchSQLClient(auth_client) else: logger.error('You need to provide valid credentials, run with -h parameter for details') import sys sys.exit(1) # Batch SQL API operations if args.operation == 'create': # create a batch api job createJob = batchSQLClient.create(args.query) for a, b in createJob.items(): logger.info('{key}: {value}'.format(key=a, value=b)) elif args.operation == 'read': readJob = batchSQLClient.read(args.job_id) for a, b in readJob.items(): logger.info('{key}: {value}'.format(key=a, value=b)) elif args.operation == 'update': updateJob = batchSQLClient.update(args.job_id, args.query) for a, b in updateJob.items(): logger.info('{key}: {value}'.format(key=a, value=b)) elif args.operation == 'cancel': cancelJob = batchSQLClient.cancel(args.job_id) for a, b in cancelJob.items(): logger.info('{key}: {value}'.format(key=a, value=b)) else: logger.info("You have not written a correct operation option")
bsd-3-clause