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
mathslinux/ceilometer
ceilometer/network/services/fwaas.py
9
3063
# # Copyright 2014 Cisco 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. from oslo_log import log from oslo_utils import timeutils from ceilometer.i18n import _ from ceilometer.network.services import base from ceilometer import sample LOG = log.getLogger(__name__) class FirewallPollster(base.BaseServicesPollster): """Pollster to capture firewalls status samples.""" FIELDS = ['admin_state_up', 'description', 'name', 'status', 'firewall_policy_id', ] @property def default_discovery(self): return 'fw_services' def get_samples(self, manager, cache, resources): resources = resources or [] for fw in resources: LOG.debug("Firewall : %s" % fw) status = self.get_status_id(fw['status']) if status == -1: # unknown status, skip this sample LOG.warn(_("Unknown status %(stat)s received on fw %(id)s," "skipping sample") % {'stat': fw['status'], 'id': fw['id']}) continue yield sample.Sample( name='network.services.firewall', type=sample.TYPE_GAUGE, unit='firewall', volume=status, user_id=None, project_id=fw['tenant_id'], resource_id=fw['id'], timestamp=timeutils.utcnow().isoformat(), resource_metadata=self.extract_metadata(fw) ) class FirewallPolicyPollster(base.BaseServicesPollster): """Pollster to capture firewall policy samples.""" FIELDS = ['name', 'description', 'name', 'firewall_rules', 'shared', 'audited', ] @property def default_discovery(self): return 'fw_policy' def get_samples(self, manager, cache, resources): resources = resources or [] for fw in resources: LOG.debug("Firewall Policy: %s" % fw) yield sample.Sample( name='network.services.firewall.policy', type=sample.TYPE_GAUGE, unit='firewall_policy', volume=1, user_id=None, project_id=fw['tenant_id'], resource_id=fw['id'], timestamp=timeutils.utcnow().isoformat(), resource_metadata=self.extract_metadata(fw) )
apache-2.0
odyaka341/django-page-cms
doc/conf.py
5
6433
# -*- coding: utf-8 -*- # # django-page-cms documentation build configuration file, created by # sphinx-quickstart on Sun Jul 19 23:15:46 2009. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If your extensions (or modules documented by autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.append(os.path.abspath('..')) from django.conf import settings import django settings.configure(DEBUG=True, TEMPLATE_DEBUG=True, DEFAULT_PAGE_TEMPLATE='index.html', PAGE_TAGGING=False, TEMPLATE_DIRS=('/home/web-apps/myapp', '/home/web-apps/base')) # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest'] # Add any paths that contain templates here, relative to this directory. templates_path = ['.templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = u'django-page-cms' copyright = u'2009, Batiste Bieler' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = __import__('pages').__version__ # The full version, including alpha/beta/rc tags. release = __import__('pages').__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = ['.build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # Options for HTML output # ----------------------- # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_style = 'default.css' # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['.static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. html_use_modindex = True # If false, no index is generated. html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, the reST sources are included in the HTML build as _sources/<name>. #html_copy_source = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'django-page-cmsdoc' # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). latex_documents = [ ('index', 'django-page-cms.tex', ur'django-page-cms Documentation', ur'Batiste Bieler', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True
bsd-3-clause
Dapid/scipy
scipy/optimize/linesearch.py
61
24200
""" Functions --------- .. autosummary:: :toctree: generated/ line_search_armijo line_search_wolfe1 line_search_wolfe2 scalar_search_wolfe1 scalar_search_wolfe2 """ from __future__ import division, print_function, absolute_import from warnings import warn from scipy.optimize import minpack2 import numpy as np from scipy._lib.six import xrange __all__ = ['LineSearchWarning', 'line_search_wolfe1', 'line_search_wolfe2', 'scalar_search_wolfe1', 'scalar_search_wolfe2', 'line_search_armijo'] class LineSearchWarning(RuntimeWarning): pass #------------------------------------------------------------------------------ # Minpack's Wolfe line and scalar searches #------------------------------------------------------------------------------ def line_search_wolfe1(f, fprime, xk, pk, gfk=None, old_fval=None, old_old_fval=None, args=(), c1=1e-4, c2=0.9, amax=50, amin=1e-8, xtol=1e-14): """ As `scalar_search_wolfe1` but do a line search to direction `pk` Parameters ---------- f : callable Function `f(x)` fprime : callable Gradient of `f` xk : array_like Current point pk : array_like Search direction gfk : array_like, optional Gradient of `f` at point `xk` old_fval : float, optional Value of `f` at point `xk` old_old_fval : float, optional Value of `f` at point preceding `xk` The rest of the parameters are the same as for `scalar_search_wolfe1`. Returns ------- stp, f_count, g_count, fval, old_fval As in `line_search_wolfe1` gval : array Gradient of `f` at the final point """ if gfk is None: gfk = fprime(xk) if isinstance(fprime, tuple): eps = fprime[1] fprime = fprime[0] newargs = (f, eps) + args gradient = False else: newargs = args gradient = True gval = [gfk] gc = [0] fc = [0] def phi(s): fc[0] += 1 return f(xk + s*pk, *args) def derphi(s): gval[0] = fprime(xk + s*pk, *newargs) if gradient: gc[0] += 1 else: fc[0] += len(xk) + 1 return np.dot(gval[0], pk) derphi0 = np.dot(gfk, pk) stp, fval, old_fval = scalar_search_wolfe1( phi, derphi, old_fval, old_old_fval, derphi0, c1=c1, c2=c2, amax=amax, amin=amin, xtol=xtol) return stp, fc[0], gc[0], fval, old_fval, gval[0] def scalar_search_wolfe1(phi, derphi, phi0=None, old_phi0=None, derphi0=None, c1=1e-4, c2=0.9, amax=50, amin=1e-8, xtol=1e-14): """ Scalar function search for alpha that satisfies strong Wolfe conditions alpha > 0 is assumed to be a descent direction. Parameters ---------- phi : callable phi(alpha) Function at point `alpha` derphi : callable dphi(alpha) Derivative `d phi(alpha)/ds`. Returns a scalar. phi0 : float, optional Value of `f` at 0 old_phi0 : float, optional Value of `f` at the previous point derphi0 : float, optional Value `derphi` at 0 c1, c2 : float, optional Wolfe parameters amax, amin : float, optional Maximum and minimum step size xtol : float, optional Relative tolerance for an acceptable step. Returns ------- alpha : float Step size, or None if no suitable step was found phi : float Value of `phi` at the new point `alpha` phi0 : float Value of `phi` at `alpha=0` Notes ----- Uses routine DCSRCH from MINPACK. """ if phi0 is None: phi0 = phi(0.) if derphi0 is None: derphi0 = derphi(0.) if old_phi0 is not None and derphi0 != 0: alpha1 = min(1.0, 1.01*2*(phi0 - old_phi0)/derphi0) if alpha1 < 0: alpha1 = 1.0 else: alpha1 = 1.0 phi1 = phi0 derphi1 = derphi0 isave = np.zeros((2,), np.intc) dsave = np.zeros((13,), float) task = b'START' maxiter = 30 for i in xrange(maxiter): stp, phi1, derphi1, task = minpack2.dcsrch(alpha1, phi1, derphi1, c1, c2, xtol, task, amin, amax, isave, dsave) if task[:2] == b'FG': alpha1 = stp phi1 = phi(stp) derphi1 = derphi(stp) else: break else: # maxiter reached, the line search did not converge stp = None if task[:5] == b'ERROR' or task[:4] == b'WARN': stp = None # failed return stp, phi1, phi0 line_search = line_search_wolfe1 #------------------------------------------------------------------------------ # Pure-Python Wolfe line and scalar searches #------------------------------------------------------------------------------ def line_search_wolfe2(f, myfprime, xk, pk, gfk=None, old_fval=None, old_old_fval=None, args=(), c1=1e-4, c2=0.9, amax=50): """Find alpha that satisfies strong Wolfe conditions. Parameters ---------- f : callable f(x,*args) Objective function. myfprime : callable f'(x,*args) Objective function gradient. xk : ndarray Starting point. pk : ndarray Search direction. gfk : ndarray, optional Gradient value for x=xk (xk being the current parameter estimate). Will be recomputed if omitted. old_fval : float, optional Function value for x=xk. Will be recomputed if omitted. old_old_fval : float, optional Function value for the point preceding x=xk args : tuple, optional Additional arguments passed to objective function. c1 : float, optional Parameter for Armijo condition rule. c2 : float, optional Parameter for curvature condition rule. amax : float, optional Maximum step size Returns ------- alpha : float or None Alpha for which ``x_new = x0 + alpha * pk``, or None if the line search algorithm did not converge. fc : int Number of function evaluations made. gc : int Number of gradient evaluations made. new_fval : float or None New function value ``f(x_new)=f(x0+alpha*pk)``, or None if the line search algorithm did not converge. old_fval : float Old function value ``f(x0)``. new_slope : float or None The local slope along the search direction at the new value ``<myfprime(x_new), pk>``, or None if the line search algorithm did not converge. Notes ----- Uses the line search algorithm to enforce strong Wolfe conditions. See Wright and Nocedal, 'Numerical Optimization', 1999, pg. 59-60. For the zoom phase it uses an algorithm by [...]. """ fc = [0] gc = [0] gval = [None] def phi(alpha): fc[0] += 1 return f(xk + alpha * pk, *args) if isinstance(myfprime, tuple): def derphi(alpha): fc[0] += len(xk) + 1 eps = myfprime[1] fprime = myfprime[0] newargs = (f, eps) + args gval[0] = fprime(xk + alpha * pk, *newargs) # store for later use return np.dot(gval[0], pk) else: fprime = myfprime def derphi(alpha): gc[0] += 1 gval[0] = fprime(xk + alpha * pk, *args) # store for later use return np.dot(gval[0], pk) if gfk is None: gfk = fprime(xk, *args) derphi0 = np.dot(gfk, pk) alpha_star, phi_star, old_fval, derphi_star = scalar_search_wolfe2( phi, derphi, old_fval, old_old_fval, derphi0, c1, c2, amax) if derphi_star is None: warn('The line search algorithm did not converge', LineSearchWarning) else: # derphi_star is a number (derphi) -- so use the most recently # calculated gradient used in computing it derphi = gfk*pk # this is the gradient at the next step no need to compute it # again in the outer loop. derphi_star = gval[0] return alpha_star, fc[0], gc[0], phi_star, old_fval, derphi_star def scalar_search_wolfe2(phi, derphi=None, phi0=None, old_phi0=None, derphi0=None, c1=1e-4, c2=0.9, amax=50): """Find alpha that satisfies strong Wolfe conditions. alpha > 0 is assumed to be a descent direction. Parameters ---------- phi : callable f(x) Objective scalar function. derphi : callable f'(x), optional Objective function derivative (can be None) phi0 : float, optional Value of phi at s=0 old_phi0 : float, optional Value of phi at previous point derphi0 : float, optional Value of derphi at s=0 c1 : float, optional Parameter for Armijo condition rule. c2 : float, optional Parameter for curvature condition rule. amax : float, optional Maximum step size Returns ------- alpha_star : float or None Best alpha, or None if the line search algorithm did not converge. phi_star : float phi at alpha_star phi0 : float phi at 0 derphi_star : float or None derphi at alpha_star, or None if the line search algorithm did not converge. Notes ----- Uses the line search algorithm to enforce strong Wolfe conditions. See Wright and Nocedal, 'Numerical Optimization', 1999, pg. 59-60. For the zoom phase it uses an algorithm by [...]. """ if phi0 is None: phi0 = phi(0.) if derphi0 is None and derphi is not None: derphi0 = derphi(0.) alpha0 = 0 if old_phi0 is not None and derphi0 != 0: alpha1 = min(1.0, 1.01*2*(phi0 - old_phi0)/derphi0) else: alpha1 = 1.0 if alpha1 < 0: alpha1 = 1.0 if alpha1 == 0: # This shouldn't happen. Perhaps the increment has slipped below # machine precision? For now, set the return variables skip the # useless while loop, and raise warnflag=2 due to possible imprecision. alpha_star = None phi_star = phi0 phi0 = old_phi0 derphi_star = None phi_a1 = phi(alpha1) #derphi_a1 = derphi(alpha1) evaluated below phi_a0 = phi0 derphi_a0 = derphi0 i = 1 maxiter = 10 for i in xrange(maxiter): if alpha1 == 0: break if (phi_a1 > phi0 + c1 * alpha1 * derphi0) or \ ((phi_a1 >= phi_a0) and (i > 1)): alpha_star, phi_star, derphi_star = \ _zoom(alpha0, alpha1, phi_a0, phi_a1, derphi_a0, phi, derphi, phi0, derphi0, c1, c2) break derphi_a1 = derphi(alpha1) if (abs(derphi_a1) <= -c2*derphi0): alpha_star = alpha1 phi_star = phi_a1 derphi_star = derphi_a1 break if (derphi_a1 >= 0): alpha_star, phi_star, derphi_star = \ _zoom(alpha1, alpha0, phi_a1, phi_a0, derphi_a1, phi, derphi, phi0, derphi0, c1, c2) break alpha2 = 2 * alpha1 # increase by factor of two on each iteration i = i + 1 alpha0 = alpha1 alpha1 = alpha2 phi_a0 = phi_a1 phi_a1 = phi(alpha1) derphi_a0 = derphi_a1 else: # stopping test maxiter reached alpha_star = alpha1 phi_star = phi_a1 derphi_star = None warn('The line search algorithm did not converge', LineSearchWarning) return alpha_star, phi_star, phi0, derphi_star def _cubicmin(a, fa, fpa, b, fb, c, fc): """ Finds the minimizer for a cubic polynomial that goes through the points (a,fa), (b,fb), and (c,fc) with derivative at a of fpa. If no minimizer can be found return None """ # f(x) = A *(x-a)^3 + B*(x-a)^2 + C*(x-a) + D with np.errstate(divide='raise', over='raise', invalid='raise'): try: C = fpa db = b - a dc = c - a denom = (db * dc) ** 2 * (db - dc) d1 = np.empty((2, 2)) d1[0, 0] = dc ** 2 d1[0, 1] = -db ** 2 d1[1, 0] = -dc ** 3 d1[1, 1] = db ** 3 [A, B] = np.dot(d1, np.asarray([fb - fa - C * db, fc - fa - C * dc]).flatten()) A /= denom B /= denom radical = B * B - 3 * A * C xmin = a + (-B + np.sqrt(radical)) / (3 * A) except ArithmeticError: return None if not np.isfinite(xmin): return None return xmin def _quadmin(a, fa, fpa, b, fb): """ Finds the minimizer for a quadratic polynomial that goes through the points (a,fa), (b,fb) with derivative at a of fpa, """ # f(x) = B*(x-a)^2 + C*(x-a) + D with np.errstate(divide='raise', over='raise', invalid='raise'): try: D = fa C = fpa db = b - a * 1.0 B = (fb - D - C * db) / (db * db) xmin = a - C / (2.0 * B) except ArithmeticError: return None if not np.isfinite(xmin): return None return xmin def _zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo, phi, derphi, phi0, derphi0, c1, c2): """ Part of the optimization algorithm in `scalar_search_wolfe2`. """ maxiter = 10 i = 0 delta1 = 0.2 # cubic interpolant check delta2 = 0.1 # quadratic interpolant check phi_rec = phi0 a_rec = 0 while True: # interpolate to find a trial step length between a_lo and # a_hi Need to choose interpolation here. Use cubic # interpolation and then if the result is within delta * # dalpha or outside of the interval bounded by a_lo or a_hi # then use quadratic interpolation, if the result is still too # close, then use bisection dalpha = a_hi - a_lo if dalpha < 0: a, b = a_hi, a_lo else: a, b = a_lo, a_hi # minimizer of cubic interpolant # (uses phi_lo, derphi_lo, phi_hi, and the most recent value of phi) # # if the result is too close to the end points (or out of the # interval) then use quadratic interpolation with phi_lo, # derphi_lo and phi_hi if the result is stil too close to the # end points (or out of the interval) then use bisection if (i > 0): cchk = delta1 * dalpha a_j = _cubicmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi, a_rec, phi_rec) if (i == 0) or (a_j is None) or (a_j > b - cchk) or (a_j < a + cchk): qchk = delta2 * dalpha a_j = _quadmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi) if (a_j is None) or (a_j > b-qchk) or (a_j < a+qchk): a_j = a_lo + 0.5*dalpha # Check new value of a_j phi_aj = phi(a_j) if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo): phi_rec = phi_hi a_rec = a_hi a_hi = a_j phi_hi = phi_aj else: derphi_aj = derphi(a_j) if abs(derphi_aj) <= -c2*derphi0: a_star = a_j val_star = phi_aj valprime_star = derphi_aj break if derphi_aj*(a_hi - a_lo) >= 0: phi_rec = phi_hi a_rec = a_hi a_hi = a_lo phi_hi = phi_lo else: phi_rec = phi_lo a_rec = a_lo a_lo = a_j phi_lo = phi_aj derphi_lo = derphi_aj i += 1 if (i > maxiter): # Failed to find a conforming step size a_star = None val_star = None valprime_star = None break return a_star, val_star, valprime_star #------------------------------------------------------------------------------ # Armijo line and scalar searches #------------------------------------------------------------------------------ def line_search_armijo(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=1): """Minimize over alpha, the function ``f(xk+alpha pk)``. Parameters ---------- f : callable Function to be minimized. xk : array_like Current point. pk : array_like Search direction. gfk : array_like Gradient of `f` at point `xk`. old_fval : float Value of `f` at point `xk`. args : tuple, optional Optional arguments. c1 : float, optional Value to control stopping criterion. alpha0 : scalar, optional Value of `alpha` at start of the optimization. Returns ------- alpha f_count f_val_at_alpha Notes ----- Uses the interpolation algorithm (Armijo backtracking) as suggested by Wright and Nocedal in 'Numerical Optimization', 1999, pg. 56-57 """ xk = np.atleast_1d(xk) fc = [0] def phi(alpha1): fc[0] += 1 return f(xk + alpha1*pk, *args) if old_fval is None: phi0 = phi(0.) else: phi0 = old_fval # compute f(xk) -- done in past loop derphi0 = np.dot(gfk, pk) alpha, phi1 = scalar_search_armijo(phi, phi0, derphi0, c1=c1, alpha0=alpha0) return alpha, fc[0], phi1 def line_search_BFGS(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=1): """ Compatibility wrapper for `line_search_armijo` """ r = line_search_armijo(f, xk, pk, gfk, old_fval, args=args, c1=c1, alpha0=alpha0) return r[0], r[1], 0, r[2] def scalar_search_armijo(phi, phi0, derphi0, c1=1e-4, alpha0=1, amin=0): """Minimize over alpha, the function ``phi(alpha)``. Uses the interpolation algorithm (Armijo backtracking) as suggested by Wright and Nocedal in 'Numerical Optimization', 1999, pg. 56-57 alpha > 0 is assumed to be a descent direction. Returns ------- alpha phi1 """ phi_a0 = phi(alpha0) if phi_a0 <= phi0 + c1*alpha0*derphi0: return alpha0, phi_a0 # Otherwise compute the minimizer of a quadratic interpolant: alpha1 = -(derphi0) * alpha0**2 / 2.0 / (phi_a0 - phi0 - derphi0 * alpha0) phi_a1 = phi(alpha1) if (phi_a1 <= phi0 + c1*alpha1*derphi0): return alpha1, phi_a1 # Otherwise loop with cubic interpolation until we find an alpha which # satifies the first Wolfe condition (since we are backtracking, we will # assume that the value of alpha is not too small and satisfies the second # condition. while alpha1 > amin: # we are assuming alpha>0 is a descent direction factor = alpha0**2 * alpha1**2 * (alpha1-alpha0) a = alpha0**2 * (phi_a1 - phi0 - derphi0*alpha1) - \ alpha1**2 * (phi_a0 - phi0 - derphi0*alpha0) a = a / factor b = -alpha0**3 * (phi_a1 - phi0 - derphi0*alpha1) + \ alpha1**3 * (phi_a0 - phi0 - derphi0*alpha0) b = b / factor alpha2 = (-b + np.sqrt(abs(b**2 - 3 * a * derphi0))) / (3.0*a) phi_a2 = phi(alpha2) if (phi_a2 <= phi0 + c1*alpha2*derphi0): return alpha2, phi_a2 if (alpha1 - alpha2) > alpha1 / 2.0 or (1 - alpha2/alpha1) < 0.96: alpha2 = alpha1 / 2.0 alpha0 = alpha1 alpha1 = alpha2 phi_a0 = phi_a1 phi_a1 = phi_a2 # Failed to find a suitable step length return None, phi_a1 #------------------------------------------------------------------------------ # Non-monotone line search for DF-SANE #------------------------------------------------------------------------------ def _nonmonotone_line_search_cruz(f, x_k, d, prev_fs, eta, gamma=1e-4, tau_min=0.1, tau_max=0.5): """ Nonmonotone backtracking line search as described in [1]_ Parameters ---------- f : callable Function returning a tuple ``(f, F)`` where ``f`` is the value of a merit function and ``F`` the residual. x_k : ndarray Initial position d : ndarray Search direction prev_fs : float List of previous merit function values. Should have ``len(prev_fs) <= M`` where ``M`` is the nonmonotonicity window parameter. eta : float Allowed merit function increase, see [1]_ gamma, tau_min, tau_max : float, optional Search parameters, see [1]_ Returns ------- alpha : float Step length xp : ndarray Next position fp : float Merit function value at next position Fp : ndarray Residual at next position References ---------- [1] "Spectral residual method without gradient information for solving large-scale nonlinear systems of equations." W. La Cruz, J.M. Martinez, M. Raydan. Math. Comp. **75**, 1429 (2006). """ f_k = prev_fs[-1] f_bar = max(prev_fs) alpha_p = 1 alpha_m = 1 alpha = 1 while True: xp = x_k + alpha_p * d fp, Fp = f(xp) if fp <= f_bar + eta - gamma * alpha_p**2 * f_k: alpha = alpha_p break alpha_tp = alpha_p**2 * f_k / (fp + (2*alpha_p - 1)*f_k) xp = x_k - alpha_m * d fp, Fp = f(xp) if fp <= f_bar + eta - gamma * alpha_m**2 * f_k: alpha = -alpha_m break alpha_tm = alpha_m**2 * f_k / (fp + (2*alpha_m - 1)*f_k) alpha_p = np.clip(alpha_tp, tau_min * alpha_p, tau_max * alpha_p) alpha_m = np.clip(alpha_tm, tau_min * alpha_m, tau_max * alpha_m) return alpha, xp, fp, Fp def _nonmonotone_line_search_cheng(f, x_k, d, f_k, C, Q, eta, gamma=1e-4, tau_min=0.1, tau_max=0.5, nu=0.85): """ Nonmonotone line search from [1] Parameters ---------- f : callable Function returning a tuple ``(f, F)`` where ``f`` is the value of a merit function and ``F`` the residual. x_k : ndarray Initial position d : ndarray Search direction f_k : float Initial merit function value C, Q : float Control parameters. On the first iteration, give values Q=1.0, C=f_k eta : float Allowed merit function increase, see [1]_ nu, gamma, tau_min, tau_max : float, optional Search parameters, see [1]_ Returns ------- alpha : float Step length xp : ndarray Next position fp : float Merit function value at next position Fp : ndarray Residual at next position C : float New value for the control parameter C Q : float New value for the control parameter Q References ---------- .. [1] W. Cheng & D.-H. Li, ''A derivative-free nonmonotone line search and its application to the spectral residual method'', IMA J. Numer. Anal. 29, 814 (2009). """ alpha_p = 1 alpha_m = 1 alpha = 1 while True: xp = x_k + alpha_p * d fp, Fp = f(xp) if fp <= C + eta - gamma * alpha_p**2 * f_k: alpha = alpha_p break alpha_tp = alpha_p**2 * f_k / (fp + (2*alpha_p - 1)*f_k) xp = x_k - alpha_m * d fp, Fp = f(xp) if fp <= C + eta - gamma * alpha_m**2 * f_k: alpha = -alpha_m break alpha_tm = alpha_m**2 * f_k / (fp + (2*alpha_m - 1)*f_k) alpha_p = np.clip(alpha_tp, tau_min * alpha_p, tau_max * alpha_p) alpha_m = np.clip(alpha_tm, tau_min * alpha_m, tau_max * alpha_m) # Update C and Q Q_next = nu * Q + 1 C = (nu * Q * (C + eta) + fp) / Q_next Q = Q_next return alpha, xp, fp, Fp, C, Q
bsd-3-clause
ykim362/mxnet
python/mxnet/gluon/data/dataset.py
4
2943
# 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. # coding: utf-8 # pylint: disable= """Dataset container.""" __all__ = ['Dataset', 'ArrayDataset', 'RecordFileDataset'] import os from ... import recordio, ndarray class Dataset(object): """Abstract dataset class. All datasets should have this interface. Subclasses need to override `__getitem__`, which returns the i-th element, and `__len__`, which returns the total number elements. .. note:: An mxnet or numpy array can be directly used as a dataset. """ def __getitem__(self, idx): raise NotImplementedError def __len__(self): raise NotImplementedError class ArrayDataset(Dataset): """A dataset of multiple arrays. The i-th sample is `(x1[i], x2[i], ...)`. Parameters ---------- *args : one or more arrays The data arrays. """ def __init__(self, *args): assert len(args) > 0, "Needs at least 1 arrays" self._length = len(args[0]) self._data = [] for i, data in enumerate(args): assert len(data) == self._length, \ "All arrays must have the same length; array[0] has length %d " \ "while array[%d] has %d." % (self._length, i+1, len(data)) if isinstance(data, ndarray.NDArray) and len(data.shape) == 1: data = data.asnumpy() self._data.append(data) def __getitem__(self, idx): if len(self._data) == 1: return self._data[0][idx] else: return tuple(data[idx] for data in self._data) def __len__(self): return self._length class RecordFileDataset(Dataset): """A dataset wrapping over a RecordIO (.rec) file. Each sample is a string representing the raw content of an record. Parameters ---------- filename : str Path to rec file. """ def __init__(self, filename): idx_file = os.path.splitext(filename)[0] + '.idx' self._record = recordio.MXIndexedRecordIO(idx_file, filename, 'r') def __getitem__(self, idx): return self._record.read_idx(self._record.keys[idx]) def __len__(self): return len(self._record.keys)
apache-2.0
webmasterraj/GaSiProMo
flask/lib/python2.7/site-packages/shapely/geometry/polygon.py
5
16303
"""Polygons and their linear ring components """ import sys if sys.version_info[0] < 3: range = xrange from ctypes import c_double, c_void_p, cast, POINTER from ctypes import ArgumentError import weakref from shapely.algorithms.cga import signed_area from shapely.coords import required from shapely.geos import lgeos from shapely.geometry.base import BaseGeometry, geos_geom_from_py from shapely.geometry.linestring import LineString, LineStringAdapter from shapely.geometry.proxy import PolygonProxy __all__ = ['Polygon', 'asPolygon', 'LinearRing', 'asLinearRing'] class LinearRing(LineString): """ A closed one-dimensional feature comprising one or more line segments A LinearRing that crosses itself or touches itself at a single point is invalid and operations on it may fail. """ def __init__(self, coordinates=None): """ Parameters ---------- coordinates : sequence A sequence of (x, y [,z]) numeric coordinate pairs or triples Rings are implicitly closed. There is no need to specific a final coordinate pair identical to the first. Example ------- Construct a square ring. >>> ring = LinearRing( ((0, 0), (0, 1), (1 ,1 ), (1 , 0)) ) >>> ring.is_closed True >>> ring.length 4.0 """ BaseGeometry.__init__(self) if coordinates is not None: self._set_coords(coordinates) @property def __geo_interface__(self): return { 'type': 'LinearRing', 'coordinates': tuple(self.coords) } # Coordinate access _get_coords = BaseGeometry._get_coords def _set_coords(self, coordinates): self.empty() self._geom, self._ndim = geos_linearring_from_py(coordinates) coords = property(_get_coords, _set_coords) @property def is_ccw(self): """True is the ring is oriented counter clock-wise""" return bool(self.impl['is_ccw'](self)) @property def is_simple(self): """True if the geometry is simple, meaning that any self-intersections are only at boundary points, else False""" return LineString(self).is_simple class LinearRingAdapter(LineStringAdapter): __p__ = None def __init__(self, context): self.context = context self.factory = geos_linearring_from_py @property def __geo_interface__(self): return { 'type': 'LinearRing', 'coordinates': tuple(self.coords) } coords = property(BaseGeometry._get_coords) def asLinearRing(context): """Adapt an object to the LinearRing interface""" return LinearRingAdapter(context) class InteriorRingSequence(object): _factory = None _geom = None __p__ = None _ndim = None _index = 0 _length = 0 __rings__ = None _gtag = None def __init__(self, parent): self.__p__ = parent self._geom = parent._geom self._ndim = parent._ndim def __iter__(self): self._index = 0 self._length = self.__len__() return self def __next__(self): if self._index < self._length: ring = self._get_ring(self._index) self._index += 1 return ring else: raise StopIteration if sys.version_info[0] < 3: next = __next__ def __len__(self): return lgeos.GEOSGetNumInteriorRings(self._geom) def __getitem__(self, key): m = self.__len__() if isinstance(key, int): if key + m < 0 or key >= m: raise IndexError("index out of range") if key < 0: i = m + key else: i = key return self._get_ring(i) elif isinstance(key, slice): res = [] start, stop, stride = key.indices(m) for i in range(start, stop, stride): res.append(self._get_ring(i)) return res else: raise TypeError("key must be an index or slice") @property def _longest(self): max = 0 for g in iter(self): l = len(g.coords) if l > max: max = l def gtag(self): return hash(repr(self.__p__)) def _get_ring(self, i): gtag = self.gtag() if gtag != self._gtag: self.__rings__ = {} if i not in self.__rings__: g = lgeos.GEOSGetInteriorRingN(self._geom, i) ring = LinearRing() ring._geom = g ring.__p__ = self ring._other_owned = True ring._ndim = self._ndim self.__rings__[i] = weakref.ref(ring) return self.__rings__[i]() class Polygon(BaseGeometry): """ A two-dimensional figure bounded by a linear ring A polygon has a non-zero area. It may have one or more negative-space "holes" which are also bounded by linear rings. If any rings cross each other, the feature is invalid and operations on it may fail. Attributes ---------- exterior : LinearRing The ring which bounds the positive space of the polygon. interiors : sequence A sequence of rings which bound all existing holes. """ _exterior = None _interiors = [] _ndim = 2 def __init__(self, shell=None, holes=None): """ Parameters ---------- shell : sequence A sequence of (x, y [,z]) numeric coordinate pairs or triples holes : sequence A sequence of objects which satisfy the same requirements as the shell parameters above Example ------- Create a square polygon with no holes >>> coords = ((0., 0.), (0., 1.), (1., 1.), (1., 0.), (0., 0.)) >>> polygon = Polygon(coords) >>> polygon.area 1.0 """ BaseGeometry.__init__(self) if shell is not None: self._geom, self._ndim = geos_polygon_from_py(shell, holes) @property def exterior(self): if self.is_empty: return None elif self._exterior is None or self._exterior() is None: g = lgeos.GEOSGetExteriorRing(self._geom) ring = LinearRing() ring._geom = g ring.__p__ = self ring._other_owned = True ring._ndim = self._ndim self._exterior = weakref.ref(ring) return self._exterior() @property def interiors(self): if self.is_empty: return [] return InteriorRingSequence(self) def __eq__(self, other): if not isinstance(other, Polygon): return False my_coords = [ tuple(self.exterior.coords), [tuple(interior.coords) for interior in self.interiors] ] other_coords = [ tuple(other.exterior.coords), [tuple(interior.coords) for interior in other.interiors] ] return my_coords == other_coords def __ne__(self, other): return not self.__eq__(other) __hash__ = object.__hash__ @property def ctypes(self): if not self._ctypes_data: self._ctypes_data = self.exterior.ctypes return self._ctypes_data @property def __array_interface__(self): raise NotImplementedError( "A polygon does not itself provide the array interface. Its rings do.") def _get_coords(self): raise NotImplementedError( "Component rings have coordinate sequences, but the polygon does not") def _set_coords(self, ob): raise NotImplementedError( "Component rings have coordinate sequences, but the polygon does not") @property def coords(self): raise NotImplementedError( "Component rings have coordinate sequences, but the polygon does not") @property def __geo_interface__(self): coords = [tuple(self.exterior.coords)] for hole in self.interiors: coords.append(tuple(hole.coords)) return { 'type': 'Polygon', 'coordinates': tuple(coords) } def svg(self, scale_factor=1., fill_color=None): """Returns SVG path element for the Polygon geometry. Parameters ========== scale_factor : float Multiplication factor for the SVG stroke-width. Default is 1. fill_color : str, optional Hex string for fill color. Default is to use "#66cc99" if geometry is valid, and "#ff3333" if invalid. """ if self.is_empty: return '<g />' if fill_color is None: fill_color = "#66cc99" if self.is_valid else "#ff3333" exterior_coords = [ ["{0},{1}".format(*c) for c in self.exterior.coords]] interior_coords = [ ["{0},{1}".format(*c) for c in interior.coords] for interior in self.interiors] path = " ".join([ "M {0} L {1} z".format(coords[0], " L ".join(coords[1:])) for coords in exterior_coords + interior_coords]) return ( '<path fill-rule="evenodd" fill="{2}" stroke="#555555" ' 'stroke-width="{0}" opacity="0.6" d="{1}" />' ).format(2. * scale_factor, path, fill_color) class PolygonAdapter(PolygonProxy, Polygon): def __init__(self, shell, holes=None): self.shell = shell self.holes = holes self.context = (shell, holes) self.factory = geos_polygon_from_py @property def _ndim(self): try: # From array protocol array = self.shell.__array_interface__ n = array['shape'][1] assert n == 2 or n == 3 return n except AttributeError: # Fall back on list return len(self.shell[0]) def asPolygon(shell, holes=None): """Adapt objects to the Polygon interface""" return PolygonAdapter(shell, holes) def orient(polygon, sign=1.0): s = float(sign) rings = [] ring = polygon.exterior if signed_area(ring)/s >= 0.0: rings.append(ring) else: rings.append(list(ring.coords)[::-1]) for ring in polygon.interiors: if signed_area(ring)/s <= 0.0: rings.append(ring) else: rings.append(list(ring.coords)[::-1]) return Polygon(rings[0], rings[1:]) def geos_linearring_from_py(ob, update_geom=None, update_ndim=0): # If a LinearRing is passed in, clone it and return # If a LineString is passed in, clone the coord seq and return a LinearRing if isinstance(ob, LineString): if type(ob) == LinearRing: return geos_geom_from_py(ob) else: if ob.is_closed and len(ob.coords) >= 4: return geos_geom_from_py(ob, lgeos.GEOSGeom_createLinearRing) # If numpy is present, we use numpy.require to ensure that we have a # C-continguous array that owns its data. View data will be copied. ob = required(ob) try: # From array protocol array = ob.__array_interface__ assert len(array['shape']) == 2 m = array['shape'][0] n = array['shape'][1] if m < 3: raise ValueError( "A LinearRing must have at least 3 coordinate tuples") assert n == 2 or n == 3 # Make pointer to the coordinate array if isinstance(array['data'], tuple): # numpy tuple (addr, read-only) cp = cast(array['data'][0], POINTER(c_double)) else: cp = array['data'] # Add closing coordinates to sequence? if cp[0] != cp[m*n-n] or cp[1] != cp[m*n-n+1]: M = m + 1 else: M = m # Create a coordinate sequence if update_geom is not None: cs = lgeos.GEOSGeom_getCoordSeq(update_geom) if n != update_ndim: raise ValueError( "Wrong coordinate dimensions; this geometry has dimensions: %d" \ % update_ndim) else: cs = lgeos.GEOSCoordSeq_create(M, n) # add to coordinate sequence for i in range(m): # Because of a bug in the GEOS C API, # always set X before Y lgeos.GEOSCoordSeq_setX(cs, i, cp[n*i]) lgeos.GEOSCoordSeq_setY(cs, i, cp[n*i+1]) if n == 3: lgeos.GEOSCoordSeq_setZ(cs, i, cp[n*i+2]) # Add closing coordinates to sequence? if M > m: # Because of a bug in the GEOS C API, # always set X before Y lgeos.GEOSCoordSeq_setX(cs, M-1, cp[0]) lgeos.GEOSCoordSeq_setY(cs, M-1, cp[1]) if n == 3: lgeos.GEOSCoordSeq_setZ(cs, M-1, cp[2]) except AttributeError: # Fall back on list try: m = len(ob) except TypeError: # Iterators, e.g. Python 3 zip ob = list(ob) m = len(ob) n = len(ob[0]) if m < 3: raise ValueError( "A LinearRing must have at least 3 coordinate tuples") assert (n == 2 or n == 3) # Add closing coordinates if not provided if m == 3 or ob[0][0] != ob[-1][0] or ob[0][1] != ob[-1][1]: M = m + 1 else: M = m # Create a coordinate sequence if update_geom is not None: cs = lgeos.GEOSGeom_getCoordSeq(update_geom) if n != update_ndim: raise ValueError( "Wrong coordinate dimensions; this geometry has dimensions: %d" \ % update_ndim) else: cs = lgeos.GEOSCoordSeq_create(M, n) # add to coordinate sequence for i in range(m): coords = ob[i] # Because of a bug in the GEOS C API, # always set X before Y lgeos.GEOSCoordSeq_setX(cs, i, coords[0]) lgeos.GEOSCoordSeq_setY(cs, i, coords[1]) if n == 3: try: lgeos.GEOSCoordSeq_setZ(cs, i, coords[2]) except IndexError: raise ValueError("Inconsistent coordinate dimensionality") # Add closing coordinates to sequence? if M > m: coords = ob[0] # Because of a bug in the GEOS C API, # always set X before Y lgeos.GEOSCoordSeq_setX(cs, M-1, coords[0]) lgeos.GEOSCoordSeq_setY(cs, M-1, coords[1]) if n == 3: lgeos.GEOSCoordSeq_setZ(cs, M-1, coords[2]) if update_geom is not None: return None else: return lgeos.GEOSGeom_createLinearRing(cs), n def update_linearring_from_py(geom, ob): geos_linearring_from_py(ob, geom._geom, geom._ndim) def geos_polygon_from_py(shell, holes=None): if isinstance(shell, Polygon): return geos_geom_from_py(shell) if shell is not None: geos_shell, ndim = geos_linearring_from_py(shell) if holes is not None and len(holes) > 0: ob = holes L = len(ob) exemplar = ob[0] try: N = len(exemplar[0]) except TypeError: N = exemplar._ndim if not L >= 1: raise ValueError("number of holes must be non zero") if not N in (2, 3): raise ValueError("insufficiant coordinate dimension") # Array of pointers to ring geometries geos_holes = (c_void_p * L)() # add to coordinate sequence for l in range(L): geom, ndim = geos_linearring_from_py(ob[l]) geos_holes[l] = cast(geom, c_void_p) else: geos_holes = POINTER(c_void_p)() L = 0 return ( lgeos.GEOSGeom_createPolygon( c_void_p(geos_shell), geos_holes, L ), ndim ) # Test runner def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test()
gpl-2.0
avedaee/DIRAC
DataManagementSystem/Client/ReplicaContainers.py
1
4513
# $HeadURL$ __RCSID__ = "$Id$" """ This module contains three classes associated to Replicas. The Replica class contains simply three member elements: SE, PFN and Status and provides access methods for each (inluding type checking). The CatalogReplica class inherits the Replica class. The PhysicalReplica class inherits the Replica class and adds the 'size','checksum','online' and 'migrated' members. In this context Replica refers to any copy of a file. This can be the first or an additional copy. OBSOLETE? K.C. """ import types from DIRAC import S_OK, S_ERROR from DIRAC.Core.Utilities.CFG import CFG class Replica: def __init__(self,pfn='',storageElement='',status=''): # These are the possible attributes for a replica if not type(pfn) in types.StringTypes: raise AttributeError, "pfn should be string type" self.pfn = str(pfn) if not type(storageElement) in types.StringTypes: raise AttributeError, "storageElement should be string type" self.se = str(storageElement) if not type(status) in types.StringTypes: raise AttributeError, "status should be string type" self.status = str(status) def setPFN(self,pfn): if not type(pfn) in types.StringTypes: return S_ERROR("PFN should be %s and not %s" % (types.StringType,type(pfn))) self.pfn = str(pfn) return S_OK() def setSE(self,se): if not type(se) in types.StringTypes: return S_ERROR("SE should be %s and not %s" % (types.StringType,type(se))) self.se = str(se) return S_OK() def setStatus(self,status): if not type(status) in types.StringTypes: return S_ERROR("Status should be %s and not %s" % (types.StringType,type(status))) self.status = str(status) return S_OK() def getPFN(self): return S_OK(self.pfn) def getSE(self): return S_OK(self.se) def getStatus(self): return S_OK(self.status) def digest(self): """ Get short description string of replica and status """ return S_OK("%s:%s:%s" % (self.se,self.pfn,self.status)) def toCFG(self): oCFG = CFG() oCFG.createNewSection(self.se) oCFG.setOption('%s/Status' % (self.se), self.status) oCFG.setOption('%s/PFN' % (self.se), self.pfn) return S_OK(str(oCFG)) class CatalogReplica(Replica): def __init__(self,pfn='',storageElement='',status='U'): Replica.__init__(self,pfn,storageElement,status) class PhysicalReplica(Replica): def __init__(self,pfn='',storageElement='',status='',size=0,checksum='',online=False,migrated=False): # These are the possible attributes for a physical replica Replica.__init__(self,pfn,storageElement,status) try: self.size = int(size) except: raise AttributeError, "size should be integer type" if not type(checksum) in types.StringTypes: raise AttributeError, "checksum should be string type" self.checksum = str(checksum) if not type(online) == types.BooleanType: raise AttributeError, "online should be bool type" self.online = online if not type(migrated) == types.BooleanType: raise AttributeError, "migrated should be bool type" self.migrated = migrated def setSize(self,size): try: self.size = int(size) return S_OK() except: return S_ERROR("Size should be %s and not %s" % (types.IntType,type(size))) def setChecksum(self,checksum): if not type(checksum) in types.StringTypes: return S_ERROR("Checksum should be %s and not %s" % (types.StringType,type(checksum))) self.checksum = str(checksum) return S_OK() def setOnline(self,online): if not type(online) == types.BooleanType: return S_ERROR("online should be %s and not %s" % (types.BooleanType,type(online))) self.online = online return S_OK() def setMigrated(self,migrated): if not type(migrated) == types.BooleanType: return S_ERROR("migrated should be %s and not %s" % (types.BooleanType,type(migrated))) self.migrated = migrated return S_OK() def getSize(self): return S_OK(self.size) def getChecksum(self): return S_OK(self.checksum) def getOnline(self): return S_OK(self.online) def getMigrated(self): return S_OK(self.migrated) def digest(self): online = 'NotOnline' if self.online: online = 'Online' migrated = 'NotMigrated' if self.migrated: migrated = 'Migrated' return S_OK("%s:%s:%d:%s:%s:%s" % (self.se,self.pfn,self.size,self.status,online,migrated))
gpl-3.0
MartynShaw/audacity
lib-src/lv2/sratom/waflib/Tools/d_config.py
316
1208
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file from waflib import Utils from waflib.Configure import conf @conf def d_platform_flags(self): v=self.env if not v.DEST_OS: v.DEST_OS=Utils.unversioned_sys_platform() binfmt=Utils.destos_to_binfmt(self.env.DEST_OS) if binfmt=='pe': v['dprogram_PATTERN']='%s.exe' v['dshlib_PATTERN']='lib%s.dll' v['dstlib_PATTERN']='lib%s.a' elif binfmt=='mac-o': v['dprogram_PATTERN']='%s' v['dshlib_PATTERN']='lib%s.dylib' v['dstlib_PATTERN']='lib%s.a' else: v['dprogram_PATTERN']='%s' v['dshlib_PATTERN']='lib%s.so' v['dstlib_PATTERN']='lib%s.a' DLIB=''' version(D_Version2) { import std.stdio; int main() { writefln("phobos2"); return 0; } } else { version(Tango) { import tango.stdc.stdio; int main() { printf("tango"); return 0; } } else { import std.stdio; int main() { writefln("phobos1"); return 0; } } } ''' @conf def check_dlibrary(self,execute=True): ret=self.check_cc(features='d dprogram',fragment=DLIB,compile_filename='test.d',execute=execute,define_ret=True) if execute: self.env.DLIBRARY=ret.strip()
gpl-2.0
Acehaidrey/incubator-airflow
airflow/providers/microsoft/azure/secrets/azure_key_vault.py
7
6445
# 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. from typing import Optional from azure.core.exceptions import ResourceNotFoundError from azure.identity import DefaultAzureCredential from azure.keyvault.secrets import SecretClient from cached_property import cached_property from airflow.secrets import BaseSecretsBackend from airflow.utils.log.logging_mixin import LoggingMixin class AzureKeyVaultBackend(BaseSecretsBackend, LoggingMixin): """ Retrieves Airflow Connections or Variables from Azure Key Vault secrets. The Azure Key Vault can be configured as a secrets backend in the ``airflow.cfg``: .. code-block:: ini [secrets] backend = airflow.providers.microsoft.azure.secrets.azure_key_vault.AzureKeyVaultBackend backend_kwargs = {"connections_prefix": "airflow-connections", "vault_url": "<azure_key_vault_uri>"} For example, if the secrets prefix is ``airflow-connections-smtp-default``, this would be accessible if you provide ``{"connections_prefix": "airflow-connections"}`` and request conn_id ``smtp-default``. And if variables prefix is ``airflow-variables-hello``, this would be accessible if you provide ``{"variables_prefix": "airflow-variables"}`` and request variable key ``hello``. :param connections_prefix: Specifies the prefix of the secret to read to get Connections If set to None (null), requests for connections will not be sent to Azure Key Vault :type connections_prefix: str :param variables_prefix: Specifies the prefix of the secret to read to get Variables If set to None (null), requests for variables will not be sent to Azure Key Vault :type variables_prefix: str :param config_prefix: Specifies the prefix of the secret to read to get Variables. If set to None (null), requests for configurations will not be sent to Azure Key Vault :type config_prefix: str :param vault_url: The URL of an Azure Key Vault to use :type vault_url: str :param sep: separator used to concatenate secret_prefix and secret_id. Default: "-" :type sep: str """ def __init__( self, connections_prefix: str = 'airflow-connections', variables_prefix: str = 'airflow-variables', config_prefix: str = 'airflow-config', vault_url: str = '', sep: str = '-', **kwargs, ) -> None: super().__init__() self.vault_url = vault_url if connections_prefix is not None: self.connections_prefix = connections_prefix.rstrip(sep) else: self.connections_prefix = connections_prefix if variables_prefix is not None: self.variables_prefix = variables_prefix.rstrip(sep) else: self.variables_prefix = variables_prefix if config_prefix is not None: self.config_prefix = config_prefix.rstrip(sep) else: self.config_prefix = config_prefix self.sep = sep self.kwargs = kwargs @cached_property def client(self) -> SecretClient: """Create a Azure Key Vault client.""" credential = DefaultAzureCredential() client = SecretClient(vault_url=self.vault_url, credential=credential, **self.kwargs) return client def get_conn_uri(self, conn_id: str) -> Optional[str]: """ Get an Airflow Connection URI from an Azure Key Vault secret :param conn_id: The Airflow connection id to retrieve :type conn_id: str """ if self.connections_prefix is None: return None return self._get_secret(self.connections_prefix, conn_id) def get_variable(self, key: str) -> Optional[str]: """ Get an Airflow Variable from an Azure Key Vault secret. :param key: Variable Key :type key: str :return: Variable Value """ if self.variables_prefix is None: return None return self._get_secret(self.variables_prefix, key) def get_config(self, key: str) -> Optional[str]: """ Get Airflow Configuration :param key: Configuration Option Key :return: Configuration Option Value """ if self.config_prefix is None: return None return self._get_secret(self.config_prefix, key) @staticmethod def build_path(path_prefix: str, secret_id: str, sep: str = '-') -> str: """ Given a path_prefix and secret_id, build a valid secret name for the Azure Key Vault Backend. Also replaces underscore in the path with dashes to support easy switching between environment variables, so ``connection_default`` becomes ``connection-default``. :param path_prefix: The path prefix of the secret to retrieve :type path_prefix: str :param secret_id: Name of the secret :type secret_id: str :param sep: Separator used to concatenate path_prefix and secret_id :type sep: str """ path = f'{path_prefix}{sep}{secret_id}' return path.replace('_', sep) def _get_secret(self, path_prefix: str, secret_id: str) -> Optional[str]: """ Get an Azure Key Vault secret value :param path_prefix: Prefix for the Path to get Secret :type path_prefix: str :param secret_id: Secret Key :type secret_id: str """ name = self.build_path(path_prefix, secret_id, self.sep) try: secret = self.client.get_secret(name=name) return secret.value except ResourceNotFoundError as ex: self.log.debug('Secret %s not found: %s', name, ex) return None
apache-2.0
zaina/nova
plugins/xenserver/networking/etc/xensource/scripts/ovs_configure_vif_flows.py
99
10338
#!/usr/bin/env python # Copyright 2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ This script is used to configure openvswitch flows on XenServer hosts. """ import os import sys # This is written to Python 2.4, since that is what is available on XenServer import netaddr import simplejson as json import novalib # noqa OVS_OFCTL = '/usr/bin/ovs-ofctl' class OvsFlow(object): def __init__(self, bridge, params): self.bridge = bridge self.params = params def add(self, rule): novalib.execute(OVS_OFCTL, 'add-flow', self.bridge, rule % self.params) def clear_flows(self, ofport): novalib.execute(OVS_OFCTL, 'del-flows', self.bridge, "in_port=%s" % ofport) def main(command, vif_raw, net_type): if command not in ('online', 'offline'): return vif_name, dom_id, vif_index = vif_raw.split('-') vif = "%s%s.%s" % (vif_name, dom_id, vif_index) bridge = novalib.execute_get_output('/usr/bin/ovs-vsctl', 'iface-to-br', vif) xsls = novalib.execute_get_output('/usr/bin/xenstore-ls', '/local/domain/%s/vm-data/networking' % dom_id) macs = [line.split("=")[0].strip() for line in xsls.splitlines()] for mac in macs: xsread = novalib.execute_get_output('/usr/bin/xenstore-read', '/local/domain/%s/vm-data/networking/%s' % (dom_id, mac)) data = json.loads(xsread) if data["label"] == "public": this_vif = "vif%s.0" % dom_id phys_dev = "eth0" else: this_vif = "vif%s.1" % dom_id phys_dev = "eth1" if vif == this_vif: vif_ofport = novalib.execute_get_output('/usr/bin/ovs-vsctl', 'get', 'Interface', vif, 'ofport') phys_ofport = novalib.execute_get_output('/usr/bin/ovs-vsctl', 'get', 'Interface', phys_dev, 'ofport') params = dict(VIF_NAME=vif, MAC=data['mac'], OF_PORT=vif_ofport, PHYS_PORT=phys_ofport) ovs = OvsFlow(bridge, params) if command == 'offline': # I haven't found a way to clear only IPv4 or IPv6 rules. ovs.clear_flows(vif_ofport) if command == 'online': if net_type in ('ipv4', 'all') and 'ips' in data: for ip4 in data['ips']: ovs.params.update({'IPV4_ADDR': ip4['ip']}) apply_ovs_ipv4_flows(ovs, bridge, params) if net_type in ('ipv6', 'all') and 'ip6s' in data: for ip6 in data['ip6s']: mac_eui64 = netaddr.EUI(data['mac']).eui64() link_local = str(mac_eui64.ipv6_link_local()) ovs.params.update({'IPV6_LINK_LOCAL_ADDR': link_local}) ovs.params.update({'IPV6_GLOBAL_ADDR': ip6['ip']}) apply_ovs_ipv6_flows(ovs, bridge, params) def apply_ovs_ipv4_flows(ovs, bridge, params): # When ARP traffic arrives from a vif, push it to virtual port # 9999 for further processing ovs.add("priority=4,arp,in_port=%(OF_PORT)s,dl_src=%(MAC)s," "nw_src=%(IPV4_ADDR)s,arp_sha=%(MAC)s,actions=resubmit:9999") ovs.add("priority=4,arp,in_port=%(OF_PORT)s,dl_src=%(MAC)s," "nw_src=0.0.0.0,arp_sha=%(MAC)s,actions=resubmit:9999") # When IP traffic arrives from a vif, push it to virtual port 9999 # for further processing ovs.add("priority=4,ip,in_port=%(OF_PORT)s,dl_src=%(MAC)s," "nw_src=%(IPV4_ADDR)s,actions=resubmit:9999") # Drop IP bcast/mcast ovs.add("priority=6,ip,in_port=%(OF_PORT)s,dl_dst=ff:ff:ff:ff:ff:ff," "actions=drop") ovs.add("priority=5,ip,in_port=%(OF_PORT)s,nw_dst=224.0.0.0/4," "actions=drop") ovs.add("priority=5,ip,in_port=%(OF_PORT)s,nw_dst=240.0.0.0/4," "actions=drop") # Pass ARP requests coming from any VMs on the local HV (port # 9999) or coming from external sources (PHYS_PORT) to the VM and # physical NIC. We output this to the physical NIC as well, since # with instances of shared ip groups, the active host for the # destination IP might be elsewhere... ovs.add("priority=3,arp,in_port=9999,nw_dst=%(IPV4_ADDR)s," "actions=output:%(OF_PORT)s,output:%(PHYS_PORT)s") # Pass ARP traffic originating from external sources the VM with # the matching IP address ovs.add("priority=3,arp,in_port=%(PHYS_PORT)s,nw_dst=%(IPV4_ADDR)s," "actions=output:%(OF_PORT)s") # Pass ARP traffic from one VM (src mac already validated) to # another VM on the same HV ovs.add("priority=3,arp,in_port=9999,dl_dst=%(MAC)s," "actions=output:%(OF_PORT)s") # Pass ARP replies coming from the external environment to the # target VM ovs.add("priority=3,arp,in_port=%(PHYS_PORT)s,dl_dst=%(MAC)s," "actions=output:%(OF_PORT)s") # ALL IP traffic: Pass IP data coming from any VMs on the local HV # (port 9999) or coming from external sources (PHYS_PORT) to the # VM and physical NIC. We output this to the physical NIC as # well, since with instances of shared ip groups, the active host # for the destination IP might be elsewhere... ovs.add("priority=3,ip,in_port=9999,dl_dst=%(MAC)s," "nw_dst=%(IPV4_ADDR)s,actions=output:%(OF_PORT)s," "output:%(PHYS_PORT)s") # Pass IP traffic from the external environment to the VM ovs.add("priority=3,ip,in_port=%(PHYS_PORT)s,dl_dst=%(MAC)s," "nw_dst=%(IPV4_ADDR)s,actions=output:%(OF_PORT)s") # Send any local traffic to the physical NIC's OVS port for # physical network learning ovs.add("priority=2,in_port=9999,actions=output:%(PHYS_PORT)s") def apply_ovs_ipv6_flows(ovs, bridge, params): # allow valid IPv6 ND outbound (are both global and local IPs needed?) # Neighbor Solicitation ovs.add("priority=6,in_port=%(OF_PORT)s,dl_src=%(MAC)s,icmp6," "ipv6_src=%(IPV6_LINK_LOCAL_ADDR)s,icmp_type=135,nd_sll=%(MAC)s," "actions=normal") ovs.add("priority=6,in_port=%(OF_PORT)s,dl_src=%(MAC)s,icmp6," "ipv6_src=%(IPV6_LINK_LOCAL_ADDR)s,icmp_type=135,actions=normal") ovs.add("priority=6,in_port=%(OF_PORT)s,dl_src=%(MAC)s,icmp6," "ipv6_src=%(IPV6_GLOBAL_ADDR)s,icmp_type=135,nd_sll=%(MAC)s," "actions=normal") ovs.add("priority=6,in_port=%(OF_PORT)s,dl_src=%(MAC)s,icmp6," "ipv6_src=%(IPV6_GLOBAL_ADDR)s,icmp_type=135,actions=normal") # Neighbor Advertisement ovs.add("priority=6,in_port=%(OF_PORT)s,dl_src=%(MAC)s,icmp6," "ipv6_src=%(IPV6_LINK_LOCAL_ADDR)s,icmp_type=136," "nd_target=%(IPV6_LINK_LOCAL_ADDR)s,actions=normal") ovs.add("priority=6,in_port=%(OF_PORT)s,dl_src=%(MAC)s,icmp6," "ipv6_src=%(IPV6_LINK_LOCAL_ADDR)s,icmp_type=136,actions=normal") ovs.add("priority=6,in_port=%(OF_PORT)s,dl_src=%(MAC)s,icmp6," "ipv6_src=%(IPV6_GLOBAL_ADDR)s,icmp_type=136," "nd_target=%(IPV6_GLOBAL_ADDR)s,actions=normal") ovs.add("priority=6,in_port=%(OF_PORT)s,dl_src=%(MAC)s,icmp6," "ipv6_src=%(IPV6_GLOBAL_ADDR)s,icmp_type=136,actions=normal") # drop all other neighbor discovery (req b/c we permit all icmp6 below) ovs.add("priority=5,in_port=%(OF_PORT)s,icmp6,icmp_type=135,actions=drop") ovs.add("priority=5,in_port=%(OF_PORT)s,icmp6,icmp_type=136,actions=drop") # do not allow sending specific ICMPv6 types # Router Advertisement ovs.add("priority=5,in_port=%(OF_PORT)s,icmp6,icmp_type=134,actions=drop") # Redirect Gateway ovs.add("priority=5,in_port=%(OF_PORT)s,icmp6,icmp_type=137,actions=drop") # Mobile Prefix Solicitation ovs.add("priority=5,in_port=%(OF_PORT)s,icmp6,icmp_type=146,actions=drop") # Mobile Prefix Advertisement ovs.add("priority=5,in_port=%(OF_PORT)s,icmp6,icmp_type=147,actions=drop") # Multicast Router Advertisement ovs.add("priority=5,in_port=%(OF_PORT)s,icmp6,icmp_type=151,actions=drop") # Multicast Router Solicitation ovs.add("priority=5,in_port=%(OF_PORT)s,icmp6,icmp_type=152,actions=drop") # Multicast Router Termination ovs.add("priority=5,in_port=%(OF_PORT)s,icmp6,icmp_type=153,actions=drop") # allow valid IPv6 outbound, by type ovs.add("priority=4,in_port=%(OF_PORT)s,dl_src=%(MAC)s," "ipv6_src=%(IPV6_GLOBAL_ADDR)s,icmp6,actions=normal") ovs.add("priority=4,in_port=%(OF_PORT)s,dl_src=%(MAC)s," "ipv6_src=%(IPV6_LINK_LOCAL_ADDR)s,icmp6,actions=normal") ovs.add("priority=4,in_port=%(OF_PORT)s,dl_src=%(MAC)s," "ipv6_src=%(IPV6_GLOBAL_ADDR)s,tcp6,actions=normal") ovs.add("priority=4,in_port=%(OF_PORT)s,dl_src=%(MAC)s," "ipv6_src=%(IPV6_LINK_LOCAL_ADDR)s,tcp6,actions=normal") ovs.add("priority=4,in_port=%(OF_PORT)s,dl_src=%(MAC)s," "ipv6_src=%(IPV6_GLOBAL_ADDR)s,udp6,actions=normal") ovs.add("priority=4,in_port=%(OF_PORT)s,dl_src=%(MAC)s," "ipv6_src=%(IPV6_LINK_LOCAL_ADDR)s,udp6,actions=normal") # all else will be dropped ... if __name__ == "__main__": if len(sys.argv) != 4: print ("usage: %s [online|offline] vif-domid-idx [ipv4|ipv6|all] " % os.path.basename(sys.argv[0])) sys.exit(1) else: command, vif_raw, net_type = sys.argv[1:4] main(command, vif_raw, net_type)
apache-2.0
erikrose/oedipus
oedipus/results.py
1
4275
class SearchResults(object): """Results in the order in which they came out of Sphinx Since Sphinx stores no non-numerical attributes, we have to reach into the DB to pull them out. """ def __init__(self, type, ids, fields): self.type = type # Sphinx may return IDs of objects since deleted from the DB. self.ids = ids self.fields = fields # tuple self.objects = dict(self._objects()) # {id: obj/tuple/dict, ...} def _queryset(self): """Return a QuerySet of the objects parallel to the found docs.""" return self.type.objects.filter(id__in=self.ids) def __iter__(self): """Iterate over results in the same order they came out of Sphinx.""" # Ripped off from elasticutils return (self.objects[id] for id in self.ids if id in self.objects) class DictResults(SearchResults): """Results as an iterable of dictionaries""" def _dicts_with_ids(self): """Return an iterable of dicts with ``id`` attrs, each representing a matched DB object.""" fields = self.fields # Append ID to the requested fields so we can keep track of object # identity to sort by weight (or whatever Sphinx sorted by). We could # optimize slightly by not prepending ID if the user already # specifically asked for it, but then we'd have to keep track of its # offset. if fields and 'id' not in fields: fields += ('id',) # Get values rather than values_list, because we need to be able to # find the ID afterward, and we don't want to have to go rooting around # in the Django model to figure out what order the fields were declared # in in the case that no fields were passed in. return self._queryset().values(*fields) def _objects(self): """Return an iterable of (document ID, dict) pairs.""" should_strip_ids = self.fields and 'id' not in self.fields for d in self._dicts_with_ids(): id = d.pop('id') if should_strip_ids else d['id'] yield id, d @classmethod def content_for_fields(klass, result, fields, highlight_fields): """Returns a tuple with content values for highlight_fields. :param result: A result generated by this class. :param fields: Iterable of fields for a result from this class. :param highlight_fields: Iterable of the fields to highlight. This should be a subset of ``fields``. :returns: Tuple with content in the field indexes specified by ``highlight_fields``. :raises KeyError: If there is a field in ``highlight_fields`` that doesn't exist in ``fields``. """ return tuple(result[field] for field in highlight_fields) class TupleResults(DictResults): """Results as an iterable of tuples, like Django's values_list()""" def _objects(self): """Return an iterable of (document ID, tuple) pairs.""" for d in self._dicts_with_ids(): yield d['id'], tuple(d[k] for k in self.fields) @classmethod def content_for_fields(klass, result, fields, highlight_fields): """See ``DictResults.content_for_fields``. :raises ValueError: If there is a field in ``highlight_fields`` that doesn't exist in ``fields``. """ return tuple(result[fields.index(field)] for field in highlight_fields) class ObjectResults(SearchResults): """Results as an iterable of Django model-like objects""" def _objects(self): """Return an iterable of (document ID, model object) pairs.""" # Assuming the document ID is called "id" lets us depend on fewer # Djangoisms than assuming it's the pk; we'd have to get # self.type._meta to get the name of the pk. return ((o.id, o) for o in self._queryset()) @classmethod def content_for_fields(klass, result, fields, highlight_fields): """See ``DictResults.content_for_fields``. :raises AttributeError: If there is a field in ``highlight_fields`` that doesn't exist in ``fields``. """ return tuple(getattr(result, field) for field in highlight_fields)
bsd-3-clause
arjunasuresh3/Mypykoans
python 2/koans/about_monkey_patching.py
1
1451
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Related to AboutOpenClasses in the Ruby Koans # from runner.koan import * class AboutMonkeyPatching(Koan): class Dog(object): def bark(self): return "WOOF" def test_as_defined_dogs_do_bark(self): fido = self.Dog() self.assertEqual("WOOF", fido.bark()) # ------------------------------------------------------------------ # Add a new method to an existing class. def test_after_patching_dogs_can_both_wag_and_bark(self): def wag(self): return "HAPPY" self.Dog.wag = wag fido = self.Dog() self.assertEqual("HAPPY", fido.wag()) self.assertEqual("WOOF", fido.bark()) # ------------------------------------------------------------------ def test_most_built_in_classes_cannot_be_monkey_patched(self): try: int.is_even = lambda self: (self % 2) == 0 except StandardError as ex: self.assertMatch("can't set attributes of built-in/extension type 'int'", ex[0]) # ------------------------------------------------------------------ class MyInt(int): pass def test_subclasses_of_built_in_classes_can_be_be_monkey_patched(self): self.MyInt.is_even = lambda self: (self % 2) == 0 self.assertEqual(False, self.MyInt(1).is_even()) self.assertEqual(True, self.MyInt(2).is_even())
mit
vbtdung/DCTCP-assignment
dctcp-assignment/util/plot_tcpprobe.py
3
2603
from helper import * from collections import defaultdict import argparse parser = argparse.ArgumentParser() parser.add_argument('-p', '--port', dest="port", default='5001') parser.add_argument('-f', dest="files", nargs='+', required=True) parser.add_argument('-o', '--out', dest="out", default=None) parser.add_argument('-H', '--histogram', dest="histogram", help="Plot histogram of sum(cwnd_i)", action="store_true", default=False) args = parser.parse_args() def first(lst): return map(lambda e: e[0], lst) def second(lst): return map(lambda e: e[1], lst) """ Sample line: 2.221032535 10.0.0.2:39815 10.0.0.1:5001 32 0x1a2a710c 0x1a2a387c 11 2147483647 14592 85 """ def parse_file(f): times = defaultdict(list) cwnd = defaultdict(list) srtt = [] for l in open(f).xreadlines(): fields = l.strip().split(' ') if len(fields) != 10: break if fields[2].split(':')[1] != args.port: continue sport = int(fields[1].split(':')[1]) times[sport].append(float(fields[0])) c = int(fields[6]) cwnd[sport].append(c * 1480 / 1024.0) srtt.append(int(fields[-1])) return times, cwnd added = defaultdict(int) events = [] def plot_cwnds(ax): global events for f in args.files: times, cwnds = parse_file(f) for port in sorted(cwnds.keys()): t = times[port] cwnd = cwnds[port] events += zip(t, [port]*len(t), cwnd) ax.plot(t, cwnd) events.sort() total_cwnd = 0 cwnd_time = [] min_total_cwnd = 10**10 max_total_cwnd = 0 totalcwnds = [] m.rc('figure', figsize=(16, 6)) fig = plt.figure() plots = 1 if args.histogram: plots = 2 axPlot = fig.add_subplot(1, plots, 1) plot_cwnds(axPlot) for (t,p,c) in events: if added[p]: total_cwnd -= added[p] total_cwnd += c cwnd_time.append((t, total_cwnd)) added[p] = c totalcwnds.append(total_cwnd) axPlot.plot(first(cwnd_time), second(cwnd_time), lw=2, label="$\sum_i W_i$") axPlot.grid(True) axPlot.legend() axPlot.set_xlabel("seconds") axPlot.set_ylabel("cwnd KB") axPlot.set_title("TCP congestion window (cwnd) timeseries") if args.histogram: axHist = fig.add_subplot(1, 2, 2) n, bins, patches = axHist.hist(totalcwnds, 50, normed=1, facecolor='green', alpha=0.75) axHist.set_xlabel("bins (KB)") axHist.set_ylabel("Fraction") axHist.set_title("Histogram of sum(cwnd_i)") if args.out: print 'saving to', args.out plt.savefig(args.out) else: plt.show()
unlicense
siouka/dmind
plugin.video.veetle/flvlib/astypes.py
98
8332
import os import calendar import datetime import logging from primitives import * from constants import * from helpers import OrderedAttrDict, utc """ The AS types and their FLV representations. """ log = logging.getLogger('flvlib.astypes') class MalformedFLV(Exception): pass # Number def get_number(f, max_offset=None): return get_double(f) def make_number(num): return make_double(num) # Boolean def get_boolean(f, max_offset=None): value = get_ui8(f) return bool(value) def make_boolean(value): return make_ui8((value and 1) or 0) # String def get_string(f, max_offset=None): # First 16 bits are the string's length length = get_ui16(f) # Then comes the string itself ret = f.read(length) return ret def make_string(string): if isinstance(string, unicode): # We need a blob, not unicode. Arbitrarily choose UTF-8 string = string.encode('UTF-8') length = make_ui16(len(string)) return length + string # Longstring def get_longstring(f, max_offset=None): # First 32 bits are the string's length length = get_ui32(f) # Then comes the string itself ret = f.read(length) return ret def make_longstring(string): if isinstance(string, unicode): # We need a blob, not unicode. Arbitrarily choose UTF-8 string = string.encode('UTF-8') length = make_ui32(len(string)) return length + string # ECMA Array class ECMAArray(OrderedAttrDict): pass def get_ecma_array(f, max_offset=None): length = get_ui32(f) log.debug("The ECMA array has approximately %d elements", length) array = ECMAArray() while True: if max_offset and (f.tell() == max_offset): log.debug("Prematurely terminating reading an ECMA array") break marker = get_ui24(f) if marker == 9: log.debug("Marker!") break else: f.seek(-3, os.SEEK_CUR) name, value = get_script_data_variable(f, max_offset=max_offset) array[name] = value return array def make_ecma_array(d): length = make_ui32(len(d)) rest = ''.join([make_script_data_variable(name, value) for name, value in d.iteritems()]) marker = make_ui24(9) return length + rest + marker # Strict Array def get_strict_array(f, max_offset=None): length = get_ui32(f) log.debug("The length is %d", length) elements = [get_script_data_value(f, max_offset=max_offset) for _ in xrange(length)] return elements def make_strict_array(l): ret = make_ui32(len(l)) rest = ''.join([make_script_data_value(value) for value in l]) return ret + rest # Date def get_date(f, max_offset=None): timestamp = get_number(f) / 1000.0 # From the following document: # http://opensource.adobe.com/wiki/download/ # attachments/1114283/amf0_spec_121207.pdf # # Section 2.13 Date Type # # (...) While the design of this type reserves room for time zone offset # information, it should not be filled in, nor used (...) _ignored = get_si16(f) return datetime.datetime.fromtimestamp(timestamp, utc) def make_date(date): if date.tzinfo: utc_date = date.astimezone(utc) else: # assume it's UTC utc_date = date.replace(tzinfo=utc) ret = make_number(calendar.timegm(utc_date.timetuple()) * 1000) offset = 0 return ret + make_si16(offset) # Null def get_null(f, max_offset=None): return None def make_null(none): return '' # Object class FLVObject(OrderedAttrDict): pass def get_object(f, max_offset=None): ret = FLVObject() while True: if max_offset and (f.tell() == max_offset): log.debug("Prematurely terminating reading an object") break marker = get_ui24(f) if marker == 9: log.debug("Marker!") break else: f.seek(-3, os.SEEK_CUR) name, value = get_script_data_variable(f) setattr(ret, name, value) return ret def make_object(obj): # If the object is iterable, serialize keys/values. If not, fall # back on iterating over __dict__. # This makes sure that make_object(get_object(StringIO(blob))) == blob try: iterator = obj.iteritems() except AttributeError: iterator = obj.__dict__.iteritems() ret = ''.join([make_script_data_variable(name, value) for name, value in iterator]) marker = make_ui24(9) return ret + marker # MovieClip class MovieClip(object): def __init__(self, path): self.path = path def __eq__(self, other): return isinstance(other, MovieClip) and self.path == other.path def __repr__(self): return "<MovieClip at %s>" % self.path def get_movieclip(f, max_offset=None): ret = get_string(f) return MovieClip(ret) def make_movieclip(clip): return make_string(clip.path) # Undefined class Undefined(object): def __eq__(self, other): return isinstance(other, Undefined) def __repr__(self): return '<Undefined>' def get_undefined(f, max_offset=None): return Undefined() def make_undefined(undefined): return '' # Reference class Reference(object): def __init__(self, ref): self.ref = ref def __eq__(self, other): return isinstance(other, Reference) and self.ref == other.ref def __repr__(self): return "<Reference to %d>" % self.ref def get_reference(f, max_offset=None): ret = get_ui16(f) return Reference(ret) def make_reference(reference): return make_ui16(reference.ref) as_type_to_getter_and_maker = { VALUE_TYPE_NUMBER: (get_number, make_number), VALUE_TYPE_BOOLEAN: (get_boolean, make_boolean), VALUE_TYPE_STRING: (get_string, make_string), VALUE_TYPE_OBJECT: (get_object, make_object), VALUE_TYPE_MOVIECLIP: (get_movieclip, make_movieclip), VALUE_TYPE_NULL: (get_null, make_null), VALUE_TYPE_UNDEFINED: (get_undefined, make_undefined), VALUE_TYPE_REFERENCE: (get_reference, make_reference), VALUE_TYPE_ECMA_ARRAY: (get_ecma_array, make_ecma_array), VALUE_TYPE_STRICT_ARRAY: (get_strict_array, make_strict_array), VALUE_TYPE_DATE: (get_date, make_date), VALUE_TYPE_LONGSTRING: (get_longstring, make_longstring) } type_to_as_type = { bool: VALUE_TYPE_BOOLEAN, int: VALUE_TYPE_NUMBER, long: VALUE_TYPE_NUMBER, float: VALUE_TYPE_NUMBER, # WARNING: not supporting Longstrings here. # With a max length of 65535 chars, noone will notice. str: VALUE_TYPE_STRING, unicode: VALUE_TYPE_STRING, list: VALUE_TYPE_STRICT_ARRAY, dict: VALUE_TYPE_ECMA_ARRAY, ECMAArray: VALUE_TYPE_ECMA_ARRAY, datetime.datetime: VALUE_TYPE_DATE, Undefined: VALUE_TYPE_UNDEFINED, MovieClip: VALUE_TYPE_MOVIECLIP, Reference: VALUE_TYPE_REFERENCE, type(None): VALUE_TYPE_NULL } # SCRIPTDATAVARIABLE def get_script_data_variable(f, max_offset=None): name = get_string(f) log.debug("The name is %s", name) value = get_script_data_value(f, max_offset=max_offset) log.debug("The value is %r", value) return (name, value) def make_script_data_variable(name, value): log.debug("The name is %s", name) log.debug("The value is %r", value) ret = make_string(name) + make_script_data_value(value) return ret # SCRIPTDATAVALUE def get_script_data_value(f, max_offset=None): value_type = get_ui8(f) log.debug("The value type is %r", value_type) try: get_value = as_type_to_getter_and_maker[value_type][0] except KeyError: raise MalformedFLV("Invalid script data value type: %d", value_type) log.debug("The getter function is %r", get_value) value = get_value(f, max_offset=max_offset) return value def make_script_data_value(value): value_type = type_to_as_type.get(value.__class__, VALUE_TYPE_OBJECT) log.debug("The value type is %r", value_type) # KeyError can't happen here, because we always fall back on # VALUE_TYPE_OBJECT when determining value_type make_value = as_type_to_getter_and_maker[value_type][1] log.debug("The maker function is %r", make_value) type_tag = make_ui8(value_type) ret = make_value(value) return type_tag + ret
gpl-2.0
ColinIanKing/autotest
client/shared/test_utils/mock_demo.py
7
3155
#!/usr/bin/python __author__ = "raphtee@google.com (Travis Miller)" import mock, mock_demo_MUT class MyError(Exception): pass class A(object): var = 8 def __init__(self): self.x = 0 def method1(self): self.x += 1 return self.x def method2(self, y): return y * self.x class B(A): def method3(self, z): return self.x + z def method4(self, z, w): return self.x * z + w class C(B): def method5(self): self.method1() t = self.method2(4) u = self.method3(t) return u class D(C): def method6(self, error): if error: raise MyError("woops") else: return 10 class E(D): def __init__(self, val): self.val = val # say we want to test that do_stuff is doing what we think it is doing def do_stuff(a, b, func): print b.method1() print b.method3(10) print func("how many") print a.method2(5) print b.method1() print b.method4(1, 4) print b.method2(3) print b.method2("hello") def do_more_stuff(d): print d.method6(False) try: d.method6(True) except Exception: print "caught error" def main(): god = mock.mock_god() m1 = god.create_mock_class(A, "A") print m1.var m2 = god.create_mock_class(B, "B") f = god.create_mock_function("func") print dir(m1) print dir(m2) # sets up the "recording" m2.method1.expect_call().and_return(1) m2.method3.expect_call(10).and_return(10) f.expect_call("how many").and_return(42) m1.method2.expect_call(5).and_return(0) m2.method1.expect_call().and_return(2) m2.method4.expect_call(1, 4).and_return(6) m2.method2.expect_call(3).and_return(6) m2.method2.expect_call(mock.is_string_comparator()).and_return("foo") # check the recording order for func_call in god.recording: print func_call # once we start making calls into the methods we are in # playback mode do_stuff(m1, m2, f) # we can now check that playback succeeded god.check_playback() # now test the ability to mock out all methods of an object # except those under test c = C() god.mock_up(c, "c") # setup recording c.method1.expect_call() c.method2.expect_call(4).and_return(4) c.method3.expect_call(4).and_return(5) # perform the test answer = c.method5.run_original_function() # check playback print "answer = %s" % (answer) god.check_playback() # check exception returns too m3 = god.create_mock_class(D, "D") m3.method6.expect_call(False).and_return(10) m3.method6.expect_call(True).and_raises(MyError("woops")) do_more_stuff(m3) god.check_playback() # now check we can mock out a whole class (rather than just an instance) mockE = god.create_mock_class_obj(E, "E") oldE = mock_demo_MUT.E mock_demo_MUT.E = mockE m4 = mockE.expect_new(val=7) m4.method1.expect_call().and_return(1) mock_demo_MUT.do_create_stuff() god.check_playback() mock_demo_MUT.E = oldE if __name__ == "__main__": main()
gpl-2.0
cccfran/sympy
sympy/assumptions/handlers/calculus.py
18
8089
""" This module contains query handlers responsible for calculus queries: infinitesimal, bounded, etc. """ from __future__ import print_function, division from sympy.logic.boolalg import conjuncts from sympy.assumptions import Q, ask from sympy.assumptions.handlers import CommonHandler class AskInfinitesimalHandler(CommonHandler): """ Handler for key 'infinitesimal' Test that a given expression is equivalent to an infinitesimal number """ @staticmethod def _number(expr, assumptions): # helper method return expr.evalf() == 0 @staticmethod def Basic(expr, assumptions): if expr.is_number: return AskInfinitesimalHandler._number(expr, assumptions) @staticmethod def Mul(expr, assumptions): """ Infinitesimal*Bounded -> Infinitesimal """ if expr.is_number: return AskInfinitesimalHandler._number(expr, assumptions) result = False for arg in expr.args: if ask(Q.infinitesimal(arg), assumptions): result = True elif ask(Q.bounded(arg), assumptions): continue else: break else: return result Add, Pow = [Mul]*2 @staticmethod def Number(expr, assumptions): return expr == 0 NumberSymbol = Number ImaginaryUnit = staticmethod(CommonHandler.AlwaysFalse) class AskBoundedHandler(CommonHandler): """ Handler for key 'bounded'. Test that an expression is bounded respect to all its variables. Examples of usage: >>> from sympy import Symbol, Q >>> from sympy.assumptions.handlers.calculus import AskBoundedHandler >>> from sympy.abc import x >>> a = AskBoundedHandler() >>> a.Symbol(x, Q.positive(x)) == None True >>> a.Symbol(x, Q.bounded(x)) True """ @staticmethod def Symbol(expr, assumptions): """ Handles Symbol. Examples: >>> from sympy import Symbol, Q >>> from sympy.assumptions.handlers.calculus import AskBoundedHandler >>> from sympy.abc import x >>> a = AskBoundedHandler() >>> a.Symbol(x, Q.positive(x)) == None True >>> a.Symbol(x, Q.bounded(x)) True """ if Q.bounded(expr) in conjuncts(assumptions): return True return None @staticmethod def Add(expr, assumptions): """ Return True if expr is bounded, False if not and None if unknown. Truth Table: +-------+-----+-----------+-----------+ | | | | | | | B | U | ? | | | | | | +-------+-----+---+---+---+---+---+---+ | | | | | | | | | | | |'+'|'-'|'x'|'+'|'-'|'x'| | | | | | | | | | +-------+-----+---+---+---+---+---+---+ | | | | | | B | B | U | ? | | | | | | +---+---+-----+---+---+---+---+---+---+ | | | | | | | | | | | |'+'| | U | ? | ? | U | ? | ? | | | | | | | | | | | | +---+-----+---+---+---+---+---+---+ | | | | | | | | | | | U |'-'| | ? | U | ? | ? | U | ? | | | | | | | | | | | | +---+-----+---+---+---+---+---+---+ | | | | | | | |'x'| | ? | ? | | | | | | | +---+---+-----+---+---+---+---+---+---+ | | | | | | ? | | | ? | | | | | | +-------+-----+-----------+---+---+---+ * 'B' = Bounded * 'U' = Unbounded * '?' = unknown boundedness * '+' = positive sign * '-' = negative sign * 'x' = sign unknown | * All Bounded -> True * 1 Unbounded and the rest Bounded -> False * >1 Unbounded, all with same known sign -> False * Any Unknown and unknown sign -> None * Else -> None When the signs are not the same you can have an undefined result as in oo - oo, hence 'bounded' is also undefined. """ sign = -1 # sign of unknown or infinite result = True for arg in expr.args: _bounded = ask(Q.bounded(arg), assumptions) if _bounded: continue s = ask(Q.positive(arg), assumptions) # if there has been more than one sign or if the sign of this arg # is None and Bounded is None or there was already # an unknown sign, return None if sign != -1 and s != sign or \ s is None and (s == _bounded or s == sign): return None else: sign = s # once False, do not change if result is not False: result = _bounded return result @staticmethod def Mul(expr, assumptions): """ Return True if expr is bounded, False if not and None if unknown. Truth Table: +---+---+---+--------+ | | | | | | | B | U | ? | | | | | | +---+---+---+---+----+ | | | | | | | | | | s | /s | | | | | | | +---+---+---+---+----+ | | | | | | B | B | U | ? | | | | | | +---+---+---+---+----+ | | | | | | | U | | U | U | ? | | | | | | | +---+---+---+---+----+ | | | | | | ? | | | ? | | | | | | +---+---+---+---+----+ * B = Bounded * U = Unbounded * ? = unknown boundedness * s = signed (hence nonzero) * /s = not signed """ result = True for arg in expr.args: _bounded = ask(Q.bounded(arg), assumptions) if _bounded: continue elif _bounded is None: if result is None: return None if ask(Q.nonzero(arg), assumptions) is None: return None if result is not False: result = None else: result = False return result @staticmethod def Pow(expr, assumptions): """ Unbounded ** NonZero -> Unbounded Bounded ** Bounded -> Bounded Abs()<=1 ** Positive -> Bounded Abs()>=1 ** Negative -> Bounded Otherwise unknown """ base_bounded = ask(Q.bounded(expr.base), assumptions) exp_bounded = ask(Q.bounded(expr.exp), assumptions) if base_bounded is None and exp_bounded is None: # Common Case return None if base_bounded is False and ask(Q.nonzero(expr.exp), assumptions): return False if base_bounded and exp_bounded: return True if (abs(expr.base) <= 1) == True and ask(Q.positive(expr.exp), assumptions): return True if (abs(expr.base) >= 1) == True and ask(Q.negative(expr.exp), assumptions): return True if (abs(expr.base) >= 1) == True and exp_bounded is False: return False return None @staticmethod def log(expr, assumptions): return ask(Q.bounded(expr.args[0]), assumptions) exp = log cos, sin, Number, Pi, Exp1, GoldenRatio, ImaginaryUnit, sign = \ [staticmethod(CommonHandler.AlwaysTrue)]*8 Infinity, NegativeInfinity = [staticmethod(CommonHandler.AlwaysFalse)]*2
bsd-3-clause
NeCTAR-RC/neutron
neutron/api/rpc/handlers/metadata_rpc.py
58
1561
# Copyright (c) 2014 OpenStack Foundation. # # 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 oslo_messaging from neutron.common import constants from neutron import manager class MetadataRpcCallback(object): """Metadata agent RPC callback in plugin implementations. This class implements the server side of an rpc interface used by the metadata service to make calls back into the Neutron plugin. The client side is defined in neutron.agent.metadata.agent.MetadataPluginAPI. For more information about changing rpc interfaces, see doc/source/devref/rpc_api.rst. """ # 1.0 MetadataPluginAPI BASE_RPC_API_VERSION target = oslo_messaging.Target(version='1.0', namespace=constants.RPC_NAMESPACE_METADATA) @property def plugin(self): if not hasattr(self, '_plugin'): self._plugin = manager.NeutronManager.get_plugin() return self._plugin def get_ports(self, context, filters): return self.plugin.get_ports(context, filters=filters)
apache-2.0
kenshay/ImageScript
ProgramData/SystemFiles/Python/Lib/site-packages/pygame/tests/test_utils/run_tests.py
6
12020
import sys if __name__ == '__main__': sys.exit("This module is for import only") test_pkg_name = '.'.join(__name__.split('.')[0:-2]) is_pygame_pkg = test_pkg_name == 'pygame.tests' test_runner_mod = test_pkg_name + '.test_utils.test_runner' if is_pygame_pkg: from pygame.tests.test_utils import import_submodule from pygame.tests.test_utils.test_runner \ import prepare_test_env, run_test, combine_results, \ get_test_results, TEST_RESULTS_START else: from test.test_utils import import_submodule from test.test_utils.test_runner \ import prepare_test_env, run_test, combine_results, \ get_test_results, TEST_RESULTS_START import pygame import pygame.threads import os import re import shutil import tempfile import time import random from pprint import pformat was_run = False def run(*args, **kwds): """Run the Pygame unit test suite and return (total tests run, fails dict) Positional arguments (optional): The names of tests to include. If omitted then all tests are run. Test names need not include the trailing '_test'. Keyword arguments: incomplete - fail incomplete tests (default False) nosubprocess - run all test suites in the current process (default False, use separate subprocesses) dump - dump failures/errors as dict ready to eval (default False) file - if provided, the name of a file into which to dump failures/errors timings - if provided, the number of times to run each individual test to get an average run time (default is run each test once) exclude - A list of TAG names to exclude from the run. The items may be comma or space separated. show_output - show silenced stderr/stdout on errors (default False) all - dump all results, not just errors (default False) randomize - randomize order of tests (default False) seed - if provided, a seed randomizer integer multi_thread - if provided, the number of THREADS in which to run subprocessed tests time_out - if subprocess is True then the time limit in seconds before killing a test (default 30) fake - if provided, the name of the fake tests package in the run_tests__tests subpackage to run instead of the normal Pygame tests python - the path to a python executable to run subprocessed tests (default sys.executable) interative - allow tests tagged 'interative'. Return value: A tuple of total number of tests run, dictionary of error information. The dictionary is empty if no errors were recorded. By default individual test modules are run in separate subprocesses. This recreates normal Pygame usage where pygame.init() and pygame.quit() are called only once per program execution, and avoids unfortunate interactions between test modules. Also, a time limit is placed on test execution, so frozen tests are killed when there time allotment expired. Use the single process option if threading is not working properly or if tests are taking too long. It is not guaranteed that all tests will pass in single process mode. Tests are run in a randomized order if the randomize argument is True or a seed argument is provided. If no seed integer is provided then the system time is used. Individual test modules may have a corresponding *_tags.py module, defining a __tags__ attribute, a list of tag strings used to selectively omit modules from a run. By default only the 'interactive', 'ignore', and 'subprocess_ignore' tags are ignored. 'interactive' is for modules that take user input, like cdrom_test.py. 'ignore' and 'subprocess_ignore' for for disabling modules for foreground and subprocess modes respectively. These are for disabling tests on optional modules or for experimental modules with known problems. These modules can be run from the console as a Python program. This function can only be called once per Python session. It is not reentrant. """ global was_run if was_run: raise RuntimeError("run() was already called this session") was_run = True options = kwds.copy() option_nosubprocess = options.get('nosubprocess', False) option_dump = options.pop('dump', False) option_file = options.pop('file', None) option_randomize = options.get('randomize', False) option_seed = options.get('seed', None) option_multi_thread = options.pop('multi_thread', 1) option_time_out = options.pop('time_out', 120) option_fake = options.pop('fake', None) option_python = options.pop('python', sys.executable) option_exclude = options.pop('exclude', ()) option_interactive = options.pop('interactive', False) if not option_interactive and 'interactive' not in option_exclude: option_exclude += ('interactive',) if not option_nosubprocess and 'subprocess_ignore' not in option_exclude: option_exclude += ('subprocess_ignore',) elif 'ignore' not in option_exclude: option_exclude += ('ignore',) if sys.version_info < (3, 0, 0): option_exclude += ('python2_ignore',) else: option_exclude += ('python3_ignore',) main_dir, test_subdir, fake_test_subdir = prepare_test_env() ########################################################################### # Compile a list of test modules. If fake, then compile list of fake # xxxx_test.py from run_tests__tests TEST_MODULE_RE = re.compile('^(.+_test)\.py$') test_mods_pkg_name = test_pkg_name working_dir_temp = tempfile.mkdtemp() if option_fake is not None: test_mods_pkg_name = '.'.join([test_mods_pkg_name, 'run_tests__tests', option_fake]) test_subdir = os.path.join(fake_test_subdir, option_fake) working_dir = test_subdir else: working_dir = working_dir_temp # Added in because some machines will need os.environ else there will be # false failures in subprocess mode. Same issue as python2.6. Needs some # env vars. test_env = os.environ fmt1 = '%s.%%s' % test_mods_pkg_name fmt2 = '%s.%%s_test' % test_mods_pkg_name if args: test_modules = [ m.endswith('_test') and (fmt1 % m) or (fmt2 % m) for m in args ] else: test_modules = [] for f in sorted(os.listdir(test_subdir)): for match in TEST_MODULE_RE.findall(f): test_modules.append(fmt1 % (match,)) ########################################################################### # Remove modules to be excluded. tmp = test_modules test_modules = [] for name in tmp: tag_module_name = "%s_tags" % (name[0:-5],) try: tag_module = import_submodule(tag_module_name) except ImportError: test_modules.append(name) else: try: tags = tag_module.__tags__ except AttributeError: print ("%s has no tags: ignoring" % (tag_module_name,)) test_modules.append(name) else: for tag in tags: if tag in option_exclude: print ("skipping %s (tag '%s')" % (name, tag)) break else: test_modules.append(name) del tmp, tag_module_name, name ########################################################################### # Meta results results = {} meta_results = {'__meta__' : {}} meta = meta_results['__meta__'] ########################################################################### # Randomization if option_randomize or option_seed is not None: if option_seed is None: option_seed = time.time() meta['random_seed'] = option_seed print ("\nRANDOM SEED USED: %s\n" % option_seed) random.seed(option_seed) random.shuffle(test_modules) ########################################################################### # Single process mode if option_nosubprocess: options['exclude'] = option_exclude t = time.time() for module in test_modules: results.update(run_test(module, **options)) t = time.time() - t ########################################################################### # Subprocess mode # else: if is_pygame_pkg: from pygame.tests.test_utils.async_sub import proc_in_time_or_kill else: from test.test_utils.async_sub import proc_in_time_or_kill pass_on_args = ['--exclude', ','.join(option_exclude)] for field in ['randomize', 'incomplete', 'unbuffered']: if kwds.get(field, False): pass_on_args.append('--'+field) def sub_test(module): print ('loading %s' % module) cmd = [option_python, '-m', test_runner_mod, module] + pass_on_args return (module, (cmd, test_env, working_dir), proc_in_time_or_kill(cmd, option_time_out, env=test_env, wd=working_dir)) if option_multi_thread > 1: def tmap(f, args): return pygame.threads.tmap ( f, args, stop_on_error = False, num_workers = option_multi_thread ) else: tmap = map t = time.time() for module, cmd, (return_code, raw_return) in tmap(sub_test, test_modules): test_file = '%s.py' % os.path.join(test_subdir, module) cmd, test_env, working_dir = cmd test_results = get_test_results(raw_return) if test_results: results.update(test_results) else: results[module] = {} results[module].update(dict( return_code=return_code, raw_return=raw_return, cmd=cmd, test_file=test_file, test_env=test_env, working_dir=working_dir, module=module, )) t = time.time() - t ########################################################################### # Output Results # untrusty_total, combined = combine_results(results, t) total, n_errors, n_failures = count_results(results) meta['total_tests'] = total meta['combined'] = combined meta['total_errors'] = n_errors meta['total_failures'] = n_failures results.update(meta_results) if option_nosubprocess: assert total == untrusty_total if not option_dump: print (combined) else: print (TEST_RESULTS_START) print (pformat(results)) if option_file is not None: results_file = open(option_file, 'w') try: results_file.write(pformat(results)) finally: results_file.close() shutil.rmtree(working_dir_temp) return total, n_errors + n_failures def count_results(results): total = errors = failures = 0 for result in results.values(): if result.get('return_code', 0): total += 1 errors += 1 else: total += result['num_tests'] errors += result['num_errors'] failures += result['num_failures'] return total, errors, failures def run_and_exit(*args, **kwargs): """Run the tests, and if there are failures, exit with a return code of 1. This is needed for various buildbots to recognise that the tests have failed. """ total, fails = run(*args, **kwargs) if fails: sys.exit(1) sys.exit(0)
gpl-3.0
Tagar/incubator-airflow
airflow/hooks/oracle_hook.py
3
6157
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import cx_Oracle from airflow.hooks.dbapi_hook import DbApiHook from builtins import str from past.builtins import basestring from datetime import datetime import numpy class OracleHook(DbApiHook): """ Interact with Oracle SQL. """ conn_name_attr = 'oracle_conn_id' default_conn_name = 'oracle_default' supports_autocommit = False def get_conn(self): """ Returns a oracle connection object Optional parameters for using a custom DSN connection (instead of using a server alias from tnsnames.ora) The dsn (data source name) is the TNS entry (from the Oracle names server or tnsnames.ora file) or is a string like the one returned from makedsn(). :param dsn: the host address for the Oracle server :param service_name: the db_unique_name of the database that you are connecting to (CONNECT_DATA part of TNS) You can set these parameters in the extra fields of your connection as in ``{ "dsn":"some.host.address" , "service_name":"some.service.name" }`` """ conn = self.get_connection(self.oracle_conn_id) dsn = conn.extra_dejson.get('dsn', None) sid = conn.extra_dejson.get('sid', None) mod = conn.extra_dejson.get('module', None) service_name = conn.extra_dejson.get('service_name', None) if dsn and sid and not service_name: dsn = cx_Oracle.makedsn(dsn, conn.port, sid) conn = cx_Oracle.connect(conn.login, conn.password, dsn=dsn) elif dsn and service_name and not sid: dsn = cx_Oracle.makedsn(dsn, conn.port, service_name=service_name) conn = cx_Oracle.connect(conn.login, conn.password, dsn=dsn) else: conn = cx_Oracle.connect(conn.login, conn.password, conn.host) if mod is not None: conn.module = mod return conn def insert_rows(self, table, rows, target_fields=None, commit_every=1000): """ A generic way to insert a set of tuples into a table, the whole set of inserts is treated as one transaction Changes from standard DbApiHook implementation: - Oracle SQL queries in cx_Oracle can not be terminated with a semicolon (';') - Replace NaN values with NULL using numpy.nan_to_num (not using is_nan() because of input types error for strings) - Coerce datetime cells to Oracle DATETIME format during insert """ if target_fields: target_fields = ', '.join(target_fields) target_fields = '({})'.format(target_fields) else: target_fields = '' conn = self.get_conn() cur = conn.cursor() if self.supports_autocommit: cur.execute('SET autocommit = 0') conn.commit() i = 0 for row in rows: i += 1 l = [] for cell in row: if isinstance(cell, basestring): l.append("'" + str(cell).replace("'", "''") + "'") elif cell is None: l.append('NULL') elif type(cell) == float and numpy.isnan(cell): # coerce numpy NaN to NULL l.append('NULL') elif isinstance(cell, numpy.datetime64): l.append("'" + str(cell) + "'") elif isinstance(cell, datetime): l.append("to_date('" + cell.strftime('%Y-%m-%d %H:%M:%S') + "','YYYY-MM-DD HH24:MI:SS')") else: l.append(str(cell)) values = tuple(l) sql = 'INSERT /*+ APPEND */ INTO {0} {1} VALUES ({2})'.format(table, target_fields, ','.join(values)) cur.execute(sql) if i % commit_every == 0: conn.commit() self.log.info('Loaded {i} into {table} rows so far'.format(**locals())) conn.commit() cur.close() conn.close() self.log.info('Done loading. Loaded a total of {i} rows'.format(**locals())) def bulk_insert_rows(self, table, rows, target_fields=None, commit_every=5000): """A performant bulk insert for cx_Oracle that uses prepared statements via `executemany()`. For best performance, pass in `rows` as an iterator. """ conn = self.get_conn() cursor = conn.cursor() values = ', '.join(':%s' % i for i in range(1, len(target_fields) + 1)) prepared_stm = 'insert into {tablename} ({columns}) values ({values})'.format( tablename=table, columns=', '.join(target_fields), values=values, ) row_count = 0 # Chunk the rows row_chunk = [] for row in rows: row_chunk.append(row) row_count += 1 if row_count % commit_every == 0: cursor.prepare(prepared_stm) cursor.executemany(None, row_chunk) conn.commit() self.log.info('[%s] inserted %s rows', table, row_count) # Empty chunk row_chunk = [] # Commit the leftover chunk cursor.prepare(prepared_stm) cursor.executemany(None, row_chunk) conn.commit() self.log.info('[%s] inserted %s rows', table, row_count) cursor.close() conn.close()
apache-2.0
TalShafir/ansible
lib/ansible/modules/system/locale_gen.py
50
7255
#!/usr/bin/python # -*- coding: utf-8 -*- # 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: locale_gen short_description: Creates or removes locales description: - Manages locales by editing /etc/locale.gen and invoking locale-gen. version_added: "1.6" author: - Augustus Kling (@AugustusKling) options: name: description: - Name and encoding of the locale, such as "en_GB.UTF-8". required: true state: description: - Whether the locale shall be present. choices: [ absent, present ] default: present ''' EXAMPLES = ''' - name: Ensure a locale exists locale_gen: name: de_CH.UTF-8 state: present ''' import os import re from subprocess import Popen, PIPE, call from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_native LOCALE_NORMALIZATION = { ".utf8": ".UTF-8", ".eucjp": ".EUC-JP", ".iso885915": ".ISO-8859-15", ".cp1251": ".CP1251", ".koi8r": ".KOI8-R", ".armscii8": ".ARMSCII-8", ".euckr": ".EUC-KR", ".gbk": ".GBK", ".gb18030": ".GB18030", ".euctw": ".EUC-TW", } # =========================================== # location module specific support methods. # def is_available(name, ubuntuMode): """Check if the given locale is available on the system. This is done by checking either : * if the locale is present in /etc/locales.gen * or if the locale is present in /usr/share/i18n/SUPPORTED""" if ubuntuMode: __regexp = r'^(?P<locale>\S+_\S+) (?P<charset>\S+)\s*$' __locales_available = '/usr/share/i18n/SUPPORTED' else: __regexp = r'^#{0,1}\s*(?P<locale>\S+_\S+) (?P<charset>\S+)\s*$' __locales_available = '/etc/locale.gen' re_compiled = re.compile(__regexp) fd = open(__locales_available, 'r') for line in fd: result = re_compiled.match(line) if result and result.group('locale') == name: return True fd.close() return False def is_present(name): """Checks if the given locale is currently installed.""" output = Popen(["locale", "-a"], stdout=PIPE).communicate()[0] output = to_native(output) return any(fix_case(name) == fix_case(line) for line in output.splitlines()) def fix_case(name): """locale -a might return the encoding in either lower or upper case. Passing through this function makes them uniform for comparisons.""" for s, r in LOCALE_NORMALIZATION.items(): name = name.replace(s, r) return name def replace_line(existing_line, new_line): """Replaces lines in /etc/locale.gen""" try: f = open("/etc/locale.gen", "r") lines = [line.replace(existing_line, new_line) for line in f] finally: f.close() try: f = open("/etc/locale.gen", "w") f.write("".join(lines)) finally: f.close() def set_locale(name, enabled=True): """ Sets the state of the locale. Defaults to enabled. """ search_string = r'#{0,1}\s*%s (?P<charset>.+)' % name if enabled: new_string = r'%s \g<charset>' % (name) else: new_string = r'# %s \g<charset>' % (name) try: f = open("/etc/locale.gen", "r") lines = [re.sub(search_string, new_string, line) for line in f] finally: f.close() try: f = open("/etc/locale.gen", "w") f.write("".join(lines)) finally: f.close() def apply_change(targetState, name): """Create or remove locale. Keyword arguments: targetState -- Desired state, either present or absent. name -- Name including encoding such as de_CH.UTF-8. """ if targetState == "present": # Create locale. set_locale(name, enabled=True) else: # Delete locale. set_locale(name, enabled=False) localeGenExitValue = call("locale-gen") if localeGenExitValue != 0: raise EnvironmentError(localeGenExitValue, "locale.gen failed to execute, it returned " + str(localeGenExitValue)) def apply_change_ubuntu(targetState, name): """Create or remove locale. Keyword arguments: targetState -- Desired state, either present or absent. name -- Name including encoding such as de_CH.UTF-8. """ if targetState == "present": # Create locale. # Ubuntu's patched locale-gen automatically adds the new locale to /var/lib/locales/supported.d/local localeGenExitValue = call(["locale-gen", name]) else: # Delete locale involves discarding the locale from /var/lib/locales/supported.d/local and regenerating all locales. try: f = open("/var/lib/locales/supported.d/local", "r") content = f.readlines() finally: f.close() try: f = open("/var/lib/locales/supported.d/local", "w") for line in content: locale, charset = line.split(' ') if locale != name: f.write(line) finally: f.close() # Purge locales and regenerate. # Please provide a patch if you know how to avoid regenerating the locales to keep! localeGenExitValue = call(["locale-gen", "--purge"]) if localeGenExitValue != 0: raise EnvironmentError(localeGenExitValue, "locale.gen failed to execute, it returned " + str(localeGenExitValue)) def main(): module = AnsibleModule( argument_spec=dict( name=dict(type='str', required=True), state=dict(type='str', default='present', choices=['absent', 'present']), ), supports_check_mode=True, ) name = module.params['name'] state = module.params['state'] if not os.path.exists("/etc/locale.gen"): if os.path.exists("/var/lib/locales/supported.d/"): # Ubuntu created its own system to manage locales. ubuntuMode = True else: module.fail_json(msg="/etc/locale.gen and /var/lib/locales/supported.d/local are missing. Is the package \"locales\" installed?") else: # We found the common way to manage locales. ubuntuMode = False if not is_available(name, ubuntuMode): module.fail_json(msg="The locales you've entered is not available " "on your system.") if is_present(name): prev_state = "present" else: prev_state = "absent" changed = (prev_state != state) if module.check_mode: module.exit_json(changed=changed) else: if changed: try: if ubuntuMode is False: apply_change(state, name) else: apply_change_ubuntu(state, name) except EnvironmentError as e: module.fail_json(msg=to_native(e), exitValue=e.errno) module.exit_json(name=name, changed=changed, msg="OK") if __name__ == '__main__': main()
gpl-3.0
strukturag/vlc-2.1
extras/misc/mpris.py
117
9763
#!/usr/bin/env python # -*- coding: utf8 -*- # # Copyright © 2006-2011 Rafaël Carré <funman at videolanorg> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. # # # NOTE: This controller is a SAMPLE, and thus doesn't use all the # Media Player Remote Interface Specification (MPRIS for short) capabilities # # MPRIS: http://www.mpris.org/2.1/spec/ # # You'll need pygtk >= 2.12 # # TODO # Ability to choose the Media Player if several are connected to the bus # core dbus stuff import dbus import dbus.glib # core interface stuff import gtk # timer from gobject import timeout_add # file loading import os global win_position # store the window position on the screen global playing playing = False global shuffle global root global player global tracklist global props global bus # Connection to the session bus mpris='org.mpris.MediaPlayer2' # If a Media Player connects to the bus, we'll use it # Note that we forget the previous Media Player we were connected to def NameOwnerChanged(name, new, old): if old != '' and mpris in name: Connect(name) def PropGet(prop): global props return props.Get(mpris + '.Player', prop) def PropSet(prop, val): global props props.Set(mpris + '.Player', prop, val) # Callback for when 'TrackChange' signal is emitted def TrackChange(Track): try: a = Track['xesam:artist'] except: a = '' try: t = Track['xesam:title'] except: t = Track['xesam:url'] try: length = Track['mpris:length'] except: length = 0 if length > 0: time_s.set_range(0, length) time_s.set_sensitive(True) else: # disable the position scale if length isn't available time_s.set_sensitive(False) # update the labels l_artist.set_text(a) l_title.set_text(t) # Connects to the Media Player we detected def Connect(name): global root, player, tracklist, props global playing, shuffle root_o = bus.get_object(name, '/org/mpris/MediaPlayer2') root = dbus.Interface(root_o, mpris) tracklist = dbus.Interface(root_o, mpris + '.TrackList') player = dbus.Interface(root_o, mpris + '.Player') props = dbus.Interface(root_o, dbus.PROPERTIES_IFACE) # FIXME : doesn't exist anymore in mpris 2.1 # connect to the TrackChange signal # root_o.connect_to_signal('TrackChange', TrackChange, dbus_interface=mpris) # determine if the Media Player is playing something if PropGet('PlaybackStatus') == 'Playing': playing = True TrackChange(PropGet('Metadata')) window.set_title(props.Get(mpris, 'Identity')) #plays an element def AddTrack(widget): mrl = e_mrl.get_text() if mrl != None and mrl != '': tracklist.AddTrack(mrl, '/', True) e_mrl.set_text('') else: mrl = bt_file.get_filename() if mrl != None and mrl != '': tracklist.AddTrack('directory://' + mrl, '/', True) update(0) # basic control def Next(widget): player.Next(reply_handler=(lambda *args: None), error_handler=(lambda *args: None)) update(0) def Prev(widget): player.Prev(reply_handler=(lambda *args: None), error_handler=(lambda *args: None)) update(0) def Stop(widget): player.Stop(reply_handler=(lambda *args: None), error_handler=(lambda *args: None)) update(0) def Quit(widget): global props if props.Get(mpris, 'CanQuit'): root.Quit(reply_handler=(lambda *args: None), error_handler=(lambda *args: None)) l_title.set_text('') window.set_title('') def Pause(widget): player.PlayPause() if PropGet('PlaybackStatus') == 'Playing': icon = gtk.STOCK_MEDIA_PAUSE else: icon = gtk.STOCK_MEDIA_PLAY img_bt_toggle.set_from_stock(icon, gtk.ICON_SIZE_SMALL_TOOLBAR) update(0) def Shuffle(widget): global shuffle shuffle = not shuffle PropSet('Shuffle', shuffle) # update status display def update(widget): Track = PropGet('Metadata') vol.set_value(PropGet('Volume') * 100.0) TrackChange(Track) GetPlayStatus(0) # callback for volume change def volchange(widget): PropSet('Volume', vol.get_value_as_int() / 100.0) # callback for position change def timechange(widget, x=None, y=None): player.SetPosition(PropGet('Metadata')['mpris:trackid'], time_s.get_value(), reply_handler=(lambda *args: None), error_handler=(lambda *args: None)) # refresh position change def timeset(): global playing if playing == True: try: time_s.set_value(PropGet('Position')) except: playing = False return True # toggle simple/full display def expander(widget): if exp.get_expanded() == False: exp.set_label('Less') else: exp.set_label('More') # close event : hide in the systray def delete_event(self, widget): self.hide() return True # shouldn't happen def destroy(widget): gtk.main_quit() # hide the controller when 'Esc' is pressed def key_release(widget, event): if event.keyval == gtk.keysyms.Escape: global win_position win_position = window.get_position() widget.hide() # callback for click on the tray icon def tray_button(widget): global win_position if window.get_property('visible'): # store position win_position = window.get_position() window.hide() else: # restore position window.move(win_position[0], win_position[1]) window.show() # hack: update position, volume, and metadata def icon_clicked(widget, event): update(0) # get playing status, modify the Play/Pause button accordingly def GetPlayStatus(widget): global playing global shuffle playing = PropGet('PlaybackStatus') == 'Playing' if playing: img_bt_toggle.set_from_stock('gtk-media-pause', gtk.ICON_SIZE_SMALL_TOOLBAR) else: img_bt_toggle.set_from_stock('gtk-media-play', gtk.ICON_SIZE_SMALL_TOOLBAR) shuffle = PropGet('Shuffle') bt_shuffle.set_active( shuffle ) # loads UI file from the directory where the script is, # so we can use /path/to/mpris.py to execute it. import sys xml = gtk.Builder() gtk.Builder.add_from_file(xml, os.path.join(os.path.dirname(sys.argv[0]) , 'mpris.xml')) # ui setup bt_close = xml.get_object('close') bt_quit = xml.get_object('quit') bt_file = xml.get_object('ChooseFile') bt_next = xml.get_object('next') bt_prev = xml.get_object('prev') bt_stop = xml.get_object('stop') bt_toggle = xml.get_object('toggle') bt_mrl = xml.get_object('AddMRL') bt_shuffle = xml.get_object('shuffle') l_artist = xml.get_object('l_artist') l_title = xml.get_object('l_title') e_mrl = xml.get_object('mrl') window = xml.get_object('window1') img_bt_toggle=xml.get_object('image6') exp = xml.get_object('expander2') expvbox = xml.get_object('expandvbox') audioicon = xml.get_object('eventicon') vol = xml.get_object('vol') time_s = xml.get_object('time_s') time_l = xml.get_object('time_l') # connect to the different callbacks window.connect('delete_event', delete_event) window.connect('destroy', destroy) window.connect('key_release_event', key_release) tray = gtk.status_icon_new_from_icon_name('audio-x-generic') tray.connect('activate', tray_button) bt_close.connect('clicked', destroy) bt_quit.connect('clicked', Quit) bt_mrl.connect('clicked', AddTrack) bt_toggle.connect('clicked', Pause) bt_next.connect('clicked', Next) bt_prev.connect('clicked', Prev) bt_stop.connect('clicked', Stop) bt_shuffle.connect('clicked', Shuffle) exp.connect('activate', expander) vol.connect('changed', volchange) time_s.connect('adjust-bounds', timechange) audioicon.set_events(gtk.gdk.BUTTON_PRESS_MASK) # hack for the bottom right icon audioicon.connect('button_press_event', icon_clicked) time_s.set_update_policy(gtk.UPDATE_DISCONTINUOUS) library = '/media/mp3' # editme # set the Directory chooser to a default location try: os.chdir(library) bt_file.set_current_folder(library) except: bt_file.set_current_folder(os.path.expanduser('~')) # connect to the bus bus = dbus.SessionBus() dbus_names = bus.get_object( 'org.freedesktop.DBus', '/org/freedesktop/DBus' ) dbus_names.connect_to_signal('NameOwnerChanged', NameOwnerChanged, dbus_interface='org.freedesktop.DBus') # to detect new Media Players dbus_o = bus.get_object('org.freedesktop.DBus', '/') dbus_intf = dbus.Interface(dbus_o, 'org.freedesktop.DBus') # connect to the first Media Player found for n in dbus_intf.ListNames(): if mpris in n: Connect(n) vol.set_value(PropGet('Volume') * 100.0) update(0) break # run a timer to update position timeout_add( 1000, timeset) window.set_icon_name('audio-x-generic') window.show() window.set_icon(gtk.icon_theme_get_default().load_icon('audio-x-generic',24,0)) win_position = window.get_position() gtk.main() # execute the main loop
gpl-2.0
strint/tensorflow
tensorflow/contrib/framework/python/framework/experimental.py
179
2476
# Copyright 2016 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. # ============================================================================== """Tensor utility functions.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import functools from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util import decorator_utils def _add_experimental_function_notice_to_docstring(doc): """Adds an experimental notice to a docstring for experimental functions.""" return decorator_utils.add_notice_to_docstring( doc, '', 'EXPERIMENTAL FUNCTION', '(experimental)', ['THIS FUNCTION IS EXPERIMENTAL. It may change or ' 'be removed at any time, and without warning.']) def experimental(func): """Decorator for marking functions or methods experimental. This decorator logs an experimental warning whenever the decorated function is called. It has the following format: <function> (from <module>) is experimental and may change or be removed at any time, and without warning. <function> will include the class name if it is a method. It also edits the docstring of the function: ' (experimental)' is appended to the first line of the docstring and a notice is prepended to the rest of the docstring. Args: func: A function or method to mark experimental. Returns: Decorated function or method. """ decorator_utils.validate_callable(func, 'experimental') @functools.wraps(func) def new_func(*args, **kwargs): logging.warning( '%s (from %s) is experimental and may change or be removed at ' 'any time, and without warning.', decorator_utils.get_qualified_name(func), func.__module__) return func(*args, **kwargs) new_func.__doc__ = _add_experimental_function_notice_to_docstring( func.__doc__) return new_func
apache-2.0
Eficent/account-invoice-reporting
__unported__/invoice_report_assemble/res_config.py
10
1813
# -*- coding: utf-8 -*- ############################################################################## # # Author: Yannick Vaucher # Copyright 2013 Camptocamp SA # # 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 orm, fields class AccountConfigSettings(orm.TransientModel): _inherit = 'account.config.settings' _columns = { 'assemble_invoice_report_ids': fields.related( 'company_id', 'assemble_invoice_report_ids', string='Account Invoice Report Assemblage', type='one2many', relation='assembled.report'), } def onchange_company_id(self, cr, uid, ids, company_id, context=None): res = super(AccountConfigSettings, self).onchange_company_id( cr, uid, ids, company_id, context=context) company = self.pool.get('res.company').browse(cr, uid, company_id, context=context) r_ids = [r.id for r in company.assemble_invoice_report_ids] res['value']['assemble_invoice_report_ids'] = r_ids return res
agpl-3.0
havt/odoo
addons/delivery/delivery.py
64
13497
# -*- 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/>. # ############################################################################## import logging import time from openerp.osv import fields,osv from openerp.tools.translate import _ import openerp.addons.decimal_precision as dp from openerp.tools.safe_eval import safe_eval as eval _logger = logging.getLogger(__name__) class delivery_carrier(osv.osv): _name = "delivery.carrier" _description = "Carrier" def name_get(self, cr, uid, ids, context=None): if not len(ids): return [] if context is None: context = {} order_id = context.get('order_id',False) if not order_id: res = super(delivery_carrier, self).name_get(cr, uid, ids, context=context) else: order = self.pool.get('sale.order').browse(cr, uid, order_id, context=context) currency = order.pricelist_id.currency_id.name or '' res = [(r['id'], r['name']+' ('+(str(r['price']))+' '+currency+')') for r in self.read(cr, uid, ids, ['name', 'price'], context)] return res def get_price(self, cr, uid, ids, field_name, arg=None, context=None): res={} if context is None: context = {} sale_obj=self.pool.get('sale.order') grid_obj=self.pool.get('delivery.grid') for carrier in self.browse(cr, uid, ids, context=context): order_id=context.get('order_id',False) price=False available = False if order_id: order = sale_obj.browse(cr, uid, order_id, context=context) carrier_grid=self.grid_get(cr,uid,[carrier.id],order.partner_shipping_id.id,context) if carrier_grid: try: price=grid_obj.get_price(cr, uid, carrier_grid, order, time.strftime('%Y-%m-%d'), context) available = True except osv.except_osv, e: # no suitable delivery method found, probably configuration error _logger.error("Carrier %s: %s\n%s" % (carrier.name, e.name, e.value)) price = 0.0 else: price = 0.0 res[carrier.id] = { 'price': price, 'available': available } return res _columns = { 'name': fields.char('Delivery Method', required=True), 'partner_id': fields.many2one('res.partner', 'Transport Company', required=True, help="The partner that is doing the delivery service."), 'product_id': fields.many2one('product.product', 'Delivery Product', required=True), 'grids_id': fields.one2many('delivery.grid', 'carrier_id', 'Delivery Grids'), 'available' : fields.function(get_price, string='Available',type='boolean', multi='price', help="Is the carrier method possible with the current order."), 'price' : fields.function(get_price, string='Price', multi='price'), 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the delivery carrier without removing it."), 'normal_price': fields.float('Normal Price', help="Keep empty if the pricing depends on the advanced pricing per destination"), 'free_if_more_than': fields.boolean('Free If Order Total Amount Is More Than', help="If the order is more expensive than a certain amount, the customer can benefit from a free shipping"), 'amount': fields.float('Amount', help="Amount of the order to benefit from a free shipping, expressed in the company currency"), 'use_detailed_pricelist': fields.boolean('Advanced Pricing per Destination', help="Check this box if you want to manage delivery prices that depends on the destination, the weight, the total of the order, etc."), 'pricelist_ids': fields.one2many('delivery.grid', 'carrier_id', 'Advanced Pricing'), } _defaults = { 'active': 1, 'free_if_more_than': False, } def grid_get(self, cr, uid, ids, contact_id, context=None): contact = self.pool.get('res.partner').browse(cr, uid, contact_id, context=context) for carrier in self.browse(cr, uid, ids, context=context): for grid in carrier.grids_id: get_id = lambda x: x.id country_ids = map(get_id, grid.country_ids) state_ids = map(get_id, grid.state_ids) if country_ids and not contact.country_id.id in country_ids: continue if state_ids and not contact.state_id.id in state_ids: continue if grid.zip_from and (contact.zip or '')< grid.zip_from: continue if grid.zip_to and (contact.zip or '')> grid.zip_to: continue return grid.id return False def create_grid_lines(self, cr, uid, ids, vals, context=None): if context is None: context = {} grid_line_pool = self.pool.get('delivery.grid.line') grid_pool = self.pool.get('delivery.grid') for record in self.browse(cr, uid, ids, context=context): # if using advanced pricing per destination: do not change if record.use_detailed_pricelist: continue # not using advanced pricing per destination: override grid grid_id = grid_pool.search(cr, uid, [('carrier_id', '=', record.id)], context=context) if grid_id and not (record.normal_price is not False or record.free_if_more_than): grid_pool.unlink(cr, uid, grid_id, context=context) grid_id = None if not (record.normal_price is not False or record.free_if_more_than): continue if not grid_id: grid_data = { 'name': record.name, 'carrier_id': record.id, 'sequence': 10, } grid_id = [grid_pool.create(cr, uid, grid_data, context=context)] lines = grid_line_pool.search(cr, uid, [('grid_id','in',grid_id)], context=context) if lines: grid_line_pool.unlink(cr, uid, lines, context=context) #create the grid lines if record.free_if_more_than: line_data = { 'grid_id': grid_id and grid_id[0], 'name': _('Free if more than %.2f') % record.amount, 'type': 'price', 'operator': '>=', 'max_value': record.amount, 'standard_price': 0.0, 'list_price': 0.0, } grid_line_pool.create(cr, uid, line_data, context=context) if record.normal_price is not False: line_data = { 'grid_id': grid_id and grid_id[0], 'name': _('Default price'), 'type': 'price', 'operator': '>=', 'max_value': 0.0, 'standard_price': record.normal_price, 'list_price': record.normal_price, } grid_line_pool.create(cr, uid, line_data, context=context) return True def write(self, cr, uid, ids, vals, context=None): if isinstance(ids, (int,long)): ids = [ids] res = super(delivery_carrier, self).write(cr, uid, ids, vals, context=context) self.create_grid_lines(cr, uid, ids, vals, context=context) return res def create(self, cr, uid, vals, context=None): res_id = super(delivery_carrier, self).create(cr, uid, vals, context=context) self.create_grid_lines(cr, uid, [res_id], vals, context=context) return res_id class delivery_grid(osv.osv): _name = "delivery.grid" _description = "Delivery Grid" _columns = { 'name': fields.char('Grid Name', required=True), 'sequence': fields.integer('Sequence', required=True, help="Gives the sequence order when displaying a list of delivery grid."), 'carrier_id': fields.many2one('delivery.carrier', 'Carrier', required=True, ondelete='cascade'), 'country_ids': fields.many2many('res.country', 'delivery_grid_country_rel', 'grid_id', 'country_id', 'Countries'), 'state_ids': fields.many2many('res.country.state', 'delivery_grid_state_rel', 'grid_id', 'state_id', 'States'), 'zip_from': fields.char('Start Zip', size=12), 'zip_to': fields.char('To Zip', size=12), 'line_ids': fields.one2many('delivery.grid.line', 'grid_id', 'Grid Line', copy=True), 'active': fields.boolean('Active', help="If the active field is set to False, it will allow you to hide the delivery grid without removing it."), } _defaults = { 'active': lambda *a: 1, 'sequence': lambda *a: 1, } _order = 'sequence' def get_price(self, cr, uid, id, order, dt, context=None): total = 0 weight = 0 volume = 0 quantity = 0 total_delivery = 0.0 product_uom_obj = self.pool.get('product.uom') for line in order.order_line: if line.state == 'cancel': continue if line.is_delivery: total_delivery += line.price_subtotal + self.pool['sale.order']._amount_line_tax(cr, uid, line, context=context) if not line.product_id or line.is_delivery: continue q = product_uom_obj._compute_qty(cr, uid, line.product_uom.id, line.product_uom_qty, line.product_id.uom_id.id) weight += (line.product_id.weight or 0.0) * q volume += (line.product_id.volume or 0.0) * q quantity += q total = (order.amount_total or 0.0) - total_delivery return self.get_price_from_picking(cr, uid, id, total,weight, volume, quantity, context=context) def get_price_from_picking(self, cr, uid, id, total, weight, volume, quantity, context=None): grid = self.browse(cr, uid, id, context=context) price = 0.0 ok = False price_dict = {'price': total, 'volume':volume, 'weight': weight, 'wv':volume*weight, 'quantity': quantity} for line in grid.line_ids: test = eval(line.type+line.operator+str(line.max_value), price_dict) if test: if line.price_type=='variable': price = line.list_price * price_dict[line.variable_factor] else: price = line.list_price ok = True break if not ok: raise osv.except_osv(_("Unable to fetch delivery method!"), _("Selected product in the delivery method doesn't fulfill any of the delivery grid(s) criteria.")) return price class delivery_grid_line(osv.osv): _name = "delivery.grid.line" _description = "Delivery Grid Line" _columns = { 'name': fields.char('Name', required=True), 'sequence': fields.integer('Sequence', required=True, help="Gives the sequence order when calculating delivery grid."), 'grid_id': fields.many2one('delivery.grid', 'Grid',required=True, ondelete='cascade'), 'type': fields.selection([('weight','Weight'),('volume','Volume'),\ ('wv','Weight * Volume'), ('price','Price'), ('quantity','Quantity')],\ 'Variable', required=True), 'operator': fields.selection([('==','='),('<=','<='),('<','<'),('>=','>='),('>','>')], 'Operator', required=True), 'max_value': fields.float('Maximum Value', required=True), 'price_type': fields.selection([('fixed','Fixed'),('variable','Variable')], 'Price Type', required=True), 'variable_factor': fields.selection([('weight','Weight'),('volume','Volume'),('wv','Weight * Volume'), ('price','Price'), ('quantity','Quantity')], 'Variable Factor', required=True), 'list_price': fields.float('Sale Price', digits_compute= dp.get_precision('Product Price'), required=True), 'standard_price': fields.float('Cost Price', digits_compute= dp.get_precision('Product Price'), required=True), } _defaults = { 'sequence': lambda *args: 10, 'type': lambda *args: 'weight', 'operator': lambda *args: '<=', 'price_type': lambda *args: 'fixed', 'variable_factor': lambda *args: 'weight', } _order = 'sequence, list_price' # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
darkleons/lama
addons/document/test_cindex.py
444
1553
#!/usr/bin/python import sys import os import glob import time import logging from optparse import OptionParser logging.basicConfig(level=logging.DEBUG) parser = OptionParser() parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") parser.add_option("-C", "--content", action="store_true", dest="docontent", default=False, help="Disect content, rather than the file.") parser.add_option("--delay", action="store_true", dest="delay", default=False, help="delay after the operation, to inspect child processes") (options, args) = parser.parse_args() import content_index, std_index from content_index import cntIndex for fname in args: try: if options.docontent: fp = open(fname,'rb') content = fp.read() fp.close() res = cntIndex.doIndex(content, fname, None, None, True) else: res = cntIndex.doIndex(None, fname, None, fname,True) if options.verbose: for line in res[:5]: print line if options.delay: time.sleep(30) except Exception,e: import traceback tb_s = reduce(lambda x, y: x+y, traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback)) except KeyboardInterrupt: print "Keyboard interrupt" #eof # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
CameronLonsdale/sec-tools
python2/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/response.py
360
18615
from __future__ import absolute_import from contextlib import contextmanager import zlib import io from socket import timeout as SocketTimeout from socket import error as SocketError from ._collections import HTTPHeaderDict from .exceptions import ( ProtocolError, DecodeError, ReadTimeoutError, ResponseNotChunked ) from .packages.six import string_types as basestring, binary_type, PY3 from .packages.six.moves import http_client as httplib from .connection import HTTPException, BaseSSLError from .util.response import is_fp_closed, is_response_to_head class DeflateDecoder(object): def __init__(self): self._first_try = True self._data = binary_type() self._obj = zlib.decompressobj() def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): if not data: return data if not self._first_try: return self._obj.decompress(data) self._data += data try: return self._obj.decompress(data) except zlib.error: self._first_try = False self._obj = zlib.decompressobj(-zlib.MAX_WBITS) try: return self.decompress(self._data) finally: self._data = None class GzipDecoder(object): def __init__(self): self._obj = zlib.decompressobj(16 + zlib.MAX_WBITS) def __getattr__(self, name): return getattr(self._obj, name) def decompress(self, data): if not data: return data return self._obj.decompress(data) def _get_decoder(mode): if mode == 'gzip': return GzipDecoder() return DeflateDecoder() class HTTPResponse(io.IOBase): """ HTTP Response container. Backwards-compatible to httplib's HTTPResponse but the response ``body`` is loaded and decoded on-demand when the ``data`` property is accessed. This class is also compatible with the Python standard library's :mod:`io` module, and can hence be treated as a readable object in the context of that framework. Extra parameters for behaviour not present in httplib.HTTPResponse: :param preload_content: If True, the response's body will be preloaded during construction. :param decode_content: If True, attempts to decode specific content-encoding's based on headers (like 'gzip' and 'deflate') will be skipped and raw data will be used instead. :param original_response: When this HTTPResponse wrapper is generated from an httplib.HTTPResponse object, it's convenient to include the original for debug purposes. It's otherwise unused. """ CONTENT_DECODERS = ['gzip', 'deflate'] REDIRECT_STATUSES = [301, 302, 303, 307, 308] def __init__(self, body='', headers=None, status=0, version=0, reason=None, strict=0, preload_content=True, decode_content=True, original_response=None, pool=None, connection=None): if isinstance(headers, HTTPHeaderDict): self.headers = headers else: self.headers = HTTPHeaderDict(headers) self.status = status self.version = version self.reason = reason self.strict = strict self.decode_content = decode_content self._decoder = None self._body = None self._fp = None self._original_response = original_response self._fp_bytes_read = 0 if body and isinstance(body, (basestring, binary_type)): self._body = body self._pool = pool self._connection = connection if hasattr(body, 'read'): self._fp = body # Are we using the chunked-style of transfer encoding? self.chunked = False self.chunk_left = None tr_enc = self.headers.get('transfer-encoding', '').lower() # Don't incur the penalty of creating a list and then discarding it encodings = (enc.strip() for enc in tr_enc.split(",")) if "chunked" in encodings: self.chunked = True # If requested, preload the body. if preload_content and not self._body: self._body = self.read(decode_content=decode_content) def get_redirect_location(self): """ Should we redirect and where to? :returns: Truthy redirect location string if we got a redirect status code and valid location. ``None`` if redirect status and no location. ``False`` if not a redirect status code. """ if self.status in self.REDIRECT_STATUSES: return self.headers.get('location') return False def release_conn(self): if not self._pool or not self._connection: return self._pool._put_conn(self._connection) self._connection = None @property def data(self): # For backwords-compat with earlier urllib3 0.4 and earlier. if self._body: return self._body if self._fp: return self.read(cache_content=True) @property def connection(self): return self._connection def tell(self): """ Obtain the number of bytes pulled over the wire so far. May differ from the amount of content returned by :meth:``HTTPResponse.read`` if bytes are encoded on the wire (e.g, compressed). """ return self._fp_bytes_read def _init_decoder(self): """ Set-up the _decoder attribute if necessar. """ # Note: content-encoding value should be case-insensitive, per RFC 7230 # Section 3.2 content_encoding = self.headers.get('content-encoding', '').lower() if self._decoder is None and content_encoding in self.CONTENT_DECODERS: self._decoder = _get_decoder(content_encoding) def _decode(self, data, decode_content, flush_decoder): """ Decode the data passed in and potentially flush the decoder. """ try: if decode_content and self._decoder: data = self._decoder.decompress(data) except (IOError, zlib.error) as e: content_encoding = self.headers.get('content-encoding', '').lower() raise DecodeError( "Received response with content-encoding: %s, but " "failed to decode it." % content_encoding, e) if flush_decoder and decode_content: data += self._flush_decoder() return data def _flush_decoder(self): """ Flushes the decoder. Should only be called if the decoder is actually being used. """ if self._decoder: buf = self._decoder.decompress(b'') return buf + self._decoder.flush() return b'' @contextmanager def _error_catcher(self): """ Catch low-level python exceptions, instead re-raising urllib3 variants, so that low-level exceptions are not leaked in the high-level api. On exit, release the connection back to the pool. """ clean_exit = False try: try: yield except SocketTimeout: # FIXME: Ideally we'd like to include the url in the ReadTimeoutError but # there is yet no clean way to get at it from this context. raise ReadTimeoutError(self._pool, None, 'Read timed out.') except BaseSSLError as e: # FIXME: Is there a better way to differentiate between SSLErrors? if 'read operation timed out' not in str(e): # Defensive: # This shouldn't happen but just in case we're missing an edge # case, let's avoid swallowing SSL errors. raise raise ReadTimeoutError(self._pool, None, 'Read timed out.') except (HTTPException, SocketError) as e: # This includes IncompleteRead. raise ProtocolError('Connection broken: %r' % e, e) # If no exception is thrown, we should avoid cleaning up # unnecessarily. clean_exit = True finally: # If we didn't terminate cleanly, we need to throw away our # connection. if not clean_exit: # The response may not be closed but we're not going to use it # anymore so close it now to ensure that the connection is # released back to the pool. if self._original_response: self._original_response.close() # Closing the response may not actually be sufficient to close # everything, so if we have a hold of the connection close that # too. if self._connection: self._connection.close() # If we hold the original response but it's closed now, we should # return the connection back to the pool. if self._original_response and self._original_response.isclosed(): self.release_conn() def read(self, amt=None, decode_content=None, cache_content=False): """ Similar to :meth:`httplib.HTTPResponse.read`, but with two additional parameters: ``decode_content`` and ``cache_content``. :param amt: How much of the content to read. If specified, caching is skipped because it doesn't make sense to cache partial content as the full response. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. :param cache_content: If True, will save the returned data such that the same result is returned despite of the state of the underlying file object. This is useful if you want the ``.data`` property to continue working after having ``.read()`` the file object. (Overridden if ``amt`` is set.) """ self._init_decoder() if decode_content is None: decode_content = self.decode_content if self._fp is None: return flush_decoder = False data = None with self._error_catcher(): if amt is None: # cStringIO doesn't like amt=None data = self._fp.read() flush_decoder = True else: cache_content = False data = self._fp.read(amt) if amt != 0 and not data: # Platform-specific: Buggy versions of Python. # Close the connection when no data is returned # # This is redundant to what httplib/http.client _should_ # already do. However, versions of python released before # December 15, 2012 (http://bugs.python.org/issue16298) do # not properly close the connection in all cases. There is # no harm in redundantly calling close. self._fp.close() flush_decoder = True if data: self._fp_bytes_read += len(data) data = self._decode(data, decode_content, flush_decoder) if cache_content: self._body = data return data def stream(self, amt=2**16, decode_content=None): """ A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator will return up to much data per iteration, but may return less. This is particularly likely when using compressed data. However, the empty string will never be returned. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ if self.chunked: for line in self.read_chunked(amt, decode_content=decode_content): yield line else: while not is_fp_closed(self._fp): data = self.read(amt=amt, decode_content=decode_content) if data: yield data @classmethod def from_httplib(ResponseCls, r, **response_kw): """ Given an :class:`httplib.HTTPResponse` instance ``r``, return a corresponding :class:`urllib3.response.HTTPResponse` object. Remaining parameters are passed to the HTTPResponse constructor, along with ``original_response=r``. """ headers = r.msg if not isinstance(headers, HTTPHeaderDict): if PY3: # Python 3 headers = HTTPHeaderDict(headers.items()) else: # Python 2 headers = HTTPHeaderDict.from_httplib(headers) # HTTPResponse objects in Python 3 don't have a .strict attribute strict = getattr(r, 'strict', 0) resp = ResponseCls(body=r, headers=headers, status=r.status, version=r.version, reason=r.reason, strict=strict, original_response=r, **response_kw) return resp # Backwards-compatibility methods for httplib.HTTPResponse def getheaders(self): return self.headers def getheader(self, name, default=None): return self.headers.get(name, default) # Overrides from io.IOBase def close(self): if not self.closed: self._fp.close() if self._connection: self._connection.close() @property def closed(self): if self._fp is None: return True elif hasattr(self._fp, 'closed'): return self._fp.closed elif hasattr(self._fp, 'isclosed'): # Python 2 return self._fp.isclosed() else: return True def fileno(self): if self._fp is None: raise IOError("HTTPResponse has no file to get a fileno from") elif hasattr(self._fp, "fileno"): return self._fp.fileno() else: raise IOError("The file-like object this HTTPResponse is wrapped " "around has no file descriptor") def flush(self): if self._fp is not None and hasattr(self._fp, 'flush'): return self._fp.flush() def readable(self): # This method is required for `io` module compatibility. return True def readinto(self, b): # This method is required for `io` module compatibility. temp = self.read(len(b)) if len(temp) == 0: return 0 else: b[:len(temp)] = temp return len(temp) def _update_chunk_length(self): # First, we'll figure out length of a chunk and then # we'll try to read it from socket. if self.chunk_left is not None: return line = self._fp.fp.readline() line = line.split(b';', 1)[0] try: self.chunk_left = int(line, 16) except ValueError: # Invalid chunked protocol response, abort. self.close() raise httplib.IncompleteRead(line) def _handle_chunk(self, amt): returned_chunk = None if amt is None: chunk = self._fp._safe_read(self.chunk_left) returned_chunk = chunk self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None elif amt < self.chunk_left: value = self._fp._safe_read(amt) self.chunk_left = self.chunk_left - amt returned_chunk = value elif amt == self.chunk_left: value = self._fp._safe_read(amt) self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None returned_chunk = value else: # amt > self.chunk_left returned_chunk = self._fp._safe_read(self.chunk_left) self._fp._safe_read(2) # Toss the CRLF at the end of the chunk. self.chunk_left = None return returned_chunk def read_chunked(self, amt=None, decode_content=None): """ Similar to :meth:`HTTPResponse.read`, but with an additional parameter: ``decode_content``. :param decode_content: If True, will attempt to decode the body based on the 'content-encoding' header. """ self._init_decoder() # FIXME: Rewrite this method and make it a class with a better structured logic. if not self.chunked: raise ResponseNotChunked( "Response is not chunked. " "Header 'transfer-encoding: chunked' is missing.") # Don't bother reading the body of a HEAD request. if self._original_response and is_response_to_head(self._original_response): self._original_response.close() return with self._error_catcher(): while True: self._update_chunk_length() if self.chunk_left == 0: break chunk = self._handle_chunk(amt) decoded = self._decode(chunk, decode_content=decode_content, flush_decoder=False) if decoded: yield decoded if decode_content: # On CPython and PyPy, we should never need to flush the # decoder. However, on Jython we *might* need to, so # lets defensively do it anyway. decoded = self._flush_decoder() if decoded: # Platform-specific: Jython. yield decoded # Chunk content ends with \r\n: discard it. while True: line = self._fp.fp.readline() if not line: # Some sites may not end with '\r\n'. break if line == b'\r\n': break # We read everything; close the "file". if self._original_response: self._original_response.close()
mit
jbtule/keyczar
cpp/src/tools/scons/scons-local-1.2.0.d20090223/SCons/Tool/tex.py
19
25091
"""SCons.Tool.tex Tool-specific initialization for TeX. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 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. # __revision__ = "src/engine/SCons/Tool/tex.py 4043 2009/02/23 09:06:45 scons" import os.path import re import string import shutil import SCons.Action import SCons.Node import SCons.Node.FS import SCons.Util import SCons.Scanner.LaTeX Verbose = False must_rerun_latex = True # these are files that just need to be checked for changes and then rerun latex check_suffixes = ['.toc', '.lof', '.lot', '.out', '.nav', '.snm'] # these are files that require bibtex or makeindex to be run when they change all_suffixes = check_suffixes + ['.bbl', '.idx', '.nlo', '.glo'] # # regular expressions used to search for Latex features # or outputs that require rerunning latex # # search for all .aux files opened by latex (recorded in the .log file) openout_aux_re = re.compile(r"\\openout.*`(.*\.aux)'") #printindex_re = re.compile(r"^[^%]*\\printindex", re.MULTILINE) #printnomenclature_re = re.compile(r"^[^%]*\\printnomenclature", re.MULTILINE) #printglossary_re = re.compile(r"^[^%]*\\printglossary", re.MULTILINE) # search to find rerun warnings warning_rerun_str = '(^LaTeX Warning:.*Rerun)|(^Package \w+ Warning:.*Rerun)' warning_rerun_re = re.compile(warning_rerun_str, re.MULTILINE) # search to find citation rerun warnings rerun_citations_str = "^LaTeX Warning:.*\n.*Rerun to get citations correct" rerun_citations_re = re.compile(rerun_citations_str, re.MULTILINE) # search to find undefined references or citations warnings undefined_references_str = '(^LaTeX Warning:.*undefined references)|(^Package \w+ Warning:.*undefined citations)' undefined_references_re = re.compile(undefined_references_str, re.MULTILINE) # used by the emitter auxfile_re = re.compile(r".", re.MULTILINE) tableofcontents_re = re.compile(r"^[^%\n]*\\tableofcontents", re.MULTILINE) makeindex_re = re.compile(r"^[^%\n]*\\makeindex", re.MULTILINE) bibliography_re = re.compile(r"^[^%\n]*\\bibliography", re.MULTILINE) listoffigures_re = re.compile(r"^[^%\n]*\\listoffigures", re.MULTILINE) listoftables_re = re.compile(r"^[^%\n]*\\listoftables", re.MULTILINE) hyperref_re = re.compile(r"^[^%\n]*\\usepackage.*\{hyperref\}", re.MULTILINE) makenomenclature_re = re.compile(r"^[^%\n]*\\makenomenclature", re.MULTILINE) makeglossary_re = re.compile(r"^[^%\n]*\\makeglossary", re.MULTILINE) beamer_re = re.compile(r"^[^%\n]*\\documentclass\{beamer\}", re.MULTILINE) # search to find all files included by Latex include_re = re.compile(r'^[^%\n]*\\(?:include|input){([^}]*)}', re.MULTILINE) # search to find all graphics files included by Latex includegraphics_re = re.compile(r'^[^%\n]*\\(?:includegraphics(?:\[[^\]]+\])?){([^}]*)}', re.MULTILINE) # search to find all files opened by Latex (recorded in .log file) openout_re = re.compile(r"\\openout.*`(.*)'") # list of graphics file extensions for TeX and LaTeX TexGraphics = SCons.Scanner.LaTeX.TexGraphics LatexGraphics = SCons.Scanner.LaTeX.LatexGraphics # An Action sufficient to build any generic tex file. TeXAction = None # An action to build a latex file. This action might be needed more # than once if we are dealing with labels and bibtex. LaTeXAction = None # An action to run BibTeX on a file. BibTeXAction = None # An action to run MakeIndex on a file. MakeIndexAction = None # An action to run MakeIndex (for nomencl) on a file. MakeNclAction = None # An action to run MakeIndex (for glossary) on a file. MakeGlossaryAction = None # Used as a return value of modify_env_var if the variable is not set. _null = SCons.Scanner.LaTeX._null modify_env_var = SCons.Scanner.LaTeX.modify_env_var def FindFile(name,suffixes,paths,env,requireExt=False): if requireExt: name,ext = SCons.Util.splitext(name) # if the user gave an extension use it. if ext: name = name + ext if Verbose: print " searching for '%s' with extensions: " % name,suffixes for path in paths: testName = os.path.join(path,name) if Verbose: print " look for '%s'" % testName if os.path.exists(testName): if Verbose: print " found '%s'" % testName return env.fs.File(testName) else: name_ext = SCons.Util.splitext(testName)[1] if name_ext: continue # if no suffix try adding those passed in for suffix in suffixes: testNameExt = testName + suffix if Verbose: print " look for '%s'" % testNameExt if os.path.exists(testNameExt): if Verbose: print " found '%s'" % testNameExt return env.fs.File(testNameExt) if Verbose: print " did not find '%s'" % name return None def InternalLaTeXAuxAction(XXXLaTeXAction, target = None, source= None, env=None): """A builder for LaTeX files that checks the output in the aux file and decides how many times to use LaTeXAction, and BibTeXAction.""" global must_rerun_latex # This routine is called with two actions. In this file for DVI builds # with LaTeXAction and from the pdflatex.py with PDFLaTeXAction # set this up now for the case where the user requests a different extension # for the target filename if (XXXLaTeXAction == LaTeXAction): callerSuffix = ".dvi" else: callerSuffix = env['PDFSUFFIX'] basename = SCons.Util.splitext(str(source[0]))[0] basedir = os.path.split(str(source[0]))[0] basefile = os.path.split(str(basename))[1] abspath = os.path.abspath(basedir) targetext = os.path.splitext(str(target[0]))[1] targetdir = os.path.split(str(target[0]))[0] saved_env = {} for var in SCons.Scanner.LaTeX.LaTeX.env_variables: saved_env[var] = modify_env_var(env, var, abspath) # Create base file names with the target directory since the auxiliary files # will be made there. That's because the *COM variables have the cd # command in the prolog. We check # for the existence of files before opening them--even ones like the # aux file that TeX always creates--to make it possible to write tests # with stubs that don't necessarily generate all of the same files. targetbase = os.path.join(targetdir, basefile) # if there is a \makeindex there will be a .idx and thus # we have to run makeindex at least once to keep the build # happy even if there is no index. # Same for glossaries and nomenclature src_content = source[0].get_text_contents() run_makeindex = makeindex_re.search(src_content) and not os.path.exists(targetbase + '.idx') run_nomenclature = makenomenclature_re.search(src_content) and not os.path.exists(targetbase + '.nlo') run_glossary = makeglossary_re.search(src_content) and not os.path.exists(targetbase + '.glo') saved_hashes = {} suffix_nodes = {} for suffix in all_suffixes: theNode = env.fs.File(targetbase + suffix) suffix_nodes[suffix] = theNode saved_hashes[suffix] = theNode.get_csig() if Verbose: print "hashes: ",saved_hashes must_rerun_latex = True # # routine to update MD5 hash and compare # # TODO(1.5): nested scopes def check_MD5(filenode, suffix, saved_hashes=saved_hashes, targetbase=targetbase): global must_rerun_latex # two calls to clear old csig filenode.clear_memoized_values() filenode.ninfo = filenode.new_ninfo() new_md5 = filenode.get_csig() if saved_hashes[suffix] == new_md5: if Verbose: print "file %s not changed" % (targetbase+suffix) return False # unchanged saved_hashes[suffix] = new_md5 must_rerun_latex = True if Verbose: print "file %s changed, rerunning Latex, new hash = " % (targetbase+suffix), new_md5 return True # changed # generate the file name that latex will generate resultfilename = targetbase + callerSuffix count = 0 while (must_rerun_latex and count < int(env.subst('$LATEXRETRIES'))) : result = XXXLaTeXAction(target, source, env) if result != 0: return result count = count + 1 must_rerun_latex = False # Decide if various things need to be run, or run again. # Read the log file to find all .aux files logfilename = targetbase + '.log' logContent = '' auxfiles = [] if os.path.exists(logfilename): logContent = open(logfilename, "rb").read() auxfiles = openout_aux_re.findall(logContent) # Now decide if bibtex will need to be run. # The information that bibtex reads from the .aux file is # pass-independent. If we find (below) that the .bbl file is unchanged, # then the last latex saw a correct bibliography. # Therefore only do this on the first pass if count == 1: for auxfilename in auxfiles: target_aux = os.path.join(targetdir, auxfilename) if os.path.exists(target_aux): content = open(target_aux, "rb").read() if string.find(content, "bibdata") != -1: if Verbose: print "Need to run bibtex" bibfile = env.fs.File(targetbase) result = BibTeXAction(bibfile, bibfile, env) if result != 0: return result must_rerun_latex = check_MD5(suffix_nodes['.bbl'],'.bbl') break # Now decide if latex will need to be run again due to index. if check_MD5(suffix_nodes['.idx'],'.idx') or (count == 1 and run_makeindex): # We must run makeindex if Verbose: print "Need to run makeindex" idxfile = suffix_nodes['.idx'] result = MakeIndexAction(idxfile, idxfile, env) if result != 0: return result # TO-DO: need to add a way for the user to extend this list for whatever # auxiliary files they create in other (or their own) packages # Harder is case is where an action needs to be called -- that should be rare (I hope?) for index in check_suffixes: check_MD5(suffix_nodes[index],index) # Now decide if latex will need to be run again due to nomenclature. if check_MD5(suffix_nodes['.nlo'],'.nlo') or (count == 1 and run_nomenclature): # We must run makeindex if Verbose: print "Need to run makeindex for nomenclature" nclfile = suffix_nodes['.nlo'] result = MakeNclAction(nclfile, nclfile, env) if result != 0: return result # Now decide if latex will need to be run again due to glossary. if check_MD5(suffix_nodes['.glo'],'.glo') or (count == 1 and run_glossary): # We must run makeindex if Verbose: print "Need to run makeindex for glossary" glofile = suffix_nodes['.glo'] result = MakeGlossaryAction(glofile, glofile, env) if result != 0: return result # Now decide if latex needs to be run yet again to resolve warnings. if warning_rerun_re.search(logContent): must_rerun_latex = True if Verbose: print "rerun Latex due to latex or package rerun warning" if rerun_citations_re.search(logContent): must_rerun_latex = True if Verbose: print "rerun Latex due to 'Rerun to get citations correct' warning" if undefined_references_re.search(logContent): must_rerun_latex = True if Verbose: print "rerun Latex due to undefined references or citations" if (count >= int(env.subst('$LATEXRETRIES')) and must_rerun_latex): print "reached max number of retries on Latex ,",int(env.subst('$LATEXRETRIES')) # end of while loop # rename Latex's output to what the target name is if not (str(target[0]) == resultfilename and os.path.exists(resultfilename)): if os.path.exists(resultfilename): print "move %s to %s" % (resultfilename, str(target[0]), ) shutil.move(resultfilename,str(target[0])) # Original comment (when TEXPICTS was not restored): # The TEXPICTS enviroment variable is needed by a dvi -> pdf step # later on Mac OSX so leave it # # It is also used when searching for pictures (implicit dependencies). # Why not set the variable again in the respective builder instead # of leaving local modifications in the environment? What if multiple # latex builds in different directories need different TEXPICTS? for var in SCons.Scanner.LaTeX.LaTeX.env_variables: if var == 'TEXPICTS': continue if saved_env[var] is _null: try: del env['ENV'][var] except KeyError: pass # was never set else: env['ENV'][var] = saved_env[var] return result def LaTeXAuxAction(target = None, source= None, env=None): result = InternalLaTeXAuxAction( LaTeXAction, target, source, env ) return result LaTeX_re = re.compile("\\\\document(style|class)") def is_LaTeX(flist): # Scan a file list to decide if it's TeX- or LaTeX-flavored. for f in flist: content = f.get_text_contents() if LaTeX_re.search(content): return 1 return 0 def TeXLaTeXFunction(target = None, source= None, env=None): """A builder for TeX and LaTeX that scans the source file to decide the "flavor" of the source and then executes the appropriate program.""" if is_LaTeX(source): result = LaTeXAuxAction(target,source,env) else: result = TeXAction(target,source,env) return result def TeXLaTeXStrFunction(target = None, source= None, env=None): """A strfunction for TeX and LaTeX that scans the source file to decide the "flavor" of the source and then returns the appropriate command string.""" if env.GetOption("no_exec"): if is_LaTeX(source): result = env.subst('$LATEXCOM',0,target,source)+" ..." else: result = env.subst("$TEXCOM",0,target,source)+" ..." else: result = '' return result def tex_eps_emitter(target, source, env): """An emitter for TeX and LaTeX sources when executing tex or latex. It will accept .ps and .eps graphics files """ (target, source) = tex_emitter_core(target, source, env, TexGraphics) return (target, source) def tex_pdf_emitter(target, source, env): """An emitter for TeX and LaTeX sources when executing pdftex or pdflatex. It will accept graphics files of types .pdf, .jpg, .png, .gif, and .tif """ (target, source) = tex_emitter_core(target, source, env, LatexGraphics) return (target, source) def ScanFiles(theFile, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir): # for theFile (a Node) update any file_tests and search for graphics files # then find all included files and call ScanFiles for each of them content = theFile.get_text_contents() if Verbose: print " scanning ",str(theFile) for i in range(len(file_tests_search)): if file_tests[i][0] == None: file_tests[i][0] = file_tests_search[i].search(content) # recursively call this on each of the included files inc_files = [ ] inc_files.extend( include_re.findall(content) ) if Verbose: print "files included by '%s': "%str(theFile),inc_files # inc_files is list of file names as given. need to find them # using TEXINPUTS paths. for src in inc_files: srcNode = srcNode = FindFile(src,['.tex','.ltx','.latex'],paths,env,requireExt=False) if srcNode != None: file_test = ScanFiles(srcNode, target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir) if Verbose: print " done scanning ",str(theFile) return file_tests def tex_emitter_core(target, source, env, graphics_extensions): """An emitter for TeX and LaTeX sources. For LaTeX sources we try and find the common created files that are needed on subsequent runs of latex to finish tables of contents, bibliographies, indices, lists of figures, and hyperlink references. """ targetbase = SCons.Util.splitext(str(target[0]))[0] basename = SCons.Util.splitext(str(source[0]))[0] basefile = os.path.split(str(basename))[1] basedir = os.path.split(str(source[0]))[0] targetdir = os.path.split(str(target[0]))[0] abspath = os.path.abspath(basedir) target[0].attributes.path = abspath # # file names we will make use of in searching the sources and log file # emit_suffixes = ['.aux', '.log', '.ilg', '.blg', '.nls', '.nlg', '.gls', '.glg'] + all_suffixes auxfilename = targetbase + '.aux' logfilename = targetbase + '.log' env.SideEffect(auxfilename,target[0]) env.SideEffect(logfilename,target[0]) env.Clean(target[0],auxfilename) env.Clean(target[0],logfilename) content = source[0].get_text_contents() idx_exists = os.path.exists(targetbase + '.idx') nlo_exists = os.path.exists(targetbase + '.nlo') glo_exists = os.path.exists(targetbase + '.glo') # set up list with the regular expressions # we use to find features used file_tests_search = [auxfile_re, makeindex_re, bibliography_re, tableofcontents_re, listoffigures_re, listoftables_re, hyperref_re, makenomenclature_re, makeglossary_re, beamer_re ] # set up list with the file suffixes that need emitting # when a feature is found file_tests_suff = [['.aux'], ['.idx', '.ind', '.ilg'], ['.bbl', '.blg'], ['.toc'], ['.lof'], ['.lot'], ['.out'], ['.nlo', '.nls', '.nlg'], ['.glo', '.gls', '.glg'], ['.nav', '.snm', '.out', '.toc'] ] # build the list of lists file_tests = [] for i in range(len(file_tests_search)): file_tests.append( [None, file_tests_suff[i]] ) # TO-DO: need to add a way for the user to extend this list for whatever # auxiliary files they create in other (or their own) packages # get path list from both env['TEXINPUTS'] and env['ENV']['TEXINPUTS'] savedpath = modify_env_var(env, 'TEXINPUTS', abspath) paths = env['ENV']['TEXINPUTS'] if SCons.Util.is_List(paths): pass else: # Split at os.pathsep to convert into absolute path # TODO(1.5) #paths = paths.split(os.pathsep) paths = string.split(paths, os.pathsep) # now that we have the path list restore the env if savedpath is _null: try: del env['ENV']['TEXINPUTS'] except KeyError: pass # was never set else: env['ENV']['TEXINPUTS'] = savedpath if Verbose: print "search path ",paths file_tests = ScanFiles(source[0], target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir) for (theSearch,suffix_list) in file_tests: if theSearch: for suffix in suffix_list: env.SideEffect(targetbase + suffix,target[0]) env.Clean(target[0],targetbase + suffix) # read log file to get all other files that latex creates and will read on the next pass if os.path.exists(logfilename): content = open(logfilename, "rb").read() out_files = openout_re.findall(content) env.SideEffect(out_files,target[0]) env.Clean(target[0],out_files) return (target, source) TeXLaTeXAction = None def generate(env): """Add Builders and construction variables for TeX to an Environment.""" # A generic tex file Action, sufficient for all tex files. global TeXAction if TeXAction is None: TeXAction = SCons.Action.Action("$TEXCOM", "$TEXCOMSTR") # An Action to build a latex file. This might be needed more # than once if we are dealing with labels and bibtex. global LaTeXAction if LaTeXAction is None: LaTeXAction = SCons.Action.Action("$LATEXCOM", "$LATEXCOMSTR") # Define an action to run BibTeX on a file. global BibTeXAction if BibTeXAction is None: BibTeXAction = SCons.Action.Action("$BIBTEXCOM", "$BIBTEXCOMSTR") # Define an action to run MakeIndex on a file. global MakeIndexAction if MakeIndexAction is None: MakeIndexAction = SCons.Action.Action("$MAKEINDEXCOM", "$MAKEINDEXCOMSTR") # Define an action to run MakeIndex on a file for nomenclatures. global MakeNclAction if MakeNclAction is None: MakeNclAction = SCons.Action.Action("$MAKENCLCOM", "$MAKENCLCOMSTR") # Define an action to run MakeIndex on a file for glossaries. global MakeGlossaryAction if MakeGlossaryAction is None: MakeGlossaryAction = SCons.Action.Action("$MAKEGLOSSARYCOM", "$MAKEGLOSSARYCOMSTR") global TeXLaTeXAction if TeXLaTeXAction is None: TeXLaTeXAction = SCons.Action.Action(TeXLaTeXFunction, strfunction=TeXLaTeXStrFunction) import dvi dvi.generate(env) bld = env['BUILDERS']['DVI'] bld.add_action('.tex', TeXLaTeXAction) bld.add_emitter('.tex', tex_eps_emitter) env['TEX'] = 'tex' env['TEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode') env['TEXCOM'] = 'cd ${TARGET.dir} && $TEX $TEXFLAGS ${SOURCE.file}' # Duplicate from latex.py. If latex.py goes away, then this is still OK. env['LATEX'] = 'latex' env['LATEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode') env['LATEXCOM'] = 'cd ${TARGET.dir} && $LATEX $LATEXFLAGS ${SOURCE.file}' env['LATEXRETRIES'] = 3 env['BIBTEX'] = 'bibtex' env['BIBTEXFLAGS'] = SCons.Util.CLVar('') env['BIBTEXCOM'] = 'cd ${TARGET.dir} && $BIBTEX $BIBTEXFLAGS ${SOURCE.filebase}' env['MAKEINDEX'] = 'makeindex' env['MAKEINDEXFLAGS'] = SCons.Util.CLVar('') env['MAKEINDEXCOM'] = 'cd ${TARGET.dir} && $MAKEINDEX $MAKEINDEXFLAGS ${SOURCE.file}' env['MAKEGLOSSARY'] = 'makeindex' env['MAKEGLOSSARYSTYLE'] = '${SOURCE.filebase}.ist' env['MAKEGLOSSARYFLAGS'] = SCons.Util.CLVar('-s ${MAKEGLOSSARYSTYLE} -t ${SOURCE.filebase}.glg') env['MAKEGLOSSARYCOM'] = 'cd ${TARGET.dir} && $MAKEGLOSSARY ${SOURCE.filebase}.glo $MAKEGLOSSARYFLAGS -o ${SOURCE.filebase}.gls' env['MAKENCL'] = 'makeindex' env['MAKENCLSTYLE'] = '$nomencl.ist' env['MAKENCLFLAGS'] = '-s ${MAKENCLSTYLE} -t ${SOURCE.filebase}.nlg' env['MAKENCLCOM'] = 'cd ${TARGET.dir} && $MAKENCL ${SOURCE.filebase}.nlo $MAKENCLFLAGS -o ${SOURCE.filebase}.nls' # Duplicate from pdflatex.py. If latex.py goes away, then this is still OK. env['PDFLATEX'] = 'pdflatex' env['PDFLATEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode') env['PDFLATEXCOM'] = 'cd ${TARGET.dir} && $PDFLATEX $PDFLATEXFLAGS ${SOURCE.file}' def exists(env): return env.Detect('tex') # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
apache-2.0
tiagocoutinho/bliss
examples/ct2/card/acq1.py
1
5788
""" ESRF-BCU acquisition with internal master: counter 11 counts the acquisition time (using internal clock); counter 12 counts the number of points """ import os import sys import time import pprint import logging import argparse import datetime import numpy from bliss.controllers.ct2.card import (P201Card, Clock, Level, CtConfig, \ OutputSrc, CtClockSrc, CtGateSrc, CtHardStartSrc, CtHardStopSrc) def configure(device, channels): device.request_exclusive_access() device.set_interrupts() device.reset() device.software_reset() # ------------------------------------------------------------------------- # Channel configuration (could be loaded from beacon, for example. We # choose to hard code it here) # ------------------------------------------------------------------------- # for counters we only care about clock source, gate source here. The rest # will be up to the actual acquisition to setup according to the type of # acquisition for _, ch_nb in channels.items(): ct_config = CtConfig(clock_source=CtClockSrc(ch_nb % 5), gate_source=CtGateSrc.GATE_CMPT, # anything will do for the remaining fields. It # will be properly setup in the acquisition slave # setup hard_start_source=CtHardStartSrc.SOFTWARE, hard_stop_source=CtHardStopSrc.SOFTWARE, reset_from_hard_soft_stop=False, stop_from_hard_stop=False) device.set_counter_config(ch_nb, ct_config) # TODO: Set input and output channel configuration (TTL/NIM level, 50ohm, # edge interrupt, etc) # internal clock 100 Mhz device.set_clock(Clock.CLK_100_MHz) def prepare_master(device, acq_time, nb_points): ct_11_config = CtConfig(clock_source=CtClockSrc.CLK_100_MHz, gate_source=CtGateSrc.CT_12_GATE_ENVELOP, hard_start_source=CtHardStartSrc.SOFTWARE, hard_stop_source=CtHardStopSrc.CT_11_EQ_CMP_11, reset_from_hard_soft_stop=True, stop_from_hard_stop=False) ct_12_config = CtConfig(clock_source=CtClockSrc.INC_CT_11_STOP, gate_source=CtGateSrc.GATE_CMPT, hard_start_source=CtHardStartSrc.SOFTWARE, hard_stop_source=CtHardStopSrc.CT_12_EQ_CMP_12, reset_from_hard_soft_stop=True, stop_from_hard_stop=True) device.set_counters_config({11:ct_11_config, 12:ct_12_config}) device.set_counter_comparator_value(11, int(acq_time * 1E8)) device.set_counter_comparator_value(12, nb_points) def prepare_slaves(device, acq_time, nb_points, channels): channel_nbs = list(channels.values()) for ch_name, ch_nb in channels.iteritems(): ct_config = device.get_counter_config(ch_nb) ct_config['gate_source'] = CtGateSrc.CT_11_GATE_ENVELOP ct_config['hard_start_source'] = CtHardStartSrc.SOFTWARE ct_config['hard_stop_source'] = CtHardStopSrc.CT_11_EQ_CMP_11 ct_config['reset_from_hard_soft_stop'] = True ct_config['stop_from_hard_stop'] = False device.set_counter_config(ch_nb, ct_config) device.set_counter_config(ch_nb, ct_config) # counter 11 will latch all active counters/channels latch_sources = dict([(ct, 11) for ct in channel_nbs + [12]]) device.set_counters_latch_sources(latch_sources) # make all counters enabled by software device.enable_counters_software(channel_nbs + [11, 12]) def main(): def to_str(values, fmt="9d"): fmt = "%" + fmt return "[" + "".join([fmt % value for value in values]) + "]" def out(msg=""): sys.stdout.write(msg) sys.stdout.flush() channels = { "I0": 3, "V2F": 5, "SCA": 6, } parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--log-level', type=str, default='info', help='log level (debug, info, warning, error) [default: info]') parser.add_argument('--nb-points', type=int, help='number of points', default=10) parser.add_argument('--acq-time', type=float, default=1, help='acquisition time') args = parser.parse_args() logging.basicConfig(level=getattr(logging, args.log_level.upper()), format="%(asctime)s %(levelname)s %(name)s: %(message)s") nb_points = args.nb_points acq_time = args.acq_time device = P201Card() configure(device, channels) prepare_master(device, acq_time, nb_points) prepare_slaves(device, acq_time, nb_points, channels) # start counting... nap = 0.1 start_time = time.time() device.start_counters_software(channels.values() + [11, 12]) while True: time.sleep(nap) counter_values = device.get_counters_values() latch_values = device.get_latches_values() status = device.get_counters_status() if not status[12]['run']: stop_time = time.time() break msg = "\r{0} {1}".format(to_str(counter_values), to_str(latch_values)) out(msg) print("\n{0} {1}".format(to_str(counter_values), to_str(latch_values))) print("Took ~{0}s (err: {1}s)".format(stop_time-start_time, nap)) pprint.pprint(device.get_counters_status()) device.relinquish_exclusive_access() if __name__ == "__main__": main()
lgpl-3.0
j-griffith/cinder
cinder/tests/unit/db/test_purge.py
3
17492
# Copyright (C) 2015 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for db purge.""" import datetime import uuid from oslo_db import exception as db_exc from oslo_utils import timeutils from sqlalchemy.dialects import sqlite from cinder import context from cinder import db from cinder.db.sqlalchemy import api as db_api from cinder import exception from cinder import test from oslo_db.sqlalchemy import utils as sqlalchemyutils class PurgeDeletedTest(test.TestCase): def setUp(self): super(PurgeDeletedTest, self).setUp() self.context = context.get_admin_context() self.engine = db_api.get_engine() self.session = db_api.get_session() self.conn = self.engine.connect() self.volumes = sqlalchemyutils.get_table( self.engine, "volumes") # The volume_metadata table has a FK of volume_id self.vm = sqlalchemyutils.get_table( self.engine, "volume_metadata") self.vol_types = sqlalchemyutils.get_table( self.engine, "volume_types") # The volume_type_projects table has a FK of volume_type_id self.vol_type_proj = sqlalchemyutils.get_table( self.engine, "volume_type_projects") self.snapshots = sqlalchemyutils.get_table( self.engine, "snapshots") self.sm = sqlalchemyutils.get_table( self.engine, "snapshot_metadata") self.vgm = sqlalchemyutils.get_table( self.engine, "volume_glance_metadata") self.qos = sqlalchemyutils.get_table( self.engine, "quality_of_service_specs") self.uuidstrs = [] for unused in range(6): self.uuidstrs.append(uuid.uuid4().hex) # Add 6 rows to table for uuidstr in self.uuidstrs: ins_stmt = self.volumes.insert().values(id=uuidstr) self.conn.execute(ins_stmt) ins_stmt = self.vm.insert().values(volume_id=uuidstr) self.conn.execute(ins_stmt) ins_stmt = self.vgm.insert().values( volume_id=uuidstr, key='image_name', value='test') self.conn.execute(ins_stmt) ins_stmt = self.vol_types.insert().values(id=uuidstr) self.conn.execute(ins_stmt) ins_stmt = self.vol_type_proj.insert().\ values(volume_type_id=uuidstr) self.conn.execute(ins_stmt) ins_stmt = self.snapshots.insert().values( id=uuidstr, volume_id=uuidstr) self.conn.execute(ins_stmt) ins_stmt = self.sm.insert().values(snapshot_id=uuidstr) self.conn.execute(ins_stmt) ins_stmt = self.vgm.insert().values( snapshot_id=uuidstr, key='image_name', value='test') self.conn.execute(ins_stmt) ins_stmt = self.qos.insert().values( id=uuidstr, key='QoS_Specs_Name', value='test') self.conn.execute(ins_stmt) ins_stmt = self.vol_types.insert().values( id=uuid.uuid4().hex, qos_specs_id=uuidstr) self.conn.execute(ins_stmt) ins_stmt = self.qos.insert().values( id=uuid.uuid4().hex, specs_id=uuidstr, key='desc', value='test') self.conn.execute(ins_stmt) # Set 5 of them deleted # 2 are 60 days ago, 2 are 20 days ago, one is just now. now = timeutils.utcnow() old = timeutils.utcnow() - datetime.timedelta(days=20) older = timeutils.utcnow() - datetime.timedelta(days=60) make_vol_now = self.volumes.update().\ where(self.volumes.c.id.in_(self.uuidstrs[0:1]))\ .values(deleted_at=now) make_vol_old = self.volumes.update().\ where(self.volumes.c.id.in_(self.uuidstrs[1:3]))\ .values(deleted_at=old) make_vol_older = self.volumes.update().\ where(self.volumes.c.id.in_(self.uuidstrs[4:6]))\ .values(deleted_at=older) make_vol_meta_now = self.vm.update().\ where(self.vm.c.volume_id.in_(self.uuidstrs[0:1]))\ .values(deleted_at=now) make_vol_meta_old = self.vm.update().\ where(self.vm.c.volume_id.in_(self.uuidstrs[1:3]))\ .values(deleted_at=old) make_vol_meta_older = self.vm.update().\ where(self.vm.c.volume_id.in_(self.uuidstrs[4:6]))\ .values(deleted_at=older) make_vol_types_now = self.vol_types.update().\ where(self.vol_types.c.id.in_(self.uuidstrs[0:1]))\ .values(deleted_at=now) make_vol_types_old = self.vol_types.update().\ where(self.vol_types.c.id.in_(self.uuidstrs[1:3]))\ .values(deleted_at=old) make_vol_types_older = self.vol_types.update().\ where(self.vol_types.c.id.in_(self.uuidstrs[4:6]))\ .values(deleted_at=older) make_vol_type_proj_now = self.vol_type_proj.update().\ where(self.vol_type_proj.c.volume_type_id.in_(self.uuidstrs[0:1]))\ .values(deleted_at=now) make_vol_type_proj_old = self.vol_type_proj.update().\ where(self.vol_type_proj.c.volume_type_id.in_(self.uuidstrs[1:3]))\ .values(deleted_at=old) make_vol_type_proj_older = self.vol_type_proj.update().\ where(self.vol_type_proj.c.volume_type_id.in_(self.uuidstrs[4:6]))\ .values(deleted_at=older) make_snap_now = self.snapshots.update().\ where(self.snapshots.c.id.in_(self.uuidstrs[0:1]))\ .values(deleted_at=now) make_snap_old = self.snapshots.update().\ where(self.snapshots.c.id.in_(self.uuidstrs[1:3]))\ .values(deleted_at=old) make_snap_older = self.snapshots.update().\ where(self.snapshots.c.id.in_(self.uuidstrs[4:6]))\ .values(deleted_at=older) make_snap_meta_now = self.sm.update().\ where(self.sm.c.snapshot_id.in_(self.uuidstrs[0:1]))\ .values(deleted_at=now) make_snap_meta_old = self.sm.update().\ where(self.sm.c.snapshot_id.in_(self.uuidstrs[1:3]))\ .values(deleted_at=old) make_snap_meta_older = self.sm.update().\ where(self.sm.c.snapshot_id.in_(self.uuidstrs[4:6]))\ .values(deleted_at=older) make_vol_glance_meta_now = self.vgm.update().\ where(self.vgm.c.volume_id.in_(self.uuidstrs[0:1]))\ .values(deleted_at=now) make_vol_glance_meta_old = self.vgm.update().\ where(self.vgm.c.volume_id.in_(self.uuidstrs[1:3]))\ .values(deleted_at=old) make_vol_glance_meta_older = self.vgm.update().\ where(self.vgm.c.volume_id.in_(self.uuidstrs[4:6]))\ .values(deleted_at=older) make_snap_glance_meta_now = self.vgm.update().\ where(self.vgm.c.snapshot_id.in_(self.uuidstrs[0:1]))\ .values(deleted_at=now) make_snap_glance_meta_old = self.vgm.update().\ where(self.vgm.c.snapshot_id.in_(self.uuidstrs[1:3]))\ .values(deleted_at=old) make_snap_glance_meta_older = self.vgm.update().\ where(self.vgm.c.snapshot_id.in_(self.uuidstrs[4:6]))\ .values(deleted_at=older) make_qos_now = self.qos.update().where( self.qos.c.id.in_(self.uuidstrs[0:1])).values(deleted_at=now) make_qos_old = self.qos.update().where( self.qos.c.id.in_(self.uuidstrs[1:3])).values(deleted_at=old) make_qos_older = self.qos.update().where( self.qos.c.id.in_(self.uuidstrs[4:6])).values(deleted_at=older) make_qos_child_record_now = self.qos.update().where( self.qos.c.specs_id.in_(self.uuidstrs[0:1])).values( deleted_at=now) make_qos_child_record_old = self.qos.update().where( self.qos.c.specs_id.in_(self.uuidstrs[1:3])).values( deleted_at=old) make_qos_child_record_older = self.qos.update().where( self.qos.c.specs_id.in_(self.uuidstrs[4:6])).values( deleted_at=older) make_vol_types1_now = self.vol_types.update().where( self.vol_types.c.qos_specs_id.in_(self.uuidstrs[0:1])).values( deleted_at=now) make_vol_types1_old = self.vol_types.update().where( self.vol_types.c.qos_specs_id.in_(self.uuidstrs[1:3])).values( deleted_at=old) make_vol_types1_older = self.vol_types.update().where( self.vol_types.c.qos_specs_id.in_(self.uuidstrs[4:6])).values( deleted_at=older) self.conn.execute(make_vol_now) self.conn.execute(make_vol_old) self.conn.execute(make_vol_older) self.conn.execute(make_vol_meta_now) self.conn.execute(make_vol_meta_old) self.conn.execute(make_vol_meta_older) self.conn.execute(make_vol_types_now) self.conn.execute(make_vol_types_old) self.conn.execute(make_vol_types_older) self.conn.execute(make_vol_type_proj_now) self.conn.execute(make_vol_type_proj_old) self.conn.execute(make_vol_type_proj_older) self.conn.execute(make_snap_now) self.conn.execute(make_snap_old) self.conn.execute(make_snap_older) self.conn.execute(make_snap_meta_now) self.conn.execute(make_snap_meta_old) self.conn.execute(make_snap_meta_older) self.conn.execute(make_vol_glance_meta_now) self.conn.execute(make_vol_glance_meta_old) self.conn.execute(make_vol_glance_meta_older) self.conn.execute(make_snap_glance_meta_now) self.conn.execute(make_snap_glance_meta_old) self.conn.execute(make_snap_glance_meta_older) self.conn.execute(make_qos_now) self.conn.execute(make_qos_old) self.conn.execute(make_qos_older) self.conn.execute(make_qos_child_record_now) self.conn.execute(make_qos_child_record_old) self.conn.execute(make_qos_child_record_older) self.conn.execute(make_vol_types1_now) self.conn.execute(make_vol_types1_old) self.conn.execute(make_vol_types1_older) def test_purge_deleted_rows_in_zero_age_in(self): dialect = self.engine.url.get_dialect() if dialect == sqlite.dialect: # We're seeing issues with foreign key support in SQLite 3.6.20 # SQLAlchemy doesn't support it at all with < SQLite 3.6.19 # It works fine in SQLite 3.7. # Force foreign_key checking if running SQLite >= 3.7 import sqlite3 tup = sqlite3.sqlite_version_info if tup[0] > 3 or (tup[0] == 3 and tup[1] >= 7): self.conn.execute("PRAGMA foreign_keys = ON") # Purge at age_in_days=0, should delete one more row db.purge_deleted_rows(self.context, age_in_days=0) vol_rows = self.session.query(self.volumes).count() vol_meta_rows = self.session.query(self.vm).count() vol_type_rows = self.session.query(self.vol_types).count() vol_type_proj_rows = self.session.query(self.vol_type_proj).count() snap_rows = self.session.query(self.snapshots).count() snap_meta_rows = self.session.query(self.sm).count() vol_glance_meta_rows = self.session.query(self.vgm).count() qos_rows = self.session.query(self.qos).count() # Verify that we only have 1 rows now self.assertEqual(1, vol_rows) self.assertEqual(1, vol_meta_rows) self.assertEqual(2, vol_type_rows) self.assertEqual(1, vol_type_proj_rows) self.assertEqual(1, snap_rows) self.assertEqual(1, snap_meta_rows) self.assertEqual(2, vol_glance_meta_rows) self.assertEqual(2, qos_rows) def test_purge_deleted_rows_old(self): dialect = self.engine.url.get_dialect() if dialect == sqlite.dialect: # We're seeing issues with foreign key support in SQLite 3.6.20 # SQLAlchemy doesn't support it at all with < SQLite 3.6.19 # It works fine in SQLite 3.7. # Force foreign_key checking if running SQLite >= 3.7 import sqlite3 tup = sqlite3.sqlite_version_info if tup[0] > 3 or (tup[0] == 3 and tup[1] >= 7): self.conn.execute("PRAGMA foreign_keys = ON") # Purge at 30 days old, should only delete 2 rows db.purge_deleted_rows(self.context, age_in_days=30) vol_rows = self.session.query(self.volumes).count() vol_meta_rows = self.session.query(self.vm).count() vol_type_rows = self.session.query(self.vol_types).count() vol_type_proj_rows = self.session.query(self.vol_type_proj).count() snap_rows = self.session.query(self.snapshots).count() snap_meta_rows = self.session.query(self.sm).count() vol_glance_meta_rows = self.session.query(self.vgm).count() qos_rows = self.session.query(self.qos).count() # Verify that we only deleted 2 self.assertEqual(4, vol_rows) self.assertEqual(4, vol_meta_rows) self.assertEqual(8, vol_type_rows) self.assertEqual(4, vol_type_proj_rows) self.assertEqual(4, snap_rows) self.assertEqual(4, snap_meta_rows) self.assertEqual(8, vol_glance_meta_rows) self.assertEqual(8, qos_rows) def test_purge_deleted_rows_older(self): dialect = self.engine.url.get_dialect() if dialect == sqlite.dialect: # We're seeing issues with foreign key support in SQLite 3.6.20 # SQLAlchemy doesn't support it at all with < SQLite 3.6.19 # It works fine in SQLite 3.7. # Force foreign_key checking if running SQLite >= 3.7 import sqlite3 tup = sqlite3.sqlite_version_info if tup[0] > 3 or (tup[0] == 3 and tup[1] >= 7): self.conn.execute("PRAGMA foreign_keys = ON") # Purge at 10 days old now, should delete 2 more rows db.purge_deleted_rows(self.context, age_in_days=10) vol_rows = self.session.query(self.volumes).count() vol_meta_rows = self.session.query(self.vm).count() vol_type_rows = self.session.query(self.vol_types).count() vol_type_proj_rows = self.session.query(self.vol_type_proj).count() snap_rows = self.session.query(self.snapshots).count() snap_meta_rows = self.session.query(self.sm).count() vol_glance_meta_rows = self.session.query(self.vgm).count() qos_rows = self.session.query(self.qos).count() # Verify that we only have 2 rows now self.assertEqual(2, vol_rows) self.assertEqual(2, vol_meta_rows) self.assertEqual(4, vol_type_rows) self.assertEqual(2, vol_type_proj_rows) self.assertEqual(2, snap_rows) self.assertEqual(2, snap_meta_rows) self.assertEqual(4, vol_glance_meta_rows) self.assertEqual(4, qos_rows) def test_purge_deleted_rows_bad_args(self): # Test with no age argument self.assertRaises(TypeError, db.purge_deleted_rows, self.context) # Test purge with non-integer self.assertRaises(exception.InvalidParameterValue, db.purge_deleted_rows, self.context, age_in_days='ten') def test_purge_deleted_rows_integrity_failure(self): dialect = self.engine.url.get_dialect() if dialect == sqlite.dialect: # We're seeing issues with foreign key support in SQLite 3.6.20 # SQLAlchemy doesn't support it at all with < SQLite 3.6.19 # It works fine in SQLite 3.7. # So return early to skip this test if running SQLite < 3.7 import sqlite3 tup = sqlite3.sqlite_version_info if tup[0] < 3 or (tup[0] == 3 and tup[1] < 7): self.skipTest( 'sqlite version too old for reliable SQLA foreign_keys') self.conn.execute("PRAGMA foreign_keys = ON") # add new entry in volume and volume_admin_metadata for # integrity check uuid_str = uuid.uuid4().hex ins_stmt = self.volumes.insert().values(id=uuid_str) self.conn.execute(ins_stmt) ins_stmt = self.vm.insert().values(volume_id=uuid_str) self.conn.execute(ins_stmt) # set volume record to deleted 20 days ago old = timeutils.utcnow() - datetime.timedelta(days=20) make_old = self.volumes.update().where( self.volumes.c.id.in_([uuid_str])).values(deleted_at=old) self.conn.execute(make_old) # Verify that purge_deleted_rows fails due to Foreign Key constraint self.assertRaises(db_exc.DBReferenceError, db.purge_deleted_rows, self.context, age_in_days=10)
apache-2.0
amyvmiwei/kbengine
kbe/src/lib/python/Lib/idlelib/PathBrowser.py
10
2877
import os import sys import importlib.machinery from idlelib.TreeWidget import TreeItem from idlelib.ClassBrowser import ClassBrowser, ModuleBrowserTreeItem class PathBrowser(ClassBrowser): def __init__(self, flist): self.init(flist) def settitle(self): self.top.wm_title("Path Browser") self.top.wm_iconname("Path Browser") def rootnode(self): return PathBrowserTreeItem() class PathBrowserTreeItem(TreeItem): def GetText(self): return "sys.path" def GetSubList(self): sublist = [] for dir in sys.path: item = DirBrowserTreeItem(dir) sublist.append(item) return sublist class DirBrowserTreeItem(TreeItem): def __init__(self, dir, packages=[]): self.dir = dir self.packages = packages def GetText(self): if not self.packages: return self.dir else: return self.packages[-1] + ": package" def GetSubList(self): try: names = os.listdir(self.dir or os.curdir) except OSError: return [] packages = [] for name in names: file = os.path.join(self.dir, name) if self.ispackagedir(file): nn = os.path.normcase(name) packages.append((nn, name, file)) packages.sort() sublist = [] for nn, name, file in packages: item = DirBrowserTreeItem(file, self.packages + [name]) sublist.append(item) for nn, name in self.listmodules(names): item = ModuleBrowserTreeItem(os.path.join(self.dir, name)) sublist.append(item) return sublist def ispackagedir(self, file): if not os.path.isdir(file): return 0 init = os.path.join(file, "__init__.py") return os.path.exists(init) def listmodules(self, allnames): modules = {} suffixes = importlib.machinery.EXTENSION_SUFFIXES[:] suffixes += importlib.machinery.SOURCE_SUFFIXES[:] suffixes += importlib.machinery.BYTECODE_SUFFIXES[:] sorted = [] for suff in suffixes: i = -len(suff) for name in allnames[:]: normed_name = os.path.normcase(name) if normed_name[i:] == suff: mod_name = name[:i] if mod_name not in modules: modules[mod_name] = None sorted.append((normed_name, name)) allnames.remove(name) sorted.sort() return sorted def main(): from idlelib import PyShell PathBrowser(PyShell.flist) if sys.stdin is sys.__stdin__: mainloop() if __name__ == "__main__": from unittest import main main('idlelib.idle_test.test_pathbrowser', verbosity=2, exit=False)
lgpl-3.0
rbalda/neural_ocr
env/lib/python2.7/site-packages/matplotlib/compat/subprocess.py
19
2827
""" A replacement wrapper around the subprocess module, with a number of work-arounds: - Provides the check_output function (which subprocess only provides from Python 2.7 onwards). - Provides a stub implementation of subprocess members on Google App Engine (which are missing in subprocess). Instead of importing subprocess, other modules should use this as follows: from matplotlib.compat import subprocess This module is safe to import from anywhere within matplotlib. """ from __future__ import absolute_import # Required to import subprocess from __future__ import print_function import subprocess __all__ = ['Popen', 'PIPE', 'STDOUT', 'check_output', 'CalledProcessError'] if hasattr(subprocess, 'Popen'): Popen = subprocess.Popen # Assume that it also has the other constants. PIPE = subprocess.PIPE STDOUT = subprocess.STDOUT CalledProcessError = subprocess.CalledProcessError else: # In restricted environments (such as Google App Engine), these are # non-existent. Replace them with dummy versions that always raise OSError. def Popen(*args, **kwargs): raise OSError("subprocess.Popen is not supported") PIPE = -1 STDOUT = -2 # There is no need to catch CalledProcessError. These stubs cannot raise # it. None in an except clause will simply not match any exceptions. CalledProcessError = None def _check_output(*popenargs, **kwargs): r"""Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example:: >>> check_output(["ls", "-l", "/dev/null"]) 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT.:: >>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) 'ls: non_existent_file: No such file or directory\n' """ if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = Popen(stdout=PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise subprocess.CalledProcessError(retcode, cmd, output=output) return output # python2.7's subprocess provides a check_output method if hasattr(subprocess, 'check_output'): check_output = subprocess.check_output else: check_output = _check_output
mit
jaggu303619/asylum
openerp/addons/l10n_it/__openerp__.py
165
2072
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010 # OpenERP Italian Community (<http://www.openerp-italia.org>) # Servabit srl # Agile Business Group sagl # Domsense srl # Albatos srl # # Copyright (C) 2011-2012 # Associazione OpenERP Italia (<http://www.openerp-italia.org>) # # 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/>. # ############################################################################## { 'name': 'Italy - Accounting', 'version': '0.2', 'depends': ['base_vat','account_chart','base_iban'], 'author': 'OpenERP Italian Community', 'description': """ Piano dei conti italiano di un'impresa generica. ================================================ Italian accounting chart and localization. """, 'license': 'AGPL-3', 'category': 'Localization/Account Charts', 'website': 'http://www.openerp-italia.org/', 'data': [ 'data/account.account.template.csv', 'data/account.tax.code.template.csv', 'account_chart.xml', 'data/account.tax.template.csv', 'data/account.fiscal.position.template.csv', 'l10n_chart_it_generic.xml', ], 'demo': [], 'installable': True, 'auto_install': False, 'images': ['images/config_chart_l10n_it.jpeg','images/l10n_it_chart.jpeg'], }
agpl-3.0
open-homeautomation/home-assistant
homeassistant/components/tts/__init__.py
3
16938
""" Provide functionality to TTS. For more details about this component, please refer to the documentation at https://home-assistant.io/components/tts/ """ import asyncio import ctypes import functools as ft import hashlib import logging import mimetypes import os import re import io from aiohttp import web import voluptuous as vol from homeassistant.const import ATTR_ENTITY_ID from homeassistant.bootstrap import async_prepare_setup_platform from homeassistant.core import callback from homeassistant.config import load_yaml_config_file from homeassistant.components.http import HomeAssistantView from homeassistant.components.media_player import ( SERVICE_PLAY_MEDIA, MEDIA_TYPE_MUSIC, ATTR_MEDIA_CONTENT_ID, ATTR_MEDIA_CONTENT_TYPE, DOMAIN as DOMAIN_MP) from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_per_platform import homeassistant.helpers.config_validation as cv DOMAIN = 'tts' DEPENDENCIES = ['http'] REQUIREMENTS = ["mutagen==1.36.2"] _LOGGER = logging.getLogger(__name__) MEM_CACHE_FILENAME = 'filename' MEM_CACHE_VOICE = 'voice' CONF_LANG = 'language' CONF_CACHE = 'cache' CONF_CACHE_DIR = 'cache_dir' CONF_TIME_MEMORY = 'time_memory' DEFAULT_CACHE = True DEFAULT_CACHE_DIR = "tts" DEFAULT_TIME_MEMORY = 300 SERVICE_SAY = 'say' SERVICE_CLEAR_CACHE = 'clear_cache' ATTR_MESSAGE = 'message' ATTR_CACHE = 'cache' ATTR_LANGUAGE = 'language' ATTR_OPTIONS = 'options' _RE_VOICE_FILE = re.compile( r"([a-f0-9]{40})_([^_]+)_([^_]+)_([a-z_]+)\.[a-z0-9]{3,4}") KEY_PATTERN = '{0}_{1}_{2}_{3}' PLATFORM_SCHEMA = cv.PLATFORM_SCHEMA.extend({ vol.Optional(CONF_CACHE, default=DEFAULT_CACHE): cv.boolean, vol.Optional(CONF_CACHE_DIR, default=DEFAULT_CACHE_DIR): cv.string, vol.Optional(CONF_TIME_MEMORY, default=DEFAULT_TIME_MEMORY): vol.All(vol.Coerce(int), vol.Range(min=60, max=57600)), }) SCHEMA_SERVICE_SAY = vol.Schema({ vol.Required(ATTR_MESSAGE): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(ATTR_CACHE): cv.boolean, vol.Optional(ATTR_LANGUAGE): cv.string, vol.Optional(ATTR_OPTIONS): dict, }) SCHEMA_SERVICE_CLEAR_CACHE = vol.Schema({}) @asyncio.coroutine def async_setup(hass, config): """Setup TTS.""" tts = SpeechManager(hass) try: conf = config[DOMAIN][0] if len(config.get(DOMAIN, [])) > 0 else {} use_cache = conf.get(CONF_CACHE, DEFAULT_CACHE) cache_dir = conf.get(CONF_CACHE_DIR, DEFAULT_CACHE_DIR) time_memory = conf.get(CONF_TIME_MEMORY, DEFAULT_TIME_MEMORY) yield from tts.async_init_cache(use_cache, cache_dir, time_memory) except (HomeAssistantError, KeyError) as err: _LOGGER.error("Error on cache init %s", err) return False hass.http.register_view(TextToSpeechView(tts)) descriptions = yield from hass.loop.run_in_executor( None, load_yaml_config_file, os.path.join(os.path.dirname(__file__), 'services.yaml')) @asyncio.coroutine def async_setup_platform(p_type, p_config, disc_info=None): """Setup a tts platform.""" platform = yield from async_prepare_setup_platform( hass, config, DOMAIN, p_type) if platform is None: return try: if hasattr(platform, 'async_get_engine'): provider = yield from platform.async_get_engine( hass, p_config) else: provider = yield from hass.loop.run_in_executor( None, platform.get_engine, hass, p_config) if provider is None: _LOGGER.error('Error setting up platform %s', p_type) return tts.async_register_engine(p_type, provider, p_config) except Exception: # pylint: disable=broad-except _LOGGER.exception('Error setting up platform %s', p_type) return @asyncio.coroutine def async_say_handle(service): """Service handle for say.""" entity_ids = service.data.get(ATTR_ENTITY_ID) message = service.data.get(ATTR_MESSAGE) cache = service.data.get(ATTR_CACHE) language = service.data.get(ATTR_LANGUAGE) options = service.data.get(ATTR_OPTIONS) try: url = yield from tts.async_get_url( p_type, message, cache=cache, language=language, options=options ) except HomeAssistantError as err: _LOGGER.error("Error on init tts: %s", err) return data = { ATTR_MEDIA_CONTENT_ID: url, ATTR_MEDIA_CONTENT_TYPE: MEDIA_TYPE_MUSIC, } if entity_ids: data[ATTR_ENTITY_ID] = entity_ids yield from hass.services.async_call( DOMAIN_MP, SERVICE_PLAY_MEDIA, data, blocking=True) hass.services.async_register( DOMAIN, "{}_{}".format(p_type, SERVICE_SAY), async_say_handle, descriptions.get(SERVICE_SAY), schema=SCHEMA_SERVICE_SAY) setup_tasks = [async_setup_platform(p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN)] if setup_tasks: yield from asyncio.wait(setup_tasks, loop=hass.loop) @asyncio.coroutine def async_clear_cache_handle(service): """Handle clear cache service call.""" yield from tts.async_clear_cache() hass.services.async_register( DOMAIN, SERVICE_CLEAR_CACHE, async_clear_cache_handle, descriptions.get(SERVICE_CLEAR_CACHE), schema=SCHEMA_SERVICE_CLEAR_CACHE) return True class SpeechManager(object): """Representation of a speech store.""" def __init__(self, hass): """Initialize a speech store.""" self.hass = hass self.providers = {} self.use_cache = DEFAULT_CACHE self.cache_dir = DEFAULT_CACHE_DIR self.time_memory = DEFAULT_TIME_MEMORY self.file_cache = {} self.mem_cache = {} @asyncio.coroutine def async_init_cache(self, use_cache, cache_dir, time_memory): """Init config folder and load file cache.""" self.use_cache = use_cache self.time_memory = time_memory def init_tts_cache_dir(cache_dir): """Init cache folder.""" if not os.path.isabs(cache_dir): cache_dir = self.hass.config.path(cache_dir) if not os.path.isdir(cache_dir): _LOGGER.info("Create cache dir %s.", cache_dir) os.mkdir(cache_dir) return cache_dir try: self.cache_dir = yield from self.hass.loop.run_in_executor( None, init_tts_cache_dir, cache_dir) except OSError as err: raise HomeAssistantError( "Can't init cache dir {}".format(err)) def get_cache_files(): """Return a dict of given engine files.""" cache = {} folder_data = os.listdir(self.cache_dir) for file_data in folder_data: record = _RE_VOICE_FILE.match(file_data) if record: key = KEY_PATTERN.format( record.group(1), record.group(2), record.group(3), record.group(4) ) cache[key.lower()] = file_data.lower() return cache try: cache_files = yield from self.hass.loop.run_in_executor( None, get_cache_files) except OSError as err: raise HomeAssistantError( "Can't read cache dir {}".format(err)) if cache_files: self.file_cache.update(cache_files) @asyncio.coroutine def async_clear_cache(self): """Read file cache and delete files.""" self.mem_cache = {} def remove_files(): """Remove files from filesystem.""" for _, filename in self.file_cache.items(): try: os.remove(os.path.join(self.cache_dir, filename)) except OSError as err: _LOGGER.warning( "Can't remove cache file '%s': %s", filename, err) yield from self.hass.loop.run_in_executor(None, remove_files) self.file_cache = {} @callback def async_register_engine(self, engine, provider, config): """Register a TTS provider.""" provider.hass = self.hass if provider.name is None: provider.name = engine self.providers[engine] = provider @asyncio.coroutine def async_get_url(self, engine, message, cache=None, language=None, options=None): """Get URL for play message. This method is a coroutine. """ provider = self.providers[engine] msg_hash = hashlib.sha1(bytes(message, 'utf-8')).hexdigest() use_cache = cache if cache is not None else self.use_cache # languages language = language or provider.default_language if language is None or \ language not in provider.supported_languages: raise HomeAssistantError("Not supported language {0}".format( language)) # options if provider.default_options and options: options = provider.default_options.copy().update(options) options = options or provider.default_options if options is not None: invalid_opts = [opt_name for opt_name in options.keys() if opt_name not in provider.supported_options] if invalid_opts: raise HomeAssistantError( "Invalid options found: %s", invalid_opts) options_key = ctypes.c_size_t(hash(frozenset(options))).value else: options_key = '-' key = KEY_PATTERN.format( msg_hash, language, options_key, engine).lower() # is speech allready in memory if key in self.mem_cache: filename = self.mem_cache[key][MEM_CACHE_FILENAME] # is file store in file cache elif use_cache and key in self.file_cache: filename = self.file_cache[key] self.hass.async_add_job(self.async_file_to_mem(key)) # load speech from provider into memory else: filename = yield from self.async_get_tts_audio( engine, key, message, use_cache, language, options) return "{}/api/tts_proxy/{}".format( self.hass.config.api.base_url, filename) @asyncio.coroutine def async_get_tts_audio(self, engine, key, message, cache, language, options): """Receive TTS and store for view in cache. This method is a coroutine. """ provider = self.providers[engine] extension, data = yield from provider.async_get_tts_audio( message, language, options) if data is None or extension is None: raise HomeAssistantError( "No TTS from {} for '{}'".format(engine, message)) # create file infos filename = ("{}.{}".format(key, extension)).lower() data = self.write_tags( filename, data, provider, message, language, options) # save to memory self._async_store_to_memcache(key, filename, data) if cache: self.hass.async_add_job( self.async_save_tts_audio(key, filename, data)) return filename @asyncio.coroutine def async_save_tts_audio(self, key, filename, data): """Store voice data to file and file_cache. This method is a coroutine. """ voice_file = os.path.join(self.cache_dir, filename) def save_speech(): """Store speech to filesystem.""" with open(voice_file, 'wb') as speech: speech.write(data) try: yield from self.hass.loop.run_in_executor(None, save_speech) self.file_cache[key] = filename except OSError: _LOGGER.error("Can't write %s", filename) @asyncio.coroutine def async_file_to_mem(self, key): """Load voice from file cache into memory. This method is a coroutine. """ filename = self.file_cache.get(key) if not filename: raise HomeAssistantError("Key {} not in file cache!".format(key)) voice_file = os.path.join(self.cache_dir, filename) def load_speech(): """Load a speech from filesystem.""" with open(voice_file, 'rb') as speech: return speech.read() try: data = yield from self.hass.loop.run_in_executor(None, load_speech) except OSError: del self.file_cache[key] raise HomeAssistantError("Can't read {}".format(voice_file)) self._async_store_to_memcache(key, filename, data) @callback def _async_store_to_memcache(self, key, filename, data): """Store data to memcache and set timer to remove it.""" self.mem_cache[key] = { MEM_CACHE_FILENAME: filename, MEM_CACHE_VOICE: data, } @callback def async_remove_from_mem(): """Cleanup memcache.""" self.mem_cache.pop(key) self.hass.loop.call_later(self.time_memory, async_remove_from_mem) @asyncio.coroutine def async_read_tts(self, filename): """Read a voice file and return binary. This method is a coroutine. """ record = _RE_VOICE_FILE.match(filename.lower()) if not record: raise HomeAssistantError("Wrong tts file format!") key = KEY_PATTERN.format( record.group(1), record.group(2), record.group(3), record.group(4)) if key not in self.mem_cache: if key not in self.file_cache: raise HomeAssistantError("%s not in cache!", key) yield from self.async_file_to_mem(key) content, _ = mimetypes.guess_type(filename) return (content, self.mem_cache[key][MEM_CACHE_VOICE]) @staticmethod def write_tags(filename, data, provider, message, language, options): """Write ID3 tags to file. Async friendly. """ import mutagen data_bytes = io.BytesIO(data) data_bytes.name = filename data_bytes.seek(0) album = provider.name artist = language if options is not None: if options.get('voice') is not None: artist = options.get('voice') try: tts_file = mutagen.File(data_bytes, easy=True) if tts_file is not None: tts_file['artist'] = artist tts_file['album'] = album tts_file['title'] = message tts_file.save(data_bytes) except mutagen.MutagenError as err: _LOGGER.error("ID3 tag error: %s", err) return data_bytes.getvalue() class Provider(object): """Represent a single provider.""" hass = None name = None @property def default_language(self): """Default language.""" return None @property def supported_languages(self): """List of supported languages.""" return None @property def supported_options(self): """List of supported options like voice, emotionen.""" return None @property def default_options(self): """Dict include default options.""" return None def get_tts_audio(self, message, language, options=None): """Load tts audio file from provider.""" raise NotImplementedError() def async_get_tts_audio(self, message, language, options=None): """Load tts audio file from provider. Return a tuple of file extension and data as bytes. This method must be run in the event loop and returns a coroutine. """ return self.hass.loop.run_in_executor( None, ft.partial( self.get_tts_audio, message, language, options=options)) class TextToSpeechView(HomeAssistantView): """TTS view to serve an speech audio.""" requires_auth = False url = "/api/tts_proxy/{filename}" name = "api:tts:speech" def __init__(self, tts): """Initialize a tts view.""" self.tts = tts @asyncio.coroutine def get(self, request, filename): """Start a get request.""" try: content, data = yield from self.tts.async_read_tts(filename) except HomeAssistantError as err: _LOGGER.error("Error on load tts: %s", err) return web.Response(status=404) return web.Response(body=data, content_type=content)
apache-2.0
alanljj/connector-telephony
asterisk_click2dial/scripts/set_name_agi.py
8
17048
#! /usr/bin/python # -*- encoding: utf-8 -*- # Copyright (C) 2010-2015 Alexis de Lattre <alexis.delattre@akretion.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/>. """ Name lookup in OpenERP for incoming and outgoing calls with an Asterisk IPBX This script is designed to be used as an AGI on an Asterisk IPBX... BUT I advise you to use a wrapper around this script to control the execution time. Why ? Because if the script takes too much time to execute or get stucks (in the XML-RPC request for example), then the incoming phone call will also get stucks and you will miss a call ! The simplest solution I found is to use the "timeout" shell command to call this script, for example : # timeout 2s get_name_agi.py <OPTIONS> See my 2 sample wrappers "set_name_incoming_timeout.sh" and "set_name_outgoing_timeout.sh" It's probably a good idea to create a user in OpenERP dedicated to this task. This user only needs to be part of the group "Phone CallerID", which has read access on the 'res.partner' and other objects with phone numbers and names. Note that this script can be used without OpenERP, with just the geolocalisation feature : for that, don't use option --server ; only use --geoloc This script can be used both on incoming and outgoing calls : 1) INCOMING CALLS When executed from the dialplan on an incoming phone call, it will lookup in OpenERP's partners and other objects with phone numbers (leads, employees, etc...), and, if it finds the phone number, it will get the corresponding name of the person and use this name as CallerID name for the incoming call. Requires the "base_phone" module available from https://code.launchpad.net/openerp-asterisk-connector for OpenERP version >= 7.0 Asterisk dialplan example : [from-extern] exten = _0141981242,1,AGI(/usr/local/bin/set_name_incoming_timeout.sh) same = n,Dial(SIP/10, 30) same = n,Answer same = n,Voicemail(10@default,u) same = n,Hangup 2) OUTGOING CALLS When executed from the dialplan on an outgoing call, it will lookup in OpenERP the name corresponding to the phone number that is called by the user and it will update the name of the callee on the screen of the phone of the caller. For that, it uses the CONNECTEDLINE dialplan function of Asterisk See the following page for more info: https://wiki.asterisk.org/wiki/display/AST/Manipulating+Party+ID+Information It is not possible to set the CONNECTEDLINE directly from an AGI script, (at least not with Asterisk 11) so the AGI script sets a variable "connectedlinename" that can then be read from the dialplan and passed as parameter to the CONNECTEDLINE function. Here is the code that I used on the pre-process subroutine "openerp-out-call" of the Outgoing Call of my Xivo server : [openerp-out-call] exten = s,1,AGI(/var/lib/asterisk/agi-bin/set_name_outgoing_timeout.sh) same = n,Set(CONNECTEDLINE(name,i)=${connectedlinename}) same = n,Set(CONNECTEDLINE(name-pres,i)=allowed) same = n,Set(CONNECTEDLINE(num,i)=${XIVO_DSTNUM}) same = n,Set(CONNECTEDLINE(num-pres)=allowed) same = n,Return() Of course, you should adapt this example to the Asterisk server you are using. """ import xmlrpclib import sys from optparse import OptionParser __author__ = "Alexis de Lattre <alexis.delattre@akretion.com>" __date__ = "June 2015" __version__ = "0.6" # Name that will be displayed if there is no match # and no geolocalisation. Set it to False if you don't want # to have a 'not_found_name' when nothing is found not_found_name = "Not in Odoo" # Define command line options options = [ {'names': ('-s', '--server'), 'dest': 'server', 'type': 'string', 'action': 'store', 'default': False, 'help': 'DNS or IP address of the OpenERP server. Default = none ' '(will not try to connect to OpenERP)'}, {'names': ('-p', '--port'), 'dest': 'port', 'type': 'int', 'action': 'store', 'default': 8069, 'help': "Port of OpenERP's XML-RPC interface. Default = 8069"}, {'names': ('-e', '--ssl'), 'dest': 'ssl', 'help': "Use SSL connections instead of clear connections. " "Default = no, use clear XML-RPC or JSON-RPC", 'action': 'store_true', 'default': False}, {'names': ('-j', '--jsonrpc'), 'dest': 'jsonrpc', 'help': "Use JSON-RPC instead of the default protocol XML-RPC. " "Default = no, use XML-RPC", 'action': 'store_true', 'default': False}, {'names': ('-d', '--database'), 'dest': 'database', 'type': 'string', 'action': 'store', 'default': 'openerp', 'help': "OpenERP database name. Default = 'openerp'"}, {'names': ('-u', '--user-id'), 'dest': 'userid', 'type': 'int', 'action': 'store', 'default': 2, 'help': "OpenERP user ID to use when connecting to OpenERP in " "XML-RPC. Default = 2"}, {'names': ('-t', '--username'), 'dest': 'username', 'type': 'string', 'action': 'store', 'default': 'demo', 'help': "OpenERP username to use when connecting to OpenERP in " "JSON-RPC. Default = demo"}, {'names': ('-w', '--password'), 'dest': 'password', 'type': 'string', 'action': 'store', 'default': 'demo', 'help': "Password of the OpenERP user. Default = 'demo'"}, {'names': ('-a', '--ascii'), 'dest': 'ascii', 'action': 'store_true', 'default': False, 'help': "Convert name from UTF-8 to ASCII. Default = no, keep UTF-8"}, {'names': ('-n', '--notify'), 'dest': 'notify', 'action': 'store_true', 'default': False, 'help': "Notify OpenERP users via a pop-up (requires the OpenERP " "module 'base_phone_popup'). If you use this option, you must pass " "the logins of the OpenERP users to notify as argument to the " "script. Default = no"}, {'names': ('-g', '--geoloc'), 'dest': 'geoloc', 'action': 'store_true', 'default': False, 'help': "Try to geolocate phone numbers unknown to OpenERP. This " "features requires the 'phonenumbers' Python lib. To install it, " "run 'sudo pip install phonenumbers' Default = no"}, {'names': ('-l', '--geoloc-lang'), 'dest': 'lang', 'type': 'string', 'action': 'store', 'default': "en", 'help': "Language in which the name of the country and city name " "will be displayed by the geolocalisation database. Use the 2 " "letters ISO code of the language. Default = 'en'"}, {'names': ('-c', '--geoloc-country'), 'dest': 'country', 'type': 'string', 'action': 'store', 'default': "FR", 'help': "2 letters ISO code for your country e.g. 'FR' for France. " "This will be used by the geolocalisation system to parse the phone " "number of the calling party. Default = 'FR'"}, {'names': ('-o', '--outgoing'), 'dest': 'outgoing', 'action': 'store_true', 'default': False, 'help': "Update the Connected Line ID name on outgoing calls via a " "call to the Asterisk function CONNECTEDLINE(), instead of updating " "the Caller ID name on incoming calls. Default = no."}, {'names': ('-i', '--outgoing-agi-variable'), 'dest': 'outgoing_agi_var', 'type': 'string', 'action': 'store', 'default': "extension", 'help': "Enter the name of the AGI variable (without the 'agi_' " "prefix) from which the script will get the phone number dialed by " "the user on outgoing calls. For example, with Xivo, you should " "specify 'dnid' as the AGI variable. Default = 'extension'"}, {'names': ('-m', '--max-size'), 'dest': 'max_size', 'type': 'int', 'action': 'store', 'default': 40, 'help': "If the name has more characters this maximum size, cut it " "to this maximum size. Default = 40"}, ] def stdout_write(string): '''Wrapper on sys.stdout.write''' sys.stdout.write(string.encode(sys.stdout.encoding or 'utf-8', 'replace')) sys.stdout.flush() # When we output a command, we get an answer "200 result=1" on stdin # Purge stdin to avoid these Asterisk error messages : # utils.c ast_carefulwrite: write() returned error: Broken pipe sys.stdin.readline() return True def stderr_write(string): '''Wrapper on sys.stderr.write''' sys.stderr.write(string.encode(sys.stdout.encoding or 'utf-8', 'replace')) sys.stdout.flush() return True def geolocate_phone_number(number, my_country_code, lang): import phonenumbers import phonenumbers.geocoder res = '' phonenum = phonenumbers.parse(number, my_country_code.upper()) city = phonenumbers.geocoder.description_for_number(phonenum, lang.lower()) country_code = phonenumbers.region_code_for_number(phonenum) # We don't display the country name when it's my own country if country_code == my_country_code.upper(): if city: res = city else: # Convert country code to country name country = phonenumbers.geocoder._region_display_name( country_code, lang.lower()) if country and city: res = country + ' ' + city elif country and not city: res = country return res def convert_to_ascii(my_unicode): '''Convert to ascii, with clever management of accents (é -> e, è -> e)''' import unicodedata if isinstance(my_unicode, unicode): my_unicode_with_ascii_chars_only = ''.join(( char for char in unicodedata.normalize('NFD', my_unicode) if unicodedata.category(char) != 'Mn')) return str(my_unicode_with_ascii_chars_only) # If the argument is already of string type, return it with the same value elif isinstance(my_unicode, str): return my_unicode else: return False def main(options, arguments): # print 'options = %s' % options # print 'arguments = %s' % arguments # AGI passes parameters to the script on standard input stdinput = {} while 1: input_line = sys.stdin.readline() if not input_line: break line = input_line.strip() try: variable, value = line.split(':') except: break if variable[:4] != 'agi_': # All AGI parameters start with 'agi_' stderr_write("bad stdin variable : %s\n" % variable) continue variable = variable.strip() value = value.strip() if variable and value: stdinput[variable] = value stderr_write("full AGI environnement :\n") for variable in stdinput.keys(): stderr_write("%s = %s\n" % (variable, stdinput.get(variable))) if options.outgoing: phone_number = stdinput.get('agi_%s' % options.outgoing_agi_var) stdout_write('VERBOSE "Dialed phone number is %s"\n' % phone_number) else: # If we already have a "True" caller ID name # i.e. not just digits, but a real name, then we don't try to # connect to OpenERP or geoloc, we just keep it if ( stdinput.get('agi_calleridname') and not stdinput.get('agi_calleridname').isdigit() and stdinput.get('agi_calleridname').lower() not in ['asterisk', 'unknown', 'anonymous'] and not options.notify): stdout_write( 'VERBOSE "Incoming CallerID name is %s"\n' % stdinput.get('agi_calleridname')) stdout_write( 'VERBOSE "As it is a real name, we do not change it"\n') return True phone_number = stdinput.get('agi_callerid') stderr_write('stdout encoding = %s\n' % sys.stdout.encoding or 'utf-8') if not isinstance(phone_number, str): stdout_write('VERBOSE "Phone number is empty"\n') exit(0) # Match for particular cases and anonymous phone calls # To test anonymous call in France, dial 3651 + number if not phone_number.isdigit(): stdout_write( 'VERBOSE "Phone number (%s) is not a digit"\n' % phone_number) exit(0) stdout_write('VERBOSE "Phone number = %s"\n' % phone_number) if options.notify and not arguments: stdout_write( 'VERBOSE "When using the notify option, you must give arguments ' 'to the script"\n') exit(0) if options.notify: method = 'incall_notify_by_login' else: method = 'get_name_from_phone_number' res = False # Yes, this script can be used without "-s openerp_server" ! if options.server and options.jsonrpc: import odoorpc proto = options.ssl and 'jsonrpc+ssl' or 'jsonrpc' stdout_write( 'VERBOSE "Starting %s request on OpenERP %s:%d database ' '%s username %s"\n' % ( proto.upper(), options.server, options.port, options.database, options.username)) try: odoo = odoorpc.ODOO(options.server, proto, options.port) odoo.login(options.database, options.username, options.password) if options.notify: res = odoo.execute( 'phone.common', method, phone_number, arguments) else: res = odoo.execute('phone.common', method, phone_number) stdout_write('VERBOSE "Called method %s"\n' % method) except: stdout_write( 'VERBOSE "Could not connect to OpenERP in JSON-RPC"\n') elif options.server: proto = options.ssl and 'https' or 'http' stdout_write( 'VERBOSE "Starting %s XML-RPC request on OpenERP %s:%d ' 'database %s user ID %d"\n' % ( proto, options.server, options.port, options.database, options.userid)) sock = xmlrpclib.ServerProxy( '%s://%s:%d/xmlrpc/object' % (proto, options.server, options.port)) try: if options.notify: res = sock.execute( options.database, options.userid, options.password, 'phone.common', method, phone_number, arguments) else: res = sock.execute( options.database, options.userid, options.password, 'phone.common', method, phone_number) stdout_write('VERBOSE "Called method %s"\n' % method) except: stdout_write('VERBOSE "Could not connect to OpenERP in XML-RPC"\n') # To simulate a long execution of the XML-RPC request # import time # time.sleep(5) # Function to limit the size of the name if res: if len(res) > options.max_size: res = res[0:options.max_size] elif options.geoloc: # if the number is not found in OpenERP, we try to geolocate stdout_write( 'VERBOSE "Trying to geolocate with country %s and lang %s"\n' % (options.country, options.lang)) res = geolocate_phone_number( phone_number, options.country, options.lang) else: # if the number is not found in OpenERP and geoloc is off, # we put 'not_found_name' as Name stdout_write('VERBOSE "Phone number not found in OpenERP"\n') res = not_found_name # All SIP phones should support UTF-8... # but in case you have analog phones over TDM # or buggy phones, you should use the command line option --ascii if options.ascii: res = convert_to_ascii(res) stdout_write('VERBOSE "Name = %s"\n' % res) if res: if options.outgoing: stdout_write('SET VARIABLE connectedlinename "%s"\n' % res) else: stdout_write('SET CALLERID "%s"<%s>\n' % (res, phone_number)) return True if __name__ == '__main__': usage = "Usage: get_name_agi.py [options] login1 login2 login3 ..." epilog = "Script written by Alexis de Lattre. " "Published under the GNU AGPL licence." description = "This is an AGI script that sends a query to OpenERP. " "It can also be used without OpenERP as to geolocate phone numbers " "of incoming calls." parser = OptionParser(usage=usage, epilog=epilog, description=description) for option in options: param = option['names'] del option['names'] parser.add_option(*param, **option) options, arguments = parser.parse_args() sys.argv[:] = arguments main(options, arguments)
agpl-3.0
leeseuljeong/leeseulstack_neutron
neutron/plugins/openvswitch/common/constants.py
11
2390
# Copyright (c) 2012 OpenStack Foundation. # # 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 neutron.plugins.common import constants as p_const # Special vlan_id value in ovs_vlan_allocations table indicating flat network FLAT_VLAN_ID = -1 # Topic for tunnel notifications between the plugin and agent TUNNEL = 'tunnel' # Name prefixes for veth device or patch port pair linking the integration # bridge with the physical bridge for a physical network PEER_INTEGRATION_PREFIX = 'int-' PEER_PHYSICAL_PREFIX = 'phy-' # Nonexistent peer used to create patch ports without associating them, it # allows to define flows before association NONEXISTENT_PEER = 'nonexistent-peer' # The different types of tunnels TUNNEL_NETWORK_TYPES = [p_const.TYPE_GRE, p_const.TYPE_VXLAN] # Various tables for DVR use of integration bridge flows LOCAL_SWITCHING = 0 DVR_TO_SRC_MAC = 1 # Various tables for tunneling flows DVR_PROCESS = 1 PATCH_LV_TO_TUN = 2 GRE_TUN_TO_LV = 3 VXLAN_TUN_TO_LV = 4 DVR_NOT_LEARN = 9 LEARN_FROM_TUN = 10 UCAST_TO_TUN = 20 ARP_RESPONDER = 21 FLOOD_TO_TUN = 22 # Tables for integration bridge # Table 0 is used for forwarding. CANARY_TABLE = 23 # Map tunnel types to tables number TUN_TABLE = {p_const.TYPE_GRE: GRE_TUN_TO_LV, p_const.TYPE_VXLAN: VXLAN_TUN_TO_LV} # The default respawn interval for the ovsdb monitor DEFAULT_OVSDBMON_RESPAWN = 30 # Represent invalid OF Port OFPORT_INVALID = -1 ARP_RESPONDER_ACTIONS = ('move:NXM_OF_ETH_SRC[]->NXM_OF_ETH_DST[],' 'mod_dl_src:%(mac)s,' 'load:0x2->NXM_OF_ARP_OP[],' 'move:NXM_NX_ARP_SHA[]->NXM_NX_ARP_THA[],' 'move:NXM_OF_ARP_SPA[]->NXM_OF_ARP_TPA[],' 'load:%(mac)#x->NXM_NX_ARP_SHA[],' 'load:%(ip)#x->NXM_OF_ARP_SPA[],' 'in_port')
apache-2.0
RHavar/bitcoin
test/functional/p2p_leak.py
14
5283
#!/usr/bin/env python3 # Copyright (c) 2017-2018 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 message sending before handshake completion. A node should never send anything other than VERSION/VERACK/REJECT until it's received a VERACK. This test connects to a node and sends it a few messages, trying to entice it into sending us something it shouldn't.""" import time from test_framework.messages import msg_getaddr, msg_ping, msg_verack from test_framework.mininode import mininode_lock, P2PInterface from test_framework.test_framework import BitcoinTestFramework from test_framework.util import wait_until banscore = 10 class CLazyNode(P2PInterface): def __init__(self): super().__init__() self.unexpected_msg = False self.ever_connected = False def bad_message(self, message): self.unexpected_msg = True self.log.info("should not have received message: %s" % message.command) def on_open(self): self.ever_connected = True def on_version(self, message): self.bad_message(message) def on_verack(self, message): self.bad_message(message) def on_reject(self, message): self.bad_message(message) def on_inv(self, message): self.bad_message(message) def on_addr(self, message): self.bad_message(message) def on_getdata(self, message): self.bad_message(message) def on_getblocks(self, message): self.bad_message(message) def on_tx(self, message): self.bad_message(message) def on_block(self, message): self.bad_message(message) def on_getaddr(self, message): self.bad_message(message) def on_headers(self, message): self.bad_message(message) def on_getheaders(self, message): self.bad_message(message) def on_ping(self, message): self.bad_message(message) def on_mempool(self, message): self.bad_message(message) def on_pong(self, message): self.bad_message(message) def on_feefilter(self, message): self.bad_message(message) def on_sendheaders(self, message): self.bad_message(message) def on_sendcmpct(self, message): self.bad_message(message) def on_cmpctblock(self, message): self.bad_message(message) def on_getblocktxn(self, message): self.bad_message(message) def on_blocktxn(self, message): self.bad_message(message) # Node that never sends a version. We'll use this to send a bunch of messages # anyway, and eventually get disconnected. class CNodeNoVersionBan(CLazyNode): # send a bunch of veracks without sending a message. This should get us disconnected. # NOTE: implementation-specific check here. Remove if bitcoind ban behavior changes def on_open(self): super().on_open() for i in range(banscore): self.send_message(msg_verack()) def on_reject(self, message): pass # Node that never sends a version. This one just sits idle and hopes to receive # any message (it shouldn't!) class CNodeNoVersionIdle(CLazyNode): def __init__(self): super().__init__() # Node that sends a version but not a verack. class CNodeNoVerackIdle(CLazyNode): def __init__(self): self.version_received = False super().__init__() def on_reject(self, message): pass def on_verack(self, message): pass # When version is received, don't reply with a verack. Instead, see if the # node will give us a message that it shouldn't. This is not an exhaustive # list! def on_version(self, message): self.version_received = True self.send_message(msg_ping()) self.send_message(msg_getaddr()) class P2PLeakTest(BitcoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.extra_args = [['-banscore=' + str(banscore)]] def run_test(self): no_version_bannode = self.nodes[0].add_p2p_connection(CNodeNoVersionBan(), send_version=False, wait_for_verack=False) no_version_idlenode = self.nodes[0].add_p2p_connection(CNodeNoVersionIdle(), send_version=False, wait_for_verack=False) no_verack_idlenode = self.nodes[0].add_p2p_connection(CNodeNoVerackIdle()) wait_until(lambda: no_version_bannode.ever_connected, timeout=10, lock=mininode_lock) wait_until(lambda: no_version_idlenode.ever_connected, timeout=10, lock=mininode_lock) wait_until(lambda: no_verack_idlenode.version_received, timeout=10, lock=mininode_lock) # Mine a block and make sure that it's not sent to the connected nodes self.nodes[0].generatetoaddress(1, self.nodes[0].get_deterministic_priv_key().address) #Give the node enough time to possibly leak out a message time.sleep(5) #This node should have been banned assert not no_version_bannode.is_connected self.nodes[0].disconnect_p2ps() # Wait until all connections are closed wait_until(lambda: len(self.nodes[0].getpeerinfo()) == 0) # Make sure no unexpected messages came in assert(no_version_bannode.unexpected_msg == False) assert(no_version_idlenode.unexpected_msg == False) assert(no_verack_idlenode.unexpected_msg == False) if __name__ == '__main__': P2PLeakTest().main()
mit
nzavagli/UnrealPy
UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/Python-2.7.10/Demo/tkinter/matt/menu-simple.py
12
3251
from Tkinter import * # some vocabulary to keep from getting confused. This terminology # is something I cooked up for this file, but follows the man pages # pretty closely # # # # This is a MENUBUTTON # V # +-------------+ # | | # # +------------++------------++------------+ # | || || | # | File || Edit || Options | <-------- the MENUBAR # | || || | # +------------++------------++------------+ # | New... | # | Open... | # | Print | # | | <------ This is a MENU. The lines of text in the menu are # | | MENU ENTRIES # | +---------------+ # | Open Files > | file1 | # | | file2 | # | | another file | <------ this cascading part is also a MENU # +----------------| | # | | # | | # | | # +---------------+ def new_file(): print "opening new file" def open_file(): print "opening OLD file" def makeFileMenu(): # make menu button : "File" File_button = Menubutton(mBar, text='File', underline=0) File_button.pack(side=LEFT, padx="1m") File_button.menu = Menu(File_button) # add an item. The first param is a menu entry type, # must be one of: "cascade", "checkbutton", "command", "radiobutton", "separator" # see menu-demo-2.py for examples of use File_button.menu.add_command(label='New...', underline=0, command=new_file) File_button.menu.add_command(label='Open...', underline=0, command=open_file) File_button.menu.add_command(label='Quit', underline=0, command='exit') # set up a pointer from the file menubutton back to the file menu File_button['menu'] = File_button.menu return File_button def makeEditMenu(): Edit_button = Menubutton(mBar, text='Edit', underline=0) Edit_button.pack(side=LEFT, padx="1m") Edit_button.menu = Menu(Edit_button) # just to be cute, let's disable the undo option: Edit_button.menu.add('command', label="Undo") # Since the tear-off bar is the 0th entry, # undo is the 1st entry... Edit_button.menu.entryconfig(1, state=DISABLED) # and these are just for show. No "command" callbacks attached. Edit_button.menu.add_command(label="Cut") Edit_button.menu.add_command(label="Copy") Edit_button.menu.add_command(label="Paste") # set up a pointer from the file menubutton back to the file menu Edit_button['menu'] = Edit_button.menu return Edit_button ################################################# #### Main starts here ... root = Tk() # make a menu bar mBar = Frame(root, relief=RAISED, borderwidth=2) mBar.pack(fill=X) File_button = makeFileMenu() Edit_button = makeEditMenu() # finally, install the buttons in the menu bar. # This allows for scanning from one menubutton to the next. mBar.tk_menuBar(File_button, Edit_button) root.title('menu demo') root.iconname('packer') root.mainloop()
mit
vikatory/kbengine
kbe/src/lib/python/Lib/test/test_abc.py
80
13652
# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Unit tests for abc.py.""" import unittest from test import support import abc from inspect import isabstract class TestLegacyAPI(unittest.TestCase): def test_abstractproperty_basics(self): @abc.abstractproperty def foo(self): pass self.assertTrue(foo.__isabstractmethod__) def bar(self): pass self.assertFalse(hasattr(bar, "__isabstractmethod__")) class C(metaclass=abc.ABCMeta): @abc.abstractproperty def foo(self): return 3 self.assertRaises(TypeError, C) class D(C): @property def foo(self): return super().foo self.assertEqual(D().foo, 3) self.assertFalse(getattr(D.foo, "__isabstractmethod__", False)) def test_abstractclassmethod_basics(self): @abc.abstractclassmethod def foo(cls): pass self.assertTrue(foo.__isabstractmethod__) @classmethod def bar(cls): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc.ABCMeta): @abc.abstractclassmethod def foo(cls): return cls.__name__ self.assertRaises(TypeError, C) class D(C): @classmethod def foo(cls): return super().foo() self.assertEqual(D.foo(), 'D') self.assertEqual(D().foo(), 'D') def test_abstractstaticmethod_basics(self): @abc.abstractstaticmethod def foo(): pass self.assertTrue(foo.__isabstractmethod__) @staticmethod def bar(): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc.ABCMeta): @abc.abstractstaticmethod def foo(): return 3 self.assertRaises(TypeError, C) class D(C): @staticmethod def foo(): return 4 self.assertEqual(D.foo(), 4) self.assertEqual(D().foo(), 4) class TestABC(unittest.TestCase): def test_ABC_helper(self): # create an ABC using the helper class and perform basic checks class C(abc.ABC): @classmethod @abc.abstractmethod def foo(cls): return cls.__name__ self.assertEqual(type(C), abc.ABCMeta) self.assertRaises(TypeError, C) class D(C): @classmethod def foo(cls): return super().foo() self.assertEqual(D.foo(), 'D') def test_abstractmethod_basics(self): @abc.abstractmethod def foo(self): pass self.assertTrue(foo.__isabstractmethod__) def bar(self): pass self.assertFalse(hasattr(bar, "__isabstractmethod__")) def test_abstractproperty_basics(self): @property @abc.abstractmethod def foo(self): pass self.assertTrue(foo.__isabstractmethod__) def bar(self): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc.ABCMeta): @property @abc.abstractmethod def foo(self): return 3 self.assertRaises(TypeError, C) class D(C): @C.foo.getter def foo(self): return super().foo self.assertEqual(D().foo, 3) def test_abstractclassmethod_basics(self): @classmethod @abc.abstractmethod def foo(cls): pass self.assertTrue(foo.__isabstractmethod__) @classmethod def bar(cls): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc.ABCMeta): @classmethod @abc.abstractmethod def foo(cls): return cls.__name__ self.assertRaises(TypeError, C) class D(C): @classmethod def foo(cls): return super().foo() self.assertEqual(D.foo(), 'D') self.assertEqual(D().foo(), 'D') def test_abstractstaticmethod_basics(self): @staticmethod @abc.abstractmethod def foo(): pass self.assertTrue(foo.__isabstractmethod__) @staticmethod def bar(): pass self.assertFalse(getattr(bar, "__isabstractmethod__", False)) class C(metaclass=abc.ABCMeta): @staticmethod @abc.abstractmethod def foo(): return 3 self.assertRaises(TypeError, C) class D(C): @staticmethod def foo(): return 4 self.assertEqual(D.foo(), 4) self.assertEqual(D().foo(), 4) def test_abstractmethod_integration(self): for abstractthing in [abc.abstractmethod, abc.abstractproperty, abc.abstractclassmethod, abc.abstractstaticmethod]: class C(metaclass=abc.ABCMeta): @abstractthing def foo(self): pass # abstract def bar(self): pass # concrete self.assertEqual(C.__abstractmethods__, {"foo"}) self.assertRaises(TypeError, C) # because foo is abstract self.assertTrue(isabstract(C)) class D(C): def bar(self): pass # concrete override of concrete self.assertEqual(D.__abstractmethods__, {"foo"}) self.assertRaises(TypeError, D) # because foo is still abstract self.assertTrue(isabstract(D)) class E(D): def foo(self): pass self.assertEqual(E.__abstractmethods__, set()) E() # now foo is concrete, too self.assertFalse(isabstract(E)) class F(E): @abstractthing def bar(self): pass # abstract override of concrete self.assertEqual(F.__abstractmethods__, {"bar"}) self.assertRaises(TypeError, F) # because bar is abstract now self.assertTrue(isabstract(F)) def test_descriptors_with_abstractmethod(self): class C(metaclass=abc.ABCMeta): @property @abc.abstractmethod def foo(self): return 3 @foo.setter @abc.abstractmethod def foo(self, val): pass self.assertRaises(TypeError, C) class D(C): @C.foo.getter def foo(self): return super().foo self.assertRaises(TypeError, D) class E(D): @D.foo.setter def foo(self, val): pass self.assertEqual(E().foo, 3) # check that the property's __isabstractmethod__ descriptor does the # right thing when presented with a value that fails truth testing: class NotBool(object): def __nonzero__(self): raise ValueError() __len__ = __nonzero__ with self.assertRaises(ValueError): class F(C): def bar(self): pass bar.__isabstractmethod__ = NotBool() foo = property(bar) def test_customdescriptors_with_abstractmethod(self): class Descriptor: def __init__(self, fget, fset=None): self._fget = fget self._fset = fset def getter(self, callable): return Descriptor(callable, self._fget) def setter(self, callable): return Descriptor(self._fget, callable) @property def __isabstractmethod__(self): return (getattr(self._fget, '__isabstractmethod__', False) or getattr(self._fset, '__isabstractmethod__', False)) class C(metaclass=abc.ABCMeta): @Descriptor @abc.abstractmethod def foo(self): return 3 @foo.setter @abc.abstractmethod def foo(self, val): pass self.assertRaises(TypeError, C) class D(C): @C.foo.getter def foo(self): return super().foo self.assertRaises(TypeError, D) class E(D): @D.foo.setter def foo(self, val): pass self.assertFalse(E.foo.__isabstractmethod__) def test_metaclass_abc(self): # Metaclasses can be ABCs, too. class A(metaclass=abc.ABCMeta): @abc.abstractmethod def x(self): pass self.assertEqual(A.__abstractmethods__, {"x"}) class meta(type, A): def x(self): return 1 class C(metaclass=meta): pass def test_registration_basics(self): class A(metaclass=abc.ABCMeta): pass class B(object): pass b = B() self.assertFalse(issubclass(B, A)) self.assertFalse(issubclass(B, (A,))) self.assertNotIsInstance(b, A) self.assertNotIsInstance(b, (A,)) B1 = A.register(B) self.assertTrue(issubclass(B, A)) self.assertTrue(issubclass(B, (A,))) self.assertIsInstance(b, A) self.assertIsInstance(b, (A,)) self.assertIs(B1, B) class C(B): pass c = C() self.assertTrue(issubclass(C, A)) self.assertTrue(issubclass(C, (A,))) self.assertIsInstance(c, A) self.assertIsInstance(c, (A,)) def test_register_as_class_deco(self): class A(metaclass=abc.ABCMeta): pass @A.register class B(object): pass b = B() self.assertTrue(issubclass(B, A)) self.assertTrue(issubclass(B, (A,))) self.assertIsInstance(b, A) self.assertIsInstance(b, (A,)) @A.register class C(B): pass c = C() self.assertTrue(issubclass(C, A)) self.assertTrue(issubclass(C, (A,))) self.assertIsInstance(c, A) self.assertIsInstance(c, (A,)) self.assertIs(C, A.register(C)) def test_isinstance_invalidation(self): class A(metaclass=abc.ABCMeta): pass class B: pass b = B() self.assertFalse(isinstance(b, A)) self.assertFalse(isinstance(b, (A,))) token_old = abc.get_cache_token() A.register(B) token_new = abc.get_cache_token() self.assertNotEqual(token_old, token_new) self.assertTrue(isinstance(b, A)) self.assertTrue(isinstance(b, (A,))) def test_registration_builtins(self): class A(metaclass=abc.ABCMeta): pass A.register(int) self.assertIsInstance(42, A) self.assertIsInstance(42, (A,)) self.assertTrue(issubclass(int, A)) self.assertTrue(issubclass(int, (A,))) class B(A): pass B.register(str) class C(str): pass self.assertIsInstance("", A) self.assertIsInstance("", (A,)) self.assertTrue(issubclass(str, A)) self.assertTrue(issubclass(str, (A,))) self.assertTrue(issubclass(C, A)) self.assertTrue(issubclass(C, (A,))) def test_registration_edge_cases(self): class A(metaclass=abc.ABCMeta): pass A.register(A) # should pass silently class A1(A): pass self.assertRaises(RuntimeError, A1.register, A) # cycles not allowed class B(object): pass A1.register(B) # ok A1.register(B) # should pass silently class C(A): pass A.register(C) # should pass silently self.assertRaises(RuntimeError, C.register, A) # cycles not allowed C.register(B) # ok def test_register_non_class(self): class A(metaclass=abc.ABCMeta): pass self.assertRaisesRegex(TypeError, "Can only register classes", A.register, 4) def test_registration_transitiveness(self): class A(metaclass=abc.ABCMeta): pass self.assertTrue(issubclass(A, A)) self.assertTrue(issubclass(A, (A,))) class B(metaclass=abc.ABCMeta): pass self.assertFalse(issubclass(A, B)) self.assertFalse(issubclass(A, (B,))) self.assertFalse(issubclass(B, A)) self.assertFalse(issubclass(B, (A,))) class C(metaclass=abc.ABCMeta): pass A.register(B) class B1(B): pass self.assertTrue(issubclass(B1, A)) self.assertTrue(issubclass(B1, (A,))) class C1(C): pass B1.register(C1) self.assertFalse(issubclass(C, B)) self.assertFalse(issubclass(C, (B,))) self.assertFalse(issubclass(C, B1)) self.assertFalse(issubclass(C, (B1,))) self.assertTrue(issubclass(C1, A)) self.assertTrue(issubclass(C1, (A,))) self.assertTrue(issubclass(C1, B)) self.assertTrue(issubclass(C1, (B,))) self.assertTrue(issubclass(C1, B1)) self.assertTrue(issubclass(C1, (B1,))) C1.register(int) class MyInt(int): pass self.assertTrue(issubclass(MyInt, A)) self.assertTrue(issubclass(MyInt, (A,))) self.assertIsInstance(42, A) self.assertIsInstance(42, (A,)) def test_all_new_methods_are_called(self): class A(metaclass=abc.ABCMeta): pass class B(object): counter = 0 def __new__(cls): B.counter += 1 return super().__new__(cls) class C(A, B): pass self.assertEqual(B.counter, 0) C() self.assertEqual(B.counter, 1) if __name__ == "__main__": unittest.main()
lgpl-3.0
EricSB/nupic
tests/integration/nupic/algorithms/monitor_mixin/temporal_memory_monitor_mixin_test.py
5
7606
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2014, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # 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 Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import unittest from nupic.data.generators.pattern_machine import ConsecutivePatternMachine from nupic.data.generators.sequence_machine import SequenceMachine from nupic.research.temporal_memory import TemporalMemory from nupic.research.monitor_mixin.temporal_memory_monitor_mixin import ( TemporalMemoryMonitorMixin) class MonitoredTemporalMemory(TemporalMemoryMonitorMixin, TemporalMemory): pass class TemporalMemoryMonitorMixinTest(unittest.TestCase): def setUp(self): self.patternMachine = ConsecutivePatternMachine(100, 5) self.sequenceMachine = SequenceMachine(self.patternMachine) self.tm = MonitoredTemporalMemory(columnDimensions=[100], cellsPerColumn=4, initialPermanence=0.6, connectedPermanence=0.5, minThreshold=1, maxNewSynapseCount=6, permanenceIncrement=0.1, permanenceDecrement=0.05, activationThreshold=1) def testFeedSequence(self): sequence = self._generateSequence() sequenceLength = len(sequence) - 3 # without resets # Replace last pattern (before the None) with an unpredicted one sequence[-2] = self.patternMachine.get(4) self._feedSequence(sequence, sequenceLabel="Test") activeColumnsTrace = self.tm.mmGetTraceActiveColumns() predictiveCellsTrace = self.tm.mmGetTracePredictiveCells() sequenceLabelsTrace = self.tm.mmGetTraceSequenceLabels() resetsTrace = self.tm.mmGetTraceResets() predictedActiveCellsTrace = self.tm.mmGetTracePredictedActiveCells() predictedInactiveCellsTrace = self.tm.mmGetTracePredictedInactiveCells() predictedActiveColumnsTrace = self.tm.mmGetTracePredictedActiveColumns() predictedInactiveColumnsTrace = self.tm.mmGetTracePredictedInactiveColumns() unpredictedActiveColumnsTrace = self.tm.mmGetTraceUnpredictedActiveColumns() self.assertEqual(len(activeColumnsTrace.data), sequenceLength) self.assertEqual(len(predictiveCellsTrace.data), sequenceLength) self.assertEqual(len(sequenceLabelsTrace.data), sequenceLength) self.assertEqual(len(resetsTrace.data), sequenceLength) self.assertEqual(len(predictedActiveCellsTrace.data), sequenceLength) self.assertEqual(len(predictedInactiveCellsTrace.data), sequenceLength) self.assertEqual(len(predictedActiveColumnsTrace.data), sequenceLength) self.assertEqual(len(predictedInactiveColumnsTrace.data), sequenceLength) self.assertEqual(len(unpredictedActiveColumnsTrace.data), sequenceLength) self.assertEqual(activeColumnsTrace.data[-1], self.patternMachine.get(4)) self.assertEqual(sequenceLabelsTrace.data[-1], "Test") self.assertEqual(resetsTrace.data[0], True) self.assertEqual(resetsTrace.data[1], False) self.assertEqual(resetsTrace.data[10], True) self.assertEqual(resetsTrace.data[-1], False) self.assertEqual(len(predictedActiveCellsTrace.data[-2]), 5) self.assertEqual(len(predictedActiveCellsTrace.data[-1]), 0) self.assertEqual(len(predictedInactiveCellsTrace.data[-2]), 0) self.assertEqual(len(predictedInactiveCellsTrace.data[-1]), 5) self.assertEqual(len(predictedActiveColumnsTrace.data[-2]), 5) self.assertEqual(len(predictedActiveColumnsTrace.data[-1]), 0) self.assertEqual(len(predictedInactiveColumnsTrace.data[-2]), 0) self.assertEqual(len(predictedInactiveColumnsTrace.data[-1]), 5) self.assertEqual(len(unpredictedActiveColumnsTrace.data[-2]), 0) self.assertEqual(len(unpredictedActiveColumnsTrace.data[-1]), 5) def testClearHistory(self): sequence = self._generateSequence() self._feedSequence(sequence, sequenceLabel="Test") self.tm.mmClearHistory() activeColumnsTrace = self.tm.mmGetTraceActiveColumns() predictiveCellsTrace = self.tm.mmGetTracePredictiveCells() sequenceLabelsTrace = self.tm.mmGetTraceSequenceLabels() resetsTrace = self.tm.mmGetTraceResets() predictedActiveCellsTrace = self.tm.mmGetTracePredictedActiveCells() predictedInactiveCellsTrace = self.tm.mmGetTracePredictedInactiveCells() predictedActiveColumnsTrace = self.tm.mmGetTracePredictedActiveColumns() predictedInactiveColumnsTrace = self.tm.mmGetTracePredictedInactiveColumns() unpredictedActiveColumnsTrace = self.tm.mmGetTraceUnpredictedActiveColumns() self.assertEqual(len(activeColumnsTrace.data), 0) self.assertEqual(len(predictiveCellsTrace.data), 0) self.assertEqual(len(sequenceLabelsTrace.data), 0) self.assertEqual(len(resetsTrace.data), 0) self.assertEqual(len(predictedActiveCellsTrace.data), 0) self.assertEqual(len(predictedInactiveCellsTrace.data), 0) self.assertEqual(len(predictedActiveColumnsTrace.data), 0) self.assertEqual(len(predictedInactiveColumnsTrace.data), 0) self.assertEqual(len(unpredictedActiveColumnsTrace.data), 0) def testSequencesMetrics(self): sequence = self._generateSequence() self._feedSequence(sequence, "Test1") sequence.reverse() sequence.append(sequence.pop(0)) # Move None (reset) to the end self._feedSequence(sequence, "Test2") sequencesPredictedActiveCellsPerColumnMetric = \ self.tm.mmGetMetricSequencesPredictedActiveCellsPerColumn() sequencesPredictedActiveCellsSharedMetric = \ self.tm.mmGetMetricSequencesPredictedActiveCellsShared() self.assertEqual(sequencesPredictedActiveCellsPerColumnMetric.mean, 1) self.assertEqual(sequencesPredictedActiveCellsSharedMetric.mean, 1) self._feedSequence(sequence, "Test3") sequencesPredictedActiveCellsPerColumnMetric = \ self.tm.mmGetMetricSequencesPredictedActiveCellsPerColumn() sequencesPredictedActiveCellsSharedMetric = \ self.tm.mmGetMetricSequencesPredictedActiveCellsShared() self.assertEqual(sequencesPredictedActiveCellsPerColumnMetric.mean, 1) self.assertTrue(sequencesPredictedActiveCellsSharedMetric.mean > 1) # ============================== # Helper functions # ============================== def _generateSequence(self): numbers = range(0, 10) sequence = self.sequenceMachine.generateFromNumbers(numbers) sequence.append(None) sequence *= 3 return sequence def _feedSequence(self, sequence, sequenceLabel=None): for pattern in sequence: if pattern is None: self.tm.reset() else: self.tm.compute(pattern, sequenceLabel=sequenceLabel) if __name__ == "__main__": unittest.main()
agpl-3.0
ccortezb/troposphere
troposphere/autoscaling.py
16
9610
# Copyright (c) 2012-2013, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSHelperFn, AWSObject, AWSProperty, Ref, FindInMap from .validators import boolean, integer from . import cloudformation EC2_INSTANCE_LAUNCH = "autoscaling:EC2_INSTANCE_LAUNCH" EC2_INSTANCE_LAUNCH_ERROR = "autoscaling:EC2_INSTANCE_LAUNCH_ERROR" EC2_INSTANCE_TERMINATE = "autoscaling:EC2_INSTANCE_TERMINATE" EC2_INSTANCE_TERMINATE_ERROR = "autoscaling:EC2_INSTANCE_TERMINATE_ERROR" TEST_NOTIFICATION = "autoscaling:TEST_NOTIFICATION" # Termination Policy constants Default = 'Default' OldestInstance = 'OldestInstance' NewestInstance = 'NewestInstance' OldestLaunchConfiguration = 'OldestLaunchConfiguration' ClosestToNextInstanceHour = 'ClosestToNextInstanceHour' class Tag(AWSHelperFn): def __init__(self, key, value, propogate): self.data = { 'Key': key, 'Value': value, 'PropagateAtLaunch': propogate, } def JSONrepr(self): return self.data class Tags(AWSHelperFn): defaultPropagateAtLaunch = True manyType = [type([]), type(())] def __init__(self, **kwargs): self.tags = [] for k, v in sorted(kwargs.iteritems()): if type(v) in self.manyType: propagate = str(v[1]).lower() v = v[0] else: propagate = str(self.defaultPropagateAtLaunch).lower() self.tags.append({ 'Key': k, 'Value': v, 'PropagateAtLaunch': propagate, }) def JSONrepr(self): return self.tags class NotificationConfigurations(AWSProperty): props = { 'TopicARN': (basestring, True), 'NotificationTypes': (list, True), } class MetricsCollection(AWSProperty): props = { 'Granularity': (basestring, True), 'Metrics': (list, False), } class Metadata(AWSHelperFn): def __init__(self, init, authentication=None): self.validate(init, authentication) # get keys and values from init and authentication # if there's only one data point, then we know its the default # cfn-init; where the key is 'config' if len(init.data) == 1: initKey, initValue = init.data.popitem() self.data = {initKey: initValue} else: self.data = init.data if authentication: authKey, authValue = authentication.data.popitem() self.data[authKey] = authValue def validate(self, init, authentication): if not isinstance(init, cloudformation.Init): raise ValueError( 'init must be of type cloudformation.Init' ) is_instance = isinstance(authentication, cloudformation.Authentication) if authentication and not is_instance: raise ValueError( 'authentication must be of type cloudformation.Authentication' ) def JSONrepr(self): return self.data class AutoScalingGroup(AWSObject): resource_type = "AWS::AutoScaling::AutoScalingGroup" props = { 'AvailabilityZones': (list, False), 'Cooldown': (integer, False), 'DesiredCapacity': (integer, False), 'HealthCheckGracePeriod': (integer, False), 'HealthCheckType': (basestring, False), 'InstanceId': (basestring, False), 'LaunchConfigurationName': (basestring, False), 'LoadBalancerNames': (list, False), 'MaxSize': (integer, True), 'MetricsCollection': ([MetricsCollection], False), 'MinSize': (integer, True), 'NotificationConfigurations': ([NotificationConfigurations], False), 'PlacementGroup': (basestring, False), 'Tags': (list, False), 'TerminationPolicies': ([basestring], False), 'VPCZoneIdentifier': (list, False), } def validate(self): if 'UpdatePolicy' in self.resource: update_policy = self.resource['UpdatePolicy'] if 'AutoScalingRollingUpdate' in update_policy.properties: rolling_update = update_policy.AutoScalingRollingUpdate isMinNoCheck = isinstance( rolling_update.MinInstancesInService, (FindInMap, Ref) ) isMaxNoCheck = isinstance(self.MaxSize, (FindInMap, Ref)) if not (isMinNoCheck or isMaxNoCheck): maxCount = int(self.MaxSize) minCount = int(rolling_update.MinInstancesInService) if minCount >= maxCount: raise ValueError( "The UpdatePolicy attribute " "MinInstancesInService must be less than the " "autoscaling group's MaxSize") launch_config = self.properties.get('LaunchConfigurationName') instance_id = self.properties.get('InstanceId') if launch_config and instance_id: raise ValueError("LaunchConfigurationName and InstanceId " "are mutually exclusive.") if not launch_config and not instance_id: raise ValueError("Must specify either LaunchConfigurationName or " "InstanceId: http://docs.aws.amazon.com/AWSCloud" "Formation/latest/UserGuide/aws-properties-as-gr" "oup.html#cfn-as-group-instanceid") availability_zones = self.properties.get('AvailabilityZones') vpc_zone_identifier = self.properties.get('VPCZoneIdentifier') if not availability_zones and not vpc_zone_identifier: raise ValueError("Must specify AvailabilityZones and/or " "VPCZoneIdentifier: http://docs.aws.amazon.com/A" "WSCloudFormation/latest/UserGuide/aws-propertie" "s-as-group.html#cfn-as-group-vpczoneidentifier") return True class LaunchConfiguration(AWSObject): resource_type = "AWS::AutoScaling::LaunchConfiguration" props = { 'AssociatePublicIpAddress': (boolean, False), 'BlockDeviceMappings': (list, False), 'ClassicLinkVPCId': (basestring, False), 'ClassicLinkVPCSecurityGroups': ([basestring], False), 'EbsOptimized': (boolean, False), 'IamInstanceProfile': (basestring, False), 'ImageId': (basestring, True), 'InstanceId': (basestring, False), 'InstanceMonitoring': (boolean, False), 'InstanceType': (basestring, True), 'KernelId': (basestring, False), 'KeyName': (basestring, False), 'Metadata': (Metadata, False), 'PlacementTenancy': (basestring, False), 'RamDiskId': (basestring, False), 'SecurityGroups': (list, False), 'SpotPrice': (basestring, False), 'UserData': (basestring, False), } class ScalingPolicy(AWSObject): resource_type = "AWS::AutoScaling::ScalingPolicy" props = { 'AdjustmentType': (basestring, True), 'AutoScalingGroupName': (basestring, True), 'Cooldown': (integer, False), 'MinAdjustmentStep': (integer, False), 'ScalingAdjustment': (basestring, True), } class ScheduledAction(AWSObject): resource_type = "AWS::AutoScaling::ScheduledAction" props = { 'AutoScalingGroupName': (basestring, True), 'DesiredCapacity': (integer, False), 'EndTime': (basestring, False), 'MaxSize': (integer, False), 'MinSize': (integer, False), 'Recurrence': (basestring, False), 'StartTime': (basestring, False), } class LifecycleHook(AWSObject): resource_type = "AWS::AutoScaling::LifecycleHook" props = { 'AutoScalingGroupName': (basestring, True), 'DefaultResult': (basestring, False), 'HeartbeatTimeout': (integer, False), 'LifecycleHookName': (basestring, False), 'LifecycleTransition': (basestring, True), 'NotificationMetadata': (basestring, False), 'NotificationTargetARN': (basestring, True), 'RoleARN': (basestring, True), } class Trigger(AWSObject): resource_type = "AWS::AutoScaling::Trigger" props = { 'AutoScalingGroupName': (basestring, True), 'BreachDuration': (integer, True), 'Dimensions': (list, True), 'LowerBreachScaleIncrement': (integer, False), 'LowerThreshold': (integer, True), 'MetricName': (basestring, True), 'Namespace': (basestring, True), 'Period': (integer, True), 'Statistic': (basestring, True), 'Unit': (basestring, False), 'UpperBreachScaleIncrement': (integer, False), 'UpperThreshold': (integer, True), } class EBSBlockDevice(AWSProperty): # http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig-blockdev-template.html props = { 'DeleteOnTermination': (boolean, False), 'Iops': (integer, False), 'SnapshotId': (basestring, False), 'VolumeSize': (integer, False), 'VolumeType': (basestring, False), } class BlockDeviceMapping(AWSProperty): # http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig-blockdev-mapping.html props = { 'DeviceName': (basestring, True), 'Ebs': (EBSBlockDevice, False), 'NoDevice': (boolean, False), 'VirtualName': (basestring, False), }
bsd-2-clause
FluidityProject/fluidity
tests/mms_p1dgp2_stressform_br_sp/mms_p1dgp2_stressform_rb_sp_tools.py
6
1028
from math import sin, cos, tanh, pi, e, sqrt def u(X): return cos(X[0]) + cos(X[1]) def v(X): return X[1]*sin(X[0]) def nu(X): return -1.20*sin(0.300*X[0]*X[1]) + 1.20*sin(1.70*X[0]) + 1.40*cos(1.10*X[1]) + 4.00 def forcing_u(X): return -(cos(X[0]) - cos(X[1]))*(-1.20*sin(0.300*X[0]*X[1]) + 1.20*sin(1.70*X[0]) + 1.40*cos(1.10*X[1]) + 4.00) - (X[1]*cos(X[0]) - sin(X[1]))*(-0.360*X[0]*cos(0.300*X[0]*X[1]) - 1.54*sin(1.10*X[1])) + (-0.720*X[1]*cos(0.300*X[0]*X[1]) + 4.08*cos(1.70*X[0]))*sin(X[0]) + (-2.40*sin(0.300*X[0]*X[1]) + 2.40*sin(1.70*X[0]) + 2.80*cos(1.10*X[1]) + 8.00)*cos(X[0]) + cos(X[0]) + cos(X[1]) def forcing_v(X): return (-1.20*sin(0.300*X[0]*X[1]) + 1.20*sin(1.70*X[0]) + 1.40*cos(1.10*X[1]) + 4.00)*X[1]*sin(X[0]) - (X[1]*cos(X[0]) - sin(X[1]))*(-0.360*X[1]*cos(0.300*X[0]*X[1]) + 2.04*cos(1.70*X[0])) - (-0.720*X[0]*cos(0.300*X[0]*X[1]) - 3.08*sin(1.10*X[1]))*sin(X[0]) + X[1]*sin(X[0]) def U(X): return [u(X), v(X)] def forcing_U(X): return [forcing_u(X), forcing_v(X)]
lgpl-2.1
chauhanhardik/populo
cms/djangoapps/contentstore/tests/test_import.py
59
12689
# -*- coding: utf-8 -*- # pylint: disable=protected-access """ Tests for import_course_from_xml using the mongo modulestore. """ from django.test.client import Client from django.test.utils import override_settings from django.conf import settings import ddt import copy from openedx.core.djangoapps.content.course_structures.tests import SignalDisconnectTestMixin from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.django import modulestore from xmodule.contentstore.django import contentstore from xmodule.modulestore.tests.factories import check_exact_number_of_calls, check_number_of_calls from xmodule.modulestore.xml_importer import import_course_from_xml from xmodule.exceptions import NotFoundError from uuid import uuid4 TEST_DATA_CONTENTSTORE = copy.deepcopy(settings.CONTENTSTORE) TEST_DATA_CONTENTSTORE['DOC_STORE_CONFIG']['db'] = 'test_xcontent_%s' % uuid4().hex TEST_DATA_DIR = settings.COMMON_TEST_DATA_ROOT @ddt.ddt @override_settings(CONTENTSTORE=TEST_DATA_CONTENTSTORE, SEARCH_ENGINE=None) class ContentStoreImportTest(SignalDisconnectTestMixin, ModuleStoreTestCase): """ Tests that rely on the toy and test_import_course courses. NOTE: refactor using CourseFactory so they do not. """ def setUp(self): password = super(ContentStoreImportTest, self).setUp() self.client = Client() self.client.login(username=self.user.username, password=password) def load_test_import_course(self, target_id=None, create_if_not_present=True, module_store=None): ''' Load the standard course used to test imports (for do_import_static=False behavior). ''' content_store = contentstore() if module_store is None: module_store = modulestore() import_course_from_xml( module_store, self.user.id, TEST_DATA_DIR, ['test_import_course'], static_content_store=content_store, do_import_static=False, verbose=True, target_id=target_id, create_if_not_present=create_if_not_present, ) course_id = module_store.make_course_key('edX', 'test_import_course', '2012_Fall') course = module_store.get_course(course_id) self.assertIsNotNone(course) return module_store, content_store, course def test_import_course_into_similar_namespace(self): # Checks to make sure that a course with an org/course like # edx/course can be imported into a namespace with an org/course # like edx/course_name module_store, __, course = self.load_test_import_course() course_items = import_course_from_xml( module_store, self.user.id, TEST_DATA_DIR, ['test_import_course_2'], target_id=course.id, verbose=True, ) self.assertEqual(len(course_items), 1) def test_unicode_chars_in_course_name_import(self): """ # Test that importing course with unicode 'id' and 'display name' doesn't give UnicodeEncodeError """ # Test with the split modulestore because store.has_course fails in old mongo with unicode characters. with modulestore().default_store(ModuleStoreEnum.Type.split): module_store = modulestore() course_id = module_store.make_course_key(u'Юникода', u'unicode_course', u'échantillon') import_course_from_xml( module_store, self.user.id, TEST_DATA_DIR, ['2014_Uni'], target_id=course_id, create_if_not_present=True ) course = module_store.get_course(course_id) self.assertIsNotNone(course) # test that course 'display_name' same as imported course 'display_name' self.assertEqual(course.display_name, u"Φυσικά το όνομα Unicode") def test_static_import(self): ''' Stuff in static_import should always be imported into contentstore ''' _, content_store, course = self.load_test_import_course() # make sure we have ONE asset in our contentstore ("should_be_imported.html") all_assets, count = content_store.get_all_content_for_course(course.id) print "len(all_assets)=%d" % len(all_assets) self.assertEqual(len(all_assets), 1) self.assertEqual(count, 1) content = None try: location = course.id.make_asset_key('asset', 'should_be_imported.html') content = content_store.find(location) except NotFoundError: pass self.assertIsNotNone(content) # make sure course.static_asset_path is correct print "static_asset_path = {0}".format(course.static_asset_path) self.assertEqual(course.static_asset_path, 'test_import_course') def test_asset_import_nostatic(self): ''' This test validates that an image asset is NOT imported when do_import_static=False ''' content_store = contentstore() module_store = modulestore() import_course_from_xml( module_store, self.user.id, TEST_DATA_DIR, ['toy'], static_content_store=content_store, do_import_static=False, create_if_not_present=True, verbose=True ) course = module_store.get_course(module_store.make_course_key('edX', 'toy', '2012_Fall')) # make sure we have NO assets in our contentstore all_assets, count = content_store.get_all_content_for_course(course.id) self.assertEqual(len(all_assets), 0) self.assertEqual(count, 0) def test_no_static_link_rewrites_on_import(self): module_store = modulestore() courses = import_course_from_xml( module_store, self.user.id, TEST_DATA_DIR, ['toy'], do_import_static=False, verbose=True, create_if_not_present=True ) course_key = courses[0].id handouts = module_store.get_item(course_key.make_usage_key('course_info', 'handouts')) self.assertIn('/static/', handouts.data) handouts = module_store.get_item(course_key.make_usage_key('html', 'toyhtml')) self.assertIn('/static/', handouts.data) def test_tab_name_imports_correctly(self): _module_store, _content_store, course = self.load_test_import_course() print "course tabs = {0}".format(course.tabs) self.assertEqual(course.tabs[2]['name'], 'Syllabus') def test_import_performance_mongo(self): store = modulestore()._get_modulestore_by_type(ModuleStoreEnum.Type.mongo) # we try to refresh the inheritance tree for each update_item in the import with check_exact_number_of_calls(store, 'refresh_cached_metadata_inheritance_tree', 28): # _get_cached_metadata_inheritance_tree should be called only once with check_exact_number_of_calls(store, '_get_cached_metadata_inheritance_tree', 1): # with bulk-edit in progress, the inheritance tree should be recomputed only at the end of the import # NOTE: On Jenkins, with memcache enabled, the number of calls here is only 1. # Locally, without memcache, the number of calls is actually 2 (once more during the publish step) with check_number_of_calls(store, '_compute_metadata_inheritance_tree', 2): self.load_test_import_course(create_if_not_present=False, module_store=store) @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) def test_reimport(self, default_ms_type): with modulestore().default_store(default_ms_type): __, __, course = self.load_test_import_course(create_if_not_present=True) self.load_test_import_course(target_id=course.id) def test_rewrite_reference_list(self): # This test fails with split modulestore (the HTML component is not in "different_course_id" namespace). # More investigation needs to be done. module_store = modulestore()._get_modulestore_by_type(ModuleStoreEnum.Type.mongo) target_id = module_store.make_course_key('testX', 'conditional_copy', 'copy_run') import_course_from_xml( module_store, self.user.id, TEST_DATA_DIR, ['conditional'], target_id=target_id ) conditional_module = module_store.get_item( target_id.make_usage_key('conditional', 'condone') ) self.assertIsNotNone(conditional_module) different_course_id = module_store.make_course_key('edX', 'different_course', None) self.assertListEqual( [ target_id.make_usage_key('problem', 'choiceprob'), different_course_id.make_usage_key('html', 'for_testing_import_rewrites') ], conditional_module.sources_list ) self.assertListEqual( [ target_id.make_usage_key('html', 'congrats'), target_id.make_usage_key('html', 'secret_page') ], conditional_module.show_tag_list ) def test_rewrite_reference(self): module_store = modulestore() target_id = module_store.make_course_key('testX', 'peergrading_copy', 'copy_run') import_course_from_xml( module_store, self.user.id, TEST_DATA_DIR, ['open_ended'], target_id=target_id, create_if_not_present=True ) peergrading_module = module_store.get_item( target_id.make_usage_key('peergrading', 'PeerGradingLinked') ) self.assertIsNotNone(peergrading_module) self.assertEqual( target_id.make_usage_key('combinedopenended', 'SampleQuestion'), peergrading_module.link_to_location ) def test_rewrite_reference_value_dict_published(self): """ Test rewriting references in ReferenceValueDict, specifically with published content. """ self._verify_split_test_import( 'split_test_copy', 'split_test_module', 'split1', {"0": 'sample_0', "2": 'sample_2'}, ) def test_rewrite_reference_value_dict_draft(self): """ Test rewriting references in ReferenceValueDict, specifically with draft content. """ self._verify_split_test_import( 'split_test_copy_with_draft', 'split_test_module_draft', 'fb34c21fe64941999eaead421a8711b8', {"0": '9f0941d021414798836ef140fb5f6841', "1": '0faf29473cf1497baa33fcc828b179cd'}, ) def _verify_split_test_import(self, target_course_name, source_course_name, split_test_name, groups_to_verticals): module_store = modulestore() target_id = module_store.make_course_key('testX', target_course_name, 'copy_run') import_course_from_xml( module_store, self.user.id, TEST_DATA_DIR, [source_course_name], target_id=target_id, create_if_not_present=True ) split_test_module = module_store.get_item( target_id.make_usage_key('split_test', split_test_name) ) self.assertIsNotNone(split_test_module) remapped_verticals = { key: target_id.make_usage_key('vertical', value) for key, value in groups_to_verticals.iteritems() } self.assertEqual(remapped_verticals, split_test_module.group_id_to_child) @ddt.data(ModuleStoreEnum.Type.mongo, ModuleStoreEnum.Type.split) def test_video_components_present_while_import(self, store): """ Test that video components with same edx_video_id are present while re-importing """ with modulestore().default_store(store): module_store = modulestore() course_id = module_store.make_course_key('edX', 'test_import_course', '2012_Fall') # Import first time __, __, course = self.load_test_import_course(target_id=course_id, module_store=module_store) # Re-import __, __, re_course = self.load_test_import_course(target_id=course.id, module_store=module_store) vertical = module_store.get_item(re_course.id.make_usage_key('vertical', 'vertical_test')) video = module_store.get_item(vertical.children[1]) self.assertEqual(video.display_name, 'default')
agpl-3.0
BonexGu/Blik2D-SDK
Blik2D/addon/tensorflow-1.2.1_for_blik/tensorflow/contrib/learn/python/learn/dataframe/transforms/difference.py
90
2389
# Copyright 2016 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. # ============================================================================== """A `Transform` that performs subtraction on two `Series`.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.learn.python.learn.dataframe import series from tensorflow.contrib.learn.python.learn.dataframe import transform from tensorflow.python.framework import sparse_tensor from tensorflow.python.ops import sparse_ops def _negate_sparse(st): return sparse_tensor.SparseTensor(indices=st.indices, values=-st.values, dense_shape=st.dense_shape) @series.Series.register_binary_op("__sub__") class Difference(transform.TensorFlowTransform): """Subtracts one 'Series` from another.""" def __init__(self): super(Difference, self).__init__() @property def name(self): return "difference" @property def input_valency(self): return 2 @property def _output_names(self): return "output", def _apply_transform(self, input_tensors, **kwargs): pair_sparsity = (isinstance(input_tensors[0], sparse_tensor.SparseTensor), isinstance(input_tensors[1], sparse_tensor.SparseTensor)) if pair_sparsity == (False, False): result = input_tensors[0] - input_tensors[1] # note tf.sparse_add accepts the mixed cases, # so long as at least one input is sparse. elif not pair_sparsity[1]: result = sparse_ops.sparse_add(input_tensors[0], - input_tensors[1]) else: result = sparse_ops.sparse_add(input_tensors[0], _negate_sparse(input_tensors[1])) # pylint: disable=not-callable return self.return_type(result)
mit
Deepakkothandan/ansible
lib/ansible/cli/__init__.py
4
38410
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # (c) 2016, Toshio Kuratomi <tkuratomi@ansible.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/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import getpass import operator import optparse import os import subprocess import re import sys import time import yaml from abc import ABCMeta, abstractmethod import ansible from ansible import constants as C from ansible.errors import AnsibleOptionsError, AnsibleError from ansible.inventory.manager import InventoryManager from ansible.module_utils.six import with_metaclass, string_types from ansible.module_utils._text import to_bytes, to_text from ansible.parsing.dataloader import DataLoader from ansible.release import __version__ from ansible.utils.path import unfrackpath from ansible.utils.vars import load_extra_vars, load_options_vars from ansible.vars.manager import VariableManager from ansible.parsing.vault import PromptVaultSecret, get_file_vault_secret try: from __main__ import display except ImportError: from ansible.utils.display import Display display = Display() class SortedOptParser(optparse.OptionParser): '''Optparser which sorts the options by opt before outputting --help''' def format_help(self, formatter=None, epilog=None): self.option_list.sort(key=operator.methodcaller('get_opt_string')) return optparse.OptionParser.format_help(self, formatter=None) # Note: Inherit from SortedOptParser so that we get our format_help method class InvalidOptsParser(SortedOptParser): '''Ignore invalid options. Meant for the special case where we need to take care of help and version but may not know the full range of options yet. (See it in use in set_action) ''' def __init__(self, parser): # Since this is special purposed to just handle help and version, we # take a pre-existing option parser here and set our options from # that. This allows us to give accurate help based on the given # option parser. SortedOptParser.__init__(self, usage=parser.usage, option_list=parser.option_list, option_class=parser.option_class, conflict_handler=parser.conflict_handler, description=parser.description, formatter=parser.formatter, add_help_option=False, prog=parser.prog, epilog=parser.epilog) self.version = parser.version def _process_long_opt(self, rargs, values): try: optparse.OptionParser._process_long_opt(self, rargs, values) except optparse.BadOptionError: pass def _process_short_opts(self, rargs, values): try: optparse.OptionParser._process_short_opts(self, rargs, values) except optparse.BadOptionError: pass class CLI(with_metaclass(ABCMeta, object)): ''' code behind bin/ansible* programs ''' VALID_ACTIONS = [] _ITALIC = re.compile(r"I\(([^)]+)\)") _BOLD = re.compile(r"B\(([^)]+)\)") _MODULE = re.compile(r"M\(([^)]+)\)") _URL = re.compile(r"U\(([^)]+)\)") _CONST = re.compile(r"C\(([^)]+)\)") PAGER = 'less' # -F (quit-if-one-screen) -R (allow raw ansi control chars) # -S (chop long lines) -X (disable termcap init and de-init) LESS_OPTS = 'FRSX' def __init__(self, args, callback=None): """ Base init method for all command line programs """ self.args = args self.options = None self.parser = None self.action = None self.callback = callback def set_action(self): """ Get the action the user wants to execute from the sys argv list. """ for i in range(0, len(self.args)): arg = self.args[i] if arg in self.VALID_ACTIONS: self.action = arg del self.args[i] break if not self.action: # if we're asked for help or version, we don't need an action. # have to use a special purpose Option Parser to figure that out as # the standard OptionParser throws an error for unknown options and # without knowing action, we only know of a subset of the options # that could be legal for this command tmp_parser = InvalidOptsParser(self.parser) tmp_options, tmp_args = tmp_parser.parse_args(self.args) if not(hasattr(tmp_options, 'help') and tmp_options.help) or (hasattr(tmp_options, 'version') and tmp_options.version): raise AnsibleOptionsError("Missing required action") def execute(self): """ Actually runs a child defined method using the execute_<action> pattern """ fn = getattr(self, "execute_%s" % self.action) fn() @abstractmethod def run(self): """Run the ansible command Subclasses must implement this method. It does the actual work of running an Ansible command. """ display.vv(to_text(self.parser.get_version())) if C.CONFIG_FILE: display.v(u"Using %s as config file" % to_text(C.CONFIG_FILE)) else: display.v(u"No config file found; using defaults") # warn about deprecated config options for deprecated in C.config.DEPRECATED: name = deprecated[0] why = deprecated[1]['why'] if 'alternative' in deprecated[1]: alt = ', use %s instead' % deprecated[1]['alternative'] else: alt = '' ver = deprecated[1]['version'] display.deprecated("%s option, %s %s" % (name, why, alt), version=ver) # warn about typing issues with configuration entries for unable in C.config.UNABLE: display.warning("Unable to set correct type for configuration entry: %s" % unable) @staticmethod def split_vault_id(vault_id): # return (before_@, after_@) # if no @, return whole string as after_ if '@' not in vault_id: return (None, vault_id) parts = vault_id.split('@', 1) ret = tuple(parts) return ret @staticmethod def build_vault_ids(vault_ids, vault_password_files=None, ask_vault_pass=None, create_new_password=None, auto_prompt=True): vault_password_files = vault_password_files or [] vault_ids = vault_ids or [] # convert vault_password_files into vault_ids slugs for password_file in vault_password_files: id_slug = u'%s@%s' % (C.DEFAULT_VAULT_IDENTITY, password_file) # note this makes --vault-id higher precendence than --vault-password-file # if we want to intertwingle them in order probably need a cli callback to populate vault_ids # used by --vault-id and --vault-password-file vault_ids.append(id_slug) # if an action needs an encrypt password (create_new_password=True) and we dont # have other secrets setup, then automatically add a password prompt as well. if ask_vault_pass or (auto_prompt and not vault_ids): id_slug = u'%s@%s' % (C.DEFAULT_VAULT_IDENTITY, u'prompt_ask_vault_pass') vault_ids.append(id_slug) return vault_ids # TODO: remove the now unused args @staticmethod def setup_vault_secrets(loader, vault_ids, vault_password_files=None, ask_vault_pass=None, create_new_password=False, auto_prompt=True): # list of tuples vault_secrets = [] # Depending on the vault_id value (including how --ask-vault-pass / --vault-password-file create a vault_id) # we need to show different prompts. This is for compat with older Towers that expect a # certain vault password prompt format, so 'promp_ask_vault_pass' vault_id gets the old format. prompt_formats = {} # If there are configured default vault identities, they are considered 'first' # so we prepend them to vault_ids (from cli) here vault_password_files = vault_password_files or [] if C.DEFAULT_VAULT_PASSWORD_FILE: vault_password_files.append(C.DEFAULT_VAULT_PASSWORD_FILE) if create_new_password: prompt_formats['prompt'] = ['New vault password (%(vault_id)s): ', 'Confirm vew vault password (%(vault_id)s): '] # 2.3 format prompts for --ask-vault-pass prompt_formats['prompt_ask_vault_pass'] = ['New Vault password: ', 'Confirm New Vault password: '] else: prompt_formats['prompt'] = ['Vault password (%(vault_id)s): '] # The format when we use just --ask-vault-pass needs to match 'Vault password:\s*?$' prompt_formats['prompt_ask_vault_pass'] = ['Vault password: '] vault_ids = CLI.build_vault_ids(vault_ids, vault_password_files, ask_vault_pass, create_new_password, auto_prompt=auto_prompt) for vault_id_slug in vault_ids: vault_id_name, vault_id_value = CLI.split_vault_id(vault_id_slug) if vault_id_value in ['prompt', 'prompt_ask_vault_pass']: # prompts cant/shouldnt work without a tty, so dont add prompt secrets if not sys.stdin.isatty(): continue # --vault-id some_name@prompt_ask_vault_pass --vault-id other_name@prompt_ask_vault_pass will be a little # confusing since it will use the old format without the vault id in the prompt built_vault_id = vault_id_name or C.DEFAULT_VAULT_IDENTITY # choose the prompt based on --vault-id=prompt or --ask-vault-pass. --ask-vault-pass # always gets the old format for Tower compatibility. # ie, we used --ask-vault-pass, so we need to use the old vault password prompt # format since Tower needs to match on that format. prompted_vault_secret = PromptVaultSecret(prompt_formats=prompt_formats[vault_id_value], vault_id=built_vault_id) # a empty or invalid password from the prompt will warn and continue to the next # without erroring globablly try: prompted_vault_secret.load() except AnsibleError as exc: display.warning('Error in vault password prompt (%s): %s' % (vault_id_name, exc)) raise vault_secrets.append((built_vault_id, prompted_vault_secret)) # update loader with new secrets incrementally, so we can load a vault password # that is encrypted with a vault secret provided earlier loader.set_vault_secrets(vault_secrets) continue # assuming anything else is a password file display.vvvvv('Reading vault password file: %s' % vault_id_value) # read vault_pass from a file file_vault_secret = get_file_vault_secret(filename=vault_id_value, vault_id_name=vault_id_name, loader=loader) # an invalid password file will error globally try: file_vault_secret.load() except AnsibleError as exc: display.warning('Error in vault password file loading (%s): %s' % (vault_id_name, exc)) raise if vault_id_name: vault_secrets.append((vault_id_name, file_vault_secret)) else: vault_secrets.append((C.DEFAULT_VAULT_IDENTITY, file_vault_secret)) # update loader with as-yet-known vault secrets loader.set_vault_secrets(vault_secrets) return vault_secrets def ask_passwords(self): ''' prompt for connection and become passwords if needed ''' op = self.options sshpass = None becomepass = None become_prompt = '' try: if op.ask_pass: sshpass = getpass.getpass(prompt="SSH password: ") become_prompt = "%s password[defaults to SSH password]: " % op.become_method.upper() if sshpass: sshpass = to_bytes(sshpass, errors='strict', nonstring='simplerepr') else: become_prompt = "%s password: " % op.become_method.upper() if op.become_ask_pass: becomepass = getpass.getpass(prompt=become_prompt) if op.ask_pass and becomepass == '': becomepass = sshpass if becomepass: becomepass = to_bytes(becomepass) except EOFError: pass return (sshpass, becomepass) def normalize_become_options(self): ''' this keeps backwards compatibility with sudo/su self.options ''' self.options.become_ask_pass = self.options.become_ask_pass or self.options.ask_sudo_pass or self.options.ask_su_pass or C.DEFAULT_BECOME_ASK_PASS self.options.become_user = self.options.become_user or self.options.sudo_user or self.options.su_user or C.DEFAULT_BECOME_USER def _dep(which): display.deprecated('The %s command line option has been deprecated in favor of the "become" command line arguments' % which, '2.6') if self.options.become: pass elif self.options.sudo: self.options.become = True self.options.become_method = 'sudo' _dep('sudo') elif self.options.su: self.options.become = True self.options.become_method = 'su' _dep('su') # other deprecations: if self.options.ask_sudo_pass or self.options.sudo_user: _dep('sudo') if self.options.ask_su_pass or self.options.su_user: _dep('su') def validate_conflicts(self, vault_opts=False, runas_opts=False, fork_opts=False): ''' check for conflicting options ''' op = self.options if vault_opts: # Check for vault related conflicts if (op.ask_vault_pass and op.vault_password_files): self.parser.error("--ask-vault-pass and --vault-password-file are mutually exclusive") if runas_opts: # Check for privilege escalation conflicts if ((op.su or op.su_user) and (op.sudo or op.sudo_user) or (op.su or op.su_user) and (op.become or op.become_user) or (op.sudo or op.sudo_user) and (op.become or op.become_user)): self.parser.error("Sudo arguments ('--sudo', '--sudo-user', and '--ask-sudo-pass') and su arguments ('--su', '--su-user', and '--ask-su-pass') " "and become arguments ('--become', '--become-user', and '--ask-become-pass') are exclusive of each other") if fork_opts: if op.forks < 1: self.parser.error("The number of processes (--forks) must be >= 1") @staticmethod def unfrack_paths(option, opt, value, parser): paths = getattr(parser.values, option.dest) if paths is None: paths = [] if isinstance(value, string_types): paths[:0] = [unfrackpath(x) for x in value.split(os.pathsep) if x] elif isinstance(value, list): paths[:0] = [unfrackpath(x) for x in value if x] else: pass # FIXME: should we raise options error? setattr(parser.values, option.dest, paths) @staticmethod def unfrack_path(option, opt, value, parser): setattr(parser.values, option.dest, unfrackpath(value)) @staticmethod def base_parser(usage="", output_opts=False, runas_opts=False, meta_opts=False, runtask_opts=False, vault_opts=False, module_opts=False, async_opts=False, connect_opts=False, subset_opts=False, check_opts=False, inventory_opts=False, epilog=None, fork_opts=False, runas_prompt_opts=False, desc=None): ''' create an options parser for most ansible scripts ''' # base opts parser = SortedOptParser(usage, version=CLI.version("%prog"), description=desc, epilog=epilog) parser.add_option('-v', '--verbose', dest='verbosity', default=C.DEFAULT_VERBOSITY, action="count", help="verbose mode (-vvv for more, -vvvv to enable connection debugging)") if inventory_opts: parser.add_option('-i', '--inventory', '--inventory-file', dest='inventory', action="append", help="specify inventory host path (default=[%s]) or comma separated host list. " "--inventory-file is deprecated" % C.DEFAULT_HOST_LIST) parser.add_option('--list-hosts', dest='listhosts', action='store_true', help='outputs a list of matching hosts; does not execute anything else') parser.add_option('-l', '--limit', default=C.DEFAULT_SUBSET, dest='subset', help='further limit selected hosts to an additional pattern') if module_opts: parser.add_option('-M', '--module-path', dest='module_path', default=None, help="prepend colon-separated path(s) to module library (default=%s)" % C.DEFAULT_MODULE_PATH, action="callback", callback=CLI.unfrack_paths, type='str') if runtask_opts: parser.add_option('-e', '--extra-vars', dest="extra_vars", action="append", help="set additional variables as key=value or YAML/JSON, if filename prepend with @", default=[]) if fork_opts: parser.add_option('-f', '--forks', dest='forks', default=C.DEFAULT_FORKS, type='int', help="specify number of parallel processes to use (default=%s)" % C.DEFAULT_FORKS) if vault_opts: parser.add_option('--ask-vault-pass', default=C.DEFAULT_ASK_VAULT_PASS, dest='ask_vault_pass', action='store_true', help='ask for vault password') parser.add_option('--vault-password-file', default=[], dest='vault_password_files', help="vault password file", action="callback", callback=CLI.unfrack_paths, type='string') parser.add_option('--new-vault-password-file', default=[], dest='new_vault_password_files', help="new vault password file for rekey", action="callback", callback=CLI.unfrack_paths, type='string') parser.add_option('--vault-id', default=[], dest='vault_ids', action='append', type='string', help='the vault identity to use') parser.add_option('--new-vault-id', default=None, dest='new_vault_id', type='string', help='the new vault identity to use for rekey') if subset_opts: parser.add_option('-t', '--tags', dest='tags', default=C.TAGS_RUN, action='append', help="only run plays and tasks tagged with these values") parser.add_option('--skip-tags', dest='skip_tags', default=C.TAGS_SKIP, action='append', help="only run plays and tasks whose tags do not match these values") if output_opts: parser.add_option('-o', '--one-line', dest='one_line', action='store_true', help='condense output') parser.add_option('-t', '--tree', dest='tree', default=None, help='log output to this directory') if connect_opts: connect_group = optparse.OptionGroup(parser, "Connection Options", "control as whom and how to connect to hosts") connect_group.add_option('-k', '--ask-pass', default=C.DEFAULT_ASK_PASS, dest='ask_pass', action='store_true', help='ask for connection password') connect_group.add_option('--private-key', '--key-file', default=C.DEFAULT_PRIVATE_KEY_FILE, dest='private_key_file', help='use this file to authenticate the connection', action="callback", callback=CLI.unfrack_path, type='string') connect_group.add_option('-u', '--user', default=C.DEFAULT_REMOTE_USER, dest='remote_user', help='connect as this user (default=%s)' % C.DEFAULT_REMOTE_USER) connect_group.add_option('-c', '--connection', dest='connection', default=C.DEFAULT_TRANSPORT, help="connection type to use (default=%s)" % C.DEFAULT_TRANSPORT) connect_group.add_option('-T', '--timeout', default=C.DEFAULT_TIMEOUT, type='int', dest='timeout', help="override the connection timeout in seconds (default=%s)" % C.DEFAULT_TIMEOUT) connect_group.add_option('--ssh-common-args', default='', dest='ssh_common_args', help="specify common arguments to pass to sftp/scp/ssh (e.g. ProxyCommand)") connect_group.add_option('--sftp-extra-args', default='', dest='sftp_extra_args', help="specify extra arguments to pass to sftp only (e.g. -f, -l)") connect_group.add_option('--scp-extra-args', default='', dest='scp_extra_args', help="specify extra arguments to pass to scp only (e.g. -l)") connect_group.add_option('--ssh-extra-args', default='', dest='ssh_extra_args', help="specify extra arguments to pass to ssh only (e.g. -R)") parser.add_option_group(connect_group) runas_group = None rg = optparse.OptionGroup(parser, "Privilege Escalation Options", "control how and which user you become as on target hosts") if runas_opts: runas_group = rg # priv user defaults to root later on to enable detecting when this option was given here runas_group.add_option("-s", "--sudo", default=C.DEFAULT_SUDO, action="store_true", dest='sudo', help="run operations with sudo (nopasswd) (deprecated, use become)") runas_group.add_option('-U', '--sudo-user', dest='sudo_user', default=None, help='desired sudo user (default=root) (deprecated, use become)') runas_group.add_option('-S', '--su', default=C.DEFAULT_SU, action='store_true', help='run operations with su (deprecated, use become)') runas_group.add_option('-R', '--su-user', default=None, help='run operations with su as this user (default=%s) (deprecated, use become)' % C.DEFAULT_SU_USER) # consolidated privilege escalation (become) runas_group.add_option("-b", "--become", default=C.DEFAULT_BECOME, action="store_true", dest='become', help="run operations with become (does not imply password prompting)") runas_group.add_option('--become-method', dest='become_method', default=C.DEFAULT_BECOME_METHOD, type='choice', choices=C.BECOME_METHODS, help="privilege escalation method to use (default=%s), valid choices: [ %s ]" % (C.DEFAULT_BECOME_METHOD, ' | '.join(C.BECOME_METHODS))) runas_group.add_option('--become-user', default=None, dest='become_user', type='string', help='run operations as this user (default=%s)' % C.DEFAULT_BECOME_USER) if runas_opts or runas_prompt_opts: if not runas_group: runas_group = rg runas_group.add_option('--ask-sudo-pass', default=C.DEFAULT_ASK_SUDO_PASS, dest='ask_sudo_pass', action='store_true', help='ask for sudo password (deprecated, use become)') runas_group.add_option('--ask-su-pass', default=C.DEFAULT_ASK_SU_PASS, dest='ask_su_pass', action='store_true', help='ask for su password (deprecated, use become)') runas_group.add_option('-K', '--ask-become-pass', default=False, dest='become_ask_pass', action='store_true', help='ask for privilege escalation password') if runas_group: parser.add_option_group(runas_group) if async_opts: parser.add_option('-P', '--poll', default=C.DEFAULT_POLL_INTERVAL, type='int', dest='poll_interval', help="set the poll interval if using -B (default=%s)" % C.DEFAULT_POLL_INTERVAL) parser.add_option('-B', '--background', dest='seconds', type='int', default=0, help='run asynchronously, failing after X seconds (default=N/A)') if check_opts: parser.add_option("-C", "--check", default=False, dest='check', action='store_true', help="don't make any changes; instead, try to predict some of the changes that may occur") parser.add_option('--syntax-check', dest='syntax', action='store_true', help="perform a syntax check on the playbook, but do not execute it") parser.add_option("-D", "--diff", default=C.DIFF_ALWAYS, dest='diff', action='store_true', help="when changing (small) files and templates, show the differences in those files; works great with --check") if meta_opts: parser.add_option('--force-handlers', default=C.DEFAULT_FORCE_HANDLERS, dest='force_handlers', action='store_true', help="run handlers even if a task fails") parser.add_option('--flush-cache', dest='flush_cache', action='store_true', help="clear the fact cache") return parser @abstractmethod def parse(self): """Parse the command line args This method parses the command line arguments. It uses the parser stored in the self.parser attribute and saves the args and options in self.args and self.options respectively. Subclasses need to implement this method. They will usually create a base_parser, add their own options to the base_parser, and then call this method to do the actual parsing. An implementation will look something like this:: def parse(self): parser = super(MyCLI, self).base_parser(usage="My Ansible CLI", inventory_opts=True) parser.add_option('--my-option', dest='my_option', action='store') self.parser = parser super(MyCLI, self).parse() # If some additional transformations are needed for the # arguments and options, do it here. """ self.options, self.args = self.parser.parse_args(self.args[1:]) # process tags if hasattr(self.options, 'tags') and not self.options.tags: # optparse defaults does not do what's expected self.options.tags = ['all'] if hasattr(self.options, 'tags') and self.options.tags: if not C.MERGE_MULTIPLE_CLI_TAGS: if len(self.options.tags) > 1: display.deprecated('Specifying --tags multiple times on the command line currently uses the last specified value. ' 'In 2.4, values will be merged instead. Set merge_multiple_cli_tags=True in ansible.cfg to get this behavior now.', version=2.5, removed=False) self.options.tags = [self.options.tags[-1]] tags = set() for tag_set in self.options.tags: for tag in tag_set.split(u','): tags.add(tag.strip()) self.options.tags = list(tags) # process skip_tags if hasattr(self.options, 'skip_tags') and self.options.skip_tags: if not C.MERGE_MULTIPLE_CLI_TAGS: if len(self.options.skip_tags) > 1: display.deprecated('Specifying --skip-tags multiple times on the command line currently uses the last specified value. ' 'In 2.4, values will be merged instead. Set merge_multiple_cli_tags=True in ansible.cfg to get this behavior now.', version=2.5, removed=False) self.options.skip_tags = [self.options.skip_tags[-1]] skip_tags = set() for tag_set in self.options.skip_tags: for tag in tag_set.split(u','): skip_tags.add(tag.strip()) self.options.skip_tags = list(skip_tags) # process inventory options if hasattr(self.options, 'inventory'): if self.options.inventory: # should always be list if isinstance(self.options.inventory, string_types): self.options.inventory = [self.options.inventory] # Ensure full paths when needed self.options.inventory = [unfrackpath(opt) if ',' not in opt else opt for opt in self.options.inventory] else: self.options.inventory = C.DEFAULT_HOST_LIST @staticmethod def version(prog): ''' return ansible version ''' result = "{0} {1}".format(prog, __version__) gitinfo = CLI._gitinfo() if gitinfo: result = result + " {0}".format(gitinfo) result += "\n config file = %s" % C.CONFIG_FILE if C.DEFAULT_MODULE_PATH is None: cpath = "Default w/o overrides" else: cpath = C.DEFAULT_MODULE_PATH result = result + "\n configured module search path = %s" % cpath result = result + "\n ansible python module location = %s" % ':'.join(ansible.__path__) result = result + "\n executable location = %s" % sys.argv[0] result = result + "\n python version = %s" % ''.join(sys.version.splitlines()) return result @staticmethod def version_info(gitinfo=False): ''' return full ansible version info ''' if gitinfo: # expensive call, user with care ansible_version_string = CLI.version('') else: ansible_version_string = __version__ ansible_version = ansible_version_string.split()[0] ansible_versions = ansible_version.split('.') for counter in range(len(ansible_versions)): if ansible_versions[counter] == "": ansible_versions[counter] = 0 try: ansible_versions[counter] = int(ansible_versions[counter]) except: pass if len(ansible_versions) < 3: for counter in range(len(ansible_versions), 3): ansible_versions.append(0) return {'string': ansible_version_string.strip(), 'full': ansible_version, 'major': ansible_versions[0], 'minor': ansible_versions[1], 'revision': ansible_versions[2]} @staticmethod def _git_repo_info(repo_path): ''' returns a string containing git branch, commit id and commit date ''' result = None if os.path.exists(repo_path): # Check if the .git is a file. If it is a file, it means that we are in a submodule structure. if os.path.isfile(repo_path): try: gitdir = yaml.safe_load(open(repo_path)).get('gitdir') # There is a possibility the .git file to have an absolute path. if os.path.isabs(gitdir): repo_path = gitdir else: repo_path = os.path.join(repo_path[:-4], gitdir) except (IOError, AttributeError): return '' f = open(os.path.join(repo_path, "HEAD")) line = f.readline().rstrip("\n") if line.startswith("ref:"): branch_path = os.path.join(repo_path, line[5:]) else: branch_path = None f.close() if branch_path and os.path.exists(branch_path): branch = '/'.join(line.split('/')[2:]) f = open(branch_path) commit = f.readline()[:10] f.close() else: # detached HEAD commit = line[:10] branch = 'detached HEAD' branch_path = os.path.join(repo_path, "HEAD") date = time.localtime(os.stat(branch_path).st_mtime) if time.daylight == 0: offset = time.timezone else: offset = time.altzone result = "({0} {1}) last updated {2} (GMT {3:+04d})".format(branch, commit, time.strftime("%Y/%m/%d %H:%M:%S", date), int(offset / -36)) else: result = '' return result @staticmethod def _gitinfo(): basedir = os.path.join(os.path.dirname(__file__), '..', '..', '..') repo_path = os.path.join(basedir, '.git') result = CLI._git_repo_info(repo_path) submodules = os.path.join(basedir, '.gitmodules') if not os.path.exists(submodules): return result f = open(submodules) for line in f: tokens = line.strip().split(' ') if tokens[0] == 'path': submodule_path = tokens[2] submodule_info = CLI._git_repo_info(os.path.join(basedir, submodule_path, '.git')) if not submodule_info: submodule_info = ' not found - use git submodule update --init ' + submodule_path result += "\n {0}: {1}".format(submodule_path, submodule_info) f.close() return result def pager(self, text): ''' find reasonable way to display text ''' # this is a much simpler form of what is in pydoc.py if not sys.stdout.isatty(): display.display(text, screen_only=True) elif 'PAGER' in os.environ: if sys.platform == 'win32': display.display(text, screen_only=True) else: self.pager_pipe(text, os.environ['PAGER']) else: p = subprocess.Popen('less --version', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.communicate() if p.returncode == 0: self.pager_pipe(text, 'less') else: display.display(text, screen_only=True) @staticmethod def pager_pipe(text, cmd): ''' pipe text through a pager ''' if 'LESS' not in os.environ: os.environ['LESS'] = CLI.LESS_OPTS try: cmd = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=sys.stdout) cmd.communicate(input=to_bytes(text)) except IOError: pass except KeyboardInterrupt: pass @classmethod def tty_ify(cls, text): t = cls._ITALIC.sub("`" + r"\1" + "'", text) # I(word) => `word' t = cls._BOLD.sub("*" + r"\1" + "*", t) # B(word) => *word* t = cls._MODULE.sub("[" + r"\1" + "]", t) # M(word) => [word] t = cls._URL.sub(r"\1", t) # U(word) => word t = cls._CONST.sub("`" + r"\1" + "'", t) # C(word) => `word' return t @staticmethod def _play_prereqs(options): # all needs loader loader = DataLoader() vault_ids = options.vault_ids default_vault_ids = C.DEFAULT_VAULT_IDENTITY_LIST vault_ids = default_vault_ids + vault_ids vault_secrets = CLI.setup_vault_secrets(loader, vault_ids=vault_ids, vault_password_files=options.vault_password_files, ask_vault_pass=options.ask_vault_pass, auto_prompt=False) loader.set_vault_secrets(vault_secrets) # create the inventory, and filter it based on the subset specified (if any) inventory = InventoryManager(loader=loader, sources=options.inventory) # create the variable manager, which will be shared throughout # the code, ensuring a consistent view of global variables variable_manager = VariableManager(loader=loader, inventory=inventory) # load vars from cli options variable_manager.extra_vars = load_extra_vars(loader=loader, options=options) variable_manager.options_vars = load_options_vars(options, CLI.version_info(gitinfo=False)) return loader, inventory, variable_manager
gpl-3.0
beni55/edx-platform
common/djangoapps/util/memcache.py
251
1344
""" This module provides a KEY_FUNCTION suitable for use with a memcache backend so that we can cache any keys, not just ones that memcache would ordinarily accept """ from django.utils.encoding import smart_str import hashlib import urllib def fasthash(string): """ Hashes `string` into a string representation of a 128-bit digest. """ md4 = hashlib.new("md4") md4.update(string) return md4.hexdigest() def cleaned_string(val): """ Converts `val` to unicode and URL-encodes special characters (including quotes and spaces) """ return urllib.quote_plus(smart_str(val)) def safe_key(key, key_prefix, version): """ Given a `key`, `key_prefix`, and `version`, return a key that is safe to use with memcache. `key`, `key_prefix`, and `version` can be numbers, strings, or unicode. """ # Clean for whitespace and control characters, which # cause memcache to raise an exception key = cleaned_string(key) key_prefix = cleaned_string(key_prefix) version = cleaned_string(version) # Attempt to combine the prefix, version, and key combined = ":".join([key_prefix, version, key]) # If the total length is too long for memcache, hash it if len(combined) > 250: combined = fasthash(combined) # Return the result return combined
agpl-3.0
raajitr/django_hangman
env/lib/python2.7/site-packages/django/core/cache/backends/base.py
57
9737
"Base Cache class." from __future__ import unicode_literals import time import warnings from django.core.exceptions import DjangoRuntimeWarning, ImproperlyConfigured from django.utils.module_loading import import_string class InvalidCacheBackendError(ImproperlyConfigured): pass class CacheKeyWarning(DjangoRuntimeWarning): pass # Stub class to ensure not passing in a `timeout` argument results in # the default timeout DEFAULT_TIMEOUT = object() # Memcached does not accept keys longer than this. MEMCACHE_MAX_KEY_LENGTH = 250 def default_key_func(key, key_prefix, version): """ Default function to generate keys. Constructs the key used by all other methods. By default it prepends the `key_prefix'. KEY_FUNCTION can be used to specify an alternate function with custom key making behavior. """ return '%s:%s:%s' % (key_prefix, version, key) def get_key_func(key_func): """ Function to decide which key function to use. Defaults to ``default_key_func``. """ if key_func is not None: if callable(key_func): return key_func else: return import_string(key_func) return default_key_func class BaseCache(object): def __init__(self, params): timeout = params.get('timeout', params.get('TIMEOUT', 300)) if timeout is not None: try: timeout = int(timeout) except (ValueError, TypeError): timeout = 300 self.default_timeout = timeout options = params.get('OPTIONS', {}) max_entries = params.get('max_entries', options.get('MAX_ENTRIES', 300)) try: self._max_entries = int(max_entries) except (ValueError, TypeError): self._max_entries = 300 cull_frequency = params.get('cull_frequency', options.get('CULL_FREQUENCY', 3)) try: self._cull_frequency = int(cull_frequency) except (ValueError, TypeError): self._cull_frequency = 3 self.key_prefix = params.get('KEY_PREFIX', '') self.version = params.get('VERSION', 1) self.key_func = get_key_func(params.get('KEY_FUNCTION')) def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT): """ Returns the timeout value usable by this backend based upon the provided timeout. """ if timeout == DEFAULT_TIMEOUT: timeout = self.default_timeout elif timeout == 0: # ticket 21147 - avoid time.time() related precision issues timeout = -1 return None if timeout is None else time.time() + timeout def make_key(self, key, version=None): """Constructs the key used by all other methods. By default it uses the key_func to generate a key (which, by default, prepends the `key_prefix' and 'version'). A different key function can be provided at the time of cache construction; alternatively, you can subclass the cache backend to provide custom key making behavior. """ if version is None: version = self.version new_key = self.key_func(key, self.key_prefix, version) return new_key def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): """ Set a value in the cache if the key does not already exist. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. Returns True if the value was stored, False otherwise. """ raise NotImplementedError('subclasses of BaseCache must provide an add() method') def get(self, key, default=None, version=None): """ Fetch a given key from the cache. If the key does not exist, return default, which itself defaults to None. """ raise NotImplementedError('subclasses of BaseCache must provide a get() method') def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): """ Set a value in the cache. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. """ raise NotImplementedError('subclasses of BaseCache must provide a set() method') def delete(self, key, version=None): """ Delete a key from the cache, failing silently. """ raise NotImplementedError('subclasses of BaseCache must provide a delete() method') def get_many(self, keys, version=None): """ Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values. Returns a dict mapping each key in keys to its value. If the given key is missing, it will be missing from the response dict. """ d = {} for k in keys: val = self.get(k, version=version) if val is not None: d[k] = val return d def get_or_set(self, key, default, timeout=DEFAULT_TIMEOUT, version=None): """ Fetch a given key from the cache. If the key does not exist, the key is added and set to the default value. The default value can also be any callable. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. Return the value of the key stored or retrieved. """ val = self.get(key, version=version) if val is None and default is not None: if callable(default): default = default() self.add(key, default, timeout=timeout, version=version) # Fetch the value again to avoid a race condition if another caller # added a value between the first get() and the add() above. return self.get(key, default, version=version) return val def has_key(self, key, version=None): """ Returns True if the key is in the cache and has not expired. """ return self.get(key, version=version) is not None def incr(self, key, delta=1, version=None): """ Add delta to value in the cache. If the key does not exist, raise a ValueError exception. """ value = self.get(key, version=version) if value is None: raise ValueError("Key '%s' not found" % key) new_value = value + delta self.set(key, new_value, version=version) return new_value def decr(self, key, delta=1, version=None): """ Subtract delta from value in the cache. If the key does not exist, raise a ValueError exception. """ return self.incr(key, -delta, version=version) def __contains__(self, key): """ Returns True if the key is in the cache and has not expired. """ # This is a separate method, rather than just a copy of has_key(), # so that it always has the same functionality as has_key(), even # if a subclass overrides it. return self.has_key(key) def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None): """ Set a bunch of values in the cache at once from a dict of key/value pairs. For certain backends (memcached), this is much more efficient than calling set() multiple times. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used. """ for key, value in data.items(): self.set(key, value, timeout=timeout, version=version) def delete_many(self, keys, version=None): """ Delete a bunch of values in the cache at once. For certain backends (memcached), this is much more efficient than calling delete() multiple times. """ for key in keys: self.delete(key, version=version) def clear(self): """Remove *all* values from the cache at once.""" raise NotImplementedError('subclasses of BaseCache must provide a clear() method') def validate_key(self, key): """ Warn about keys that would not be portable to the memcached backend. This encourages (but does not force) writing backend-portable cache code. """ if len(key) > MEMCACHE_MAX_KEY_LENGTH: warnings.warn( 'Cache key will cause errors if used with memcached: %r ' '(longer than %s)' % (key, MEMCACHE_MAX_KEY_LENGTH), CacheKeyWarning ) for char in key: if ord(char) < 33 or ord(char) == 127: warnings.warn( 'Cache key contains characters that will cause errors if ' 'used with memcached: %r' % key, CacheKeyWarning ) break def incr_version(self, key, delta=1, version=None): """Adds delta to the cache version for the supplied key. Returns the new version. """ if version is None: version = self.version value = self.get(key, version=version) if value is None: raise ValueError("Key '%s' not found" % key) self.set(key, value, version=version + delta) self.delete(key, version=version) return version + delta def decr_version(self, key, delta=1, version=None): """Subtracts delta from the cache version for the supplied key. Returns the new version. """ return self.incr_version(key, -delta, version) def close(self, **kwargs): """Close the cache connection""" pass
mit
eirannejad/pyRevit
pyrevitlib/pyrevit/versionmgr/upgrade.py
1
1082
"""Perform upgrades between version, e.g. adding a new config parameter""" #pylint: disable=W0611 import os import os.path as op from pyrevit.coreutils import appdata def upgrade_user_config(user_config): #pylint: disable=W0613 """Upgarde user configurations. Args: user_config (:obj:`pyrevit.userconfig.PyRevitConfig`): config object val (type): desc """ # upgrade value formats for section in user_config: for option in section: setattr(section, option, getattr(section, option)) def remove_leftover_temp_files(): """4.8.5 had a bug that would create temp files with extension ..bak This cleans them up """ univ_path = op.dirname(appdata.get_universal_data_file("X", 'bak')) if op.exists(univ_path): for entry in os.listdir(univ_path): if op.isfile(entry) and entry.lower().endswith('..bak'): appdata.garbage_data_file(op.join(univ_path, entry)) def upgrade_existing_pyrevit(): """Upgrade existing pyRevit deployment.""" remove_leftover_temp_files()
gpl-3.0
AndrewGrossman/django
tests/template_tests/filter_tests/test_dictsortreversed.py
342
1066
from django.template.defaultfilters import dictsortreversed from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): def test_sort(self): sorted_dicts = dictsortreversed( [{'age': 23, 'name': 'Barbara-Ann'}, {'age': 63, 'name': 'Ra Ra Rasputin'}, {'name': 'Jonny B Goode', 'age': 18}], 'age', ) self.assertEqual( [sorted(dict.items()) for dict in sorted_dicts], [[('age', 63), ('name', 'Ra Ra Rasputin')], [('age', 23), ('name', 'Barbara-Ann')], [('age', 18), ('name', 'Jonny B Goode')]], ) def test_invalid_values(self): """ If dictsortreversed is passed something other than a list of dictionaries, fail silently. """ self.assertEqual(dictsortreversed([1, 2, 3], 'age'), '') self.assertEqual(dictsortreversed('Hello!', 'age'), '') self.assertEqual(dictsortreversed({'a': 1}, 'age'), '') self.assertEqual(dictsortreversed(1, 'age'), '')
bsd-3-clause
wtsi-hgi/docker-icat
tests/test_builds.py
1
3327
import logging import os import unittest from abc import ABCMeta from typing import List, Optional, Tuple, Union import docker from hgicommon.docker.client import create_client from hgicommon.helpers import create_random_string from hgicommon.testing import create_tests, TestUsingObject, ObjectTypeUsedInTest from tests._common import setups from useintest.predefined.irods import build_irods_service_controller_type, IrodsDockerisedService _PROJECT_ROOT = "%s/.." % os.path.dirname(os.path.realpath(__file__)) class _TestICAT(TestUsingObject[ObjectTypeUsedInTest], metaclass=ABCMeta): """ Tests for an iCAT setup. """ @staticmethod def _build_image(top_level_image: Tuple[Optional[Tuple], Tuple[str, str]]): """ Builds images bottom up, building the top level image last. :param top_level_image: representation of the top level image """ image = top_level_image images = [] # type: List[Tuple[str, str]] while image is not None: images.insert(0, image[1]) image = image[0] docker_client = create_client() for image in images: tag = image[0] directory = "%s/%s" % (_PROJECT_ROOT, image[1]) for line in docker_client.build(tag=tag, path=directory): logging.debug(line) @staticmethod def _run(command: Union[str, List[str]], service: IrodsDockerisedService) -> str: """ Run the given commend on the containerised server. :param command: the command to run :param service: the containerised service managing the iCAT """ container_id = service.container["Id"] docker_client = create_client() id = docker_client.exec_create(container_id, cmd=command) chunks = [] for chunk in docker_client.exec_start(id, stream=True): logging.debug(chunk) chunks.append(chunk.decode("utf-8")) return "".join(chunks) def setUp(self): self.setup = self.get_object_to_test() self.test_image_name = create_random_string(self.setup.image_name) type(self)._build_image((self.setup.base_image_to_build, (self.test_image_name, self.setup.location))) repository, tag = self.test_image_name.split(":") ServiceController = build_irods_service_controller_type(repository, tag, self.setup.superclass) self.service_controller = ServiceController() self.service = self.service_controller.start_service() def tearDown(self): self.service_controller.stop_service(self.service) client = docker.from_env() client.images.remove(self.test_image_name, force=True) def test_starts(self): test_file_name = "test123" self._run(["touch", test_file_name], self.service) self._run(["iput", test_file_name], self.service) self.assertIn(test_file_name, self._run(["ils"], self.service)) # Setup tests globals().update(create_tests(_TestICAT, setups, lambda superclass, test_object: "TestICATWith%s" % test_object.location.split("/")[1])) # Fix for stupidity of test runners del _TestICAT, TestUsingObject, create_tests if __name__ == "__main__": unittest.main()
gpl-3.0
tedlaz/pyted
misthodosia/m13a/fmy.py
1
2802
# -*- coding: utf-8 -*- ''' Created on 16 Ιαν 2013 @author: tedlaz ''' from utils import dec as d def f13(poso): poso = d(poso) ekp = d(0) if poso < d(21500): ekp = d(2100) elif poso < d(22500): ekp = d(2000) elif poso < d(23500): ekp = d(1900) elif poso < d(24500): ekp = d(1800) elif poso < d(25500): ekp = d(1700) elif poso < d(26500): ekp = d(1600) elif poso < d(27500): ekp = d(1500) elif poso < d(28500): ekp = d(1400) elif poso < d(29500): ekp = d(1300) elif poso < d(30500): ekp = d(1200) elif poso < d(31500): ekp = d(1100) elif poso < d(32500): ekp = d(1000) elif poso < d(33500): ekp = d(900) elif poso < d(34500): ekp = d(800) elif poso < d(35500): ekp = d(700) elif poso < d(36500): ekp = d(600) elif poso < d(37500): ekp = d(500) elif poso < d(38500): ekp = d(400) elif poso < d(39500): ekp = d(300) elif poso < d(40500): ekp = d(200) elif poso < d(41500): ekp = d(100) else: ekp = d(0) #print 'ekptosi',poso,ekp foros = d(0) if poso <= d(25000): foros = d(poso * d(22) / d(100)) else: foros = d(5500) poso = poso - d(25000) if poso <= d(17000): foros += d(poso * d(32) / d(100)) else: foros += d(5440) poso = poso - d(17000) foros += d(poso * d(42) / d(100)) foros = foros - ekp if foros < d(0) : foros = d(0) return foros def eea(poso): poso = d(poso) if poso <= d(12000): synt = d(0) elif poso <= d(20000): synt = d(1) elif poso <= d(50000): synt = d(2) elif poso <= d(100000): synt = d(3) else: synt = d(4) return d(poso * synt / d(100)) def eeap(poso,bar=1): #bar : 1 εάν ολόκληρη περίοδος 2 εάν μισή (πχ.επίδομα αδείας) poso = d(poso) tb = d(14) * d(bar) eis = poso * tb ee = eea(eis) return d(ee / tb) def fp13(poso,bar=1): poso = poso tb = 14 * bar eis = poso * tb f = f13(eis) #pf = d(f - d(0.015,3) * f) return f / tb def fpXrisis(poso,bar=1,xrisi=2013): if xrisi == 2013: return fp13(poso,bar) else: return 0 def eeaXrisis(poso,bar=1,xrisi=2013): if xrisi == 2012 or xrisi == 2013: return eeap(poso,bar) else: return d(0) if __name__ == '__main__': p = 2035.72 print fpXrisis(p,1,2013) print eeaXrisis(p,1,2013)
gpl-3.0
igemsoftware/SYSU-Software2013
project/Python27_32/Lib/encodings/ascii.py
858
1248
""" Python 'ascii' Codec Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs class Codec(codecs.Codec): # Note: Binding these as C functions will result in the class not # converting them to methods. This is intended. encode = codecs.ascii_encode decode = codecs.ascii_decode class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.ascii_encode(input, self.errors)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.ascii_decode(input, self.errors)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass class StreamConverter(StreamWriter,StreamReader): encode = codecs.ascii_decode decode = codecs.ascii_encode ### encodings module API def getregentry(): return codecs.CodecInfo( name='ascii', encode=Codec.encode, decode=Codec.decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamwriter=StreamWriter, streamreader=StreamReader, )
mit
gangadhar-kadam/nassimlib
webnotes/utils/file_manager.py
33
6643
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import webnotes import os, base64, re from webnotes.utils import cstr, cint, get_site_path from webnotes import _ from webnotes import conf class MaxFileSizeReachedError(webnotes.ValidationError): pass def upload(): # get record details dt = webnotes.form_dict.doctype dn = webnotes.form_dict.docname file_url = webnotes.form_dict.file_url filename = webnotes.form_dict.filename if not filename and not file_url: webnotes.msgprint(_("Please select a file or url"), raise_exception=True) # save if filename: filedata = save_uploaded(dt, dn) elif file_url: filedata = save_url(file_url, dt, dn) return {"fid": filedata.name, "filename": filedata.file_name or filedata.file_url } def save_uploaded(dt, dn): fname, content = get_uploaded_content() if content: return save_file(fname, content, dt, dn) else: raise Exception def save_url(file_url, dt, dn): if not (file_url.startswith("http://") or file_url.startswith("https://")): webnotes.msgprint("URL must start with 'http://' or 'https://'") return None, None f = webnotes.bean({ "doctype": "File Data", "file_url": file_url, "attached_to_doctype": dt, "attached_to_name": dn }) f.ignore_permissions = True f.insert(); return f.doc def get_uploaded_content(): # should not be unicode when reading a file, hence using webnotes.form if 'filedata' in webnotes.form_dict: webnotes.uploaded_content = base64.b64decode(webnotes.form_dict.filedata) webnotes.uploaded_filename = webnotes.form_dict.filename return webnotes.uploaded_filename, webnotes.uploaded_content else: webnotes.msgprint('No File') return None, None def extract_images_from_html(doc, fieldname): content = doc.get(fieldname) webnotes.flags.has_dataurl = False def _save_file(match): data = match.group(1) headers, content = data.split(",") filename = headers.split("filename=")[-1] filename = save_file(filename, content, doc.doctype, doc.name, decode=True).get("file_name") if not webnotes.flags.has_dataurl: webnotes.flags.has_dataurl = True return '<img src="{filename}"'.format(filename = filename) if content: content = re.sub('<img\s*src=\s*["\'](data:[^"\']*)["\']', _save_file, content) if webnotes.flags.has_dataurl: doc.fields[fieldname] = content def save_file(fname, content, dt, dn, decode=False): if decode: if isinstance(content, unicode): content = content.encode("utf-8") content = base64.b64decode(content) import filecmp from webnotes.model.code import load_doctype_module files_path = get_site_path(conf.files_path) module = load_doctype_module(dt, webnotes.conn.get_value("DocType", dt, "module")) if hasattr(module, "attachments_folder"): files_path = os.path.join(files_path, module.attachments_folder) file_size = check_max_file_size(content) temp_fname = write_file(content, files_path) fname = scrub_file_name(fname) fname_parts = fname.split(".", -1) main = ".".join(fname_parts[:-1]) extn = fname_parts[-1] versions = get_file_versions(files_path, main, extn) if versions: found_match = False for version in versions: if filecmp.cmp(os.path.join(files_path, version), temp_fname): # remove new file, already exists! os.remove(temp_fname) fname = version fpath = os.path.join(files_path, fname) found_match = True break if not found_match: # get_new_version name fname = get_new_fname_based_on_version(files_path, main, extn, versions) fpath = os.path.join(files_path, fname) # rename if os.path.exists(fpath.encode("utf-8")): webnotes.throw("File already exists: " + fname) os.rename(temp_fname, fpath.encode("utf-8")) else: fpath = os.path.join(files_path, fname) # rename new file if os.path.exists(fpath.encode("utf-8")): webnotes.throw("File already exists: " + fname) os.rename(temp_fname, fpath.encode("utf-8")) f = webnotes.bean({ "doctype": "File Data", "file_name": os.path.relpath(os.path.join(files_path, fname), get_site_path(conf.get("public_path", "public"))), "attached_to_doctype": dt, "attached_to_name": dn, "file_size": file_size }) f.ignore_permissions = True try: f.insert(); except webnotes.DuplicateEntryError: return {"file_name": f.doc.file_name} return f.doc def get_file_versions(files_path, main, extn): out = [] for f in os.listdir(files_path): f = cstr(f) if f.startswith(main) and f.endswith(extn): out.append(f) return out def get_new_fname_based_on_version(files_path, main, extn, versions): versions.sort() if "-" in versions[-1]: version = cint(versions[-1].split("-")[-1]) or 1 else: version = 1 new_fname = main + "-" + str(version) + "." + extn while os.path.exists(os.path.join(files_path, new_fname).encode("utf-8")): version += 1 new_fname = main + "-" + str(version) + "." + extn if version > 100: webnotes.msgprint("Too many versions", raise_exception=True) return new_fname def scrub_file_name(fname): if '\\' in fname: fname = fname.split('\\')[-1] if '/' in fname: fname = fname.split('/')[-1] return fname def check_max_file_size(content): max_file_size = conf.get('max_file_size') or 1000000 file_size = len(content) if file_size > max_file_size: webnotes.msgprint(_("File size exceeded the maximum allowed size"), raise_exception=MaxFileSizeReachedError) return file_size def write_file(content, files_path): """write file to disk with a random name (to compare)""" # create account folder (if not exists) webnotes.create_folder(files_path) fname = os.path.join(files_path, webnotes.generate_hash()) # write the file with open(fname, 'w+') as f: f.write(content) return fname def remove_all(dt, dn): """remove all files in a transaction""" try: for fid in webnotes.conn.sql_list("""select name from `tabFile Data` where attached_to_doctype=%s and attached_to_name=%s""", (dt, dn)): remove_file(fid) except Exception, e: if e.args[0]!=1054: raise # (temp till for patched) def remove_file(fid): """Remove file and File Data entry""" webnotes.delete_doc("File Data", fid) def get_file(fname): f = webnotes.conn.sql("""select file_name from `tabFile Data` where name=%s or file_name=%s""", (fname, fname)) if f: file_name = f[0][0] else: file_name = fname if not "/" in file_name: file_name = "files/" + file_name # read the file with open(get_site_path("public", file_name), 'r') as f: content = f.read() return [file_name, content]
mit
Sorsly/subtle
google-cloud-sdk/lib/surface/genomics/variantsets/list.py
3
2113
# 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. """variantsets list command.""" from apitools.base.py import list_pager from googlecloudsdk.api_lib.genomics import genomics_util from googlecloudsdk.calliope import base class List(base.ListCommand): """List Genomics variant sets in a dataset. Prints a table with summary information on variant sets in the dataset. """ @staticmethod def Args(parser): """Args is called by calliope to gather arguments for this command. Args: parser: An argparse parser that you can use to add arguments that go on the command line after this command. Positional arguments are allowed. """ parser.add_argument( 'dataset_id', help="""Restrict the query to variant sets within the given dataset.""") def Collection(self): return 'genomics.variantsets' def Run(self, args): """Run 'variantsets list'. Args: args: argparse.Namespace, The arguments that this command was invoked with. Returns: The list of variant sets for this dataset. """ apitools_client = genomics_util.GetGenomicsClient() req_class = genomics_util.GetGenomicsMessages().SearchVariantSetsRequest request = req_class(datasetIds=[args.dataset_id]) return list_pager.YieldFromList( apitools_client.variantsets, request, method='Search', limit=args.limit, batch_size_attribute='pageSize', batch_size=args.limit, # Use limit if any, else server default. field='variantSets')
mit
iDTLabssl/hr
hr_unported/hr_payroll_register_report/__openerp__.py
20
1512
# -*- coding:utf-8 -*- # # # Copyright (C) 2011,2013 Michael Telahun Makonnen <mmakonnen@gmail.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/>. # # { 'name': 'Payroll Register Report', 'version': '1.0', 'category': 'Generic Modules/Human Resources', 'description': """ Payroll Register Report ======================= - Complete list of employees and payroll lines - Comprehensive report that includes all departments - Printed Pay Slips """, 'author': "Michael Telahun Makonnen <mmakonnen@gmail.com>,Odoo Community Association (OCA)", 'website': 'http://miketelahun.wordpress.com', 'license': 'AGPL-3', 'depends': [ 'hr_payroll_register', 'report_aeroo', ], 'data': [ 'hr_payroll_register_report.xml', ], 'test': [ ], 'installable': False, }
agpl-3.0
mkieszek/odoo
addons/hr_payroll/wizard/hr_payroll_contribution_register_report.py
47
1128
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time from datetime import datetime from dateutil import relativedelta from openerp.osv import fields, osv class payslip_lines_contribution_register(osv.osv_memory): _name = 'payslip.lines.contribution.register' _description = 'PaySlip Lines by Contribution Registers' _columns = { 'date_from': fields.date('Date From', required=True), 'date_to': fields.date('Date To', required=True), } _defaults = { 'date_from': lambda *a: time.strftime('%Y-%m-01'), 'date_to': lambda *a: str(datetime.now() + relativedelta.relativedelta(months=+1, day=1, days=-1))[:10], } def print_report(self, cr, uid, ids, context=None): datas = { 'ids': context.get('active_ids', []), 'model': 'hr.contribution.register', 'form': self.read(cr, uid, ids, context=context)[0] } return self.pool['report'].get_action( cr, uid, [], 'hr_payroll.report_contributionregister', data=datas, context=context )
agpl-3.0
sonali0901/zulip
zerver/management/commands/dump_messages.py
7
1529
from __future__ import absolute_import from __future__ import print_function from typing import Any from optparse import make_option from django.core.management.base import BaseCommand, CommandParser from zerver.models import get_realm, Message, Realm, Stream, Recipient import datetime import time class Command(BaseCommand): def add_arguments(self, parser): # type: (CommandParser) -> None default_cutoff = time.time() - 60 * 60 * 24 * 30 # 30 days. parser.add_argument('--realm', dest='string_id', type=str, help='The subdomain/string_id of realm whose public streams you want to dump.') parser.add_argument('--since', dest='since', type=int, default=default_cutoff, help='The time in epoch since from which to start the dump.') def handle(self, *args, **options): # type: (*Any, **Any) -> None realm = get_realm(options["string_id"]) streams = Stream.objects.filter(realm=realm, invite_only=False) recipients = Recipient.objects.filter( type=Recipient.STREAM, type_id__in=[stream.id for stream in streams]) cutoff = datetime.datetime.fromtimestamp(options["since"]) messages = Message.objects.filter(pub_date__gt=cutoff, recipient__in=recipients) for message in messages: print(message.to_dict(False))
apache-2.0
ltiao/networkx
networkx/algorithms/bipartite/tests/test_basic.py
14
3970
#!/usr/bin/env python from nose.tools import * from nose import SkipTest from nose.plugins.attrib import attr import networkx as nx from networkx.algorithms import bipartite class TestBipartiteBasic: def test_is_bipartite(self): assert_true(bipartite.is_bipartite(nx.path_graph(4))) assert_true(bipartite.is_bipartite(nx.DiGraph([(1,0)]))) assert_false(bipartite.is_bipartite(nx.complete_graph(3))) def test_bipartite_color(self): G=nx.path_graph(4) c=bipartite.color(G) assert_equal(c,{0: 1, 1: 0, 2: 1, 3: 0}) @raises(nx.NetworkXError) def test_not_bipartite_color(self): c=bipartite.color(nx.complete_graph(4)) def test_bipartite_directed(self): G = bipartite.random_graph(10, 10, 0.1, directed=True) assert_true(bipartite.is_bipartite(G)) def test_bipartite_sets(self): G=nx.path_graph(4) X,Y=bipartite.sets(G) assert_equal(X,set([0,2])) assert_equal(Y,set([1,3])) def test_is_bipartite_node_set(self): G=nx.path_graph(4) assert_true(bipartite.is_bipartite_node_set(G,[0,2])) assert_true(bipartite.is_bipartite_node_set(G,[1,3])) assert_false(bipartite.is_bipartite_node_set(G,[1,2])) G.add_path([10,20]) assert_true(bipartite.is_bipartite_node_set(G,[0,2,10])) assert_true(bipartite.is_bipartite_node_set(G,[0,2,20])) assert_true(bipartite.is_bipartite_node_set(G,[1,3,10])) assert_true(bipartite.is_bipartite_node_set(G,[1,3,20])) def test_bipartite_density(self): G=nx.path_graph(5) X,Y=bipartite.sets(G) density=float(len(list(G.edges())))/(len(X)*len(Y)) assert_equal(bipartite.density(G,X),density) D = nx.DiGraph(G.edges()) assert_equal(bipartite.density(D,X),density/2.0) assert_equal(bipartite.density(nx.Graph(),{}),0.0) def test_bipartite_degrees(self): G=nx.path_graph(5) X=set([1,3]) Y=set([0,2,4]) u,d=bipartite.degrees(G,Y) assert_equal(dict(u), {1:2,3:2}) assert_equal(dict(d), {0:1,2:2,4:1}) def test_bipartite_weighted_degrees(self): G=nx.path_graph(5) G.add_edge(0,1,weight=0.1,other=0.2) X=set([1,3]) Y=set([0,2,4]) u,d=bipartite.degrees(G,Y,weight='weight') assert_equal(dict(u), {1:1.1,3:2}) assert_equal(dict(d), {0:0.1,2:2,4:1}) u,d=bipartite.degrees(G,Y,weight='other') assert_equal(dict(u), {1:1.2,3:2}) assert_equal(dict(d), {0:0.2,2:2,4:1}) @attr('numpy') def test_biadjacency_matrix_weight(self): try: import scipy except ImportError: raise SkipTest('SciPy not available.') G=nx.path_graph(5) G.add_edge(0,1,weight=2,other=4) X=[1,3] Y=[0,2,4] M = bipartite.biadjacency_matrix(G,X,weight='weight') assert_equal(M[0,0], 2) M = bipartite.biadjacency_matrix(G, X, weight='other') assert_equal(M[0,0], 4) @attr('numpy') def test_biadjacency_matrix(self): try: import scipy except ImportError: raise SkipTest('SciPy not available.') tops = [2,5,10] bots = [5,10,15] for i in range(len(tops)): G = bipartite.random_graph(tops[i], bots[i], 0.2) top = [n for n,d in G.nodes(data=True) if d['bipartite']==0] M = bipartite.biadjacency_matrix(G, top) assert_equal(M.shape[0],tops[i]) assert_equal(M.shape[1],bots[i]) @attr('numpy') def test_biadjacency_matrix_order(self): try: import scipy except ImportError: raise SkipTest('SciPy not available.') G=nx.path_graph(5) G.add_edge(0,1,weight=2) X=[3,1] Y=[4,2,0] M = bipartite.biadjacency_matrix(G,X,Y,weight='weight') assert_equal(M[1,2], 2)
bsd-3-clause
chouseknecht/ansible
test/units/executor/test_task_executor.py
5
23759
# (c) 2012-2014, 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/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import mock from units.compat import unittest from units.compat.mock import patch, MagicMock from ansible.errors import AnsibleError from ansible.executor.task_executor import TaskExecutor, remove_omit from ansible.plugins.loader import action_loader, lookup_loader from ansible.parsing.yaml.objects import AnsibleUnicode from ansible.utils.unsafe_proxy import AnsibleUnsafeText, AnsibleUnsafeBytes from ansible.module_utils.six import text_type from units.mock.loader import DictDataLoader class TestTaskExecutor(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_task_executor_init(self): fake_loader = DictDataLoader({}) mock_host = MagicMock() mock_task = MagicMock() mock_play_context = MagicMock() mock_shared_loader = MagicMock() new_stdin = None job_vars = dict() mock_queue = MagicMock() te = TaskExecutor( host=mock_host, task=mock_task, job_vars=job_vars, play_context=mock_play_context, new_stdin=new_stdin, loader=fake_loader, shared_loader_obj=mock_shared_loader, final_q=mock_queue, ) def test_task_executor_run(self): fake_loader = DictDataLoader({}) mock_host = MagicMock() mock_task = MagicMock() mock_task._role._role_path = '/path/to/role/foo' mock_play_context = MagicMock() mock_shared_loader = MagicMock() mock_queue = MagicMock() new_stdin = None job_vars = dict() te = TaskExecutor( host=mock_host, task=mock_task, job_vars=job_vars, play_context=mock_play_context, new_stdin=new_stdin, loader=fake_loader, shared_loader_obj=mock_shared_loader, final_q=mock_queue, ) te._get_loop_items = MagicMock(return_value=None) te._execute = MagicMock(return_value=dict()) res = te.run() te._get_loop_items = MagicMock(return_value=[]) res = te.run() te._get_loop_items = MagicMock(return_value=['a', 'b', 'c']) te._run_loop = MagicMock(return_value=[dict(item='a', changed=True), dict(item='b', failed=True), dict(item='c')]) res = te.run() te._get_loop_items = MagicMock(side_effect=AnsibleError("")) res = te.run() self.assertIn("failed", res) def test_task_executor_run_clean_res(self): te = TaskExecutor(None, MagicMock(), None, None, None, None, None, None) te._get_loop_items = MagicMock(return_value=[1]) te._run_loop = MagicMock( return_value=[ { 'unsafe_bytes': AnsibleUnsafeBytes(b'{{ $bar }}'), 'unsafe_text': AnsibleUnsafeText(u'{{ $bar }}'), 'bytes': b'bytes', 'text': u'text', 'int': 1, } ] ) res = te.run() data = res['results'][0] self.assertIsInstance(data['unsafe_bytes'], AnsibleUnsafeText) self.assertIsInstance(data['unsafe_text'], AnsibleUnsafeText) self.assertIsInstance(data['bytes'], text_type) self.assertIsInstance(data['text'], text_type) self.assertIsInstance(data['int'], int) def test_task_executor_get_loop_items(self): fake_loader = DictDataLoader({}) mock_host = MagicMock() mock_task = MagicMock() mock_task.loop_with = 'items' mock_task.loop = ['a', 'b', 'c'] mock_play_context = MagicMock() mock_shared_loader = MagicMock() mock_shared_loader.lookup_loader = lookup_loader new_stdin = None job_vars = dict() mock_queue = MagicMock() te = TaskExecutor( host=mock_host, task=mock_task, job_vars=job_vars, play_context=mock_play_context, new_stdin=new_stdin, loader=fake_loader, shared_loader_obj=mock_shared_loader, final_q=mock_queue, ) items = te._get_loop_items() self.assertEqual(items, ['a', 'b', 'c']) def test_task_executor_run_loop(self): items = ['a', 'b', 'c'] fake_loader = DictDataLoader({}) mock_host = MagicMock() def _copy(exclude_parent=False, exclude_tasks=False): new_item = MagicMock() return new_item mock_task = MagicMock() mock_task.copy.side_effect = _copy mock_play_context = MagicMock() mock_shared_loader = MagicMock() mock_queue = MagicMock() new_stdin = None job_vars = dict() te = TaskExecutor( host=mock_host, task=mock_task, job_vars=job_vars, play_context=mock_play_context, new_stdin=new_stdin, loader=fake_loader, shared_loader_obj=mock_shared_loader, final_q=mock_queue, ) def _execute(variables): return dict(item=variables.get('item')) te._squash_items = MagicMock(return_value=items) te._execute = MagicMock(side_effect=_execute) res = te._run_loop(items) self.assertEqual(len(res), 3) def test_task_executor_squash_items(self): items = ['a', 'b', 'c'] fake_loader = DictDataLoader({}) mock_host = MagicMock() loop_var = 'item' def _evaluate_conditional(templar, variables): item = variables.get(loop_var) if item == 'b': return False return True mock_task = MagicMock() mock_task.evaluate_conditional.side_effect = _evaluate_conditional mock_play_context = MagicMock() mock_shared_loader = None mock_queue = MagicMock() new_stdin = None job_vars = dict(pkg_mgr='yum') te = TaskExecutor( host=mock_host, task=mock_task, job_vars=job_vars, play_context=mock_play_context, new_stdin=new_stdin, loader=fake_loader, shared_loader_obj=mock_shared_loader, final_q=mock_queue, ) # No replacement mock_task.action = 'yum' new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) self.assertEqual(new_items, ['a', 'b', 'c']) self.assertIsInstance(mock_task.args, MagicMock) mock_task.action = 'foo' mock_task.args = {'name': '{{item}}'} new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) self.assertEqual(new_items, ['a', 'b', 'c']) self.assertEqual(mock_task.args, {'name': '{{item}}'}) mock_task.action = 'yum' mock_task.args = {'name': 'static'} new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) self.assertEqual(new_items, ['a', 'b', 'c']) self.assertEqual(mock_task.args, {'name': 'static'}) mock_task.action = 'yum' mock_task.args = {'name': '{{pkg_mgr}}'} new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) self.assertEqual(new_items, ['a', 'b', 'c']) self.assertEqual(mock_task.args, {'name': '{{pkg_mgr}}'}) mock_task.action = '{{unknown}}' mock_task.args = {'name': '{{item}}'} new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) self.assertEqual(new_items, ['a', 'b', 'c']) self.assertEqual(mock_task.args, {'name': '{{item}}'}) # Could do something like this to recover from bad deps in a package job_vars = dict(pkg_mgr='yum', packages=['a', 'b']) items = ['absent', 'latest'] mock_task.action = 'yum' mock_task.args = {'name': '{{ packages }}', 'state': '{{ item }}'} new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) self.assertEqual(new_items, items) self.assertEqual(mock_task.args, {'name': '{{ packages }}', 'state': '{{ item }}'}) # Maybe should raise an error in this case. The user would have to specify: # - yum: name="{{ packages[item] }}" # with_items: # - ['a', 'b'] # - ['foo', 'bar'] # you can't use a list as a dict key so that would probably throw # an error later. If so, we can throw it now instead. # Squashing in this case would not be intuitive as the user is being # explicit in using each list entry as a key. job_vars = dict(pkg_mgr='yum', packages={"a": "foo", "b": "bar", "foo": "baz", "bar": "quux"}) items = [['a', 'b'], ['foo', 'bar']] mock_task.action = 'yum' mock_task.args = {'name': '{{ packages[item] }}'} new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) self.assertEqual(new_items, items) self.assertEqual(mock_task.args, {'name': '{{ packages[item] }}'}) # Replaces items = ['a', 'b', 'c'] mock_task.action = 'yum' mock_task.args = {'name': '{{item}}'} new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) self.assertEqual(new_items, [['a', 'c']]) self.assertEqual(mock_task.args, {'name': ['a', 'c']}) mock_task.action = '{{pkg_mgr}}' mock_task.args = {'name': '{{item}}'} new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) self.assertEqual(new_items, [['a', 'c']]) self.assertEqual(mock_task.args, {'name': ['a', 'c']}) # New loop_var mock_task.action = 'yum' mock_task.args = {'name': '{{a_loop_var_item}}'} mock_task.loop_control = {'loop_var': 'a_loop_var_item'} loop_var = 'a_loop_var_item' new_items = te._squash_items(items=items, loop_var='a_loop_var_item', variables=job_vars) self.assertEqual(new_items, [['a', 'c']]) self.assertEqual(mock_task.args, {'name': ['a', 'c']}) loop_var = 'item' # # These are presently not optimized but could be in the future. # Expected output if they were optimized is given as a comment # Please move these to a different section if they are optimized # # Squashing lists job_vars = dict(pkg_mgr='yum') items = [['a', 'b'], ['foo', 'bar']] mock_task.action = 'yum' mock_task.args = {'name': '{{ item }}'} new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) # self.assertEqual(new_items, [['a', 'b', 'foo', 'bar']]) # self.assertEqual(mock_task.args, {'name': ['a', 'b', 'foo', 'bar']}) self.assertEqual(new_items, items) self.assertEqual(mock_task.args, {'name': '{{ item }}'}) # Retrieving from a dict items = ['a', 'b', 'foo'] mock_task.action = 'yum' mock_task.args = {'name': '{{ packages[item] }}'} new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) # self.assertEqual(new_items, [['foo', 'baz']]) # self.assertEqual(mock_task.args, {'name': ['foo', 'baz']}) self.assertEqual(new_items, items) self.assertEqual(mock_task.args, {'name': '{{ packages[item] }}'}) # Another way to retrieve from a dict job_vars = dict(pkg_mgr='yum') items = [{'package': 'foo'}, {'package': 'bar'}] mock_task.action = 'yum' mock_task.args = {'name': '{{ item["package"] }}'} new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) # self.assertEqual(new_items, [['foo', 'bar']]) # self.assertEqual(mock_task.args, {'name': ['foo', 'bar']}) self.assertEqual(new_items, items) self.assertEqual(mock_task.args, {'name': '{{ item["package"] }}'}) items = [ dict(name='a', state='present'), dict(name='b', state='present'), dict(name='c', state='present'), ] mock_task.action = 'yum' mock_task.args = {'name': '{{item.name}}', 'state': '{{item.state}}'} new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) # self.assertEqual(new_items, [dict(name=['a', 'b', 'c'], state='present')]) # self.assertEqual(mock_task.args, {'name': ['a', 'b', 'c'], 'state': 'present'}) self.assertEqual(new_items, items) self.assertEqual(mock_task.args, {'name': '{{item.name}}', 'state': '{{item.state}}'}) items = [ dict(name='a', state='present'), dict(name='b', state='present'), dict(name='c', state='absent'), ] mock_task.action = 'yum' mock_task.args = {'name': '{{item.name}}', 'state': '{{item.state}}'} new_items = te._squash_items(items=items, loop_var='item', variables=job_vars) # self.assertEqual(new_items, [dict(name=['a', 'b'], state='present'), # dict(name='c', state='absent')]) # self.assertEqual(mock_task.args, {'name': '{{item.name}}', 'state': '{{item.state}}'}) self.assertEqual(new_items, items) self.assertEqual(mock_task.args, {'name': '{{item.name}}', 'state': '{{item.state}}'}) def test_task_executor_get_action_handler(self): te = TaskExecutor( host=MagicMock(), task=MagicMock(), job_vars={}, play_context=MagicMock(), new_stdin=None, loader=DictDataLoader({}), shared_loader_obj=MagicMock(), final_q=MagicMock(), ) action_loader = te._shared_loader_obj.action_loader action_loader.has_plugin.return_value = True action_loader.get.return_value = mock.sentinel.handler mock_connection = MagicMock() mock_templar = MagicMock() action = 'namespace.prefix_sufix' te._task.action = action handler = te._get_action_handler(mock_connection, mock_templar) self.assertIs(mock.sentinel.handler, handler) action_loader.has_plugin.assert_called_once_with( action, collection_list=te._task.collections) action_loader.get.assert_called_once_with( te._task.action, task=te._task, connection=mock_connection, play_context=te._play_context, loader=te._loader, templar=mock_templar, shared_loader_obj=te._shared_loader_obj, collection_list=te._task.collections) def test_task_executor_get_handler_prefix(self): te = TaskExecutor( host=MagicMock(), task=MagicMock(), job_vars={}, play_context=MagicMock(), new_stdin=None, loader=DictDataLoader({}), shared_loader_obj=MagicMock(), final_q=MagicMock(), ) action_loader = te._shared_loader_obj.action_loader action_loader.has_plugin.return_value = False action_loader.get.return_value = mock.sentinel.handler action_loader.__contains__.return_value = True mock_connection = MagicMock() mock_templar = MagicMock() action = 'namespace.netconf_sufix' te._task.action = action handler = te._get_action_handler(mock_connection, mock_templar) self.assertIs(mock.sentinel.handler, handler) action_loader.has_plugin.assert_called_once_with( action, collection_list=te._task.collections) action_loader.get.assert_called_once_with( 'netconf', task=te._task, connection=mock_connection, play_context=te._play_context, loader=te._loader, templar=mock_templar, shared_loader_obj=te._shared_loader_obj, collection_list=te._task.collections) def test_task_executor_get_handler_normal(self): te = TaskExecutor( host=MagicMock(), task=MagicMock(), job_vars={}, play_context=MagicMock(), new_stdin=None, loader=DictDataLoader({}), shared_loader_obj=MagicMock(), final_q=MagicMock(), ) action_loader = te._shared_loader_obj.action_loader action_loader.has_plugin.return_value = False action_loader.get.return_value = mock.sentinel.handler action_loader.__contains__.return_value = False mock_connection = MagicMock() mock_templar = MagicMock() action = 'namespace.prefix_sufix' te._task.action = action handler = te._get_action_handler(mock_connection, mock_templar) self.assertIs(mock.sentinel.handler, handler) action_loader.has_plugin.assert_called_once_with( action, collection_list=te._task.collections) action_loader.get.assert_called_once_with( 'normal', task=te._task, connection=mock_connection, play_context=te._play_context, loader=te._loader, templar=mock_templar, shared_loader_obj=te._shared_loader_obj, collection_list=None) def test_task_executor_execute(self): fake_loader = DictDataLoader({}) mock_host = MagicMock() mock_task = MagicMock() mock_task.args = dict() mock_task.retries = 0 mock_task.delay = -1 mock_task.register = 'foo' mock_task.until = None mock_task.changed_when = None mock_task.failed_when = None mock_task.post_validate.return_value = None # mock_task.async_val cannot be left unset, because on Python 3 MagicMock() # > 0 raises a TypeError There are two reasons for using the value 1 # here: on Python 2 comparing MagicMock() > 0 returns True, and the # other reason is that if I specify 0 here, the test fails. ;) mock_task.async_val = 1 mock_task.poll = 0 mock_play_context = MagicMock() mock_play_context.post_validate.return_value = None mock_play_context.update_vars.return_value = None mock_connection = MagicMock() mock_connection.set_host_overrides.return_value = None mock_connection._connect.return_value = None mock_action = MagicMock() mock_queue = MagicMock() shared_loader = None new_stdin = None job_vars = dict(omit="XXXXXXXXXXXXXXXXXXX") te = TaskExecutor( host=mock_host, task=mock_task, job_vars=job_vars, play_context=mock_play_context, new_stdin=new_stdin, loader=fake_loader, shared_loader_obj=shared_loader, final_q=mock_queue, ) te._get_connection = MagicMock(return_value=mock_connection) te._get_action_handler = MagicMock(return_value=mock_action) mock_action.run.return_value = dict(ansible_facts=dict()) res = te._execute() mock_task.changed_when = MagicMock(return_value=AnsibleUnicode("1 == 1")) res = te._execute() mock_task.changed_when = None mock_task.failed_when = MagicMock(return_value=AnsibleUnicode("1 == 1")) res = te._execute() mock_task.failed_when = None mock_task.evaluate_conditional.return_value = False res = te._execute() mock_task.evaluate_conditional.return_value = True mock_task.args = dict(_raw_params='foo.yml', a='foo', b='bar') mock_task.action = 'include' res = te._execute() def test_task_executor_poll_async_result(self): fake_loader = DictDataLoader({}) mock_host = MagicMock() mock_task = MagicMock() mock_task.async_val = 0.1 mock_task.poll = 0.05 mock_play_context = MagicMock() mock_connection = MagicMock() mock_action = MagicMock() mock_queue = MagicMock() shared_loader = MagicMock() shared_loader.action_loader = action_loader new_stdin = None job_vars = dict(omit="XXXXXXXXXXXXXXXXXXX") te = TaskExecutor( host=mock_host, task=mock_task, job_vars=job_vars, play_context=mock_play_context, new_stdin=new_stdin, loader=fake_loader, shared_loader_obj=shared_loader, final_q=mock_queue, ) te._connection = MagicMock() def _get(*args, **kwargs): mock_action = MagicMock() mock_action.run.return_value = dict(stdout='') return mock_action # testing with some bad values in the result passed to poll async, # and with a bad value returned from the mock action with patch.object(action_loader, 'get', _get): mock_templar = MagicMock() res = te._poll_async_result(result=dict(), templar=mock_templar) self.assertIn('failed', res) res = te._poll_async_result(result=dict(ansible_job_id=1), templar=mock_templar) self.assertIn('failed', res) def _get(*args, **kwargs): mock_action = MagicMock() mock_action.run.return_value = dict(finished=1) return mock_action # now testing with good values with patch.object(action_loader, 'get', _get): mock_templar = MagicMock() res = te._poll_async_result(result=dict(ansible_job_id=1), templar=mock_templar) self.assertEqual(res, dict(finished=1)) def test_recursive_remove_omit(self): omit_token = 'POPCORN' data = { 'foo': 'bar', 'baz': 1, 'qux': ['one', 'two', 'three'], 'subdict': { 'remove': 'POPCORN', 'keep': 'not_popcorn', 'subsubdict': { 'remove': 'POPCORN', 'keep': 'not_popcorn', }, 'a_list': ['POPCORN'], }, 'a_list': ['POPCORN'], 'list_of_lists': [ ['some', 'thing'], ], 'list_of_dicts': [ { 'remove': 'POPCORN', } ], } expected = { 'foo': 'bar', 'baz': 1, 'qux': ['one', 'two', 'three'], 'subdict': { 'keep': 'not_popcorn', 'subsubdict': { 'keep': 'not_popcorn', }, 'a_list': ['POPCORN'], }, 'a_list': ['POPCORN'], 'list_of_lists': [ ['some', 'thing'], ], 'list_of_dicts': [{}], } self.assertEqual(remove_omit(data, omit_token), expected)
gpl-3.0
zhouzhenghui/python-for-android
python3-alpha/python3-src/Lib/test/test_imp.py
48
13451
import imp import os import os.path import shutil import sys import unittest from test import support import importlib class LockTests(unittest.TestCase): """Very basic test of import lock functions.""" def verify_lock_state(self, expected): self.assertEqual(imp.lock_held(), expected, "expected imp.lock_held() to be %r" % expected) def testLock(self): LOOPS = 50 # The import lock may already be held, e.g. if the test suite is run # via "import test.autotest". lock_held_at_start = imp.lock_held() self.verify_lock_state(lock_held_at_start) for i in range(LOOPS): imp.acquire_lock() self.verify_lock_state(True) for i in range(LOOPS): imp.release_lock() # The original state should be restored now. self.verify_lock_state(lock_held_at_start) if not lock_held_at_start: try: imp.release_lock() except RuntimeError: pass else: self.fail("release_lock() without lock should raise " "RuntimeError") class ImportTests(unittest.TestCase): def setUp(self): mod = importlib.import_module('test.encoded_modules') self.test_strings = mod.test_strings self.test_path = mod.__path__ def test_import_encoded_module(self): for modname, encoding, teststr in self.test_strings: mod = importlib.import_module('test.encoded_modules.' 'module_' + modname) self.assertEqual(teststr, mod.test) def test_find_module_encoding(self): for mod, encoding, _ in self.test_strings: with imp.find_module('module_' + mod, self.test_path)[0] as fd: self.assertEqual(fd.encoding, encoding) def test_issue1267(self): for mod, encoding, _ in self.test_strings: fp, filename, info = imp.find_module('module_' + mod, self.test_path) with fp: self.assertNotEqual(fp, None) self.assertEqual(fp.encoding, encoding) self.assertEqual(fp.tell(), 0) self.assertEqual(fp.readline(), '# test %s encoding\n' % encoding) fp, filename, info = imp.find_module("tokenize") with fp: self.assertNotEqual(fp, None) self.assertEqual(fp.encoding, "utf-8") self.assertEqual(fp.tell(), 0) self.assertEqual(fp.readline(), '"""Tokenization help for Python programs.\n') def test_issue3594(self): temp_mod_name = 'test_imp_helper' sys.path.insert(0, '.') try: with open(temp_mod_name + '.py', 'w') as file: file.write("# coding: cp1252\nu = 'test.test_imp'\n") file, filename, info = imp.find_module(temp_mod_name) file.close() self.assertEqual(file.encoding, 'cp1252') finally: del sys.path[0] support.unlink(temp_mod_name + '.py') support.unlink(temp_mod_name + '.pyc') support.unlink(temp_mod_name + '.pyo') def test_issue5604(self): # Test cannot cover imp.load_compiled function. # Martin von Loewis note what shared library cannot have non-ascii # character because init_xxx function cannot be compiled # and issue never happens for dynamic modules. # But sources modified to follow generic way for processing pathes. # the return encoding could be uppercase or None fs_encoding = sys.getfilesystemencoding() # covers utf-8 and Windows ANSI code pages # one non-space symbol from every page # (http://en.wikipedia.org/wiki/Code_page) known_locales = { 'utf-8' : b'\xc3\xa4', 'cp1250' : b'\x8C', 'cp1251' : b'\xc0', 'cp1252' : b'\xc0', 'cp1253' : b'\xc1', 'cp1254' : b'\xc0', 'cp1255' : b'\xe0', 'cp1256' : b'\xe0', 'cp1257' : b'\xc0', 'cp1258' : b'\xc0', } if sys.platform == 'darwin': self.assertEqual(fs_encoding, 'utf-8') # Mac OS X uses the Normal Form D decomposition # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html special_char = b'a\xcc\x88' else: special_char = known_locales.get(fs_encoding) if not special_char: self.skipTest("can't run this test with %s as filesystem encoding" % fs_encoding) decoded_char = special_char.decode(fs_encoding) temp_mod_name = 'test_imp_helper_' + decoded_char test_package_name = 'test_imp_helper_package_' + decoded_char init_file_name = os.path.join(test_package_name, '__init__.py') try: # if the curdir is not in sys.path the test fails when run with # ./python ./Lib/test/regrtest.py test_imp sys.path.insert(0, os.curdir) with open(temp_mod_name + '.py', 'w') as file: file.write('a = 1\n') file, filename, info = imp.find_module(temp_mod_name) with file: self.assertIsNotNone(file) self.assertTrue(filename[:-3].endswith(temp_mod_name)) self.assertEqual(info[0], '.py') self.assertEqual(info[1], 'U') self.assertEqual(info[2], imp.PY_SOURCE) mod = imp.load_module(temp_mod_name, file, filename, info) self.assertEqual(mod.a, 1) mod = imp.load_source(temp_mod_name, temp_mod_name + '.py') self.assertEqual(mod.a, 1) mod = imp.load_compiled( temp_mod_name, imp.cache_from_source(temp_mod_name + '.py')) self.assertEqual(mod.a, 1) if not os.path.exists(test_package_name): os.mkdir(test_package_name) with open(init_file_name, 'w') as file: file.write('b = 2\n') package = imp.load_package(test_package_name, test_package_name) self.assertEqual(package.b, 2) finally: del sys.path[0] for ext in ('.py', '.pyc', '.pyo'): support.unlink(temp_mod_name + ext) support.unlink(init_file_name + ext) support.rmtree(test_package_name) def test_issue9319(self): path = os.path.dirname(__file__) self.assertRaises(SyntaxError, imp.find_module, "badsyntax_pep3120", [path]) class ReloadTests(unittest.TestCase): """Very basic tests to make sure that imp.reload() operates just like reload().""" def test_source(self): # XXX (ncoghlan): It would be nice to use test.support.CleanImport # here, but that breaks because the os module registers some # handlers in copy_reg on import. Since CleanImport doesn't # revert that registration, the module is left in a broken # state after reversion. Reinitialising the module contents # and just reverting os.environ to its previous state is an OK # workaround with support.EnvironmentVarGuard(): import os imp.reload(os) def test_extension(self): with support.CleanImport('time'): import time imp.reload(time) def test_builtin(self): with support.CleanImport('marshal'): import marshal imp.reload(marshal) class PEP3147Tests(unittest.TestCase): """Tests of PEP 3147.""" tag = imp.get_tag() def test_cache_from_source(self): # Given the path to a .py file, return the path to its PEP 3147 # defined .pyc file (i.e. under __pycache__). self.assertEqual( imp.cache_from_source('/foo/bar/baz/qux.py', True), '/foo/bar/baz/__pycache__/qux.{}.pyc'.format(self.tag)) def test_cache_from_source_optimized(self): # Given the path to a .py file, return the path to its PEP 3147 # defined .pyo file (i.e. under __pycache__). self.assertEqual( imp.cache_from_source('/foo/bar/baz/qux.py', False), '/foo/bar/baz/__pycache__/qux.{}.pyo'.format(self.tag)) def test_cache_from_source_cwd(self): self.assertEqual(imp.cache_from_source('foo.py', True), os.sep.join(('__pycache__', 'foo.{}.pyc'.format(self.tag)))) def test_cache_from_source_override(self): # When debug_override is not None, it can be any true-ish or false-ish # value. self.assertEqual( imp.cache_from_source('/foo/bar/baz.py', []), '/foo/bar/__pycache__/baz.{}.pyo'.format(self.tag)) self.assertEqual( imp.cache_from_source('/foo/bar/baz.py', [17]), '/foo/bar/__pycache__/baz.{}.pyc'.format(self.tag)) # However if the bool-ishness can't be determined, the exception # propagates. class Bearish: def __bool__(self): raise RuntimeError self.assertRaises( RuntimeError, imp.cache_from_source, '/foo/bar/baz.py', Bearish()) @unittest.skipIf(os.altsep is None, 'test meaningful only where os.altsep is defined') def test_altsep_cache_from_source(self): # Windows path and PEP 3147. self.assertEqual( imp.cache_from_source('\\foo\\bar\\baz\\qux.py', True), '\\foo\\bar\\baz\\__pycache__\\qux.{}.pyc'.format(self.tag)) @unittest.skipIf(os.altsep is None, 'test meaningful only where os.altsep is defined') def test_altsep_and_sep_cache_from_source(self): # Windows path and PEP 3147 where altsep is right of sep. self.assertEqual( imp.cache_from_source('\\foo\\bar/baz\\qux.py', True), '\\foo\\bar/baz\\__pycache__\\qux.{}.pyc'.format(self.tag)) @unittest.skipIf(os.altsep is None, 'test meaningful only where os.altsep is defined') def test_sep_altsep_and_sep_cache_from_source(self): # Windows path and PEP 3147 where sep is right of altsep. self.assertEqual( imp.cache_from_source('\\foo\\bar\\baz/qux.py', True), '\\foo\\bar\\baz/__pycache__/qux.{}.pyc'.format(self.tag)) def test_source_from_cache(self): # Given the path to a PEP 3147 defined .pyc file, return the path to # its source. This tests the good path. self.assertEqual(imp.source_from_cache( '/foo/bar/baz/__pycache__/qux.{}.pyc'.format(self.tag)), '/foo/bar/baz/qux.py') def test_source_from_cache_bad_path(self): # When the path to a pyc file is not in PEP 3147 format, a ValueError # is raised. self.assertRaises( ValueError, imp.source_from_cache, '/foo/bar/bazqux.pyc') def test_source_from_cache_no_slash(self): # No slashes at all in path -> ValueError self.assertRaises( ValueError, imp.source_from_cache, 'foo.cpython-32.pyc') def test_source_from_cache_too_few_dots(self): # Too few dots in final path component -> ValueError self.assertRaises( ValueError, imp.source_from_cache, '__pycache__/foo.pyc') def test_source_from_cache_too_many_dots(self): # Too many dots in final path component -> ValueError self.assertRaises( ValueError, imp.source_from_cache, '__pycache__/foo.cpython-32.foo.pyc') def test_source_from_cache_no__pycache__(self): # Another problem with the path -> ValueError self.assertRaises( ValueError, imp.source_from_cache, '/foo/bar/foo.cpython-32.foo.pyc') def test_package___file__(self): # Test that a package's __file__ points to the right source directory. os.mkdir('pep3147') sys.path.insert(0, os.curdir) def cleanup(): if sys.path[0] == os.curdir: del sys.path[0] shutil.rmtree('pep3147') self.addCleanup(cleanup) # Touch the __init__.py file. with open('pep3147/__init__.py', 'w'): pass m = __import__('pep3147') # Ensure we load the pyc file. support.forget('pep3147') m = __import__('pep3147') self.assertEqual(m.__file__, os.sep.join(('.', 'pep3147', '__init__.py'))) class NullImporterTests(unittest.TestCase): @unittest.skipIf(support.TESTFN_UNENCODABLE is None, "Need an undecodeable filename") def test_unencodeable(self): name = support.TESTFN_UNENCODABLE os.mkdir(name) try: self.assertRaises(ImportError, imp.NullImporter, name) finally: os.rmdir(name) def test_main(): tests = [ ImportTests, PEP3147Tests, ReloadTests, NullImporterTests, ] try: import _thread except ImportError: pass else: tests.append(LockTests) support.run_unittest(*tests) if __name__ == "__main__": test_main()
apache-2.0
miguelparaiso/OdooAccessible
addons/mail/mail_message.py
141
47462
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2010-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 email.header import decode_header from email.utils import formataddr from openerp import SUPERUSER_ID, api from openerp.osv import osv, orm, fields from openerp.tools import html_email_clean from openerp.tools.translate import _ from HTMLParser import HTMLParser _logger = logging.getLogger(__name__) """ Some tools for parsing / creating email fields """ def decode(text): """Returns unicode() string conversion of the the given encoded smtp header text""" if text: text = decode_header(text.replace('\r', '')) # The joining space will not be needed as of Python 3.3 # See https://hg.python.org/cpython/rev/8c03fe231877 return ' '.join([tools.ustr(x[0], x[1]) for x in text]) class MLStripper(HTMLParser): def __init__(self): self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data() class mail_message(osv.Model): """ Messages model: system notification (replacing res.log notifications), comments (OpenChatter discussion) and incoming emails. """ _name = 'mail.message' _description = 'Message' _inherit = ['ir.needaction_mixin'] _order = 'id desc' _rec_name = 'record_name' _message_read_limit = 30 _message_read_fields = ['id', 'parent_id', 'model', 'res_id', 'body', 'subject', 'date', 'to_read', 'email_from', 'type', 'vote_user_ids', 'attachment_ids', 'author_id', 'partner_ids', 'record_name'] _message_record_name_length = 18 _message_read_more_limit = 1024 def default_get(self, cr, uid, fields, context=None): # protection for `default_type` values leaking from menu action context (e.g. for invoices) if context and context.get('default_type') and context.get('default_type') not in [ val[0] for val in self._columns['type'].selection]: context = dict(context, default_type=None) return super(mail_message, self).default_get(cr, uid, fields, context=context) def _get_to_read(self, cr, uid, ids, name, arg, context=None): """ Compute if the message is unread by the current user. """ res = dict((id, False) for id in ids) partner_id = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id notif_obj = self.pool.get('mail.notification') notif_ids = notif_obj.search(cr, uid, [ ('partner_id', 'in', [partner_id]), ('message_id', 'in', ids), ('is_read', '=', False), ], context=context) for notif in notif_obj.browse(cr, uid, notif_ids, context=context): res[notif.message_id.id] = True return res def _search_to_read(self, cr, uid, obj, name, domain, context=None): """ Search for messages to read by the current user. Condition is inversed because we search unread message on a is_read column. """ return ['&', ('notification_ids.partner_id.user_ids', 'in', [uid]), ('notification_ids.is_read', '=', not domain[0][2])] def _get_starred(self, cr, uid, ids, name, arg, context=None): """ Compute if the message is unread by the current user. """ res = dict((id, False) for id in ids) partner_id = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id notif_obj = self.pool.get('mail.notification') notif_ids = notif_obj.search(cr, uid, [ ('partner_id', 'in', [partner_id]), ('message_id', 'in', ids), ('starred', '=', True), ], context=context) for notif in notif_obj.browse(cr, uid, notif_ids, context=context): res[notif.message_id.id] = True return res def _search_starred(self, cr, uid, obj, name, domain, context=None): """ Search for starred messages by the current user.""" return ['&', ('notification_ids.partner_id.user_ids', 'in', [uid]), ('notification_ids.starred', '=', domain[0][2])] _columns = { 'type': fields.selection([ ('email', 'Email'), ('comment', 'Comment'), ('notification', 'System notification'), ], 'Type', size=12, help="Message type: email for email message, notification for system "\ "message, comment for other messages such as user replies"), 'email_from': fields.char('From', help="Email address of the sender. This field is set when no matching partner is found for incoming emails."), 'reply_to': fields.char('Reply-To', help='Reply email address. Setting the reply_to bypasses the automatic thread creation.'), 'no_auto_thread': fields.boolean('No threading for answers', help='Answers do not go in the original document\' discussion thread. This has an impact on the generated message-id.'), 'author_id': fields.many2one('res.partner', 'Author', select=1, ondelete='set null', help="Author of the message. If not set, email_from may hold an email address that did not match any partner."), 'author_avatar': fields.related('author_id', 'image_small', type="binary", string="Author's Avatar"), 'partner_ids': fields.many2many('res.partner', string='Recipients'), 'notified_partner_ids': fields.many2many('res.partner', 'mail_notification', 'message_id', 'partner_id', 'Notified partners', help='Partners that have a notification pushing this message in their mailboxes'), 'attachment_ids': fields.many2many('ir.attachment', 'message_attachment_rel', 'message_id', 'attachment_id', 'Attachments'), 'parent_id': fields.many2one('mail.message', 'Parent Message', select=True, ondelete='set null', help="Initial thread message."), 'child_ids': fields.one2many('mail.message', 'parent_id', 'Child Messages'), 'model': fields.char('Related Document Model', size=128, select=1), 'res_id': fields.integer('Related Document ID', select=1), 'record_name': fields.char('Message Record Name', help="Name get of the related document."), 'notification_ids': fields.one2many('mail.notification', 'message_id', string='Notifications', auto_join=True, help='Technical field holding the message notifications. Use notified_partner_ids to access notified partners.'), 'subject': fields.char('Subject'), 'date': fields.datetime('Date'), 'message_id': fields.char('Message-Id', help='Message unique identifier', select=1, readonly=1, copy=False), 'body': fields.html('Contents', help='Automatically sanitized HTML contents'), 'to_read': fields.function(_get_to_read, fnct_search=_search_to_read, type='boolean', string='To read', help='Current user has an unread notification linked to this message'), 'starred': fields.function(_get_starred, fnct_search=_search_starred, type='boolean', string='Starred', help='Current user has a starred notification linked to this message'), 'subtype_id': fields.many2one('mail.message.subtype', 'Subtype', ondelete='set null', select=1,), 'vote_user_ids': fields.many2many('res.users', 'mail_vote', 'message_id', 'user_id', string='Votes', help='Users that voted for this message'), 'mail_server_id': fields.many2one('ir.mail_server', 'Outgoing mail server', readonly=1), } def _needaction_domain_get(self, cr, uid, context=None): return [('to_read', '=', True)] def _get_default_from(self, cr, uid, context=None): this = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context) if this.alias_name and this.alias_domain: return formataddr((this.name, '%s@%s' % (this.alias_name, this.alias_domain))) elif this.email: return formataddr((this.name, this.email)) raise osv.except_osv(_('Invalid Action!'), _("Unable to send email, please configure the sender's email address or alias.")) def _get_default_author(self, cr, uid, context=None): return self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id _defaults = { 'type': 'email', 'date': fields.datetime.now, 'author_id': lambda self, cr, uid, ctx=None: self._get_default_author(cr, uid, ctx), 'body': '', 'email_from': lambda self, cr, uid, ctx=None: self._get_default_from(cr, uid, ctx), } #------------------------------------------------------ # Vote/Like #------------------------------------------------------ def vote_toggle(self, cr, uid, ids, context=None): ''' Toggles vote. Performed using read to avoid access rights issues. Done as SUPERUSER_ID because uid may vote for a message he cannot modify. ''' for message in self.read(cr, uid, ids, ['vote_user_ids'], context=context): new_has_voted = not (uid in message.get('vote_user_ids')) if new_has_voted: self.write(cr, SUPERUSER_ID, message.get('id'), {'vote_user_ids': [(4, uid)]}, context=context) else: self.write(cr, SUPERUSER_ID, message.get('id'), {'vote_user_ids': [(3, uid)]}, context=context) return new_has_voted or False #------------------------------------------------------ # download an attachment #------------------------------------------------------ def download_attachment(self, cr, uid, id_message, attachment_id, context=None): """ Return the content of linked attachments. """ # this will fail if you cannot read the message message_values = self.read(cr, uid, [id_message], ['attachment_ids'], context=context)[0] if attachment_id in message_values['attachment_ids']: attachment = self.pool.get('ir.attachment').browse(cr, SUPERUSER_ID, attachment_id, context=context) if attachment.datas and attachment.datas_fname: return { 'base64': attachment.datas, 'filename': attachment.datas_fname, } return False #------------------------------------------------------ # Notification API #------------------------------------------------------ @api.cr_uid_ids_context def set_message_read(self, cr, uid, msg_ids, read, create_missing=True, context=None): """ Set messages as (un)read. Technically, the notifications related to uid are set to (un)read. If for some msg_ids there are missing notifications (i.e. due to load more or thread parent fetching), they are created. :param bool read: set notification as (un)read :param bool create_missing: create notifications for missing entries (i.e. when acting on displayed messages not notified) :return number of message mark as read """ notification_obj = self.pool.get('mail.notification') user_pid = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id domain = [('partner_id', '=', user_pid), ('message_id', 'in', msg_ids)] if not create_missing: domain += [('is_read', '=', not read)] notif_ids = notification_obj.search(cr, uid, domain, context=context) # all message have notifications: already set them as (un)read if len(notif_ids) == len(msg_ids) or not create_missing: notification_obj.write(cr, uid, notif_ids, {'is_read': read}, context=context) return len(notif_ids) # some messages do not have notifications: find which one, create notification, update read status notified_msg_ids = [notification.message_id.id for notification in notification_obj.browse(cr, uid, notif_ids, context=context)] to_create_msg_ids = list(set(msg_ids) - set(notified_msg_ids)) for msg_id in to_create_msg_ids: notification_obj.create(cr, uid, {'partner_id': user_pid, 'is_read': read, 'message_id': msg_id}, context=context) notification_obj.write(cr, uid, notif_ids, {'is_read': read}, context=context) return len(notif_ids) @api.cr_uid_ids_context def set_message_starred(self, cr, uid, msg_ids, starred, create_missing=True, context=None): """ Set messages as (un)starred. Technically, the notifications related to uid are set to (un)starred. :param bool starred: set notification as (un)starred :param bool create_missing: create notifications for missing entries (i.e. when acting on displayed messages not notified) """ notification_obj = self.pool.get('mail.notification') user_pid = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id domain = [('partner_id', '=', user_pid), ('message_id', 'in', msg_ids)] if not create_missing: domain += [('starred', '=', not starred)] values = { 'starred': starred } if starred: values['is_read'] = False notif_ids = notification_obj.search(cr, uid, domain, context=context) # all message have notifications: already set them as (un)starred if len(notif_ids) == len(msg_ids) or not create_missing: notification_obj.write(cr, uid, notif_ids, values, context=context) return starred # some messages do not have notifications: find which one, create notification, update starred status notified_msg_ids = [notification.message_id.id for notification in notification_obj.browse(cr, uid, notif_ids, context=context)] to_create_msg_ids = list(set(msg_ids) - set(notified_msg_ids)) for msg_id in to_create_msg_ids: notification_obj.create(cr, uid, dict(values, partner_id=user_pid, message_id=msg_id), context=context) notification_obj.write(cr, uid, notif_ids, values, context=context) return starred #------------------------------------------------------ # Message loading for web interface #------------------------------------------------------ def _message_read_dict_postprocess(self, cr, uid, messages, message_tree, context=None): """ Post-processing on values given by message_read. This method will handle partners in batch to avoid doing numerous queries. :param list messages: list of message, as get_dict result :param dict message_tree: {[msg.id]: msg browse record} """ res_partner_obj = self.pool.get('res.partner') ir_attachment_obj = self.pool.get('ir.attachment') pid = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id # 1. Aggregate partners (author_id and partner_ids) and attachments partner_ids = set() attachment_ids = set() for key, message in message_tree.iteritems(): if message.author_id: partner_ids |= set([message.author_id.id]) if message.subtype_id and message.notified_partner_ids: # take notified people of message with a subtype partner_ids |= set([partner.id for partner in message.notified_partner_ids]) elif not message.subtype_id and message.partner_ids: # take specified people of message without a subtype (log) partner_ids |= set([partner.id for partner in message.partner_ids]) if message.attachment_ids: attachment_ids |= set([attachment.id for attachment in message.attachment_ids]) # Read partners as SUPERUSER -> display the names like classic m2o even if no access partners = res_partner_obj.name_get(cr, SUPERUSER_ID, list(partner_ids), context=context) partner_tree = dict((partner[0], partner) for partner in partners) # 2. Attachments as SUPERUSER, because could receive msg and attachments for doc uid cannot see attachments = ir_attachment_obj.read(cr, SUPERUSER_ID, list(attachment_ids), ['id', 'datas_fname', 'name', 'file_type_icon'], context=context) attachments_tree = dict((attachment['id'], { 'id': attachment['id'], 'filename': attachment['datas_fname'], 'name': attachment['name'], 'file_type_icon': attachment['file_type_icon'], }) for attachment in attachments) # 3. Update message dictionaries for message_dict in messages: message_id = message_dict.get('id') message = message_tree[message_id] if message.author_id: author = partner_tree[message.author_id.id] else: author = (0, message.email_from) partner_ids = [] if message.subtype_id: partner_ids = [partner_tree[partner.id] for partner in message.notified_partner_ids if partner.id in partner_tree] else: partner_ids = [partner_tree[partner.id] for partner in message.partner_ids if partner.id in partner_tree] attachment_ids = [] for attachment in message.attachment_ids: if attachment.id in attachments_tree: attachment_ids.append(attachments_tree[attachment.id]) message_dict.update({ 'is_author': pid == author[0], 'author_id': author, 'partner_ids': partner_ids, 'attachment_ids': attachment_ids, 'user_pid': pid }) return True def _message_read_dict(self, cr, uid, message, parent_id=False, context=None): """ Return a dict representation of the message. This representation is used in the JS client code, to display the messages. Partners and attachments related stuff will be done in post-processing in batch. :param dict message: mail.message browse record """ # private message: no model, no res_id is_private = False if not message.model or not message.res_id: is_private = True # votes and favorites: res.users ids, no prefetching should be done vote_nb = len(message.vote_user_ids) has_voted = uid in [user.id for user in message.vote_user_ids] try: if parent_id: max_length = 300 else: max_length = 100 body_short = html_email_clean(message.body, remove=False, shorten=True, max_length=max_length) except Exception: body_short = '<p><b>Encoding Error : </b><br/>Unable to convert this message (id: %s).</p>' % message.id _logger.exception(Exception) return {'id': message.id, 'type': message.type, 'subtype': message.subtype_id.name if message.subtype_id else False, 'body': message.body, 'body_short': body_short, 'model': message.model, 'res_id': message.res_id, 'record_name': message.record_name, 'subject': message.subject, 'date': message.date, 'to_read': message.to_read, 'parent_id': parent_id, 'is_private': is_private, 'author_id': False, 'author_avatar': message.author_avatar, 'is_author': False, 'partner_ids': [], 'vote_nb': vote_nb, 'has_voted': has_voted, 'is_favorite': message.starred, 'attachment_ids': [], } def _message_read_add_expandables(self, cr, uid, messages, message_tree, parent_tree, message_unload_ids=[], thread_level=0, domain=[], parent_id=False, context=None): """ Create expandables for message_read, to load new messages. 1. get the expandable for new threads if display is flat (thread_level == 0): fetch message_ids < min(already displayed ids), because we want a flat display, ordered by id else: fetch message_ids that are not childs of already displayed messages 2. get the expandables for new messages inside threads if display is not flat for each thread header, search for its childs for each hole in the child list based on message displayed, create an expandable :param list messages: list of message structure for the Chatter widget to which expandables are added :param dict message_tree: dict [id]: browse record of this message :param dict parent_tree: dict [parent_id]: [child_ids] :param list message_unload_ids: list of message_ids we do not want to load :return bool: True """ def _get_expandable(domain, message_nb, parent_id, max_limit): return { 'domain': domain, 'nb_messages': message_nb, 'type': 'expandable', 'parent_id': parent_id, 'max_limit': max_limit, } if not messages: return True message_ids = sorted(message_tree.keys()) # 1. get the expandable for new threads if thread_level == 0: exp_domain = domain + [('id', '<', min(message_unload_ids + message_ids))] else: exp_domain = domain + ['!', ('id', 'child_of', message_unload_ids + parent_tree.keys())] more_count = self.search(cr, uid, exp_domain, context=context, limit=1) if more_count: # inside a thread: prepend if parent_id: messages.insert(0, _get_expandable(exp_domain, -1, parent_id, True)) # new threads: append else: messages.append(_get_expandable(exp_domain, -1, parent_id, True)) # 2. get the expandables for new messages inside threads if display is not flat if thread_level == 0: return True for message_id in message_ids: message = message_tree[message_id] # generate only for thread header messages (TDE note: parent_id may be False is uid cannot see parent_id, seems ok) if message.parent_id: continue # check there are message for expandable child_ids = set([child.id for child in message.child_ids]) - set(message_unload_ids) child_ids = sorted(list(child_ids), reverse=True) if not child_ids: continue # make groups of unread messages id_min, id_max, nb = max(child_ids), 0, 0 for child_id in child_ids: if not child_id in message_ids: nb += 1 if id_min > child_id: id_min = child_id if id_max < child_id: id_max = child_id elif nb > 0: exp_domain = [('id', '>=', id_min), ('id', '<=', id_max), ('id', 'child_of', message_id)] idx = [msg.get('id') for msg in messages].index(child_id) + 1 # messages.append(_get_expandable(exp_domain, nb, message_id, False)) messages.insert(idx, _get_expandable(exp_domain, nb, message_id, False)) id_min, id_max, nb = max(child_ids), 0, 0 else: id_min, id_max, nb = max(child_ids), 0, 0 if nb > 0: exp_domain = [('id', '>=', id_min), ('id', '<=', id_max), ('id', 'child_of', message_id)] idx = [msg.get('id') for msg in messages].index(message_id) + 1 # messages.append(_get_expandable(exp_domain, nb, message_id, id_min)) messages.insert(idx, _get_expandable(exp_domain, nb, message_id, False)) return True @api.cr_uid_context def message_read(self, cr, uid, ids=None, domain=None, message_unload_ids=None, thread_level=0, context=None, parent_id=False, limit=None): """ Read messages from mail.message, and get back a list of structured messages to be displayed as discussion threads. If IDs is set, fetch these records. Otherwise use the domain to fetch messages. After having fetch messages, their ancestors will be added to obtain well formed threads, if uid has access to them. After reading the messages, expandable messages are added in the message list (see ``_message_read_add_expandables``). It consists in messages holding the 'read more' data: number of messages to read, domain to apply. :param list ids: optional IDs to fetch :param list domain: optional domain for searching ids if ids not set :param list message_unload_ids: optional ids we do not want to fetch, because i.e. they are already displayed somewhere :param int parent_id: context of parent_id - if parent_id reached when adding ancestors, stop going further in the ancestor search - if set in flat mode, ancestor_id is set to parent_id :param int limit: number of messages to fetch, before adding the ancestors and expandables :return list: list of message structure for the Chatter widget """ assert thread_level in [0, 1], 'message_read() thread_level should be 0 (flat) or 1 (1 level of thread); given %s.' % thread_level domain = domain if domain is not None else [] message_unload_ids = message_unload_ids if message_unload_ids is not None else [] if message_unload_ids: domain += [('id', 'not in', message_unload_ids)] limit = limit or self._message_read_limit message_tree = {} message_list = [] parent_tree = {} # no specific IDS given: fetch messages according to the domain, add their parents if uid has access to if ids is None: ids = self.search(cr, uid, domain, context=context, limit=limit) # fetch parent if threaded, sort messages for message in self.browse(cr, uid, ids, context=context): message_id = message.id if message_id in message_tree: continue message_tree[message_id] = message # find parent_id if thread_level == 0: tree_parent_id = parent_id else: tree_parent_id = message_id parent = message while parent.parent_id and parent.parent_id.id != parent_id: parent = parent.parent_id tree_parent_id = parent.id if not parent.id in message_tree: message_tree[parent.id] = parent # newest messages first parent_tree.setdefault(tree_parent_id, []) if tree_parent_id != message_id: parent_tree[tree_parent_id].append(self._message_read_dict(cr, uid, message_tree[message_id], parent_id=tree_parent_id, context=context)) if thread_level: for key, message_id_list in parent_tree.iteritems(): message_id_list.sort(key=lambda item: item['id']) message_id_list.insert(0, self._message_read_dict(cr, uid, message_tree[key], context=context)) # create final ordered message_list based on parent_tree parent_list = parent_tree.items() parent_list = sorted(parent_list, key=lambda item: max([msg.get('id') for msg in item[1]]) if item[1] else item[0], reverse=True) message_list = [message for (key, msg_list) in parent_list for message in msg_list] # get the child expandable messages for the tree self._message_read_dict_postprocess(cr, uid, message_list, message_tree, context=context) self._message_read_add_expandables(cr, uid, message_list, message_tree, parent_tree, thread_level=thread_level, message_unload_ids=message_unload_ids, domain=domain, parent_id=parent_id, context=context) return message_list #------------------------------------------------------ # mail_message internals #------------------------------------------------------ def init(self, cr): cr.execute("""SELECT indexname FROM pg_indexes WHERE indexname = 'mail_message_model_res_id_idx'""") if not cr.fetchone(): cr.execute("""CREATE INDEX mail_message_model_res_id_idx ON mail_message (model, res_id)""") def _find_allowed_model_wise(self, cr, uid, doc_model, doc_dict, context=None): doc_ids = doc_dict.keys() ctx = dict(context or {}, active_test=False) allowed_doc_ids = self.pool[doc_model].search(cr, uid, [('id', 'in', doc_ids)], context=ctx) return set([message_id for allowed_doc_id in allowed_doc_ids for message_id in doc_dict[allowed_doc_id]]) def _find_allowed_doc_ids(self, cr, uid, model_ids, context=None): model_access_obj = self.pool.get('ir.model.access') allowed_ids = set() for doc_model, doc_dict in model_ids.iteritems(): if not model_access_obj.check(cr, uid, doc_model, 'read', False): continue allowed_ids |= self._find_allowed_model_wise(cr, uid, doc_model, doc_dict, context=context) return allowed_ids def _search(self, cr, uid, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None): """ Override that adds specific access rights of mail.message, to remove ids uid could not see according to our custom rules. Please refer to check_access_rule for more details about those rules. After having received ids of a classic search, keep only: - if author_id == pid, uid is the author, OR - a notification (id, pid) exists, uid has been notified, OR - uid have read access to the related document is model, res_id - otherwise: remove the id """ # Rules do not apply to administrator if uid == SUPERUSER_ID: return super(mail_message, self)._search( cr, uid, args, offset=offset, limit=limit, order=order, context=context, count=count, access_rights_uid=access_rights_uid) # Perform a super with count as False, to have the ids, not a counter ids = super(mail_message, self)._search( cr, uid, args, offset=offset, limit=limit, order=order, context=context, count=False, access_rights_uid=access_rights_uid) if not ids and count: return 0 elif not ids: return ids pid = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=context).partner_id.id author_ids, partner_ids, allowed_ids = set([]), set([]), set([]) model_ids = {} # check read access rights before checking the actual rules on the given ids super(mail_message, self).check_access_rights(cr, access_rights_uid or uid, 'read') cr.execute("""SELECT DISTINCT m.id, m.model, m.res_id, m.author_id, n.partner_id FROM "%s" m LEFT JOIN "mail_notification" n ON n.message_id=m.id AND n.partner_id = (%%s) WHERE m.id = ANY (%%s)""" % self._table, (pid, ids,)) for id, rmod, rid, author_id, partner_id in cr.fetchall(): if author_id == pid: author_ids.add(id) elif partner_id == pid: partner_ids.add(id) elif rmod and rid: model_ids.setdefault(rmod, {}).setdefault(rid, set()).add(id) allowed_ids = self._find_allowed_doc_ids(cr, uid, model_ids, context=context) final_ids = author_ids | partner_ids | allowed_ids if count: return len(final_ids) else: # re-construct a list based on ids, because set did not keep the original order id_list = [id for id in ids if id in final_ids] return id_list def check_access_rule(self, cr, uid, ids, operation, context=None): """ Access rules of mail.message: - read: if - author_id == pid, uid is the author, OR - mail_notification (id, pid) exists, uid has been notified, OR - uid have read access to the related document if model, res_id - otherwise: raise - create: if - no model, no res_id, I create a private message OR - pid in message_follower_ids if model, res_id OR - mail_notification (parent_id.id, pid) exists, uid has been notified of the parent, OR - uid have write or create access on the related document if model, res_id, OR - otherwise: raise - write: if - author_id == pid, uid is the author, OR - uid has write or create access on the related document if model, res_id - otherwise: raise - unlink: if - uid has write or create access on the related document if model, res_id - otherwise: raise """ def _generate_model_record_ids(msg_val, msg_ids): """ :param model_record_ids: {'model': {'res_id': (msg_id, msg_id)}, ... } :param message_values: {'msg_id': {'model': .., 'res_id': .., 'author_id': ..}} """ model_record_ids = {} for id in msg_ids: vals = msg_val.get(id, {}) if vals.get('model') and vals.get('res_id'): model_record_ids.setdefault(vals['model'], set()).add(vals['res_id']) return model_record_ids if uid == SUPERUSER_ID: return if isinstance(ids, (int, long)): ids = [ids] not_obj = self.pool.get('mail.notification') fol_obj = self.pool.get('mail.followers') partner_id = self.pool['res.users'].browse(cr, SUPERUSER_ID, uid, context=None).partner_id.id # Read mail_message.ids to have their values message_values = dict((res_id, {}) for res_id in ids) cr.execute('SELECT DISTINCT id, model, res_id, author_id, parent_id FROM "%s" WHERE id = ANY (%%s)' % self._table, (ids,)) for id, rmod, rid, author_id, parent_id in cr.fetchall(): message_values[id] = {'model': rmod, 'res_id': rid, 'author_id': author_id, 'parent_id': parent_id} # Author condition (READ, WRITE, CREATE (private)) -> could become an ir.rule ? author_ids = [] if operation == 'read' or operation == 'write': author_ids = [mid for mid, message in message_values.iteritems() if message.get('author_id') and message.get('author_id') == partner_id] elif operation == 'create': author_ids = [mid for mid, message in message_values.iteritems() if not message.get('model') and not message.get('res_id')] # Parent condition, for create (check for received notifications for the created message parent) notified_ids = [] if operation == 'create': parent_ids = [message.get('parent_id') for mid, message in message_values.iteritems() if message.get('parent_id')] not_ids = not_obj.search(cr, SUPERUSER_ID, [('message_id.id', 'in', parent_ids), ('partner_id', '=', partner_id)], context=context) not_parent_ids = [notif.message_id.id for notif in not_obj.browse(cr, SUPERUSER_ID, not_ids, context=context)] notified_ids += [mid for mid, message in message_values.iteritems() if message.get('parent_id') in not_parent_ids] # Notification condition, for read (check for received notifications and create (in message_follower_ids)) -> could become an ir.rule, but not till we do not have a many2one variable field other_ids = set(ids).difference(set(author_ids), set(notified_ids)) model_record_ids = _generate_model_record_ids(message_values, other_ids) if operation == 'read': not_ids = not_obj.search(cr, SUPERUSER_ID, [ ('partner_id', '=', partner_id), ('message_id', 'in', ids), ], context=context) notified_ids = [notification.message_id.id for notification in not_obj.browse(cr, SUPERUSER_ID, not_ids, context=context)] elif operation == 'create': for doc_model, doc_ids in model_record_ids.items(): fol_ids = fol_obj.search(cr, SUPERUSER_ID, [ ('res_model', '=', doc_model), ('res_id', 'in', list(doc_ids)), ('partner_id', '=', partner_id), ], context=context) fol_mids = [follower.res_id for follower in fol_obj.browse(cr, SUPERUSER_ID, fol_ids, context=context)] notified_ids += [mid for mid, message in message_values.iteritems() if message.get('model') == doc_model and message.get('res_id') in fol_mids] # CRUD: Access rights related to the document other_ids = other_ids.difference(set(notified_ids)) model_record_ids = _generate_model_record_ids(message_values, other_ids) document_related_ids = [] for model, doc_ids in model_record_ids.items(): model_obj = self.pool[model] mids = model_obj.exists(cr, uid, list(doc_ids)) if hasattr(model_obj, 'check_mail_message_access'): model_obj.check_mail_message_access(cr, uid, mids, operation, context=context) else: self.pool['mail.thread'].check_mail_message_access(cr, uid, mids, operation, model_obj=model_obj, context=context) document_related_ids += [mid for mid, message in message_values.iteritems() if message.get('model') == model and message.get('res_id') in mids] # Calculate remaining ids: if not void, raise an error other_ids = other_ids.difference(set(document_related_ids)) if not other_ids: return raise orm.except_orm(_('Access Denied'), _('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % (self._description, operation)) def _get_record_name(self, cr, uid, values, context=None): """ Return the related document name, using name_get. It is done using SUPERUSER_ID, to be sure to have the record name correctly stored. """ if not values.get('model') or not values.get('res_id') or values['model'] not in self.pool: return False return self.pool[values['model']].name_get(cr, SUPERUSER_ID, [values['res_id']], context=context)[0][1] def _get_reply_to(self, cr, uid, values, context=None): """ Return a specific reply_to: alias of the document through message_get_reply_to or take the email_from """ model, res_id, email_from = values.get('model'), values.get('res_id'), values.get('email_from') ctx = dict(context, thread_model=model) return self.pool['mail.thread'].message_get_reply_to(cr, uid, [res_id], default=email_from, context=ctx)[res_id] def _get_message_id(self, cr, uid, values, context=None): if values.get('no_auto_thread', False) is True: message_id = tools.generate_tracking_message_id('reply_to') elif values.get('res_id') and values.get('model'): message_id = tools.generate_tracking_message_id('%(res_id)s-%(model)s' % values) else: message_id = tools.generate_tracking_message_id('private') return message_id def create(self, cr, uid, values, context=None): context = dict(context or {}) default_starred = context.pop('default_starred', False) if 'email_from' not in values: # needed to compute reply_to values['email_from'] = self._get_default_from(cr, uid, context=context) if not values.get('message_id'): values['message_id'] = self._get_message_id(cr, uid, values, context=context) if 'reply_to' not in values: values['reply_to'] = self._get_reply_to(cr, uid, values, context=context) if 'record_name' not in values and 'default_record_name' not in context: values['record_name'] = self._get_record_name(cr, uid, values, context=context) newid = super(mail_message, self).create(cr, uid, values, context) self._notify(cr, uid, newid, context=context, force_send=context.get('mail_notify_force_send', True), user_signature=context.get('mail_notify_user_signature', True)) # TDE FIXME: handle default_starred. Why not setting an inv on starred ? # Because starred will call set_message_starred, that looks for notifications. # When creating a new mail_message, it will create a notification to a message # that does not exist, leading to an error (key not existing). Also this # this means unread notifications will be created, yet we can not assure # this is what we want. if default_starred: self.set_message_starred(cr, uid, [newid], True, context=context) return newid def read(self, cr, uid, ids, fields=None, context=None, load='_classic_read'): """ Override to explicitely call check_access_rule, that is not called by the ORM. It instead directly fetches ir.rules and apply them. """ self.check_access_rule(cr, uid, ids, 'read', context=context) res = super(mail_message, self).read(cr, uid, ids, fields=fields, context=context, load=load) return res def unlink(self, cr, uid, ids, context=None): # cascade-delete attachments that are directly attached to the message (should only happen # for mail.messages that act as parent for a standalone mail.mail record). self.check_access_rule(cr, uid, ids, 'unlink', context=context) attachments_to_delete = [] for message in self.browse(cr, uid, ids, context=context): for attach in message.attachment_ids: if attach.res_model == self._name and (attach.res_id == message.id or attach.res_id == 0): attachments_to_delete.append(attach.id) if attachments_to_delete: self.pool.get('ir.attachment').unlink(cr, uid, attachments_to_delete, context=context) return super(mail_message, self).unlink(cr, uid, ids, context=context) #------------------------------------------------------ # Messaging API #------------------------------------------------------ def _notify(self, cr, uid, newid, context=None, force_send=False, user_signature=True): """ Add the related record followers to the destination partner_ids if is not a private message. Call mail_notification.notify to manage the email sending """ notification_obj = self.pool.get('mail.notification') message = self.browse(cr, uid, newid, context=context) partners_to_notify = set([]) # all followers of the mail.message document have to be added as partners and notified if a subtype is defined (otherwise: log message) if message.subtype_id and message.model and message.res_id: fol_obj = self.pool.get("mail.followers") # browse as SUPERUSER because rules could restrict the search results fol_ids = fol_obj.search( cr, SUPERUSER_ID, [ ('res_model', '=', message.model), ('res_id', '=', message.res_id), ], context=context) partners_to_notify |= set( fo.partner_id.id for fo in fol_obj.browse(cr, SUPERUSER_ID, fol_ids, context=context) if message.subtype_id.id in [st.id for st in fo.subtype_ids] ) # remove me from notified partners, unless the message is written on my own wall if message.subtype_id and message.author_id and message.model == "res.partner" and message.res_id == message.author_id.id: partners_to_notify |= set([message.author_id.id]) elif message.author_id: partners_to_notify -= set([message.author_id.id]) # all partner_ids of the mail.message have to be notified regardless of the above (even the author if explicitly added!) if message.partner_ids: partners_to_notify |= set([p.id for p in message.partner_ids]) # notify notification_obj._notify( cr, uid, newid, partners_to_notify=list(partners_to_notify), context=context, force_send=force_send, user_signature=user_signature ) message.refresh() # An error appear when a user receive a notification without notifying # the parent message -> add a read notification for the parent if message.parent_id: # all notified_partner_ids of the mail.message have to be notified for the parented messages partners_to_parent_notify = set(message.notified_partner_ids).difference(message.parent_id.notified_partner_ids) for partner in partners_to_parent_notify: notification_obj.create(cr, uid, { 'message_id': message.parent_id.id, 'partner_id': partner.id, 'is_read': True, }, context=context)
agpl-3.0
tuxfux-hlp-notes/python-batches
archieves/batch-62/files/myenv/lib/python2.7/site-packages/pip/commands/list.py
339
11369
from __future__ import absolute_import import json import logging import warnings try: from itertools import zip_longest except ImportError: from itertools import izip_longest as zip_longest from pip._vendor import six from pip.basecommand import Command from pip.exceptions import CommandError from pip.index import PackageFinder from pip.utils import ( get_installed_distributions, dist_is_editable) from pip.utils.deprecation import RemovedInPip10Warning from pip.cmdoptions import make_option_group, index_group logger = logging.getLogger(__name__) class ListCommand(Command): """ List installed packages, including editables. Packages are listed in a case-insensitive sorted order. """ name = 'list' usage = """ %prog [options]""" summary = 'List installed packages.' def __init__(self, *args, **kw): super(ListCommand, self).__init__(*args, **kw) cmd_opts = self.cmd_opts cmd_opts.add_option( '-o', '--outdated', action='store_true', default=False, help='List outdated packages') cmd_opts.add_option( '-u', '--uptodate', action='store_true', default=False, help='List uptodate packages') cmd_opts.add_option( '-e', '--editable', action='store_true', default=False, help='List editable projects.') cmd_opts.add_option( '-l', '--local', action='store_true', default=False, help=('If in a virtualenv that has global access, do not list ' 'globally-installed packages.'), ) self.cmd_opts.add_option( '--user', dest='user', action='store_true', default=False, help='Only output packages installed in user-site.') cmd_opts.add_option( '--pre', action='store_true', default=False, help=("Include pre-release and development versions. By default, " "pip only finds stable versions."), ) cmd_opts.add_option( '--format', action='store', dest='list_format', choices=('legacy', 'columns', 'freeze', 'json'), help="Select the output format among: legacy (default), columns, " "freeze or json.", ) cmd_opts.add_option( '--not-required', action='store_true', dest='not_required', help="List packages that are not dependencies of " "installed packages.", ) index_opts = make_option_group(index_group, self.parser) self.parser.insert_option_group(0, index_opts) self.parser.insert_option_group(0, cmd_opts) def _build_package_finder(self, options, index_urls, session): """ Create a package finder appropriate to this list command. """ return PackageFinder( find_links=options.find_links, index_urls=index_urls, allow_all_prereleases=options.pre, trusted_hosts=options.trusted_hosts, process_dependency_links=options.process_dependency_links, session=session, ) def run(self, options, args): if options.allow_external: warnings.warn( "--allow-external has been deprecated and will be removed in " "the future. Due to changes in the repository protocol, it no " "longer has any effect.", RemovedInPip10Warning, ) if options.allow_all_external: warnings.warn( "--allow-all-external has been deprecated and will be removed " "in the future. Due to changes in the repository protocol, it " "no longer has any effect.", RemovedInPip10Warning, ) if options.allow_unverified: warnings.warn( "--allow-unverified has been deprecated and will be removed " "in the future. Due to changes in the repository protocol, it " "no longer has any effect.", RemovedInPip10Warning, ) if options.list_format is None: warnings.warn( "The default format will switch to columns in the future. " "You can use --format=(legacy|columns) (or define a " "format=(legacy|columns) in your pip.conf under the [list] " "section) to disable this warning.", RemovedInPip10Warning, ) if options.outdated and options.uptodate: raise CommandError( "Options --outdated and --uptodate cannot be combined.") packages = get_installed_distributions( local_only=options.local, user_only=options.user, editables_only=options.editable, ) if options.outdated: packages = self.get_outdated(packages, options) elif options.uptodate: packages = self.get_uptodate(packages, options) if options.not_required: packages = self.get_not_required(packages, options) self.output_package_listing(packages, options) def get_outdated(self, packages, options): return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version > dist.parsed_version ] def get_uptodate(self, packages, options): return [ dist for dist in self.iter_packages_latest_infos(packages, options) if dist.latest_version == dist.parsed_version ] def get_not_required(self, packages, options): dep_keys = set() for dist in packages: dep_keys.update(requirement.key for requirement in dist.requires()) return set(pkg for pkg in packages if pkg.key not in dep_keys) def iter_packages_latest_infos(self, packages, options): index_urls = [options.index_url] + options.extra_index_urls if options.no_index: logger.debug('Ignoring indexes: %s', ','.join(index_urls)) index_urls = [] dependency_links = [] for dist in packages: if dist.has_metadata('dependency_links.txt'): dependency_links.extend( dist.get_metadata_lines('dependency_links.txt'), ) with self._build_session(options) as session: finder = self._build_package_finder(options, index_urls, session) finder.add_dependency_links(dependency_links) for dist in packages: typ = 'unknown' all_candidates = finder.find_all_candidates(dist.key) if not options.pre: # Remove prereleases all_candidates = [candidate for candidate in all_candidates if not candidate.version.is_prerelease] if not all_candidates: continue best_candidate = max(all_candidates, key=finder._candidate_sort_key) remote_version = best_candidate.version if best_candidate.location.is_wheel: typ = 'wheel' else: typ = 'sdist' # This is dirty but makes the rest of the code much cleaner dist.latest_version = remote_version dist.latest_filetype = typ yield dist def output_legacy(self, dist): if dist_is_editable(dist): return '%s (%s, %s)' % ( dist.project_name, dist.version, dist.location, ) else: return '%s (%s)' % (dist.project_name, dist.version) def output_legacy_latest(self, dist): return '%s - Latest: %s [%s]' % ( self.output_legacy(dist), dist.latest_version, dist.latest_filetype, ) def output_package_listing(self, packages, options): packages = sorted( packages, key=lambda dist: dist.project_name.lower(), ) if options.list_format == 'columns' and packages: data, header = format_for_columns(packages, options) self.output_package_listing_columns(data, header) elif options.list_format == 'freeze': for dist in packages: logger.info("%s==%s", dist.project_name, dist.version) elif options.list_format == 'json': logger.info(format_for_json(packages, options)) else: # legacy for dist in packages: if options.outdated: logger.info(self.output_legacy_latest(dist)) else: logger.info(self.output_legacy(dist)) def output_package_listing_columns(self, data, header): # insert the header first: we need to know the size of column names if len(data) > 0: data.insert(0, header) pkg_strings, sizes = tabulate(data) # Create and add a separator. if len(data) > 0: pkg_strings.insert(1, " ".join(map(lambda x: '-' * x, sizes))) for val in pkg_strings: logger.info(val) def tabulate(vals): # From pfmoore on GitHub: # https://github.com/pypa/pip/issues/3651#issuecomment-216932564 assert len(vals) > 0 sizes = [0] * max(len(x) for x in vals) for row in vals: sizes = [max(s, len(str(c))) for s, c in zip_longest(sizes, row)] result = [] for row in vals: display = " ".join([str(c).ljust(s) if c is not None else '' for s, c in zip_longest(sizes, row)]) result.append(display) return result, sizes def format_for_columns(pkgs, options): """ Convert the package data into something usable by output_package_listing_columns. """ running_outdated = options.outdated # Adjust the header for the `pip list --outdated` case. if running_outdated: header = ["Package", "Version", "Latest", "Type"] else: header = ["Package", "Version"] data = [] if any(dist_is_editable(x) for x in pkgs): header.append("Location") for proj in pkgs: # if we're working on the 'outdated' list, separate out the # latest_version and type row = [proj.project_name, proj.version] if running_outdated: row.append(proj.latest_version) row.append(proj.latest_filetype) if dist_is_editable(proj): row.append(proj.location) data.append(row) return data, header def format_for_json(packages, options): data = [] for dist in packages: info = { 'name': dist.project_name, 'version': six.text_type(dist.version), } if options.outdated: info['latest_version'] = six.text_type(dist.latest_version) info['latest_filetype'] = dist.latest_filetype data.append(info) return json.dumps(data)
gpl-3.0
perchrn/TaktPlayer
gui/configurationGui/CurveGui.py
1
32833
''' Created on 27. dec. 2012 @author: pcn ''' import wx from widgets.PcnImageButton import PcnImageButton from widgets.PcnCurveDisplayWindget import PcnCurveDisplayWidget from widgets.PcnEvents import EVT_DOUBLE_CLICK_EVENT, EVT_MOUSE_MOVE_EVENT from configurationGui.UtilityDialogs import updateChoices from video.Curve import Curve class CurveGui(object): def __init__(self, mainConfing): self._mainConfig = mainConfing self._updateWidget = None self._closeCallback = None self._saveCallback = None self._saveArgument = None self._curveConfig = Curve() self._helpBitmap = wx.Bitmap("graphics/helpButton.png") #@UndefinedVariable self._helpPressedBitmap = wx.Bitmap("graphics/helpButtonPressed.png") #@UndefinedVariable self._closeButtonBitmap = wx.Bitmap("graphics/closeButton.png") #@UndefinedVariable self._closeButtonPressedBitmap = wx.Bitmap("graphics/closeButtonPressed.png") #@UndefinedVariable self._updateButtonBitmap = wx.Bitmap("graphics/updateButton.png") #@UndefinedVariable self._updateButtonPressedBitmap = wx.Bitmap("graphics/updateButtonPressed.png") #@UndefinedVariable self._updateRedButtonBitmap = wx.Bitmap("graphics/updateButtonRed.png") #@UndefinedVariable self._updateRedButtonPressedBitmap = wx.Bitmap("graphics/updateButtonRedPressed.png") #@UndefinedVariable self._saveBigBitmap = wx.Bitmap("graphics/saveButtonBig.png") #@UndefinedVariable self._saveBigPressedBitmap = wx.Bitmap("graphics/saveButtonBigPressed.png") #@UndefinedVariable self._saveBigGreyBitmap = wx.Bitmap("graphics/saveButtonBigGrey.png") #@UndefinedVariable self._deleteColourButtonBitmap = wx.Bitmap("graphics/deleteColourButton.png") #@UndefinedVariable self._deleteColourButtonPressedBitmap = wx.Bitmap("graphics/deleteColourButtonPressed.png") #@UndefinedVariable self._deletePointButtonBitmap = wx.Bitmap("graphics/deletePointButton.png") #@UndefinedVariable self._deletePointButtonPressedBitmap = wx.Bitmap("graphics/deletePointButtonPressed.png") #@UndefinedVariable def setupCurveGui(self, plane, sizer, parentSizer, parentClass): self._mainCurveGuiPlane = plane self._mainCurveGuiSizer = sizer self._parentSizer = parentSizer self._hideCurveCallback = parentClass.hideCurveGui self._fixCurveGuiLayout = parentClass.fixCurveGuiLayout headerLabel = wx.StaticText(self._mainCurveGuiPlane, wx.ID_ANY, "Curve editor:") #@UndefinedVariable headerFont = headerLabel.GetFont() headerFont.SetWeight(wx.BOLD) #@UndefinedVariable headerLabel.SetFont(headerFont) self._mainCurveGuiSizer.Add(headerLabel, proportion=0, flag=wx.EXPAND) #@UndefinedVariable curveModeSizer = wx.BoxSizer(wx.HORIZONTAL) #@UndefinedVariable ||| tmpText1 = wx.StaticText(self._mainCurveGuiPlane, wx.ID_ANY, "Curve mode:") #@UndefinedVariable self._curveModeField = wx.ComboBox(self._mainCurveGuiPlane, wx.ID_ANY, size=(200, -1), choices=["Off"], style=wx.CB_READONLY) #@UndefinedVariable updateChoices(self._curveModeField, self._curveConfig.getChoices, "Off", "Off") curveModeButton = PcnImageButton(self._mainCurveGuiPlane, self._helpBitmap, self._helpPressedBitmap, (-1, -1), wx.ID_ANY, size=(17, 17)) #@UndefinedVariable curveModeButton.Bind(wx.EVT_BUTTON, self._onCurveModeHelp) #@UndefinedVariable curveModeSizer.Add(tmpText1, 1, wx.ALL, 5) #@UndefinedVariable curveModeSizer.Add(self._curveModeField, 2, wx.ALL, 5) #@UndefinedVariable curveModeSizer.Add(curveModeButton, 0, wx.ALL, 5) #@UndefinedVariable self._mainCurveGuiSizer.Add(curveModeSizer, proportion=0, flag=wx.EXPAND) #@UndefinedVariable self._mainCurveGuiPlane.Bind(wx.EVT_COMBOBOX, self._onCurveModeChosen, id=self._curveModeField.GetId()) #@UndefinedVariable self._curveSubModeSizer = wx.BoxSizer(wx.HORIZONTAL) #@UndefinedVariable ||| tmpText1 = wx.StaticText(self._mainCurveGuiPlane, wx.ID_ANY, "Curve sub mode:") #@UndefinedVariable self._curveSubModeField = wx.ComboBox(self._mainCurveGuiPlane, wx.ID_ANY, size=(200, -1), choices=["Linear"], style=wx.CB_READONLY) #@UndefinedVariable updateChoices(self._curveSubModeField, self._curveConfig.getSubChoices, "Linear", "Linear") curveSubModeButton = PcnImageButton(self._mainCurveGuiPlane, self._helpBitmap, self._helpPressedBitmap, (-1, -1), wx.ID_ANY, size=(17, 17)) #@UndefinedVariable curveSubModeButton.Bind(wx.EVT_BUTTON, self._onCurveSubModeHelp) #@UndefinedVariable self._curveSubModeSizer.Add(tmpText1, 1, wx.ALL, 5) #@UndefinedVariable self._curveSubModeSizer.Add(self._curveSubModeField, 2, wx.ALL, 5) #@UndefinedVariable self._curveSubModeSizer.Add(curveSubModeButton, 0, wx.ALL, 5) #@UndefinedVariable self._mainCurveGuiSizer.Add(self._curveSubModeSizer, proportion=0, flag=wx.EXPAND) #@UndefinedVariable self._mainCurveGuiPlane.Bind(wx.EVT_COMBOBOX, self._onCurveSubModeChosen, id=self._curveSubModeField.GetId()) #@UndefinedVariable self._curveChannelSizer = wx.BoxSizer(wx.HORIZONTAL) #@UndefinedVariable ||| tmpText1 = wx.StaticText(self._mainCurveGuiPlane, wx.ID_ANY, "Edit channel:") #@UndefinedVariable self._curveChannelField = wx.ComboBox(self._mainCurveGuiPlane, wx.ID_ANY, size=(200, -1), choices=["Red"], style=wx.CB_READONLY) #@UndefinedVariable updateChoices(self._curveChannelField, None, "Red", "Red", ["Red", "Green", "Blue"]) curveChannelButton = PcnImageButton(self._mainCurveGuiPlane, self._helpBitmap, self._helpPressedBitmap, (-1, -1), wx.ID_ANY, size=(17, 17)) #@UndefinedVariable curveChannelButton.Bind(wx.EVT_BUTTON, self._onCurveChannelHelp) #@UndefinedVariable self._curveChannelSizer.Add(tmpText1, 1, wx.ALL, 5) #@UndefinedVariable self._curveChannelSizer.Add(self._curveChannelField, 2, wx.ALL, 5) #@UndefinedVariable self._curveChannelSizer.Add(curveChannelButton, 0, wx.ALL, 5) #@UndefinedVariable self._mainCurveGuiSizer.Add(self._curveChannelSizer, proportion=0, flag=wx.EXPAND) #@UndefinedVariable self._mainCurveGuiPlane.Bind(wx.EVT_COMBOBOX, self._onCurveChannelChosen, id=self._curveChannelField.GetId()) #@UndefinedVariable self._curveGraphicsSizer = wx.BoxSizer(wx.HORIZONTAL) #@UndefinedVariable ||| self._curveGraphicsLabel = wx.StaticText(self._mainCurveGuiPlane, wx.ID_ANY, "Curve graph:") #@UndefinedVariable self._curveGraphicsDisplay = PcnCurveDisplayWidget(self._mainCurveGuiPlane) curveGraphicsValueButton = PcnImageButton(self._mainCurveGuiPlane, self._helpBitmap, self._helpPressedBitmap, (-1, -1), wx.ID_ANY, size=(17, 17)) #@UndefinedVariable curveGraphicsValueButton.Bind(wx.EVT_BUTTON, self._onCurveGraphicsHelp) #@UndefinedVariable self._curveGraphicsDisplay.Bind(wx.EVT_BUTTON, self._onCurveSingleClick) #@UndefinedVariable self._curveGraphicsDisplay.Bind(EVT_DOUBLE_CLICK_EVENT, self._onCurveDoubleClick) #@UndefinedVariable self._curveGraphicsDisplay.Bind(EVT_MOUSE_MOVE_EVENT, self._onMouseMove) #@UndefinedVariable self._curveGraphicsSizer.Add(self._curveGraphicsLabel, 1, wx.ALL, 5) #@UndefinedVariable self._curveGraphicsSizer.Add(self._curveGraphicsDisplay, 2, wx.ALL, 5) #@UndefinedVariable self._curveGraphicsSizer.Add(curveGraphicsValueButton, 0, wx.ALL, 5) #@UndefinedVariable self._mainCurveGuiSizer.Add(self._curveGraphicsSizer, proportion=0, flag=wx.EXPAND) #@UndefinedVariable self._pointSelectSizer = wx.BoxSizer(wx.HORIZONTAL) #@UndefinedVariable ||| self._pointSelectLabel = wx.StaticText(self._mainCurveGuiPlane, wx.ID_ANY, "Select:") #@UndefinedVariable self._pointSelectSlider = wx.Slider(plane, wx.ID_ANY, minValue=0, maxValue=255, size=(200, -1)) #@UndefinedVariable self._pointSelectDisplay = wx.StaticText(plane, wx.ID_ANY, "1", size=(30,-1)) #@UndefinedVariable self._pointSelectSizer.Add(self._pointSelectLabel, 1, wx.ALL, 5) #@UndefinedVariable self._pointSelectSizer.Add(self._pointSelectSlider, 2, wx.ALL, 5) #@UndefinedVariable self._pointSelectSizer.Add(self._pointSelectDisplay, 0, wx.ALL, 5) #@UndefinedVariable self._mainCurveGuiSizer.Add(self._pointSelectSizer, proportion=0, flag=wx.EXPAND) #@UndefinedVariable self._pointPositionSizer = wx.BoxSizer(wx.HORIZONTAL) #@UndefinedVariable ||| self._pointPositionLabel = wx.StaticText(self._mainCurveGuiPlane, wx.ID_ANY, "Position:") #@UndefinedVariable self._pointPositionSlider = wx.Slider(plane, wx.ID_ANY, minValue=0, maxValue=255, size=(200, -1)) #@UndefinedVariable self._pointPositionDisplay = wx.StaticText(plane, wx.ID_ANY, "1", size=(30,-1)) #@UndefinedVariable self._pointPositionSizer.Add(self._pointPositionLabel, 1, wx.ALL, 5) #@UndefinedVariable self._pointPositionSizer.Add(self._pointPositionSlider, 2, wx.ALL, 5) #@UndefinedVariable self._pointPositionSizer.Add(self._pointPositionDisplay, 0, wx.ALL, 5) #@UndefinedVariable self._mainCurveGuiSizer.Add(self._pointPositionSizer, proportion=0, flag=wx.EXPAND) #@UndefinedVariable self._pointValue1Sizer = wx.BoxSizer(wx.HORIZONTAL) #@UndefinedVariable ||| self._pointValue1Label = wx.StaticText(self._mainCurveGuiPlane, wx.ID_ANY, "Red:") #@UndefinedVariable self._pointValue1Slider = wx.Slider(plane, wx.ID_ANY, minValue=0, maxValue=255, size=(200, -1)) #@UndefinedVariable self._pointValue1Display = wx.StaticText(plane, wx.ID_ANY, "1", size=(30,-1)) #@UndefinedVariable self._pointValue1Sizer.Add(self._pointValue1Label, 1, wx.ALL, 5) #@UndefinedVariable self._pointValue1Sizer.Add(self._pointValue1Slider, 2, wx.ALL, 5) #@UndefinedVariable self._pointValue1Sizer.Add(self._pointValue1Display, 0, wx.ALL, 5) #@UndefinedVariable self._mainCurveGuiSizer.Add(self._pointValue1Sizer, proportion=0, flag=wx.EXPAND) #@UndefinedVariable self._pointValue2Sizer = wx.BoxSizer(wx.HORIZONTAL) #@UndefinedVariable ||| self._pointValue2Label = wx.StaticText(self._mainCurveGuiPlane, wx.ID_ANY, "Green:") #@UndefinedVariable self._pointValue2Slider = wx.Slider(plane, wx.ID_ANY, minValue=0, maxValue=255, size=(200, -1)) #@UndefinedVariable self._pointValue2Display = wx.StaticText(plane, wx.ID_ANY, "1", size=(30,-1)) #@UndefinedVariable self._pointValue2Sizer.Add(self._pointValue2Label, 1, wx.ALL, 5) #@UndefinedVariable self._pointValue2Sizer.Add(self._pointValue2Slider, 2, wx.ALL, 5) #@UndefinedVariable self._pointValue2Sizer.Add(self._pointValue2Display, 0, wx.ALL, 5) #@UndefinedVariable self._mainCurveGuiSizer.Add(self._pointValue2Sizer, proportion=0, flag=wx.EXPAND) #@UndefinedVariable self._pointValue3Sizer = wx.BoxSizer(wx.HORIZONTAL) #@UndefinedVariable ||| self._pointValue3Label = wx.StaticText(self._mainCurveGuiPlane, wx.ID_ANY, "Blue:") #@UndefinedVariable self._pointValue3Slider = wx.Slider(plane, wx.ID_ANY, minValue=0, maxValue=255, size=(200, -1)) #@UndefinedVariable self._pointValue3Display = wx.StaticText(plane, wx.ID_ANY, "1", size=(30,-1)) #@UndefinedVariable self._pointValue3Sizer.Add(self._pointValue3Label, 1, wx.ALL, 5) #@UndefinedVariable self._pointValue3Sizer.Add(self._pointValue3Slider, 2, wx.ALL, 5) #@UndefinedVariable self._pointValue3Sizer.Add(self._pointValue3Display, 0, wx.ALL, 5) #@UndefinedVariable self._mainCurveGuiSizer.Add(self._pointValue3Sizer, proportion=0, flag=wx.EXPAND) #@UndefinedVariable self._selectSliderId = self._pointSelectSlider.GetId() self._selectedPointId = 0 self._positionSliderId = self._pointPositionSlider.GetId() self._value1SliderId = self._pointValue1Slider.GetId() self._value2SliderId = self._pointValue2Slider.GetId() self._value3SliderId = self._pointValue3Slider.GetId() plane.Bind(wx.EVT_SLIDER, self._onSlide) #@UndefinedVariable """Buttons""" self._buttonsSizer = wx.BoxSizer(wx.HORIZONTAL) #@UndefinedVariable ||| closeButton = PcnImageButton(self._mainCurveGuiPlane, self._closeButtonBitmap, self._closeButtonPressedBitmap, (-1, -1), wx.ID_ANY, size=(55, 17)) #@UndefinedVariable closeButton.Bind(wx.EVT_BUTTON, self._onCloseButton) #@UndefinedVariable self._saveButton = PcnImageButton(self._mainCurveGuiPlane, self._updateButtonBitmap, self._updateButtonPressedBitmap, (-1, -1), wx.ID_ANY, size=(67, 17)) #@UndefinedVariable self._saveButton.Bind(wx.EVT_BUTTON, self._onSaveButton) #@UndefinedVariable self._deleteButton = PcnImageButton(self._mainCurveGuiPlane, self._deletePointButtonBitmap, self._deletePointButtonPressedBitmap, (-1, -1), wx.ID_ANY, size=(97, 17)) #@UndefinedVariable self._deleteButton.Bind(wx.EVT_BUTTON, self._onDeleteButton) #@UndefinedVariable self._buttonsSizer.Add(closeButton, 0, wx.ALL, 5) #@UndefinedVariable self._buttonsSizer.Add(self._saveButton, 0, wx.ALL, 5) #@UndefinedVariable self._buttonsSizer.Add(self._deleteButton, 0, wx.ALL, 5) #@UndefinedVariable self._mainCurveGuiSizer.Add(self._buttonsSizer, proportion=0, flag=wx.EXPAND) #@UndefinedVariable def _onCurveModeHelp(self, event): text = "Selects curve mode.\n" text += "\n" text += "Off:\tNo curve modifications are done.\n" text += "All:\tOne curve controlls all channels.\n" text += "Threshold:\tSets colours for different levels. Use BW input\n" text += "RGB:\tOne curve for each RGB colour.\n" text += "HSV:\tOne curve for each HSV channel.\n" dlg = wx.MessageDialog(self._mainCurveGuiPlane, text, 'Curve mode help', wx.OK|wx.ICON_INFORMATION) #@UndefinedVariable dlg.ShowModal() dlg.Destroy() def _onCurveModeChosen(self, event): updateChoices(self._curveModeField, self._curveConfig.getChoices, self._curveModeField.GetValue(), "Off") self._curveConfig.changeModeString(self._curveModeField.GetValue()) self._onCurveChannelChosen(None) if((self._curveConfig.getMode() == Curve.Threshold) or (self._curveConfig.getMode() == Curve.Off)): self._mainCurveGuiSizer.Hide(self._curveSubModeSizer) else: self._mainCurveGuiSizer.Show(self._curveSubModeSizer) self._autoUpdateSliders() self._updateCurveGraph() def _onCurveSubModeHelp(self, event): text = "Selects how we edit the curve.\n" text += "\n" text += "Linear:\tAdd points to define curve.\n" text += "Curve:\tAdd points to define bendt curve.\n" text += "Array:\tDraw the curve pixel by pixel.\n" dlg = wx.MessageDialog(self._mainCurveGuiPlane, text, 'Curve sub mode help', wx.OK|wx.ICON_INFORMATION) #@UndefinedVariable dlg.ShowModal() dlg.Destroy() def _onCurveSubModeChosen(self, event): updateChoices(self._curveSubModeField, self._curveConfig.getSubChoices, self._curveSubModeField.GetValue(), "Linear") self._curveConfig.changeSubModeString(self._curveSubModeField.GetValue()) self._autoUpdateSliders() self._updateCurveGraph() def _onCurveChannelHelp(self, event): if(self._curveConfig.getMode() == Curve.HSV): text = "Selects which channel we are editing now.\n" text += "\n" text += "Hue:\tEdits hue curve. (Colour rotation.)\n" text += "Saturation:\tEdits saturation curve.\n" text += "Value:\tEdits value curve.\n" else: text = "Selects which channel we are editing now.\n" text += "\n" text += "Red:\tEdits red colour curve.\n" text += "Green:\tEdits green colour curve.\n" text += "Blue:\tEdits blue colour curve.\n" dlg = wx.MessageDialog(self._mainCurveGuiPlane, text, 'Curve sub mode help', wx.OK|wx.ICON_INFORMATION) #@UndefinedVariable dlg.ShowModal() dlg.Destroy() def _onCurveChannelChosen(self, event): if(self._curveConfig.getMode() == Curve.HSV): self._mainCurveGuiSizer.Show(self._curveChannelSizer) updateChoices(self._curveChannelField, None, self._curveChannelField.GetValue(), "Hue", ["Hue", "Saturation", "Value"]) elif(self._curveConfig.getMode() == Curve.RGB): self._mainCurveGuiSizer.Show(self._curveChannelSizer) updateChoices(self._curveChannelField, None, self._curveChannelField.GetValue(), "Red", ["Red", "Green", "Blue"]) else: self._mainCurveGuiSizer.Hide(self._curveChannelSizer) self._autoUpdateSliders() self._fixCurveGuiLayout() def _onCurveGraphicsHelp(self, event): if(self._curveConfig.getSubMode() == Curve.Linear): text = "Shows the curve\n" text += "\n" text += "Add points by doubble clicking.\n" text += "Select and drag points with left button." if(self._curveConfig.getSubMode() == Curve.Curve): text = "Shows the curve\n" text += "\n" text += "Add points by doubble clicking.\n" text += "Select and drag points with left button." if(self._curveConfig.getSubMode() == Curve.Array): text = "Shows the curve\n" text += "\n" text += "Set point(s) with left button." else: text = "Shows the curve." dlg = wx.MessageDialog(self._mainCurveGuiPlane, text, 'Curve display help', wx.OK|wx.ICON_INFORMATION) #@UndefinedVariable dlg.ShowModal() dlg.Destroy() def getSubId(self): if(self._curveConfig.getMode() == Curve.Off): return -1 if(self._curveConfig.getMode() == Curve.All): return -1 channelString = self._curveChannelField.GetValue() if((channelString == "Red") or (channelString == "Hue")): return 0 if((channelString == "Green") or (channelString == "Saturation")): return 1 if((channelString == "Blue") or (channelString == "Value")): return 2 def _onSlide(self, event): sliderId = event.GetEventObject().GetId() curveMode = self._curveConfig.getMode() if(sliderId == self._selectSliderId): if(curveMode == Curve.Threshold): self._updateThresholdId(False) elif(((curveMode == Curve.Off) and (curveMode == Curve.Array)) == False): self._updatePointId(False) else: self._hideSliders(curveMode == Curve.Off) elif(sliderId == self._positionSliderId): value = self._pointPositionSlider.GetValue() self._pointPositionDisplay.SetLabel(str(value)) if(curveMode == Curve.Threshold): self._updateThresholdSetting(value, None, None, None) else: self._updatePointSetting(value, None) elif(sliderId == self._value1SliderId): value = self._pointValue1Slider.GetValue() if(curveMode == Curve.Threshold): self._pointValue1Display.SetLabel("%02X" %(value)) self._updateThresholdSetting(None, value, None, None) else: self._pointValue1Display.SetLabel(str(value)) self._updatePointSetting(None, value) elif(sliderId == self._value2SliderId): value = self._pointValue2Slider.GetValue() self._pointValue2Display.SetLabel("%02X" %(value)) self._updateThresholdSetting(None, None, value, None) elif(sliderId == self._value3SliderId): value = self._pointValue3Slider.GetValue() self._pointValue3Display.SetLabel("%02X" %(value)) self._updateThresholdSetting(None, None, None, value) def _updateThresholdSetting(self, value, red, green, blue): if(self._selectedPointId != None): settingsList = self._curveConfig.getThresholdsSettings() settingsListLen = len(settingsList) if((self._selectedPointId >= 0) and (self._selectedPointId < settingsListLen)): colour, xPos = settingsList[self._selectedPointId] if(value != None): settingsList[self._selectedPointId] = colour, value elif(red != None): newColour = (colour & 0x00ffff) + (red * 0x010000) settingsList[self._selectedPointId] = newColour, xPos elif(green != None): newColour = (colour & 0xff00ff) + (green * 0x000100) settingsList[self._selectedPointId] = newColour, xPos elif(blue != None): newColour = (colour & 0xffff00) + blue settingsList[self._selectedPointId] = newColour, xPos self._curveConfig.updateFromThresholdsSettings() self._updateCurveGraph() def _updatePointSetting(self, pos, value): if(self._selectedPointId != None): settingsList = self._curveConfig.getPoints(self.getSubId())[0] settingsListLen = len(settingsList) if((self._selectedPointId >= 0) and (self._selectedPointId < settingsListLen)): xPos, yPos = settingsList[self._selectedPointId] if(pos != None): self._curveConfig.movePoint((xPos, yPos), (pos, yPos), self.getSubId()) elif(value != None): self._curveConfig.movePoint((xPos, yPos), (xPos, value), self.getSubId()) self._updateCurveGraph() def _autoUpdateSliders(self): curveMode = self._curveConfig.getMode() curveSubMode = self._curveConfig.getSubMode() if(curveMode == Curve.Threshold): self._updateThresholdId(True) elif(curveMode == Curve.Off): self._hideSliders(True) elif(curveSubMode == Curve.Array): self._hideSliders(False) else: self._updatePointId(True) self._fixCurveGuiLayout() def _hideSliders(self, isOff): self._mainCurveGuiSizer.Hide(self._pointSelectSizer) if(isOff == True): self._mainCurveGuiSizer.Hide(self._pointPositionSizer) self._mainCurveGuiSizer.Hide(self._pointValue1Sizer) else: self._mainCurveGuiSizer.Show(self._pointPositionSizer) self._mainCurveGuiSizer.Show(self._pointValue1Sizer) self._pointValue1Label.SetLabel("Value:") self._mainCurveGuiSizer.Hide(self._pointValue2Sizer) self._mainCurveGuiSizer.Hide(self._pointValue3Sizer) self._buttonsSizer.Hide(self._deleteButton) def _updateThresholdId(self, forceUpdate): settingsList = self._curveConfig.getThresholdsSettings() settingsListLen = len(settingsList) if(forceUpdate == True): thresholdId = self._selectedPointId self._selectedPointId = -1 else: value = self._pointSelectSlider.GetValue() thresholdId = int((float(value) / 256) * settingsListLen) self._mainCurveGuiSizer.Show(self._pointSelectSizer) self._mainCurveGuiSizer.Show(self._pointPositionSizer) self._pointValue1Label.SetLabel("Red:") self._mainCurveGuiSizer.Show(self._pointValue1Sizer) self._mainCurveGuiSizer.Show(self._pointValue2Sizer) self._mainCurveGuiSizer.Show(self._pointValue3Sizer) self._deleteButton.setBitmaps(self._deleteColourButtonBitmap, self._deleteColourButtonPressedBitmap) self._buttonsSizer.Show(self._deleteButton) if(thresholdId >= settingsListLen): thresholdId = settingsListLen - 1 if(thresholdId != self._selectedPointId): self._selectedPointId = thresholdId self._pointSelectSlider.SetValue(int((thresholdId + 0.5)*256/settingsListLen)) self._pointSelectDisplay.SetLabel(str(thresholdId+1)) colour, xPos = settingsList[thresholdId] red = (int(colour)&0xff0000) / 0x010000 green = (int(colour)&0x00ff00) / 0x000100 blue = (int(colour)&0x0000ff) self._pointPositionSlider.SetValue(int(xPos)) self._pointPositionDisplay.SetLabel(str(xPos)) self._pointValue1Slider.SetValue(red) self._pointValue1Display.SetLabel("%02X" %(red)) self._pointValue2Slider.SetValue(green) self._pointValue2Display.SetLabel("%02X" %(green)) self._pointValue3Slider.SetValue(blue) self._pointValue3Display.SetLabel("%02X" %(blue)) def _updatePointId(self, forceUpdate): subId = self.getSubId() curveMode = self._curveConfig.getMode() self._mainCurveGuiSizer.Show(self._pointSelectSizer) self._mainCurveGuiSizer.Show(self._pointPositionSizer) self._pointValue1Label.SetLabel("Value:") self._mainCurveGuiSizer.Show(self._pointValue1Sizer) self._mainCurveGuiSizer.Hide(self._pointValue2Sizer) self._mainCurveGuiSizer.Hide(self._pointValue3Sizer) self._deleteButton.setBitmaps(self._deletePointButtonBitmap, self._deletePointButtonPressedBitmap) self._buttonsSizer.Show(self._deleteButton) if((subId == -1) and (curveMode != Curve.All)): return settingsList = self._curveConfig.getPoints(self.getSubId())[0] settingsListLen = len(settingsList) if(forceUpdate == True): pointId = self._selectedPointId self._selectedPointId = -1 else: value = self._pointSelectSlider.GetValue() pointId = int((float(value) / 256) * settingsListLen) if(pointId >= settingsListLen): pointId = settingsListLen - 1 if(pointId != self._selectedPointId): self._selectedPointId = pointId self._pointSelectSlider.SetValue(int((pointId + 0.5)*256/settingsListLen)) self._pointSelectDisplay.SetLabel(str(pointId+1)) xPos, yPos = settingsList[pointId] self._pointPositionSlider.SetValue(int(xPos)) self._pointPositionDisplay.SetLabel(str(xPos)) self._pointValue1Slider.SetValue(yPos) self._pointValue1Display.SetLabel("%d" %(yPos)) def _onCurveSingleClick(self, event): self._curveConfig.drawingDone(self.getSubId()) self._updateCurveGraph() self._autoUpdateSliders() if((self._curveConfig.getSubMode() == Curve.Linear) or (self._curveConfig.getSubMode() == Curve.Curve)): self._curveConfig.findActivePointId(self.getSubId(), self._curveGraphicsDisplay.getLastPos()) curveActivePoint = self._curveConfig.getActivePointId(self.getSubId()) if(curveActivePoint != None): self._selectedPointId = curveActivePoint self._updatePointId(True) def _onCurveDoubleClick(self, event): thresholdPointId = self._curveConfig.addPoint(self._curveGraphicsDisplay.getLastPos(), self.getSubId()) if(self._curveConfig.getMode() == Curve.Threshold): self._curveConfig.updateFromThresholdsSettings() self._selectedPointId = thresholdPointId self._updateCurveGraph() self._autoUpdateSliders() if((self._curveConfig.getSubMode() == Curve.Linear) or (self._curveConfig.getSubMode() == Curve.Curve)): self._curveConfig.findActivePointId(self.getSubId(), self._curveGraphicsDisplay.getLastPos()) curveActivePoint = self._curveConfig.getActivePointId(self.getSubId()) if(curveActivePoint != None): self._selectedPointId = curveActivePoint self._updatePointId(True) def _onMouseMove(self, event): if(event.mousePressed == True): self._curveConfig.drawPoint(event.mousePosition, self.getSubId()) self._updateCurveGraph() else: self._curveConfig.drawingDone(-1) if(self._curveConfig.getSubMode() == Curve.Array): xPos, yPos = event.mousePosition self._pointPositionSlider.SetValue(int(xPos)) self._pointPositionDisplay.SetLabel(str(xPos)) self._pointValue1Slider.SetValue(yPos) self._pointValue1Display.SetLabel("%d" %(yPos)) def _updateCurveGraph(self): self._curveGraphicsDisplay.drawCurve(self._curveConfig) self._checkForUpdates() def _onCloseButton(self, event): if(self._closeCallback != None): self._closeCallback() self._hideCurveCallback() def _onSaveButton(self, event): curveString = self._curveConfig.getString() if(self._updateWidget != None): self._updateWidget.SetValue(curveString) if(self._saveCallback): if(self._saveArgument != None): self._saveCallback(self._saveArgument, curveString) else: self._saveCallback(None) self._lastSavedCurveString = curveString self._checkForUpdates() def _onDeleteButton(self, event): curveMode = self._curveConfig.getMode() curveSubMode = self._curveConfig.getSubMode() if(curveMode == Curve.Threshold): if(self._selectedPointId != None): settingsList = self._curveConfig.getThresholdsSettings() settingsListLen = len(settingsList) if((self._selectedPointId >= 0) and (self._selectedPointId < settingsListLen)): settingsList.pop(self._selectedPointId) self._curveConfig.updateFromThresholdsSettings() elif(curveMode == Curve.Off): pass elif(curveSubMode == Curve.Array): pass else: if(self._selectedPointId != None): settingsList = self._curveConfig.getPoints(self.getSubId())[0] settingsListLen = len(settingsList) if((self._selectedPointId >= 0) and (self._selectedPointId < settingsListLen)): settingsList.pop(self._selectedPointId) self._autoUpdateSliders() self._updateCurveGraph() def _checkForUpdates(self, event = None): newCurveString = self._curveConfig.getString() if(self._lastSavedCurveString != newCurveString): if(self._saveArgument == None): self._saveButton.setBitmaps(self._updateRedButtonBitmap, self._updateRedButtonPressedBitmap) else: self._saveButton.setBitmaps(self._saveBigBitmap, self._saveBigPressedBitmap) else: if(self._saveArgument == None): self._saveButton.setBitmaps(self._updateButtonBitmap, self._updateButtonPressedBitmap) else: self._saveButton.setBitmaps(self._saveBigGreyBitmap, self._saveBigGreyBitmap) def updateGui(self, curveConfigString, widget, closeCallback, saveCallback, saveArgument): self._updateWidget = widget self._closeCallback = closeCallback self._saveCallback = saveCallback self._saveArgument = saveArgument self._lastSavedCurveString = curveConfigString self._curveConfig.setString(curveConfigString) updateChoices(self._curveModeField, self._curveConfig.getChoices, self._curveConfig.getChoices()[self._curveConfig.getMode()], "Off") updateChoices(self._curveSubModeField, self._curveConfig.getSubChoices, self._curveConfig.getSubChoices()[self._curveConfig.getSubMode()], "Linear") self._onCurveChannelChosen(None) if((self._curveConfig.getMode() == Curve.Threshold) or (self._curveConfig.getMode() == Curve.Off)): self._mainCurveGuiSizer.Hide(self._curveSubModeSizer) else: self._mainCurveGuiSizer.Show(self._curveSubModeSizer) self._autoUpdateSliders() self._updateCurveGraph() self._checkForUpdates()
gpl-2.0
andykimpe/chromium-test-npapi
tools/telemetry/telemetry/value/string.py
10
2139
# 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. from telemetry import value as value_module from telemetry.value import list_of_string_values class StringValue(value_module.Value): def __init__(self, page, name, units, value, important=True): """A single value (float, integer or string) result from a test. A test that output a hash of the content in a page might produce a string value: StringValue(page, 'page_hash', 'hash', '74E377FF') """ super(StringValue, self).__init__(page, name, units, important) assert isinstance(value, basestring) self.value = value def __repr__(self): if self.page: page_name = self.page.url else: page_name = None return 'ScalarValue(%s, %s, %s, %s, important=%s)' % ( page_name, self.name, self.units, self.value, self.important) def GetBuildbotDataType(self, output_context): if self._IsImportantGivenOutputIntent(output_context): return 'default' return 'unimportant' def GetBuildbotValue(self): # Buildbot's print_perf_results method likes to get lists for all values, # even when they are scalar, so list-ize the return value. return [self.value] def GetRepresentativeNumber(self): return self.value def GetRepresentativeString(self): return str(self.value) @classmethod def MergeLikeValuesFromSamePage(cls, values): assert len(values) > 0 v0 = values[0] return list_of_string_values.ListOfStringValues( v0.page, v0.name, v0.units, [v.value for v in values], important=v0.important) @classmethod def MergeLikeValuesFromDifferentPages(cls, values, group_by_name_suffix=False): assert len(values) > 0 v0 = values[0] if not group_by_name_suffix: name = v0.name else: name = v0.name_suffix return list_of_string_values.ListOfStringValues( None, name, v0.units, [v.value for v in values], important=v0.important)
bsd-3-clause
endlessm/chromium-browser
third_party/logilab/logilab/astroid/brain/py2gi.py
66
4619
"""Astroid hooks for the Python 2 GObject introspection bindings. Helps with understanding everything imported from 'gi.repository' """ import inspect import itertools import sys import re from astroid import MANAGER, AstroidBuildingException from astroid.builder import AstroidBuilder _inspected_modules = {} _identifier_re = r'^[A-Za-z_]\w*$' def _gi_build_stub(parent): """ Inspect the passed module recursively and build stubs for functions, classes, etc. """ classes = {} functions = {} constants = {} methods = {} for name in dir(parent): if name.startswith("__"): continue # Check if this is a valid name in python if not re.match(_identifier_re, name): continue try: obj = getattr(parent, name) except: continue if inspect.isclass(obj): classes[name] = obj elif (inspect.isfunction(obj) or inspect.isbuiltin(obj)): functions[name] = obj elif (inspect.ismethod(obj) or inspect.ismethoddescriptor(obj)): methods[name] = obj elif type(obj) in [int, str]: constants[name] = obj elif (str(obj).startswith("<flags") or str(obj).startswith("<enum ") or str(obj).startswith("<GType ") or inspect.isdatadescriptor(obj)): constants[name] = 0 elif callable(obj): # Fall back to a function for anything callable functions[name] = obj else: # Assume everything else is some manner of constant constants[name] = 0 ret = "" if constants: ret += "# %s contants\n\n" % parent.__name__ for name in sorted(constants): if name[0].isdigit(): # GDK has some busted constant names like # Gdk.EventType.2BUTTON_PRESS continue val = constants[name] strval = str(val) if type(val) is str: strval = '"%s"' % str(val).replace("\\", "\\\\") ret += "%s = %s\n" % (name, strval) if ret: ret += "\n\n" if functions: ret += "# %s functions\n\n" % parent.__name__ for name in sorted(functions): func = functions[name] ret += "def %s(*args, **kwargs):\n" % name ret += " pass\n" if ret: ret += "\n\n" if methods: ret += "# %s methods\n\n" % parent.__name__ for name in sorted(methods): func = methods[name] ret += "def %s(self, *args, **kwargs):\n" % name ret += " pass\n" if ret: ret += "\n\n" if classes: ret += "# %s classes\n\n" % parent.__name__ for name in sorted(classes): ret += "class %s(object):\n" % name classret = _gi_build_stub(classes[name]) if not classret: classret = "pass\n" for line in classret.splitlines(): ret += " " + line + "\n" ret += "\n" return ret def _import_gi_module(modname): # we only consider gi.repository submodules if not modname.startswith('gi.repository.'): raise AstroidBuildingException() # build astroid representation unless we already tried so if modname not in _inspected_modules: modnames = [modname] optional_modnames = [] # GLib and GObject may have some special case handling # in pygobject that we need to cope with. However at # least as of pygobject3-3.13.91 the _glib module doesn't # exist anymore, so if treat these modules as optional. if modname == 'gi.repository.GLib': optional_modnames.append('gi._glib') elif modname == 'gi.repository.GObject': optional_modnames.append('gi._gobject') try: modcode = '' for m in itertools.chain(modnames, optional_modnames): try: __import__(m) modcode += _gi_build_stub(sys.modules[m]) except ImportError: if m not in optional_modnames: raise except ImportError: astng = _inspected_modules[modname] = None else: astng = AstroidBuilder(MANAGER).string_build(modcode, modname) _inspected_modules[modname] = astng else: astng = _inspected_modules[modname] if astng is None: raise AstroidBuildingException('Failed to import module %r' % modname) return astng MANAGER.register_failed_import_hook(_import_gi_module)
bsd-3-clause
khushboo9293/mailman3
src/mailman/app/tests/test_membership.py
7
10736
# Copyright (C) 2011-2015 by the Free Software Foundation, Inc. # # This file is part of GNU Mailman. # # GNU Mailman 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. # # GNU Mailman 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 Mailman. If not, see <http://www.gnu.org/licenses/>. """Tests of application level membership functions.""" __all__ = [ 'TestAddMember', 'TestDeleteMember', ] import unittest from mailman.app.lifecycle import create_list from mailman.app.membership import add_member, delete_member from mailman.core.constants import system_preferences from mailman.interfaces.bans import IBanManager from mailman.interfaces.member import ( AlreadySubscribedError, DeliveryMode, MemberRole, MembershipIsBannedError, NotAMemberError) from mailman.interfaces.subscriptions import RequestRecord from mailman.interfaces.usermanager import IUserManager from mailman.testing.layers import ConfigLayer from zope.component import getUtility class TestAddMember(unittest.TestCase): layer = ConfigLayer def setUp(self): self._mlist = create_list('test@example.com') def test_add_member_new_user(self): # Test subscribing a user to a mailing list when the email address has # not yet been associated with a user. member = add_member( self._mlist, RequestRecord('aperson@example.com', 'Anne Person', DeliveryMode.regular, system_preferences.preferred_language)) self.assertEqual(member.address.email, 'aperson@example.com') self.assertEqual(member.list_id, 'test.example.com') self.assertEqual(member.role, MemberRole.member) def test_add_member_existing_user(self): # Test subscribing a user to a mailing list when the email address has # already been associated with a user. user_manager = getUtility(IUserManager) user_manager.create_user('aperson@example.com', 'Anne Person') member = add_member( self._mlist, RequestRecord('aperson@example.com', 'Anne Person', DeliveryMode.regular, system_preferences.preferred_language)) self.assertEqual(member.address.email, 'aperson@example.com') self.assertEqual(member.list_id, 'test.example.com') def test_add_member_banned(self): # Test that members who are banned by specific address cannot # subscribe to the mailing list. IBanManager(self._mlist).ban('anne@example.com') with self.assertRaises(MembershipIsBannedError) as cm: add_member( self._mlist, RequestRecord('anne@example.com', 'Anne Person', DeliveryMode.regular, system_preferences.preferred_language)) self.assertEqual( str(cm.exception), 'anne@example.com is not allowed to subscribe to test@example.com') def test_add_member_globally_banned(self): # Test that members who are banned by specific address cannot # subscribe to the mailing list. IBanManager(None).ban('anne@example.com') self.assertRaises( MembershipIsBannedError, add_member, self._mlist, RequestRecord('anne@example.com', 'Anne Person', DeliveryMode.regular, system_preferences.preferred_language)) def test_add_member_banned_from_different_list(self): # Test that members who are banned by on a different list can still be # subscribed to other mlists. sample_list = create_list('sample@example.com') IBanManager(sample_list).ban('anne@example.com') member = add_member( self._mlist, RequestRecord('anne@example.com', 'Anne Person', DeliveryMode.regular, system_preferences.preferred_language)) self.assertEqual(member.address.email, 'anne@example.com') def test_add_member_banned_by_pattern(self): # Addresses matching regexp ban patterns cannot subscribe. IBanManager(self._mlist).ban('^.*@example.com') self.assertRaises( MembershipIsBannedError, add_member, self._mlist, RequestRecord('anne@example.com', 'Anne Person', DeliveryMode.regular, system_preferences.preferred_language)) def test_add_member_globally_banned_by_pattern(self): # Addresses matching global regexp ban patterns cannot subscribe. IBanManager(None).ban('^.*@example.com') self.assertRaises( MembershipIsBannedError, add_member, self._mlist, RequestRecord('anne@example.com', 'Anne Person', DeliveryMode.regular, system_preferences.preferred_language)) def test_add_member_banned_from_different_list_by_pattern(self): # Addresses matching regexp ban patterns on one list can still # subscribe to other mailing lists. sample_list = create_list('sample@example.com') IBanManager(sample_list).ban('^.*@example.com') member = add_member( self._mlist, RequestRecord('anne@example.com', 'Anne Person', DeliveryMode.regular, system_preferences.preferred_language)) self.assertEqual(member.address.email, 'anne@example.com') def test_add_member_moderator(self): # Test adding a moderator to a mailing list. member = add_member( self._mlist, RequestRecord('aperson@example.com', 'Anne Person', DeliveryMode.regular, system_preferences.preferred_language), MemberRole.moderator) self.assertEqual(member.address.email, 'aperson@example.com') self.assertEqual(member.list_id, 'test.example.com') self.assertEqual(member.role, MemberRole.moderator) def test_add_member_twice(self): # Adding a member with the same role twice causes an # AlreadySubscribedError to be raised. add_member( self._mlist, RequestRecord('aperson@example.com', 'Anne Person', DeliveryMode.regular, system_preferences.preferred_language), MemberRole.member) with self.assertRaises(AlreadySubscribedError) as cm: add_member( self._mlist, RequestRecord('aperson@example.com', 'Anne Person', DeliveryMode.regular, system_preferences.preferred_language), MemberRole.member) self.assertEqual(cm.exception.fqdn_listname, 'test@example.com') self.assertEqual(cm.exception.email, 'aperson@example.com') self.assertEqual(cm.exception.role, MemberRole.member) def test_add_member_with_different_roles(self): # Adding a member twice with different roles is okay. member_1 = add_member( self._mlist, RequestRecord('aperson@example.com', 'Anne Person', DeliveryMode.regular, system_preferences.preferred_language), MemberRole.member) member_2 = add_member( self._mlist, RequestRecord('aperson@example.com', 'Anne Person', DeliveryMode.regular, system_preferences.preferred_language), MemberRole.owner) self.assertEqual(member_1.list_id, member_2.list_id) self.assertEqual(member_1.address, member_2.address) self.assertEqual(member_1.user, member_2.user) self.assertNotEqual(member_1.member_id, member_2.member_id) self.assertEqual(member_1.role, MemberRole.member) self.assertEqual(member_2.role, MemberRole.owner) def test_add_member_with_mixed_case_email(self): # LP: #1425359 - Mailman is case-perserving, case-insensitive. This # test subscribes the lower case address and ensures the original # mixed case address can't be subscribed. email = 'APerson@example.com' add_member( self._mlist, RequestRecord(email.lower(), 'Ann Person', DeliveryMode.regular, system_preferences.preferred_language)) with self.assertRaises(AlreadySubscribedError) as cm: add_member( self._mlist, RequestRecord(email, 'Ann Person', DeliveryMode.regular, system_preferences.preferred_language)) self.assertEqual(cm.exception.email, email) def test_add_member_with_lower_case_email(self): # LP: #1425359 - Mailman is case-perserving, case-insensitive. This # test subscribes the mixed case address and ensures the lower cased # address can't be added. email = 'APerson@example.com' add_member( self._mlist, RequestRecord(email, 'Ann Person', DeliveryMode.regular, system_preferences.preferred_language)) with self.assertRaises(AlreadySubscribedError) as cm: add_member( self._mlist, RequestRecord(email.lower(), 'Ann Person', DeliveryMode.regular, system_preferences.preferred_language)) self.assertEqual(cm.exception.email, email.lower()) class TestDeleteMember(unittest.TestCase): layer = ConfigLayer def setUp(self): self._mlist = create_list('test@example.com') def test_delete_member_not_a_member(self): # Try to delete an address which is not a member of the mailing list. with self.assertRaises(NotAMemberError) as cm: delete_member(self._mlist, 'noperson@example.com') self.assertEqual( str(cm.exception), 'noperson@example.com is not a member of test@example.com')
gpl-2.0
ondra-novak/blink
Tools/Scripts/webkitpy/common/net/unittestresults.py
155
2347
# Copyright (c) 2012, 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. import logging import xml.dom.minidom _log = logging.getLogger(__name__) class UnitTestResults(object): @classmethod def results_from_string(self, string): if not string: return None try: dom = xml.dom.minidom.parseString(string) failures = [] for testcase in dom.getElementsByTagName('testcase'): if testcase.getElementsByTagName('failure').length != 0: testname = testcase.getAttribute('name') classname = testcase.getAttribute('classname') failures.append("%s.%s" % (classname, testname)) return failures except xml.parsers.expat.ExpatError, e: _log.error("XML error %s parsing unit test output" % str(e)) return None
bsd-3-clause
tlatzko/spmcluster
.tox/2.6-cover/lib/python2.6/site-packages/pip/_vendor/__init__.py
252
2508
""" pip._vendor is for vendoring dependencies of pip to prevent needing pip to depend on something external. Files inside of pip._vendor should be considered immutable and should only be updated to versions from upstream. """ from __future__ import absolute_import import glob import os.path import sys # Downstream redistributors which have debundled our dependencies should also # patch this value to be true. This will trigger the additional patching # to cause things like "six" to be available as pip. DEBUNDLED = False # By default, look in this directory for a bunch of .whl files which we will # add to the beginning of sys.path before attempting to import anything. This # is done to support downstream re-distributors like Debian and Fedora who # wish to create their own Wheels for our dependencies to aid in debundling. WHEEL_DIR = os.path.abspath(os.path.dirname(__file__)) # Define a small helper function to alias our vendored modules to the real ones # if the vendored ones do not exist. This idea of this was taken from # https://github.com/kennethreitz/requests/pull/2567. def vendored(modulename): vendored_name = "{0}.{1}".format(__name__, modulename) try: __import__(vendored_name, globals(), locals(), level=0) except ImportError: __import__(modulename, globals(), locals(), level=0) sys.modules[vendored_name] = sys.modules[modulename] base, head = vendored_name.rsplit(".", 1) setattr(sys.modules[base], head, sys.modules[modulename]) # If we're operating in a debundled setup, then we want to go ahead and trigger # the aliasing of our vendored libraries as well as looking for wheels to add # to our sys.path. This will cause all of this code to be a no-op typically # however downstream redistributors can enable it in a consistent way across # all platforms. if DEBUNDLED: # Actually look inside of WHEEL_DIR to find .whl files and add them to the # front of our sys.path. sys.path[:] = glob.glob(os.path.join(WHEEL_DIR, "*.whl")) + sys.path # Actually alias all of our vendored dependencies. vendored("cachecontrol") vendored("colorama") vendored("distlib") vendored("html5lib") vendored("lockfile") vendored("six") vendored("six.moves") vendored("six.moves.urllib") vendored("packaging") vendored("packaging.version") vendored("packaging.specifiers") vendored("pkg_resources") vendored("progress") vendored("retrying") vendored("requests")
bsd-2-clause
MarcoFalke/bitcoin
test/functional/wallet_create_tx.py
6
3341
#!/usr/bin/env python3 # Copyright (c) 2018-2019 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import BitcoinTestFramework from test_framework.util import ( assert_equal, assert_raises_rpc_error, ) from test_framework.blocktools import ( TIME_GENESIS_BLOCK, ) class CreateTxWalletTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def skip_test_if_missing_module(self): self.skip_if_no_wallet() def run_test(self): self.log.info('Create some old blocks') self.nodes[0].setmocktime(TIME_GENESIS_BLOCK) self.nodes[0].generate(200) self.nodes[0].setmocktime(0) self.test_anti_fee_sniping() self.test_tx_size_too_large() def test_anti_fee_sniping(self): self.log.info('Check that we have some (old) blocks and that anti-fee-sniping is disabled') assert_equal(self.nodes[0].getblockchaininfo()['blocks'], 200) txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1) tx = self.nodes[0].decoderawtransaction(self.nodes[0].gettransaction(txid)['hex']) assert_equal(tx['locktime'], 0) self.log.info('Check that anti-fee-sniping is enabled when we mine a recent block') self.nodes[0].generate(1) txid = self.nodes[0].sendtoaddress(self.nodes[0].getnewaddress(), 1) tx = self.nodes[0].decoderawtransaction(self.nodes[0].gettransaction(txid)['hex']) assert 0 < tx['locktime'] <= 201 def test_tx_size_too_large(self): # More than 10kB of outputs, so that we hit -maxtxfee with a high feerate outputs = {self.nodes[0].getnewaddress(address_type='bech32'): 0.000025 for _ in range(400)} raw_tx = self.nodes[0].createrawtransaction(inputs=[], outputs=outputs) for fee_setting in ['-minrelaytxfee=0.01', '-mintxfee=0.01', '-paytxfee=0.01']: self.log.info('Check maxtxfee in combination with {}'.format(fee_setting)) self.restart_node(0, extra_args=[fee_setting]) assert_raises_rpc_error( -6, "Fee exceeds maximum configured by user (e.g. -maxtxfee, maxfeerate)", lambda: self.nodes[0].sendmany(dummy="", amounts=outputs), ) assert_raises_rpc_error( -4, "Fee exceeds maximum configured by user (e.g. -maxtxfee, maxfeerate)", lambda: self.nodes[0].fundrawtransaction(hexstring=raw_tx), ) self.log.info('Check maxtxfee in combination with settxfee') self.restart_node(0) self.nodes[0].settxfee(0.01) assert_raises_rpc_error( -6, "Fee exceeds maximum configured by user (e.g. -maxtxfee, maxfeerate)", lambda: self.nodes[0].sendmany(dummy="", amounts=outputs), ) assert_raises_rpc_error( -4, "Fee exceeds maximum configured by user (e.g. -maxtxfee, maxfeerate)", lambda: self.nodes[0].fundrawtransaction(hexstring=raw_tx), ) self.nodes[0].settxfee(0) if __name__ == '__main__': CreateTxWalletTest().main()
mit
mrkm4ntr/incubator-airflow
airflow/providers/amazon/aws/sensors/sagemaker_endpoint.py
7
2048
# # 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. from airflow.providers.amazon.aws.hooks.sagemaker import SageMakerHook from airflow.providers.amazon.aws.sensors.sagemaker_base import SageMakerBaseSensor from airflow.utils.decorators import apply_defaults class SageMakerEndpointSensor(SageMakerBaseSensor): """ Asks for the state of the endpoint state until it reaches a terminal state. If it fails the sensor errors, the task fails. :param job_name: job_name of the endpoint instance to check the state of :type job_name: str """ template_fields = ['endpoint_name'] template_ext = () @apply_defaults def __init__(self, *, endpoint_name, **kwargs): super().__init__(**kwargs) self.endpoint_name = endpoint_name def non_terminal_states(self): return SageMakerHook.endpoint_non_terminal_states def failed_states(self): return SageMakerHook.failed_states def get_sagemaker_response(self): self.log.info('Poking Sagemaker Endpoint %s', self.endpoint_name) return self.get_hook().describe_endpoint(self.endpoint_name) def get_failed_reason_from_response(self, response): return response['FailureReason'] def state_from_response(self, response): return response['EndpointStatus']
apache-2.0
pombredanne/rekall
rekall-core/rekall/plugins/windows/kpcr.py
7
3975
# Rekall Memory Forensics # # Copyright 2013 Google Inc. All Rights Reserved. # # Authors: # Michael Cohen <scudette@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # """This plugin is used for displaying information about the Kernel Processor Control Blocks. """ # pylint: disable=protected-access from rekall import obj from rekall.plugins.windows import common class KPCR(common.WindowsCommandPlugin): """A plugin to print all KPCR blocks.""" __name = "kpcr" def kpcr(self): """A generator of KPCR objects (one for each CPU).""" # On windows 7 the KPCR is just stored in a symbol. initial_pcr = self.profile.get_constant_object( "KiInitialPCR", "_KPCR") # Validate the PCR through the self member. self_Pcr = initial_pcr.m("SelfPcr") or initial_pcr.m("Self") if self_Pcr.v() == initial_pcr.obj_offset: return initial_pcr # On windows XP the KPCR is hardcoded to 0xFFDFF000 pcr = self.profile._KPCR(0xFFDFF000) if pcr.SelfPcr.v() == pcr.obj_offset: return pcr return obj.NoneObject("Unknown KPCR") def render(self, renderer): kpcr = self.kpcr() renderer.section() renderer.table_header([("Property", "property", "<30"), ("Value", "value", "<")]) renderer.table_row("Offset (V)", "%#x" % kpcr.obj_offset) renderer.table_row("KdVersionBlock", kpcr.KdVersionBlock, style="full") renderer.table_row("IDT", "%#x" % kpcr.IDT) renderer.table_row("GDT", "%#x" % kpcr.GDT) current_thread = kpcr.ProcessorBlock.CurrentThread idle_thread = kpcr.ProcessorBlock.IdleThread next_thread = kpcr.ProcessorBlock.NextThread if current_thread: renderer.format("{0:<30}: {1:#x} TID {2} ({3}:{4})\n", "CurrentThread", current_thread, current_thread.Cid.UniqueThread, current_thread.owning_process().ImageFileName, current_thread.Cid.UniqueProcess, ) if idle_thread: renderer.format("{0:<30}: {1:#x} TID {2} ({3}:{4})\n", "IdleThread", idle_thread, idle_thread.Cid.UniqueThread, idle_thread.owning_process().ImageFileName, idle_thread.Cid.UniqueProcess, ) if next_thread: renderer.format("{0:<30}: {1:#x} TID {2} ({3}:{4})\n", "NextThread", next_thread, next_thread.Cid.UniqueThread, next_thread.owning_process().ImageFileName, next_thread.Cid.UniqueProcess, ) renderer.format("{0:<30}: CPU {1} ({2} @ {3} MHz)\n", "Details", kpcr.ProcessorBlock.Number, kpcr.ProcessorBlock.VendorString, kpcr.ProcessorBlock.MHz) renderer.format( "{0:<30}: {1:#x}\n", "CR3/DTB", kpcr.ProcessorBlock.ProcessorState.SpecialRegisters.Cr3)
gpl-2.0
rbalda/neural_ocr
env/lib/python2.7/site-packages/pybrain/rl/environments/functions/function.py
3
1960
__author__ = 'Tom Schaul, tom@idsia.ch' from scipy import zeros, array, ndarray from pybrain.rl.environments import Environment from pybrain.structure.parametercontainer import ParameterContainer from pybrain.rl.environments.fitnessevaluator import FitnessEvaluator class FunctionEnvironment(Environment, FitnessEvaluator): """ A n-to-1 mapping function to be with a single minimum of value zero, at xopt. """ # what input dimensions can the function have? xdimMin = 1 xdimMax = None xdim = None # the (single) point where f = 0 xopt = None # what would be the desired performance? by default: something close to zero desiredValue = 1e-10 toBeMinimized = True def __init__(self, xdim = None, xopt = None): if xdim is None: xdim = self.xdim if xdim is None: xdim = self.xdimMin assert xdim >= self.xdimMin and not (self.xdimMax is not None and xdim > self.xdimMax) self.xdim = xdim if xopt is None: self.xopt = zeros(self.xdim) else: self.xopt = xopt self.reset() def __call__(self, x): if isinstance(x, ParameterContainer): x = x.params assert type(x) == ndarray, 'FunctionEnvironment: Input not understood: '+str(type(x)) return self.f(x) # methods for conforming to the Environment interface: def reset(self): self.result = None def getSensors(self): """ the one sensor is the function result. """ tmp = self.result assert tmp is not None self.result = None return array([tmp]) def performAction(self, action): """ the action is an array of values for the function """ self.result = self(action) @property def indim(self): return self.xdim # does not provide any observations outdim = 0
mit
xpclove/autofp
strategy/strategy_neutron_tof.py
1
2601
'''strategy setting file, note: this is an important file. You should be careful when modifying the file. Please keep the format. The words is case sensitive. You can modify parameters group order in 'param_order' and parameters group in 'param_group'. ''' strategy={ "neutron_tof":{ # task type "type":"neutron_tof", # param group format: 'group_name':[ group_member1,group_member2,...] "param_group":{ 'scale': ["Scale","Extinct"], 'zero': ["Transparency","Zero"], 'simple background': ["BACK[0]"], 'cell a,b,c': ["a-Pha","b-P","c-P"], 'W': ["W-Pr"], 'complex background': ["BACK"], "UVW": ["Sig2-Pr", "Sig1-Pr","Sig0-Pr"], "Asym": ["ALPH","BETA"], 'Y,X': ["Gam1-Pr","Gam2-Pr"], 'Atom x y z': ["X-Atom","Y-Atom","Z-Atom"], 'Pref,Bov': ["Pref","Bov"], 'Biso-Atom': ["Biso-Atom"], 'GausS,1G': ["Z1","GausS","1G"], 'Occ-Atom': ["Occ-Atom"], 'Anisotropic Thermal factors': ["B1","B2","B3"], 'D_H': ["D_HG2","D_HL","Shift"], 'S_L,D_L': ["PA", "S_L","D_L"], #"Sysin","Displacement", #"Dtt1", # == "Sysin","Displacement", #"Gam0" # == "LorSiz","SZ", #"LStr","LSiz","Str", 'instrument': ["Dtt2"#,"Sycos","Transparency" #"Str", ], "manual background": ["BCK"], 'ABS':["ABS"] }, # param order format: [group_name1,group_name2,...] 'param_order': [ "scale", "cell a,b,c", "simple background" , "zero", "Atom x y z", "Asym", "Biso-Atom", "complex background" , "UVW", "Y,X", 'D_H', "Pref,Bov", "GausS,1G", "instrument", "Occ-Atom", "Anisotropic Thermal factors", "ABS", "manual background" ], # target function, the valid variable : R_Factor["Rwp"], R_Factor["Rp"], R_Factor["Chi2"] # MIN = minimum function 'target':'MIN=R_Factor["Rwp"]' } }
gpl-3.0
akhilari7/pa-dude
lib/python2.7/site-packages/django/views/defaults.py
339
3567
from django import http from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils import six from django.utils.encoding import force_text from django.views.decorators.csrf import requires_csrf_token # This can be called when CsrfViewMiddleware.process_view has not run, # therefore need @requires_csrf_token in case the template needs # {% csrf_token %}. @requires_csrf_token def page_not_found(request, exception, template_name='404.html'): """ Default 404 handler. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/') exception The message from the exception which triggered the 404 (if one was supplied), or the exception class name """ exception_repr = exception.__class__.__name__ # Try to get an "interesting" exception message, if any (and not the ugly # Resolver404 dictionary) try: message = exception.args[0] except (AttributeError, IndexError): pass else: if isinstance(message, six.text_type): exception_repr = message context = { 'request_path': request.path, 'exception': exception_repr, } try: template = loader.get_template(template_name) body = template.render(context, request) content_type = None # Django will use DEFAULT_CONTENT_TYPE except TemplateDoesNotExist: template = Engine().from_string( '<h1>Not Found</h1>' '<p>The requested URL {{ request_path }} was not found on this server.</p>') body = template.render(Context(context)) content_type = 'text/html' return http.HttpResponseNotFound(body, content_type=content_type) @requires_csrf_token def server_error(request, template_name='500.html'): """ 500 error handler. Templates: :template:`500.html` Context: None """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseServerError('<h1>Server Error (500)</h1>', content_type='text/html') return http.HttpResponseServerError(template.render()) @requires_csrf_token def bad_request(request, exception, template_name='400.html'): """ 400 error handler. Templates: :template:`400.html` Context: None """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html') # No exception content is passed to the template, to not disclose any sensitive information. return http.HttpResponseBadRequest(template.render()) # This can be called when CsrfViewMiddleware.process_view has not run, # therefore need @requires_csrf_token in case the template needs # {% csrf_token %}. @requires_csrf_token def permission_denied(request, exception, template_name='403.html'): """ Permission denied (403) handler. Templates: :template:`403.html` Context: None If the template does not exist, an Http403 response containing the text "403 Forbidden" (as per RFC 2616) will be returned. """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseForbidden('<h1>403 Forbidden</h1>', content_type='text/html') return http.HttpResponseForbidden( template.render(request=request, context={'exception': force_text(exception)}) )
mit
randymxj/OpenPythonSensor
lib_mpu6050/lib_mpu6050.py
2
4879
#!/usr/bin/python import time, datetime, math from ops_i2cbase import I2CBase # =========================================================================== # MPU6050 Class # # Ported from http://blog.bitify.co.uk/2013/11/reading-data-from-mpu-6050-on-raspberry.html # =========================================================================== class MPU6050: i2c = None # MPU6050 Address address = 0x68 # Command / Register Address MPU6050_PWR_MGMT_1 = 0x6B #R/W MPU6050_PWR_MGMT_2 = 0x6C #R/W MPU6050_RA_ACCEL_XOUT_H = 0x3B #R MPU6050_RA_ACCEL_XOUT_L = 0x3C #R MPU6050_RA_ACCEL_YOUT_H = 0x3D #R MPU6050_RA_ACCEL_YOUT_L = 0x3E #R MPU6050_RA_ACCEL_ZOUT_H = 0x3F #R MPU6050_RA_ACCEL_ZOUT_L = 0x40 #R MPU6050_RA_TEMP_OUT_H = 0x41 #R MPU6050_RA_TEMP_OUT_L = 0x42 #R MPU6050_RA_GYRO_XOUT_H = 0x43 #R MPU6050_RA_GYRO_XOUT_L = 0x44 #R MPU6050_RA_GYRO_YOUT_H = 0x45 #R MPU6050_RA_GYRO_YOUT_L = 0x46 #R MPU6050_RA_GYRO_ZOUT_H = 0x47 #R MPU6050_RA_GYRO_ZOUT_L = 0x48 #R MPU6050_PWR1_SLEEP_BIT = 6 # Constant pi = 3.1415926 AcceRatio = 16384.0 GyroRatio = 131.0 # Variable offset_acc_x = 0 offset_acc_y = 0 offset_acc_z = 0 offset_gyr_x = 0 offset_gyr_y = 0 offset_gyr_z = 0 last_read_time = datetime.datetime.now() # Constructor def __init__(self): self.i2c = I2CBase(self.address) self.initialize() def initialize(self): "Initiate the sensor by set and clear the power sleep bit, and collector an average offset" # Set the sleep bit self.setBit(self.MPU6050_PWR_MGMT_1, self.MPU6050_PWR1_SLEEP_BIT) # Clear the sleep bit self.clearBit(self.MPU6050_PWR_MGMT_1, self.MPU6050_PWR1_SLEEP_BIT) # The above Set/Clear process is necessary to prevent the sensor going halt or freeze # Take simple and calculate the average offset simple_time = 200 sum_acc_x = 0 sum_acc_y = 0 sum_acc_z = 0 sum_gyro_x = 0 sum_gyro_y = 0 sum_gyro_z = 0 for i in range(simple_time): x_accel = self.readSint16(self.MPU6050_RA_ACCEL_XOUT_H) / self.AcceRatio y_accel = self.readSint16(self.MPU6050_RA_ACCEL_YOUT_H) / self.AcceRatio z_accel = self.readSint16(self.MPU6050_RA_ACCEL_ZOUT_H) / self.AcceRatio x_gyro = self.readSint16(self.MPU6050_RA_GYRO_XOUT_H) / self.AcceRatio y_gyro = self.readSint16(self.MPU6050_RA_GYRO_YOUT_H) / self.AcceRatio z_gyro = self.readSint16(self.MPU6050_RA_GYRO_ZOUT_H) / self.AcceRatio temperature = self.readSint16(self.MPU6050_RA_TEMP_OUT_H) temperature = (temperature + 521.0) / 340.0 + 35.0 sum_acc_x += x_accel sum_acc_y += y_accel sum_acc_z += z_accel sum_gyro_x += x_gyro sum_gyro_y += y_gyro sum_gyro_z += z_gyro self.offset_acc_x = sum_acc_x / simple_time self.offset_acc_y = sum_acc_y / simple_time self.offset_acc_z = sum_acc_z / simple_time self.offset_gyr_x = sum_gyro_x / simple_time self.offset_gyr_y = sum_gyro_y / simple_time self.offset_gyr_z = sum_gyro_z / simple_time def setBit(self, register, bit): "Set a bit in the register" # Read original = self.i2c.readU8(register) # Set self.i2c.write8( register, original | ( 0x01 << bit ) ) def clearBit(self, register, bit): "Clear a bit in the register" # Read original = self.i2c.readU8(register) # Clear self.i2c.write8( register, original ^ ( 0x01 << bit ) ) def readSint16(self, address): "Read a signed 16 bits register" high = self.i2c.readU8(address) low = self.i2c.readU8(address + 1) value = (high << 8) + low if (value >= 0x8000): return -((65535 - value) + 1) else: return value def readMPU6050(self): "Read and return the Gyro and the Accelerometer value" current_time = datetime.datetime.now() dt_timedelta = ( current_time - self.last_read_time ) dt_milliseconds = ( dt_timedelta.seconds * 1000 * 1000 + dt_timedelta.microseconds ) / 1000 self.last_read_time = current_time x_accel = self.readSint16(self.MPU6050_RA_ACCEL_XOUT_H) / self.AcceRatio y_accel = self.readSint16(self.MPU6050_RA_ACCEL_YOUT_H) / self.AcceRatio z_accel = self.readSint16(self.MPU6050_RA_ACCEL_ZOUT_H) / self.AcceRatio x_gyro = self.readSint16(self.MPU6050_RA_GYRO_XOUT_H) / self.AcceRatio y_gyro = self.readSint16(self.MPU6050_RA_GYRO_YOUT_H) / self.AcceRatio z_gyro = self.readSint16(self.MPU6050_RA_GYRO_ZOUT_H) / self.AcceRatio temperature = self.readSint16(self.MPU6050_RA_TEMP_OUT_H) temperature = (temperature + 521.0) / 340.0 + 35.0 x_rotation = -math.degrees( math.atan2(x_accel, math.sqrt((y_accel*y_accel)+(z_accel*z_accel))) ) y_rotation = math.degrees( math.atan2(y_accel, math.sqrt((x_accel*x_accel)+(z_accel*z_accel))) ) return x_accel, y_accel, z_accel, x_gyro, y_gyro, z_gyro, temperature, x_rotation, y_rotation
mit
np/alot
alot/settings/checks.py
9
4769
# Copyright (C) 2011-2012 Patrick Totzke <patricktotzke@gmail.com> # This file is released under the GNU GPL, version 3 or a later revision. # For further details see the COPYING file import mailbox import re from urwid import AttrSpec, AttrSpecError from urlparse import urlparse from validate import VdtTypeError from validate import is_list from validate import ValidateError, VdtValueTooLongError, VdtValueError from alot import crypto from alot.errors import GPGProblem def attr_triple(value): """ Check that interprets the value as `urwid.AttrSpec` triple for the colour modes 1,16 and 256. It assumes a <6 tuple of attribute strings for mono foreground, mono background, 16c fg, 16c bg, 256 fg and 256 bg respectively. If any of these are missing, we downgrade to the next lower available pair, defaulting to 'default'. :raises: VdtValueTooLongError, VdtTypeError :rtype: triple of `urwid.AttrSpec` """ keys = ['dfg', 'dbg', '1fg', '1bg', '16fg', '16bg', '256fg', '256bg'] acc = {} if not isinstance(value, (list, tuple)): value = value, if len(value) > 6: raise VdtValueTooLongError(value) # ensure we have exactly 6 attribute strings attrstrings = (value + (6 - len(value)) * [None])[:6] # add fallbacks for the empty list attrstrings = (2 * ['default']) + attrstrings for i, value in enumerate(attrstrings): if value: acc[keys[i]] = value else: acc[keys[i]] = acc[keys[i - 2]] try: mono = AttrSpec(acc['1fg'], acc['1bg'], 1) normal = AttrSpec(acc['16fg'], acc['16bg'], 16) high = AttrSpec(acc['256fg'], acc['256bg'], 256) except AttrSpecError, e: raise ValidateError(e.message) return mono, normal, high def align_mode(value): """ test if value is one of 'left', 'right' or 'center' """ if value not in ['left', 'right', 'center']: raise VdtValueError return value def width_tuple(value): """ test if value is a valid width indicator (for a sub-widget in a column). This can either be ('fit', min, max): use the length actually needed for the content, padded to use at least width min, and cut of at width max. Here, min and max are positive integers or 0 to disable the boundary. ('weight',n): have it relative weight of n compared to other columns. Here, n is an int. """ if value is None: res = 'fit', 0, 0 elif not isinstance(value, (list, tuple)): raise VdtTypeError(value) elif value[0] not in ['fit', 'weight']: raise VdtTypeError(value) if value[0] == 'fit': if not isinstance(value[1], int) or not isinstance(value[2], int): VdtTypeError(value) res = 'fit', int(value[1]), int(value[2]) else: if not isinstance(value[1], int): VdtTypeError(value) res = 'weight', int(value[1]) return res def mail_container(value): """ Check that the value points to a valid mail container, in URI-style, e.g.: `mbox:///home/username/mail/mail.box`. The value is cast to a :class:`mailbox.Mailbox` object. """ if not re.match(r'.*://.*', value): raise VdtTypeError(value) mburl = urlparse(value) if mburl.scheme == 'mbox': box = mailbox.mbox(mburl.path) elif mburl.scheme == 'maildir': box = mailbox.Maildir(mburl.path) elif mburl.scheme == 'mh': box = mailbox.MH(mburl.path) elif mburl.scheme == 'babyl': box = mailbox.Babyl(mburl.path) elif mburl.scheme == 'mmdf': box = mailbox.MMDF(mburl.path) else: raise VdtTypeError(value) return box def force_list(value, min=None, max=None): """ Check that a value is a list, coercing strings into a list with one member. You can optionally specify the minimum and maximum number of members. A minumum of greater than one will fail if the user only supplies a string. The difference to :func:`validate.force_list` is that this test will return an empty list instead of `['']` if the config value matches `r'\s*,?\s*'`. >>> vtor.check('force_list', 'hello') ['hello'] >>> vtor.check('force_list', '') [] """ if not isinstance(value, (list, tuple)): value = [value] rlist = is_list(value, min, max) if rlist == ['']: rlist = [] return rlist def gpg_key(value): """ test if value points to a known gpg key and return that key as :class:`pyme.pygpgme._gpgme_key`. """ try: return crypto.get_key(value) except GPGProblem, e: raise ValidateError(e.message)
gpl-3.0
halvertoluke/edx-platform
cms/djangoapps/contentstore/management/commands/force_publish.py
61
3385
""" Script for force publishing a course """ from django.core.management.base import BaseCommand, CommandError from xmodule.modulestore import ModuleStoreEnum from xmodule.modulestore.django import modulestore from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from .prompt import query_yes_no from .utils import get_course_versions # To run from command line: ./manage.py cms force_publish course-v1:org+course+run class Command(BaseCommand): """Force publish a course""" help = ''' Force publish a course. Takes two arguments: <course_id>: the course id of the course you want to publish forcefully --commit: do the force publish If you do not specify '--commit', the command will print out what changes would be made. ''' def add_arguments(self, parser): parser.add_argument('course_key', help="ID of the Course to force publish") parser.add_argument('--commit', action='store_true', help="Pull updated metadata from external IDPs") def handle(self, *args, **options): """Execute the command""" try: course_key = CourseKey.from_string(options['course_key']) except InvalidKeyError: raise CommandError("Invalid course key.") if not modulestore().get_course(course_key): raise CommandError("Course not found.") # for now only support on split mongo owning_store = modulestore()._get_modulestore_for_courselike(course_key) # pylint: disable=protected-access if hasattr(owning_store, 'force_publish_course'): versions = get_course_versions(options['course_key']) print "Course versions : {0}".format(versions) if options['commit']: if query_yes_no("Are you sure to publish the {0} course forcefully?".format(course_key), default="no"): # publish course forcefully updated_versions = owning_store.force_publish_course( course_key, ModuleStoreEnum.UserID.mgmt_command, options['commit'] ) if updated_versions: # if publish and draft were different if versions['published-branch'] != versions['draft-branch']: print "Success! Published the course '{0}' forcefully.".format(course_key) print "Updated course versions : \n{0}".format(updated_versions) else: print "Course '{0}' is already in published state.".format(course_key) else: print "Error! Could not publish course {0}.".format(course_key) else: # if publish and draft were different if versions['published-branch'] != versions['draft-branch']: print "Dry run. Following would have been changed : " print "Published branch version {0} changed to draft branch version {1}".format( versions['published-branch'], versions['draft-branch'] ) else: print "Dry run. Course '{0}' is already in published state.".format(course_key) else: raise CommandError("The owning modulestore does not support this command.")
agpl-3.0
wschwa/Mr-Orange-Sick-Beard
lib/requests/packages/chardet2/gb2312freq.py
323
36001
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client 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 ######################### # GB2312 most frequently used character table # # Char to FreqOrder table , from hz6763 # 512 --> 0.79 -- 0.79 # 1024 --> 0.92 -- 0.13 # 2048 --> 0.98 -- 0.06 # 6768 --> 1.00 -- 0.02 # # Ideal Distribution Ratio = 0.79135/(1-0.79135) = 3.79 # Random Distribution Ration = 512 / (3755 - 512) = 0.157 # # Typical Distribution Ratio about 25% of Ideal one, still much higher that RDR GB2312_TYPICAL_DISTRIBUTION_RATIO = 0.9 GB2312_TABLE_SIZE = 3760 GB2312CharToFreqOrder = ( \ 1671, 749,1443,2364,3924,3807,2330,3921,1704,3463,2691,1511,1515, 572,3191,2205, 2361, 224,2558, 479,1711, 963,3162, 440,4060,1905,2966,2947,3580,2647,3961,3842, 2204, 869,4207, 970,2678,5626,2944,2956,1479,4048, 514,3595, 588,1346,2820,3409, 249,4088,1746,1873,2047,1774, 581,1813, 358,1174,3590,1014,1561,4844,2245, 670, 1636,3112, 889,1286, 953, 556,2327,3060,1290,3141, 613, 185,3477,1367, 850,3820, 1715,2428,2642,2303,2732,3041,2562,2648,3566,3946,1349, 388,3098,2091,1360,3585, 152,1687,1539, 738,1559, 59,1232,2925,2267,1388,1249,1741,1679,2960, 151,1566, 1125,1352,4271, 924,4296, 385,3166,4459, 310,1245,2850, 70,3285,2729,3534,3575, 2398,3298,3466,1960,2265, 217,3647, 864,1909,2084,4401,2773,1010,3269,5152, 853, 3051,3121,1244,4251,1895, 364,1499,1540,2313,1180,3655,2268, 562, 715,2417,3061, 544, 336,3768,2380,1752,4075, 950, 280,2425,4382, 183,2759,3272, 333,4297,2155, 1688,2356,1444,1039,4540, 736,1177,3349,2443,2368,2144,2225, 565, 196,1482,3406, 927,1335,4147, 692, 878,1311,1653,3911,3622,1378,4200,1840,2969,3149,2126,1816, 2534,1546,2393,2760, 737,2494, 13, 447, 245,2747, 38,2765,2129,2589,1079, 606, 360, 471,3755,2890, 404, 848, 699,1785,1236, 370,2221,1023,3746,2074,2026,2023, 2388,1581,2119, 812,1141,3091,2536,1519, 804,2053, 406,1596,1090, 784, 548,4414, 1806,2264,2936,1100, 343,4114,5096, 622,3358, 743,3668,1510,1626,5020,3567,2513, 3195,4115,5627,2489,2991, 24,2065,2697,1087,2719, 48,1634, 315, 68, 985,2052, 198,2239,1347,1107,1439, 597,2366,2172, 871,3307, 919,2487,2790,1867, 236,2570, 1413,3794, 906,3365,3381,1701,1982,1818,1524,2924,1205, 616,2586,2072,2004, 575, 253,3099, 32,1365,1182, 197,1714,2454,1201, 554,3388,3224,2748, 756,2587, 250, 2567,1507,1517,3529,1922,2761,2337,3416,1961,1677,2452,2238,3153, 615, 911,1506, 1474,2495,1265,1906,2749,3756,3280,2161, 898,2714,1759,3450,2243,2444, 563, 26, 3286,2266,3769,3344,2707,3677, 611,1402, 531,1028,2871,4548,1375, 261,2948, 835, 1190,4134, 353, 840,2684,1900,3082,1435,2109,1207,1674, 329,1872,2781,4055,2686, 2104, 608,3318,2423,2957,2768,1108,3739,3512,3271,3985,2203,1771,3520,1418,2054, 1681,1153, 225,1627,2929, 162,2050,2511,3687,1954, 124,1859,2431,1684,3032,2894, 585,4805,3969,2869,2704,2088,2032,2095,3656,2635,4362,2209, 256, 518,2042,2105, 3777,3657, 643,2298,1148,1779, 190, 989,3544, 414, 11,2135,2063,2979,1471, 403, 3678, 126, 770,1563, 671,2499,3216,2877, 600,1179, 307,2805,4937,1268,1297,2694, 252,4032,1448,1494,1331,1394, 127,2256, 222,1647,1035,1481,3056,1915,1048, 873, 3651, 210, 33,1608,2516, 200,1520, 415, 102, 0,3389,1287, 817, 91,3299,2940, 836,1814, 549,2197,1396,1669,2987,3582,2297,2848,4528,1070, 687, 20,1819, 121, 1552,1364,1461,1968,2617,3540,2824,2083, 177, 948,4938,2291, 110,4549,2066, 648, 3359,1755,2110,2114,4642,4845,1693,3937,3308,1257,1869,2123, 208,1804,3159,2992, 2531,2549,3361,2418,1350,2347,2800,2568,1291,2036,2680, 72, 842,1990, 212,1233, 1154,1586, 75,2027,3410,4900,1823,1337,2710,2676, 728,2810,1522,3026,4995, 157, 755,1050,4022, 710, 785,1936,2194,2085,1406,2777,2400, 150,1250,4049,1206, 807, 1910, 534, 529,3309,1721,1660, 274, 39,2827, 661,2670,1578, 925,3248,3815,1094, 4278,4901,4252, 41,1150,3747,2572,2227,4501,3658,4902,3813,3357,3617,2884,2258, 887, 538,4187,3199,1294,2439,3042,2329,2343,2497,1255, 107, 543,1527, 521,3478, 3568, 194,5062, 15, 961,3870,1241,1192,2664, 66,5215,3260,2111,1295,1127,2152, 3805,4135, 901,1164,1976, 398,1278, 530,1460, 748, 904,1054,1966,1426, 53,2909, 509, 523,2279,1534, 536,1019, 239,1685, 460,2353, 673,1065,2401,3600,4298,2272, 1272,2363, 284,1753,3679,4064,1695, 81, 815,2677,2757,2731,1386, 859, 500,4221, 2190,2566, 757,1006,2519,2068,1166,1455, 337,2654,3203,1863,1682,1914,3025,1252, 1409,1366, 847, 714,2834,2038,3209, 964,2970,1901, 885,2553,1078,1756,3049, 301, 1572,3326, 688,2130,1996,2429,1805,1648,2930,3421,2750,3652,3088, 262,1158,1254, 389,1641,1812, 526,1719, 923,2073,1073,1902, 468, 489,4625,1140, 857,2375,3070, 3319,2863, 380, 116,1328,2693,1161,2244, 273,1212,1884,2769,3011,1775,1142, 461, 3066,1200,2147,2212, 790, 702,2695,4222,1601,1058, 434,2338,5153,3640, 67,2360, 4099,2502, 618,3472,1329, 416,1132, 830,2782,1807,2653,3211,3510,1662, 192,2124, 296,3979,1739,1611,3684, 23, 118, 324, 446,1239,1225, 293,2520,3814,3795,2535, 3116, 17,1074, 467,2692,2201, 387,2922, 45,1326,3055,1645,3659,2817, 958, 243, 1903,2320,1339,2825,1784,3289, 356, 576, 865,2315,2381,3377,3916,1088,3122,1713, 1655, 935, 628,4689,1034,1327, 441, 800, 720, 894,1979,2183,1528,5289,2702,1071, 4046,3572,2399,1571,3281, 79, 761,1103, 327, 134, 758,1899,1371,1615, 879, 442, 215,2605,2579, 173,2048,2485,1057,2975,3317,1097,2253,3801,4263,1403,1650,2946, 814,4968,3487,1548,2644,1567,1285, 2, 295,2636, 97, 946,3576, 832, 141,4257, 3273, 760,3821,3521,3156,2607, 949,1024,1733,1516,1803,1920,2125,2283,2665,3180, 1501,2064,3560,2171,1592, 803,3518,1416, 732,3897,4258,1363,1362,2458, 119,1427, 602,1525,2608,1605,1639,3175, 694,3064, 10, 465, 76,2000,4846,4208, 444,3781, 1619,3353,2206,1273,3796, 740,2483, 320,1723,2377,3660,2619,1359,1137,1762,1724, 2345,2842,1850,1862, 912, 821,1866, 612,2625,1735,2573,3369,1093, 844, 89, 937, 930,1424,3564,2413,2972,1004,3046,3019,2011, 711,3171,1452,4178, 428, 801,1943, 432, 445,2811, 206,4136,1472, 730, 349, 73, 397,2802,2547, 998,1637,1167, 789, 396,3217, 154,1218, 716,1120,1780,2819,4826,1931,3334,3762,2139,1215,2627, 552, 3664,3628,3232,1405,2383,3111,1356,2652,3577,3320,3101,1703, 640,1045,1370,1246, 4996, 371,1575,2436,1621,2210, 984,4033,1734,2638, 16,4529, 663,2755,3255,1451, 3917,2257,1253,1955,2234,1263,2951, 214,1229, 617, 485, 359,1831,1969, 473,2310, 750,2058, 165, 80,2864,2419, 361,4344,2416,2479,1134, 796,3726,1266,2943, 860, 2715, 938, 390,2734,1313,1384, 248, 202, 877,1064,2854, 522,3907, 279,1602, 297, 2357, 395,3740, 137,2075, 944,4089,2584,1267,3802, 62,1533,2285, 178, 176, 780, 2440, 201,3707, 590, 478,1560,4354,2117,1075, 30, 74,4643,4004,1635,1441,2745, 776,2596, 238,1077,1692,1912,2844, 605, 499,1742,3947, 241,3053, 980,1749, 936, 2640,4511,2582, 515,1543,2162,5322,2892,2993, 890,2148,1924, 665,1827,3581,1032, 968,3163, 339,1044,1896, 270, 583,1791,1720,4367,1194,3488,3669, 43,2523,1657, 163,2167, 290,1209,1622,3378, 550, 634,2508,2510, 695,2634,2384,2512,1476,1414, 220,1469,2341,2138,2852,3183,2900,4939,2865,3502,1211,3680, 854,3227,1299,2976, 3172, 186,2998,1459, 443,1067,3251,1495, 321,1932,3054, 909, 753,1410,1828, 436, 2441,1119,1587,3164,2186,1258, 227, 231,1425,1890,3200,3942, 247, 959, 725,5254, 2741, 577,2158,2079, 929, 120, 174, 838,2813, 591,1115, 417,2024, 40,3240,1536, 1037, 291,4151,2354, 632,1298,2406,2500,3535,1825,1846,3451, 205,1171, 345,4238, 18,1163, 811, 685,2208,1217, 425,1312,1508,1175,4308,2552,1033, 587,1381,3059, 2984,3482, 340,1316,4023,3972, 792,3176, 519, 777,4690, 918, 933,4130,2981,3741, 90,3360,2911,2200,5184,4550, 609,3079,2030, 272,3379,2736, 363,3881,1130,1447, 286, 779, 357,1169,3350,3137,1630,1220,2687,2391, 747,1277,3688,2618,2682,2601, 1156,3196,5290,4034,3102,1689,3596,3128, 874, 219,2783, 798, 508,1843,2461, 269, 1658,1776,1392,1913,2983,3287,2866,2159,2372, 829,4076, 46,4253,2873,1889,1894, 915,1834,1631,2181,2318, 298, 664,2818,3555,2735, 954,3228,3117, 527,3511,2173, 681,2712,3033,2247,2346,3467,1652, 155,2164,3382, 113,1994, 450, 899, 494, 994, 1237,2958,1875,2336,1926,3727, 545,1577,1550, 633,3473, 204,1305,3072,2410,1956, 2471, 707,2134, 841,2195,2196,2663,3843,1026,4940, 990,3252,4997, 368,1092, 437, 3212,3258,1933,1829, 675,2977,2893, 412, 943,3723,4644,3294,3283,2230,2373,5154, 2389,2241,2661,2323,1404,2524, 593, 787, 677,3008,1275,2059, 438,2709,2609,2240, 2269,2246,1446, 36,1568,1373,3892,1574,2301,1456,3962, 693,2276,5216,2035,1143, 2720,1919,1797,1811,2763,4137,2597,1830,1699,1488,1198,2090, 424,1694, 312,3634, 3390,4179,3335,2252,1214, 561,1059,3243,2295,2561, 975,5155,2321,2751,3772, 472, 1537,3282,3398,1047,2077,2348,2878,1323,3340,3076, 690,2906, 51, 369, 170,3541, 1060,2187,2688,3670,2541,1083,1683, 928,3918, 459, 109,4427, 599,3744,4286, 143, 2101,2730,2490, 82,1588,3036,2121, 281,1860, 477,4035,1238,2812,3020,2716,3312, 1530,2188,2055,1317, 843, 636,1808,1173,3495, 649, 181,1002, 147,3641,1159,2414, 3750,2289,2795, 813,3123,2610,1136,4368, 5,3391,4541,2174, 420, 429,1728, 754, 1228,2115,2219, 347,2223,2733, 735,1518,3003,2355,3134,1764,3948,3329,1888,2424, 1001,1234,1972,3321,3363,1672,1021,1450,1584, 226, 765, 655,2526,3404,3244,2302, 3665, 731, 594,2184, 319,1576, 621, 658,2656,4299,2099,3864,1279,2071,2598,2739, 795,3086,3699,3908,1707,2352,2402,1382,3136,2475,1465,4847,3496,3865,1085,3004, 2591,1084, 213,2287,1963,3565,2250, 822, 793,4574,3187,1772,1789,3050, 595,1484, 1959,2770,1080,2650, 456, 422,2996, 940,3322,4328,4345,3092,2742, 965,2784, 739, 4124, 952,1358,2498,2949,2565, 332,2698,2378, 660,2260,2473,4194,3856,2919, 535, 1260,2651,1208,1428,1300,1949,1303,2942, 433,2455,2450,1251,1946, 614,1269, 641, 1306,1810,2737,3078,2912, 564,2365,1419,1415,1497,4460,2367,2185,1379,3005,1307, 3218,2175,1897,3063, 682,1157,4040,4005,1712,1160,1941,1399, 394, 402,2952,1573, 1151,2986,2404, 862, 299,2033,1489,3006, 346, 171,2886,3401,1726,2932, 168,2533, 47,2507,1030,3735,1145,3370,1395,1318,1579,3609,4560,2857,4116,1457,2529,1965, 504,1036,2690,2988,2405, 745,5871, 849,2397,2056,3081, 863,2359,3857,2096, 99, 1397,1769,2300,4428,1643,3455,1978,1757,3718,1440, 35,4879,3742,1296,4228,2280, 160,5063,1599,2013, 166, 520,3479,1646,3345,3012, 490,1937,1545,1264,2182,2505, 1096,1188,1369,1436,2421,1667,2792,2460,1270,2122, 727,3167,2143, 806,1706,1012, 1800,3037, 960,2218,1882, 805, 139,2456,1139,1521, 851,1052,3093,3089, 342,2039, 744,5097,1468,1502,1585,2087, 223, 939, 326,2140,2577, 892,2481,1623,4077, 982, 3708, 135,2131, 87,2503,3114,2326,1106, 876,1616, 547,2997,2831,2093,3441,4530, 4314, 9,3256,4229,4148, 659,1462,1986,1710,2046,2913,2231,4090,4880,5255,3392, 3274,1368,3689,4645,1477, 705,3384,3635,1068,1529,2941,1458,3782,1509, 100,1656, 2548, 718,2339, 408,1590,2780,3548,1838,4117,3719,1345,3530, 717,3442,2778,3220, 2898,1892,4590,3614,3371,2043,1998,1224,3483, 891, 635, 584,2559,3355, 733,1766, 1729,1172,3789,1891,2307, 781,2982,2271,1957,1580,5773,2633,2005,4195,3097,1535, 3213,1189,1934,5693,3262, 586,3118,1324,1598, 517,1564,2217,1868,1893,4445,3728, 2703,3139,1526,1787,1992,3882,2875,1549,1199,1056,2224,1904,2711,5098,4287, 338, 1993,3129,3489,2689,1809,2815,1997, 957,1855,3898,2550,3275,3057,1105,1319, 627, 1505,1911,1883,3526, 698,3629,3456,1833,1431, 746, 77,1261,2017,2296,1977,1885, 125,1334,1600, 525,1798,1109,2222,1470,1945, 559,2236,1186,3443,2476,1929,1411, 2411,3135,1777,3372,2621,1841,1613,3229, 668,1430,1839,2643,2916, 195,1989,2671, 2358,1387, 629,3205,2293,5256,4439, 123,1310, 888,1879,4300,3021,3605,1003,1162, 3192,2910,2010, 140,2395,2859, 55,1082,2012,2901, 662, 419,2081,1438, 680,2774, 4654,3912,1620,1731,1625,5035,4065,2328, 512,1344, 802,5443,2163,2311,2537, 524, 3399, 98,1155,2103,1918,2606,3925,2816,1393,2465,1504,3773,2177,3963,1478,4346, 180,1113,4655,3461,2028,1698, 833,2696,1235,1322,1594,4408,3623,3013,3225,2040, 3022, 541,2881, 607,3632,2029,1665,1219, 639,1385,1686,1099,2803,3231,1938,3188, 2858, 427, 676,2772,1168,2025, 454,3253,2486,3556, 230,1950, 580, 791,1991,1280, 1086,1974,2034, 630, 257,3338,2788,4903,1017, 86,4790, 966,2789,1995,1696,1131, 259,3095,4188,1308, 179,1463,5257, 289,4107,1248, 42,3413,1725,2288, 896,1947, 774,4474,4254, 604,3430,4264, 392,2514,2588, 452, 237,1408,3018, 988,4531,1970, 3034,3310, 540,2370,1562,1288,2990, 502,4765,1147, 4,1853,2708, 207, 294,2814, 4078,2902,2509, 684, 34,3105,3532,2551, 644, 709,2801,2344, 573,1727,3573,3557, 2021,1081,3100,4315,2100,3681, 199,2263,1837,2385, 146,3484,1195,2776,3949, 997, 1939,3973,1008,1091,1202,1962,1847,1149,4209,5444,1076, 493, 117,5400,2521, 972, 1490,2934,1796,4542,2374,1512,2933,2657, 413,2888,1135,2762,2314,2156,1355,2369, 766,2007,2527,2170,3124,2491,2593,2632,4757,2437, 234,3125,3591,1898,1750,1376, 1942,3468,3138, 570,2127,2145,3276,4131, 962, 132,1445,4196, 19, 941,3624,3480, 3366,1973,1374,4461,3431,2629, 283,2415,2275, 808,2887,3620,2112,2563,1353,3610, 955,1089,3103,1053, 96, 88,4097, 823,3808,1583, 399, 292,4091,3313, 421,1128, 642,4006, 903,2539,1877,2082, 596, 29,4066,1790, 722,2157, 130, 995,1569, 769, 1485, 464, 513,2213, 288,1923,1101,2453,4316, 133, 486,2445, 50, 625, 487,2207, 57, 423, 481,2962, 159,3729,1558, 491, 303, 482, 501, 240,2837, 112,3648,2392, 1783, 362, 8,3433,3422, 610,2793,3277,1390,1284,1654, 21,3823, 734, 367, 623, 193, 287, 374,1009,1483, 816, 476, 313,2255,2340,1262,2150,2899,1146,2581, 782, 2116,1659,2018,1880, 255,3586,3314,1110,2867,2137,2564, 986,2767,5185,2006, 650, 158, 926, 762, 881,3157,2717,2362,3587, 306,3690,3245,1542,3077,2427,1691,2478, 2118,2985,3490,2438, 539,2305, 983, 129,1754, 355,4201,2386, 827,2923, 104,1773, 2838,2771, 411,2905,3919, 376, 767, 122,1114, 828,2422,1817,3506, 266,3460,1007, 1609,4998, 945,2612,4429,2274, 726,1247,1964,2914,2199,2070,4002,4108, 657,3323, 1422, 579, 455,2764,4737,1222,2895,1670, 824,1223,1487,2525, 558, 861,3080, 598, 2659,2515,1967, 752,2583,2376,2214,4180, 977, 704,2464,4999,2622,4109,1210,2961, 819,1541, 142,2284, 44, 418, 457,1126,3730,4347,4626,1644,1876,3671,1864, 302, 1063,5694, 624, 723,1984,3745,1314,1676,2488,1610,1449,3558,3569,2166,2098, 409, 1011,2325,3704,2306, 818,1732,1383,1824,1844,3757, 999,2705,3497,1216,1423,2683, 2426,2954,2501,2726,2229,1475,2554,5064,1971,1794,1666,2014,1343, 783, 724, 191, 2434,1354,2220,5065,1763,2752,2472,4152, 131, 175,2885,3434, 92,1466,4920,2616, 3871,3872,3866, 128,1551,1632, 669,1854,3682,4691,4125,1230, 188,2973,3290,1302, 1213, 560,3266, 917, 763,3909,3249,1760, 868,1958, 764,1782,2097, 145,2277,3774, 4462, 64,1491,3062, 971,2132,3606,2442, 221,1226,1617, 218, 323,1185,3207,3147, 571, 619,1473,1005,1744,2281, 449,1887,2396,3685, 275, 375,3816,1743,3844,3731, 845,1983,2350,4210,1377, 773, 967,3499,3052,3743,2725,4007,1697,1022,3943,1464, 3264,2855,2722,1952,1029,2839,2467, 84,4383,2215, 820,1391,2015,2448,3672, 377, 1948,2168, 797,2545,3536,2578,2645, 94,2874,1678, 405,1259,3071, 771, 546,1315, 470,1243,3083, 895,2468, 981, 969,2037, 846,4181, 653,1276,2928, 14,2594, 557, 3007,2474, 156, 902,1338,1740,2574, 537,2518, 973,2282,2216,2433,1928, 138,2903, 1293,2631,1612, 646,3457, 839,2935, 111, 496,2191,2847, 589,3186, 149,3994,2060, 4031,2641,4067,3145,1870, 37,3597,2136,1025,2051,3009,3383,3549,1121,1016,3261, 1301, 251,2446,2599,2153, 872,3246, 637, 334,3705, 831, 884, 921,3065,3140,4092, 2198,1944, 246,2964, 108,2045,1152,1921,2308,1031, 203,3173,4170,1907,3890, 810, 1401,2003,1690, 506, 647,1242,2828,1761,1649,3208,2249,1589,3709,2931,5156,1708, 498, 666,2613, 834,3817,1231, 184,2851,1124, 883,3197,2261,3710,1765,1553,2658, 1178,2639,2351, 93,1193, 942,2538,2141,4402, 235,1821, 870,1591,2192,1709,1871, 3341,1618,4126,2595,2334, 603, 651, 69, 701, 268,2662,3411,2555,1380,1606, 503, 448, 254,2371,2646, 574,1187,2309,1770, 322,2235,1292,1801, 305, 566,1133, 229, 2067,2057, 706, 167, 483,2002,2672,3295,1820,3561,3067, 316, 378,2746,3452,1112, 136,1981, 507,1651,2917,1117, 285,4591, 182,2580,3522,1304, 335,3303,1835,2504, 1795,1792,2248, 674,1018,2106,2449,1857,2292,2845, 976,3047,1781,2600,2727,1389, 1281, 52,3152, 153, 265,3950, 672,3485,3951,4463, 430,1183, 365, 278,2169, 27, 1407,1336,2304, 209,1340,1730,2202,1852,2403,2883, 979,1737,1062, 631,2829,2542, 3876,2592, 825,2086,2226,3048,3625, 352,1417,3724, 542, 991, 431,1351,3938,1861, 2294, 826,1361,2927,3142,3503,1738, 463,2462,2723, 582,1916,1595,2808, 400,3845, 3891,2868,3621,2254, 58,2492,1123, 910,2160,2614,1372,1603,1196,1072,3385,1700, 3267,1980, 696, 480,2430, 920, 799,1570,2920,1951,2041,4047,2540,1321,4223,2469, 3562,2228,1271,2602, 401,2833,3351,2575,5157, 907,2312,1256, 410, 263,3507,1582, 996, 678,1849,2316,1480, 908,3545,2237, 703,2322, 667,1826,2849,1531,2604,2999, 2407,3146,2151,2630,1786,3711, 469,3542, 497,3899,2409, 858, 837,4446,3393,1274, 786, 620,1845,2001,3311, 484, 308,3367,1204,1815,3691,2332,1532,2557,1842,2020, 2724,1927,2333,4440, 567, 22,1673,2728,4475,1987,1858,1144,1597, 101,1832,3601, 12, 974,3783,4391, 951,1412, 1,3720, 453,4608,4041, 528,1041,1027,3230,2628, 1129, 875,1051,3291,1203,2262,1069,2860,2799,2149,2615,3278, 144,1758,3040, 31, 475,1680, 366,2685,3184, 311,1642,4008,2466,5036,1593,1493,2809, 216,1420,1668, 233, 304,2128,3284, 232,1429,1768,1040,2008,3407,2740,2967,2543, 242,2133, 778, 1565,2022,2620, 505,2189,2756,1098,2273, 372,1614, 708, 553,2846,2094,2278, 169, 3626,2835,4161, 228,2674,3165, 809,1454,1309, 466,1705,1095, 900,3423, 880,2667, 3751,5258,2317,3109,2571,4317,2766,1503,1342, 866,4447,1118, 63,2076, 314,1881, 1348,1061, 172, 978,3515,1747, 532, 511,3970, 6, 601, 905,2699,3300,1751, 276, 1467,3725,2668, 65,4239,2544,2779,2556,1604, 578,2451,1802, 992,2331,2624,1320, 3446, 713,1513,1013, 103,2786,2447,1661, 886,1702, 916, 654,3574,2031,1556, 751, 2178,2821,2179,1498,1538,2176, 271, 914,2251,2080,1325, 638,1953,2937,3877,2432, 2754, 95,3265,1716, 260,1227,4083, 775, 106,1357,3254, 426,1607, 555,2480, 772, 1985, 244,2546, 474, 495,1046,2611,1851,2061, 71,2089,1675,2590, 742,3758,2843, 3222,1433, 267,2180,2576,2826,2233,2092,3913,2435, 956,1745,3075, 856,2113,1116, 451, 3,1988,2896,1398, 993,2463,1878,2049,1341,2718,2721,2870,2108, 712,2904, 4363,2753,2324, 277,2872,2349,2649, 384, 987, 435, 691,3000, 922, 164,3939, 652, 1500,1184,4153,2482,3373,2165,4848,2335,3775,3508,3154,2806,2830,1554,2102,1664, 2530,1434,2408, 893,1547,2623,3447,2832,2242,2532,3169,2856,3223,2078, 49,3770, 3469, 462, 318, 656,2259,3250,3069, 679,1629,2758, 344,1138,1104,3120,1836,1283, 3115,2154,1437,4448, 934, 759,1999, 794,2862,1038, 533,2560,1722,2342, 855,2626, 1197,1663,4476,3127, 85,4240,2528, 25,1111,1181,3673, 407,3470,4561,2679,2713, 768,1925,2841,3986,1544,1165, 932, 373,1240,2146,1930,2673, 721,4766, 354,4333, 391,2963, 187, 61,3364,1442,1102, 330,1940,1767, 341,3809,4118, 393,2496,2062, 2211, 105, 331, 300, 439, 913,1332, 626, 379,3304,1557, 328, 689,3952, 309,1555, 931, 317,2517,3027, 325, 569, 686,2107,3084, 60,1042,1333,2794, 264,3177,4014, 1628, 258,3712, 7,4464,1176,1043,1778, 683, 114,1975, 78,1492, 383,1886, 510, 386, 645,5291,2891,2069,3305,4138,3867,2939,2603,2493,1935,1066,1848,3588,1015, 1282,1289,4609, 697,1453,3044,2666,3611,1856,2412, 54, 719,1330, 568,3778,2459, 1748, 788, 492, 551,1191,1000, 488,3394,3763, 282,1799, 348,2016,1523,3155,2390, 1049, 382,2019,1788,1170, 729,2968,3523, 897,3926,2785,2938,3292, 350,2319,3238, 1718,1717,2655,3453,3143,4465, 161,2889,2980,2009,1421, 56,1908,1640,2387,2232, 1917,1874,2477,4921, 148, 83,3438, 592,4245,2882,1822,1055, 741, 115,1496,1624, 381,1638,4592,1020, 516,3214, 458, 947,4575,1432, 211,1514,2926,1865,2142, 189, 852,1221,1400,1486, 882,2299,4036, 351, 28,1122, 700,6479,6480,6481,6482,6483, # last 512 #Everything below is of no interest for detection purpose 5508,6484,3900,3414,3974,4441,4024,3537,4037,5628,5099,3633,6485,3148,6486,3636, 5509,3257,5510,5973,5445,5872,4941,4403,3174,4627,5873,6276,2286,4230,5446,5874, 5122,6102,6103,4162,5447,5123,5323,4849,6277,3980,3851,5066,4246,5774,5067,6278, 3001,2807,5695,3346,5775,5974,5158,5448,6487,5975,5976,5776,3598,6279,5696,4806, 4211,4154,6280,6488,6489,6490,6281,4212,5037,3374,4171,6491,4562,4807,4722,4827, 5977,6104,4532,4079,5159,5324,5160,4404,3858,5359,5875,3975,4288,4610,3486,4512, 5325,3893,5360,6282,6283,5560,2522,4231,5978,5186,5449,2569,3878,6284,5401,3578, 4415,6285,4656,5124,5979,2506,4247,4449,3219,3417,4334,4969,4329,6492,4576,4828, 4172,4416,4829,5402,6286,3927,3852,5361,4369,4830,4477,4867,5876,4173,6493,6105, 4657,6287,6106,5877,5450,6494,4155,4868,5451,3700,5629,4384,6288,6289,5878,3189, 4881,6107,6290,6495,4513,6496,4692,4515,4723,5100,3356,6497,6291,3810,4080,5561, 3570,4430,5980,6498,4355,5697,6499,4724,6108,6109,3764,4050,5038,5879,4093,3226, 6292,5068,5217,4693,3342,5630,3504,4831,4377,4466,4309,5698,4431,5777,6293,5778, 4272,3706,6110,5326,3752,4676,5327,4273,5403,4767,5631,6500,5699,5880,3475,5039, 6294,5562,5125,4348,4301,4482,4068,5126,4593,5700,3380,3462,5981,5563,3824,5404, 4970,5511,3825,4738,6295,6501,5452,4516,6111,5881,5564,6502,6296,5982,6503,4213, 4163,3454,6504,6112,4009,4450,6113,4658,6297,6114,3035,6505,6115,3995,4904,4739, 4563,4942,4110,5040,3661,3928,5362,3674,6506,5292,3612,4791,5565,4149,5983,5328, 5259,5021,4725,4577,4564,4517,4364,6298,5405,4578,5260,4594,4156,4157,5453,3592, 3491,6507,5127,5512,4709,4922,5984,5701,4726,4289,6508,4015,6116,5128,4628,3424, 4241,5779,6299,4905,6509,6510,5454,5702,5780,6300,4365,4923,3971,6511,5161,3270, 3158,5985,4100, 867,5129,5703,6117,5363,3695,3301,5513,4467,6118,6512,5455,4232, 4242,4629,6513,3959,4478,6514,5514,5329,5986,4850,5162,5566,3846,4694,6119,5456, 4869,5781,3779,6301,5704,5987,5515,4710,6302,5882,6120,4392,5364,5705,6515,6121, 6516,6517,3736,5988,5457,5989,4695,2457,5883,4551,5782,6303,6304,6305,5130,4971, 6122,5163,6123,4870,3263,5365,3150,4871,6518,6306,5783,5069,5706,3513,3498,4409, 5330,5632,5366,5458,5459,3991,5990,4502,3324,5991,5784,3696,4518,5633,4119,6519, 4630,5634,4417,5707,4832,5992,3418,6124,5993,5567,4768,5218,6520,4595,3458,5367, 6125,5635,6126,4202,6521,4740,4924,6307,3981,4069,4385,6308,3883,2675,4051,3834, 4302,4483,5568,5994,4972,4101,5368,6309,5164,5884,3922,6127,6522,6523,5261,5460, 5187,4164,5219,3538,5516,4111,3524,5995,6310,6311,5369,3181,3386,2484,5188,3464, 5569,3627,5708,6524,5406,5165,4677,4492,6312,4872,4851,5885,4468,5996,6313,5709, 5710,6128,2470,5886,6314,5293,4882,5785,3325,5461,5101,6129,5711,5786,6525,4906, 6526,6527,4418,5887,5712,4808,2907,3701,5713,5888,6528,3765,5636,5331,6529,6530, 3593,5889,3637,4943,3692,5714,5787,4925,6315,6130,5462,4405,6131,6132,6316,5262, 6531,6532,5715,3859,5716,5070,4696,5102,3929,5788,3987,4792,5997,6533,6534,3920, 4809,5000,5998,6535,2974,5370,6317,5189,5263,5717,3826,6536,3953,5001,4883,3190, 5463,5890,4973,5999,4741,6133,6134,3607,5570,6000,4711,3362,3630,4552,5041,6318, 6001,2950,2953,5637,4646,5371,4944,6002,2044,4120,3429,6319,6537,5103,4833,6538, 6539,4884,4647,3884,6003,6004,4758,3835,5220,5789,4565,5407,6540,6135,5294,4697, 4852,6320,6321,3206,4907,6541,6322,4945,6542,6136,6543,6323,6005,4631,3519,6544, 5891,6545,5464,3784,5221,6546,5571,4659,6547,6324,6137,5190,6548,3853,6549,4016, 4834,3954,6138,5332,3827,4017,3210,3546,4469,5408,5718,3505,4648,5790,5131,5638, 5791,5465,4727,4318,6325,6326,5792,4553,4010,4698,3439,4974,3638,4335,3085,6006, 5104,5042,5166,5892,5572,6327,4356,4519,5222,5573,5333,5793,5043,6550,5639,5071, 4503,6328,6139,6551,6140,3914,3901,5372,6007,5640,4728,4793,3976,3836,4885,6552, 4127,6553,4451,4102,5002,6554,3686,5105,6555,5191,5072,5295,4611,5794,5296,6556, 5893,5264,5894,4975,5466,5265,4699,4976,4370,4056,3492,5044,4886,6557,5795,4432, 4769,4357,5467,3940,4660,4290,6141,4484,4770,4661,3992,6329,4025,4662,5022,4632, 4835,4070,5297,4663,4596,5574,5132,5409,5895,6142,4504,5192,4664,5796,5896,3885, 5575,5797,5023,4810,5798,3732,5223,4712,5298,4084,5334,5468,6143,4052,4053,4336, 4977,4794,6558,5335,4908,5576,5224,4233,5024,4128,5469,5225,4873,6008,5045,4729, 4742,4633,3675,4597,6559,5897,5133,5577,5003,5641,5719,6330,6560,3017,2382,3854, 4406,4811,6331,4393,3964,4946,6561,2420,3722,6562,4926,4378,3247,1736,4442,6332, 5134,6333,5226,3996,2918,5470,4319,4003,4598,4743,4744,4485,3785,3902,5167,5004, 5373,4394,5898,6144,4874,1793,3997,6334,4085,4214,5106,5642,4909,5799,6009,4419, 4189,3330,5899,4165,4420,5299,5720,5227,3347,6145,4081,6335,2876,3930,6146,3293, 3786,3910,3998,5900,5300,5578,2840,6563,5901,5579,6147,3531,5374,6564,6565,5580, 4759,5375,6566,6148,3559,5643,6336,6010,5517,6337,6338,5721,5902,3873,6011,6339, 6567,5518,3868,3649,5722,6568,4771,4947,6569,6149,4812,6570,2853,5471,6340,6341, 5644,4795,6342,6012,5723,6343,5724,6013,4349,6344,3160,6150,5193,4599,4514,4493, 5168,4320,6345,4927,3666,4745,5169,5903,5005,4928,6346,5725,6014,4730,4203,5046, 4948,3395,5170,6015,4150,6016,5726,5519,6347,5047,3550,6151,6348,4197,4310,5904, 6571,5581,2965,6152,4978,3960,4291,5135,6572,5301,5727,4129,4026,5905,4853,5728, 5472,6153,6349,4533,2700,4505,5336,4678,3583,5073,2994,4486,3043,4554,5520,6350, 6017,5800,4487,6351,3931,4103,5376,6352,4011,4321,4311,4190,5136,6018,3988,3233, 4350,5906,5645,4198,6573,5107,3432,4191,3435,5582,6574,4139,5410,6353,5411,3944, 5583,5074,3198,6575,6354,4358,6576,5302,4600,5584,5194,5412,6577,6578,5585,5413, 5303,4248,5414,3879,4433,6579,4479,5025,4854,5415,6355,4760,4772,3683,2978,4700, 3797,4452,3965,3932,3721,4910,5801,6580,5195,3551,5907,3221,3471,3029,6019,3999, 5908,5909,5266,5267,3444,3023,3828,3170,4796,5646,4979,4259,6356,5647,5337,3694, 6357,5648,5338,4520,4322,5802,3031,3759,4071,6020,5586,4836,4386,5048,6581,3571, 4679,4174,4949,6154,4813,3787,3402,3822,3958,3215,3552,5268,4387,3933,4950,4359, 6021,5910,5075,3579,6358,4234,4566,5521,6359,3613,5049,6022,5911,3375,3702,3178, 4911,5339,4521,6582,6583,4395,3087,3811,5377,6023,6360,6155,4027,5171,5649,4421, 4249,2804,6584,2270,6585,4000,4235,3045,6156,5137,5729,4140,4312,3886,6361,4330, 6157,4215,6158,3500,3676,4929,4331,3713,4930,5912,4265,3776,3368,5587,4470,4855, 3038,4980,3631,6159,6160,4132,4680,6161,6362,3923,4379,5588,4255,6586,4121,6587, 6363,4649,6364,3288,4773,4774,6162,6024,6365,3543,6588,4274,3107,3737,5050,5803, 4797,4522,5589,5051,5730,3714,4887,5378,4001,4523,6163,5026,5522,4701,4175,2791, 3760,6589,5473,4224,4133,3847,4814,4815,4775,3259,5416,6590,2738,6164,6025,5304, 3733,5076,5650,4816,5590,6591,6165,6592,3934,5269,6593,3396,5340,6594,5804,3445, 3602,4042,4488,5731,5732,3525,5591,4601,5196,6166,6026,5172,3642,4612,3202,4506, 4798,6366,3818,5108,4303,5138,5139,4776,3332,4304,2915,3415,4434,5077,5109,4856, 2879,5305,4817,6595,5913,3104,3144,3903,4634,5341,3133,5110,5651,5805,6167,4057, 5592,2945,4371,5593,6596,3474,4182,6367,6597,6168,4507,4279,6598,2822,6599,4777, 4713,5594,3829,6169,3887,5417,6170,3653,5474,6368,4216,2971,5228,3790,4579,6369, 5733,6600,6601,4951,4746,4555,6602,5418,5475,6027,3400,4665,5806,6171,4799,6028, 5052,6172,3343,4800,4747,5006,6370,4556,4217,5476,4396,5229,5379,5477,3839,5914, 5652,5807,4714,3068,4635,5808,6173,5342,4192,5078,5419,5523,5734,6174,4557,6175, 4602,6371,6176,6603,5809,6372,5735,4260,3869,5111,5230,6029,5112,6177,3126,4681, 5524,5915,2706,3563,4748,3130,6178,4018,5525,6604,6605,5478,4012,4837,6606,4534, 4193,5810,4857,3615,5479,6030,4082,3697,3539,4086,5270,3662,4508,4931,5916,4912, 5811,5027,3888,6607,4397,3527,3302,3798,2775,2921,2637,3966,4122,4388,4028,4054, 1633,4858,5079,3024,5007,3982,3412,5736,6608,3426,3236,5595,3030,6179,3427,3336, 3279,3110,6373,3874,3039,5080,5917,5140,4489,3119,6374,5812,3405,4494,6031,4666, 4141,6180,4166,6032,5813,4981,6609,5081,4422,4982,4112,3915,5653,3296,3983,6375, 4266,4410,5654,6610,6181,3436,5082,6611,5380,6033,3819,5596,4535,5231,5306,5113, 6612,4952,5918,4275,3113,6613,6376,6182,6183,5814,3073,4731,4838,5008,3831,6614, 4888,3090,3848,4280,5526,5232,3014,5655,5009,5737,5420,5527,6615,5815,5343,5173, 5381,4818,6616,3151,4953,6617,5738,2796,3204,4360,2989,4281,5739,5174,5421,5197, 3132,5141,3849,5142,5528,5083,3799,3904,4839,5480,2880,4495,3448,6377,6184,5271, 5919,3771,3193,6034,6035,5920,5010,6036,5597,6037,6378,6038,3106,5422,6618,5423, 5424,4142,6619,4889,5084,4890,4313,5740,6620,3437,5175,5307,5816,4199,5198,5529, 5817,5199,5656,4913,5028,5344,3850,6185,2955,5272,5011,5818,4567,4580,5029,5921, 3616,5233,6621,6622,6186,4176,6039,6379,6380,3352,5200,5273,2908,5598,5234,3837, 5308,6623,6624,5819,4496,4323,5309,5201,6625,6626,4983,3194,3838,4167,5530,5922, 5274,6381,6382,3860,3861,5599,3333,4292,4509,6383,3553,5481,5820,5531,4778,6187, 3955,3956,4324,4389,4218,3945,4325,3397,2681,5923,4779,5085,4019,5482,4891,5382, 5383,6040,4682,3425,5275,4094,6627,5310,3015,5483,5657,4398,5924,3168,4819,6628, 5925,6629,5532,4932,4613,6041,6630,4636,6384,4780,4204,5658,4423,5821,3989,4683, 5822,6385,4954,6631,5345,6188,5425,5012,5384,3894,6386,4490,4104,6632,5741,5053, 6633,5823,5926,5659,5660,5927,6634,5235,5742,5824,4840,4933,4820,6387,4859,5928, 4955,6388,4143,3584,5825,5346,5013,6635,5661,6389,5014,5484,5743,4337,5176,5662, 6390,2836,6391,3268,6392,6636,6042,5236,6637,4158,6638,5744,5663,4471,5347,3663, 4123,5143,4293,3895,6639,6640,5311,5929,5826,3800,6189,6393,6190,5664,5348,3554, 3594,4749,4603,6641,5385,4801,6043,5827,4183,6642,5312,5426,4761,6394,5665,6191, 4715,2669,6643,6644,5533,3185,5427,5086,5930,5931,5386,6192,6044,6645,4781,4013, 5745,4282,4435,5534,4390,4267,6045,5746,4984,6046,2743,6193,3501,4087,5485,5932, 5428,4184,4095,5747,4061,5054,3058,3862,5933,5600,6646,5144,3618,6395,3131,5055, 5313,6396,4650,4956,3855,6194,3896,5202,4985,4029,4225,6195,6647,5828,5486,5829, 3589,3002,6648,6397,4782,5276,6649,6196,6650,4105,3803,4043,5237,5830,6398,4096, 3643,6399,3528,6651,4453,3315,4637,6652,3984,6197,5535,3182,3339,6653,3096,2660, 6400,6654,3449,5934,4250,4236,6047,6401,5831,6655,5487,3753,4062,5832,6198,6199, 6656,3766,6657,3403,4667,6048,6658,4338,2897,5833,3880,2797,3780,4326,6659,5748, 5015,6660,5387,4351,5601,4411,6661,3654,4424,5935,4339,4072,5277,4568,5536,6402, 6662,5238,6663,5349,5203,6200,5204,6201,5145,4536,5016,5056,4762,5834,4399,4957, 6202,6403,5666,5749,6664,4340,6665,5936,5177,5667,6666,6667,3459,4668,6404,6668, 6669,4543,6203,6670,4276,6405,4480,5537,6671,4614,5205,5668,6672,3348,2193,4763, 6406,6204,5937,5602,4177,5669,3419,6673,4020,6205,4443,4569,5388,3715,3639,6407, 6049,4058,6206,6674,5938,4544,6050,4185,4294,4841,4651,4615,5488,6207,6408,6051, 5178,3241,3509,5835,6208,4958,5836,4341,5489,5278,6209,2823,5538,5350,5206,5429, 6675,4638,4875,4073,3516,4684,4914,4860,5939,5603,5389,6052,5057,3237,5490,3791, 6676,6409,6677,4821,4915,4106,5351,5058,4243,5539,4244,5604,4842,4916,5239,3028, 3716,5837,5114,5605,5390,5940,5430,6210,4332,6678,5540,4732,3667,3840,6053,4305, 3408,5670,5541,6410,2744,5240,5750,6679,3234,5606,6680,5607,5671,3608,4283,4159, 4400,5352,4783,6681,6411,6682,4491,4802,6211,6412,5941,6413,6414,5542,5751,6683, 4669,3734,5942,6684,6415,5943,5059,3328,4670,4144,4268,6685,6686,6687,6688,4372, 3603,6689,5944,5491,4373,3440,6416,5543,4784,4822,5608,3792,4616,5838,5672,3514, 5391,6417,4892,6690,4639,6691,6054,5673,5839,6055,6692,6056,5392,6212,4038,5544, 5674,4497,6057,6693,5840,4284,5675,4021,4545,5609,6418,4454,6419,6213,4113,4472, 5314,3738,5087,5279,4074,5610,4959,4063,3179,4750,6058,6420,6214,3476,4498,4716, 5431,4960,4685,6215,5241,6694,6421,6216,6695,5841,5945,6422,3748,5946,5179,3905, 5752,5545,5947,4374,6217,4455,6423,4412,6218,4803,5353,6696,3832,5280,6219,4327, 4702,6220,6221,6059,4652,5432,6424,3749,4751,6425,5753,4986,5393,4917,5948,5030, 5754,4861,4733,6426,4703,6697,6222,4671,5949,4546,4961,5180,6223,5031,3316,5281, 6698,4862,4295,4934,5207,3644,6427,5842,5950,6428,6429,4570,5843,5282,6430,6224, 5088,3239,6060,6699,5844,5755,6061,6431,2701,5546,6432,5115,5676,4039,3993,3327, 4752,4425,5315,6433,3941,6434,5677,4617,4604,3074,4581,6225,5433,6435,6226,6062, 4823,5756,5116,6227,3717,5678,4717,5845,6436,5679,5846,6063,5847,6064,3977,3354, 6437,3863,5117,6228,5547,5394,4499,4524,6229,4605,6230,4306,4500,6700,5951,6065, 3693,5952,5089,4366,4918,6701,6231,5548,6232,6702,6438,4704,5434,6703,6704,5953, 4168,6705,5680,3420,6706,5242,4407,6066,3812,5757,5090,5954,4672,4525,3481,5681, 4618,5395,5354,5316,5955,6439,4962,6707,4526,6440,3465,4673,6067,6441,5682,6708, 5435,5492,5758,5683,4619,4571,4674,4804,4893,4686,5493,4753,6233,6068,4269,6442, 6234,5032,4705,5146,5243,5208,5848,6235,6443,4963,5033,4640,4226,6236,5849,3387, 6444,6445,4436,4437,5850,4843,5494,4785,4894,6709,4361,6710,5091,5956,3331,6237, 4987,5549,6069,6711,4342,3517,4473,5317,6070,6712,6071,4706,6446,5017,5355,6713, 6714,4988,5436,6447,4734,5759,6715,4735,4547,4456,4754,6448,5851,6449,6450,3547, 5852,5318,6451,6452,5092,4205,6716,6238,4620,4219,5611,6239,6072,4481,5760,5957, 5958,4059,6240,6453,4227,4537,6241,5761,4030,4186,5244,5209,3761,4457,4876,3337, 5495,5181,6242,5959,5319,5612,5684,5853,3493,5854,6073,4169,5613,5147,4895,6074, 5210,6717,5182,6718,3830,6243,2798,3841,6075,6244,5855,5614,3604,4606,5496,5685, 5118,5356,6719,6454,5960,5357,5961,6720,4145,3935,4621,5119,5962,4261,6721,6455, 4786,5963,4375,4582,6245,6246,6247,6076,5437,4877,5856,3376,4380,6248,4160,6722, 5148,6456,5211,6457,6723,4718,6458,6724,6249,5358,4044,3297,6459,6250,5857,5615, 5497,5245,6460,5498,6725,6251,6252,5550,3793,5499,2959,5396,6461,6462,4572,5093, 5500,5964,3806,4146,6463,4426,5762,5858,6077,6253,4755,3967,4220,5965,6254,4989, 5501,6464,4352,6726,6078,4764,2290,5246,3906,5438,5283,3767,4964,2861,5763,5094, 6255,6256,4622,5616,5859,5860,4707,6727,4285,4708,4824,5617,6257,5551,4787,5212, 4965,4935,4687,6465,6728,6466,5686,6079,3494,4413,2995,5247,5966,5618,6729,5967, 5764,5765,5687,5502,6730,6731,6080,5397,6467,4990,6258,6732,4538,5060,5619,6733, 4719,5688,5439,5018,5149,5284,5503,6734,6081,4607,6259,5120,3645,5861,4583,6260, 4584,4675,5620,4098,5440,6261,4863,2379,3306,4585,5552,5689,4586,5285,6735,4864, 6736,5286,6082,6737,4623,3010,4788,4381,4558,5621,4587,4896,3698,3161,5248,4353, 4045,6262,3754,5183,4588,6738,6263,6739,6740,5622,3936,6741,6468,6742,6264,5095, 6469,4991,5968,6743,4992,6744,6083,4897,6745,4256,5766,4307,3108,3968,4444,5287, 3889,4343,6084,4510,6085,4559,6086,4898,5969,6746,5623,5061,4919,5249,5250,5504, 5441,6265,5320,4878,3242,5862,5251,3428,6087,6747,4237,5624,5442,6266,5553,4539, 6748,2585,3533,5398,4262,6088,5150,4736,4438,6089,6267,5505,4966,6749,6268,6750, 6269,5288,5554,3650,6090,6091,4624,6092,5690,6751,5863,4270,5691,4277,5555,5864, 6752,5692,4720,4865,6470,5151,4688,4825,6753,3094,6754,6471,3235,4653,6755,5213, 5399,6756,3201,4589,5865,4967,6472,5866,6473,5019,3016,6757,5321,4756,3957,4573, 6093,4993,5767,4721,6474,6758,5625,6759,4458,6475,6270,6760,5556,4994,5214,5252, 6271,3875,5768,6094,5034,5506,4376,5769,6761,2120,6476,5253,5770,6762,5771,5970, 3990,5971,5557,5558,5772,6477,6095,2787,4641,5972,5121,6096,6097,6272,6763,3703, 5867,5507,6273,4206,6274,4789,6098,6764,3619,3646,3833,3804,2394,3788,4936,3978, 4866,4899,6099,6100,5559,6478,6765,3599,5868,6101,5869,5870,6275,6766,4527,6767)
gpl-3.0
johndbritton/gitviz
dulwich/dulwich/server.py
2
29132
# server.py -- Implementation of the server side git protocols # Copyright (C) 2008 John Carr <john.carr@unrouted.co.uk> # # 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; version 2 # or (at your option) any later version of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. """Git smart network protocol server implementation. For more detailed implementation on the network protocol, see the Documentation/technical directory in the cgit distribution, and in particular: * Documentation/technical/protocol-capabilities.txt * Documentation/technical/pack-protocol.txt Currently supported capabilities: * include-tag * thin-pack * multi_ack_detailed * multi_ack * side-band-64k * ofs-delta * no-progress * report-status * delete-refs Known capabilities that are not supported: * shallow (http://pad.lv/909524) """ import collections import os import socket import SocketServer import sys import zlib from dulwich.errors import ( ApplyDeltaError, ChecksumMismatch, GitProtocolError, NotGitRepository, UnexpectedCommandError, ObjectFormatException, ) from dulwich import log_utils from dulwich.objects import ( hex_to_sha, ) from dulwich.pack import ( write_pack_objects, ) from dulwich.protocol import ( BufferedPktLineWriter, MULTI_ACK, MULTI_ACK_DETAILED, Protocol, ProtocolFile, ReceivableProtocol, SINGLE_ACK, TCP_GIT_PORT, ZERO_SHA, ack_type, extract_capabilities, extract_want_line_capabilities, ) from dulwich.repo import ( Repo, ) logger = log_utils.getLogger(__name__) class Backend(object): """A backend for the Git smart server implementation.""" def open_repository(self, path): """Open the repository at a path. :param path: Path to the repository :raise NotGitRepository: no git repository was found at path :return: Instance of BackendRepo """ raise NotImplementedError(self.open_repository) class BackendRepo(object): """Repository abstraction used by the Git server. Please note that the methods required here are a subset of those provided by dulwich.repo.Repo. """ object_store = None refs = None def get_refs(self): """ Get all the refs in the repository :return: dict of name -> sha """ raise NotImplementedError def get_peeled(self, name): """Return the cached peeled value of a ref, if available. :param name: Name of the ref to peel :return: The peeled value of the ref. If the ref is known not point to a tag, this will be the SHA the ref refers to. If no cached information about a tag is available, this method may return None, but it should attempt to peel the tag if possible. """ return None def fetch_objects(self, determine_wants, graph_walker, progress, get_tagged=None): """ Yield the objects required for a list of commits. :param progress: is a callback to send progress messages to the client :param get_tagged: Function that returns a dict of pointed-to sha -> tag sha for including tags. """ raise NotImplementedError class DictBackend(Backend): """Trivial backend that looks up Git repositories in a dictionary.""" def __init__(self, repos): self.repos = repos def open_repository(self, path): logger.debug('Opening repository at %s', path) try: return self.repos[path] except KeyError: raise NotGitRepository( "No git repository was found at %(path)s" % dict(path=path) ) class FileSystemBackend(Backend): """Simple backend that looks up Git repositories in the local file system.""" def open_repository(self, path): logger.debug('opening repository at %s', path) return Repo(path) class Handler(object): """Smart protocol command handler base class.""" def __init__(self, backend, proto, http_req=None): self.backend = backend self.proto = proto self.http_req = http_req self._client_capabilities = None @classmethod def capability_line(cls): return " ".join(cls.capabilities()) @classmethod def capabilities(cls): raise NotImplementedError(cls.capabilities) @classmethod def innocuous_capabilities(cls): return ("include-tag", "thin-pack", "no-progress", "ofs-delta") @classmethod def required_capabilities(cls): """Return a list of capabilities that we require the client to have.""" return [] def set_client_capabilities(self, caps): allowable_caps = set(self.innocuous_capabilities()) allowable_caps.update(self.capabilities()) for cap in caps: if cap not in allowable_caps: raise GitProtocolError('Client asked for capability %s that ' 'was not advertised.' % cap) for cap in self.required_capabilities(): if cap not in caps: raise GitProtocolError('Client does not support required ' 'capability %s.' % cap) self._client_capabilities = set(caps) logger.info('Client capabilities: %s', caps) def has_capability(self, cap): if self._client_capabilities is None: raise GitProtocolError('Server attempted to access capability %s ' 'before asking client' % cap) return cap in self._client_capabilities class UploadPackHandler(Handler): """Protocol handler for uploading a pack to the server.""" def __init__(self, backend, args, proto, http_req=None, advertise_refs=False): Handler.__init__(self, backend, proto, http_req=http_req) self.repo = backend.open_repository(args[0]) self._graph_walker = None self.advertise_refs = advertise_refs @classmethod def capabilities(cls): return ("multi_ack_detailed", "multi_ack", "side-band-64k", "thin-pack", "ofs-delta", "no-progress", "include-tag") @classmethod def required_capabilities(cls): return ("side-band-64k", "thin-pack", "ofs-delta") def progress(self, message): if self.has_capability("no-progress"): return self.proto.write_sideband(2, message) def get_tagged(self, refs=None, repo=None): """Get a dict of peeled values of tags to their original tag shas. :param refs: dict of refname -> sha of possible tags; defaults to all of the backend's refs. :param repo: optional Repo instance for getting peeled refs; defaults to the backend's repo, if available :return: dict of peeled_sha -> tag_sha, where tag_sha is the sha of a tag whose peeled value is peeled_sha. """ if not self.has_capability("include-tag"): return {} if refs is None: refs = self.repo.get_refs() if repo is None: repo = getattr(self.repo, "repo", None) if repo is None: # Bail if we don't have a Repo available; this is ok since # clients must be able to handle if the server doesn't include # all relevant tags. # TODO: fix behavior when missing return {} tagged = {} for name, sha in refs.iteritems(): peeled_sha = repo.get_peeled(name) if peeled_sha != sha: tagged[peeled_sha] = sha return tagged def handle(self): write = lambda x: self.proto.write_sideband(1, x) graph_walker = ProtocolGraphWalker(self, self.repo.object_store, self.repo.get_peeled) objects_iter = self.repo.fetch_objects( graph_walker.determine_wants, graph_walker, self.progress, get_tagged=self.get_tagged) # Did the process short-circuit (e.g. in a stateless RPC call)? Note # that the client still expects a 0-object pack in most cases. if objects_iter is None: return self.progress("dul-daemon says what\n") self.progress("counting objects: %d, done.\n" % len(objects_iter)) write_pack_objects(ProtocolFile(None, write), objects_iter) self.progress("how was that, then?\n") # we are done self.proto.write("0000") def _split_proto_line(line, allowed): """Split a line read from the wire. :param line: The line read from the wire. :param allowed: An iterable of command names that should be allowed. Command names not listed below as possible return values will be ignored. If None, any commands from the possible return values are allowed. :return: a tuple having one of the following forms: ('want', obj_id) ('have', obj_id) ('done', None) (None, None) (for a flush-pkt) :raise UnexpectedCommandError: if the line cannot be parsed into one of the allowed return values. """ if not line: fields = [None] else: fields = line.rstrip('\n').split(' ', 1) command = fields[0] if allowed is not None and command not in allowed: raise UnexpectedCommandError(command) try: if len(fields) == 1 and command in ('done', None): return (command, None) elif len(fields) == 2 and command in ('want', 'have'): hex_to_sha(fields[1]) return tuple(fields) except (TypeError, AssertionError), e: raise GitProtocolError(e) raise GitProtocolError('Received invalid line from client: %s' % line) class ProtocolGraphWalker(object): """A graph walker that knows the git protocol. As a graph walker, this class implements ack(), next(), and reset(). It also contains some base methods for interacting with the wire and walking the commit tree. The work of determining which acks to send is passed on to the implementation instance stored in _impl. The reason for this is that we do not know at object creation time what ack level the protocol requires. A call to set_ack_level() is required to set up the implementation, before any calls to next() or ack() are made. """ def __init__(self, handler, object_store, get_peeled): self.handler = handler self.store = object_store self.get_peeled = get_peeled self.proto = handler.proto self.http_req = handler.http_req self.advertise_refs = handler.advertise_refs self._wants = [] self._cached = False self._cache = [] self._cache_index = 0 self._impl = None def determine_wants(self, heads): """Determine the wants for a set of heads. The given heads are advertised to the client, who then specifies which refs he wants using 'want' lines. This portion of the protocol is the same regardless of ack type, and in fact is used to set the ack type of the ProtocolGraphWalker. :param heads: a dict of refname->SHA1 to advertise :return: a list of SHA1s requested by the client """ if not heads: # The repo is empty, so short-circuit the whole process. self.proto.write_pkt_line(None) return None values = set(heads.itervalues()) if self.advertise_refs or not self.http_req: for i, (ref, sha) in enumerate(sorted(heads.iteritems())): line = "%s %s" % (sha, ref) if not i: line = "%s\x00%s" % (line, self.handler.capability_line()) self.proto.write_pkt_line("%s\n" % line) peeled_sha = self.get_peeled(ref) if peeled_sha != sha: self.proto.write_pkt_line('%s %s^{}\n' % (peeled_sha, ref)) # i'm done.. self.proto.write_pkt_line(None) if self.advertise_refs: return None # Now client will sending want want want commands want = self.proto.read_pkt_line() if not want: return [] line, caps = extract_want_line_capabilities(want) self.handler.set_client_capabilities(caps) self.set_ack_type(ack_type(caps)) allowed = ('want', None) command, sha = _split_proto_line(line, allowed) want_revs = [] while command != None: if sha not in values: raise GitProtocolError( 'Client wants invalid object %s' % sha) want_revs.append(sha) command, sha = self.read_proto_line(allowed) self.set_wants(want_revs) if self.http_req and self.proto.eof(): # The client may close the socket at this point, expecting a # flush-pkt from the server. We might be ready to send a packfile at # this point, so we need to explicitly short-circuit in this case. return None return want_revs def ack(self, have_ref): return self._impl.ack(have_ref) def reset(self): self._cached = True self._cache_index = 0 def next(self): if not self._cached: if not self._impl and self.http_req: return None return self._impl.next() self._cache_index += 1 if self._cache_index > len(self._cache): return None return self._cache[self._cache_index] def read_proto_line(self, allowed): """Read a line from the wire. :param allowed: An iterable of command names that should be allowed. :return: A tuple of (command, value); see _split_proto_line. :raise GitProtocolError: If an error occurred reading the line. """ return _split_proto_line(self.proto.read_pkt_line(), allowed) def send_ack(self, sha, ack_type=''): if ack_type: ack_type = ' %s' % ack_type self.proto.write_pkt_line('ACK %s%s\n' % (sha, ack_type)) def send_nak(self): self.proto.write_pkt_line('NAK\n') def set_wants(self, wants): self._wants = wants def _is_satisfied(self, haves, want, earliest): """Check whether a want is satisfied by a set of haves. A want, typically a branch tip, is "satisfied" only if there exists a path back from that want to one of the haves. :param haves: A set of commits we know the client has. :param want: The want to check satisfaction for. :param earliest: A timestamp beyond which the search for haves will be terminated, presumably because we're searching too far down the wrong branch. """ o = self.store[want] pending = collections.deque([o]) while pending: commit = pending.popleft() if commit.id in haves: return True if commit.type_name != "commit": # non-commit wants are assumed to be satisfied continue for parent in commit.parents: parent_obj = self.store[parent] # TODO: handle parents with later commit times than children if parent_obj.commit_time >= earliest: pending.append(parent_obj) return False def all_wants_satisfied(self, haves): """Check whether all the current wants are satisfied by a set of haves. :param haves: A set of commits we know the client has. :note: Wants are specified with set_wants rather than passed in since in the current interface they are determined outside this class. """ haves = set(haves) earliest = min([self.store[h].commit_time for h in haves]) for want in self._wants: if not self._is_satisfied(haves, want, earliest): return False return True def set_ack_type(self, ack_type): impl_classes = { MULTI_ACK: MultiAckGraphWalkerImpl, MULTI_ACK_DETAILED: MultiAckDetailedGraphWalkerImpl, SINGLE_ACK: SingleAckGraphWalkerImpl, } self._impl = impl_classes[ack_type](self) _GRAPH_WALKER_COMMANDS = ('have', 'done', None) class SingleAckGraphWalkerImpl(object): """Graph walker implementation that speaks the single-ack protocol.""" def __init__(self, walker): self.walker = walker self._sent_ack = False def ack(self, have_ref): if not self._sent_ack: self.walker.send_ack(have_ref) self._sent_ack = True def next(self): command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS) if command in (None, 'done'): if not self._sent_ack: self.walker.send_nak() return None elif command == 'have': return sha class MultiAckGraphWalkerImpl(object): """Graph walker implementation that speaks the multi-ack protocol.""" def __init__(self, walker): self.walker = walker self._found_base = False self._common = [] def ack(self, have_ref): self._common.append(have_ref) if not self._found_base: self.walker.send_ack(have_ref, 'continue') if self.walker.all_wants_satisfied(self._common): self._found_base = True # else we blind ack within next def next(self): while True: command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS) if command is None: self.walker.send_nak() # in multi-ack mode, a flush-pkt indicates the client wants to # flush but more have lines are still coming continue elif command == 'done': # don't nak unless no common commits were found, even if not # everything is satisfied if self._common: self.walker.send_ack(self._common[-1]) else: self.walker.send_nak() return None elif command == 'have': if self._found_base: # blind ack self.walker.send_ack(sha, 'continue') return sha class MultiAckDetailedGraphWalkerImpl(object): """Graph walker implementation speaking the multi-ack-detailed protocol.""" def __init__(self, walker): self.walker = walker self._found_base = False self._common = [] def ack(self, have_ref): self._common.append(have_ref) if not self._found_base: self.walker.send_ack(have_ref, 'common') if self.walker.all_wants_satisfied(self._common): self._found_base = True self.walker.send_ack(have_ref, 'ready') # else we blind ack within next def next(self): while True: command, sha = self.walker.read_proto_line(_GRAPH_WALKER_COMMANDS) if command is None: self.walker.send_nak() if self.walker.http_req: return None continue elif command == 'done': # don't nak unless no common commits were found, even if not # everything is satisfied if self._common: self.walker.send_ack(self._common[-1]) else: self.walker.send_nak() return None elif command == 'have': if self._found_base: # blind ack; can happen if the client has more requests # inflight self.walker.send_ack(sha, 'ready') return sha class ReceivePackHandler(Handler): """Protocol handler for downloading a pack from the client.""" def __init__(self, backend, args, proto, http_req=None, advertise_refs=False): Handler.__init__(self, backend, proto, http_req=http_req) self.repo = backend.open_repository(args[0]) self.advertise_refs = advertise_refs @classmethod def capabilities(cls): return ("report-status", "delete-refs", "side-band-64k") def _apply_pack(self, refs): all_exceptions = (IOError, OSError, ChecksumMismatch, ApplyDeltaError, AssertionError, socket.error, zlib.error, ObjectFormatException) status = [] # TODO: more informative error messages than just the exception string try: p = self.repo.object_store.add_thin_pack(self.proto.read, self.proto.recv) status.append(('unpack', 'ok')) except all_exceptions, e: status.append(('unpack', str(e).replace('\n', ''))) # The pack may still have been moved in, but it may contain broken # objects. We trust a later GC to clean it up. for oldsha, sha, ref in refs: ref_status = 'ok' try: if sha == ZERO_SHA: if not 'delete-refs' in self.capabilities(): raise GitProtocolError( 'Attempted to delete refs without delete-refs ' 'capability.') try: del self.repo.refs[ref] except all_exceptions: ref_status = 'failed to delete' else: try: self.repo.refs[ref] = sha except all_exceptions: ref_status = 'failed to write' except KeyError, e: ref_status = 'bad ref' status.append((ref, ref_status)) return status def _report_status(self, status): if self.has_capability('side-band-64k'): writer = BufferedPktLineWriter( lambda d: self.proto.write_sideband(1, d)) write = writer.write def flush(): writer.flush() self.proto.write_pkt_line(None) else: write = self.proto.write_pkt_line flush = lambda: None for name, msg in status: if name == 'unpack': write('unpack %s\n' % msg) elif msg == 'ok': write('ok %s\n' % name) else: write('ng %s %s\n' % (name, msg)) write(None) flush() def handle(self): refs = sorted(self.repo.get_refs().iteritems()) if self.advertise_refs or not self.http_req: if refs: self.proto.write_pkt_line( "%s %s\x00%s\n" % (refs[0][1], refs[0][0], self.capability_line())) for i in range(1, len(refs)): ref = refs[i] self.proto.write_pkt_line("%s %s\n" % (ref[1], ref[0])) else: self.proto.write_pkt_line("%s capabilities^{}\0%s" % ( ZERO_SHA, self.capability_line())) self.proto.write("0000") if self.advertise_refs: return client_refs = [] ref = self.proto.read_pkt_line() # if ref is none then client doesnt want to send us anything.. if ref is None: return ref, caps = extract_capabilities(ref) self.set_client_capabilities(caps) # client will now send us a list of (oldsha, newsha, ref) while ref: client_refs.append(ref.split()) ref = self.proto.read_pkt_line() # backend can now deal with this refs and read a pack using self.read status = self._apply_pack(client_refs) # when we have read all the pack from the client, send a status report # if the client asked for it if self.has_capability('report-status'): self._report_status(status) # Default handler classes for git services. DEFAULT_HANDLERS = { 'git-upload-pack': UploadPackHandler, 'git-receive-pack': ReceivePackHandler, } class TCPGitRequestHandler(SocketServer.StreamRequestHandler): def __init__(self, handlers, *args, **kwargs): self.handlers = handlers SocketServer.StreamRequestHandler.__init__(self, *args, **kwargs) def handle(self): proto = ReceivableProtocol(self.connection.recv, self.wfile.write) command, args = proto.read_cmd() logger.info('Handling %s request, args=%s', command, args) cls = self.handlers.get(command, None) if not callable(cls): raise GitProtocolError('Invalid service %s' % command) h = cls(self.server.backend, args, proto) h.handle() class TCPGitServer(SocketServer.TCPServer): allow_reuse_address = True serve = SocketServer.TCPServer.serve_forever def _make_handler(self, *args, **kwargs): return TCPGitRequestHandler(self.handlers, *args, **kwargs) def __init__(self, backend, listen_addr, port=TCP_GIT_PORT, handlers=None): self.handlers = dict(DEFAULT_HANDLERS) if handlers is not None: self.handlers.update(handlers) self.backend = backend logger.info('Listening for TCP connections on %s:%d', listen_addr, port) SocketServer.TCPServer.__init__(self, (listen_addr, port), self._make_handler) def verify_request(self, request, client_address): logger.info('Handling request from %s', client_address) return True def handle_error(self, request, client_address): logger.exception('Exception happened during processing of request ' 'from %s', client_address) def main(argv=sys.argv): """Entry point for starting a TCP git server.""" if len(argv) > 1: gitdir = argv[1] else: gitdir = '.' log_utils.default_logging_config() backend = DictBackend({'/': Repo(gitdir)}) server = TCPGitServer(backend, 'localhost') server.serve_forever() def serve_command(handler_cls, argv=sys.argv, backend=None, inf=sys.stdin, outf=sys.stdout): """Serve a single command. This is mostly useful for the implementation of commands used by e.g. git+ssh. :param handler_cls: `Handler` class to use for the request :param argv: execv-style command-line arguments. Defaults to sys.argv. :param backend: `Backend` to use :param inf: File-like object to read from, defaults to standard input. :param outf: File-like object to write to, defaults to standard output. :return: Exit code for use with sys.exit. 0 on success, 1 on failure. """ if backend is None: backend = FileSystemBackend() def send_fn(data): outf.write(data) outf.flush() proto = Protocol(inf.read, send_fn) handler = handler_cls(backend, argv[1:], proto) # FIXME: Catch exceptions and write a single-line summary to outf. handler.handle() return 0 def generate_info_refs(repo): """Generate an info refs file.""" refs = repo.get_refs() for name in sorted(refs.iterkeys()): # get_refs() includes HEAD as a special case, but we don't want to # advertise it if name == 'HEAD': continue sha = refs[name] o = repo.object_store[sha] if not o: continue yield '%s\t%s\n' % (sha, name) peeled_sha = repo.get_peeled(name) if peeled_sha != sha: yield '%s\t%s^{}\n' % (peeled_sha, name) def generate_objects_info_packs(repo): """Generate an index for for packs.""" for pack in repo.object_store.packs: yield 'P pack-%s.pack\n' % pack.name() def update_server_info(repo): """Generate server info for dumb file access. This generates info/refs and objects/info/packs, similar to "git update-server-info". """ repo._put_named_file(os.path.join('info', 'refs'), "".join(generate_info_refs(repo))) repo._put_named_file(os.path.join('objects', 'info', 'packs'), "".join(generate_objects_info_packs(repo)))
mit
spesmilo/electrum
electrum/tests/test_lnrouter.py
1
40777
from math import inf import unittest import tempfile import shutil import asyncio from electrum.util import bh2u, bfh, create_and_start_event_loop from electrum.lnutil import ShortChannelID from electrum.lnonion import (OnionHopsDataSingle, new_onion_packet, process_onion_packet, _decode_onion_error, decode_onion_error, OnionFailureCode, OnionPacket) from electrum import bitcoin, lnrouter from electrum.constants import BitcoinTestnet from electrum.simple_config import SimpleConfig from electrum.lnrouter import PathEdge, LiquidityHintMgr, DEFAULT_PENALTY_PROPORTIONAL_MILLIONTH, DEFAULT_PENALTY_BASE_MSAT, fee_for_edge_msat from . import TestCaseForTestnet from .test_bitcoin import needs_test_with_all_chacha20_implementations def channel(number: int) -> ShortChannelID: return ShortChannelID(bfh(format(number, '016x'))) def node(character: str) -> bytes: return b'\x02' + f'{character}'.encode() * 32 class Test_LNRouter(TestCaseForTestnet): cdb = None def setUp(self): super().setUp() self.asyncio_loop, self._stop_loop, self._loop_thread = create_and_start_event_loop() self.config = SimpleConfig({'electrum_path': self.electrum_path}) def tearDown(self): # if the test called prepare_graph(), channeldb needs to be cleaned up if self.cdb: self.cdb.stop() asyncio.run_coroutine_threadsafe(self.cdb.stopped_event.wait(), self.asyncio_loop).result() self.asyncio_loop.call_soon_threadsafe(self._stop_loop.set_result, 1) self._loop_thread.join(timeout=1) super().tearDown() def prepare_graph(self): """ Network topology with channel ids: 3 A --- B | 2/ | 6 | E | 1 | /5 \7 | D --- C 4 valid routes from A -> E: A -3-> B -2-> E A -6-> D -5-> E A -6-> D -4-> C -7-> E A -3-> B -1-> C -7-> E A -6-> D -4-> C -1-> B -2-> E A -3-> B -1-> C -4-> D -5-> E """ class fake_network: config = self.config asyncio_loop = asyncio.get_event_loop() trigger_callback = lambda *args: None register_callback = lambda *args: None interface = None fake_network.channel_db = lnrouter.ChannelDB(fake_network()) fake_network.channel_db.data_loaded.set() self.cdb = fake_network.channel_db self.path_finder = lnrouter.LNPathFinder(self.cdb) self.assertEqual(self.cdb.num_channels, 0) self.cdb.add_channel_announcements({ 'node_id_1': node('b'), 'node_id_2': node('c'), 'bitcoin_key_1': node('b'), 'bitcoin_key_2': node('c'), 'short_channel_id': channel(1), 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'len': 0, 'features': b'' }, trusted=True) self.assertEqual(self.cdb.num_channels, 1) self.cdb.add_channel_announcements({ 'node_id_1': node('b'), 'node_id_2': node('e'), 'bitcoin_key_1': node('b'), 'bitcoin_key_2': node('e'), 'short_channel_id': channel(2), 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'len': 0, 'features': b'' }, trusted=True) self.cdb.add_channel_announcements({ 'node_id_1': node('a'), 'node_id_2': node('b'), 'bitcoin_key_1': node('a'), 'bitcoin_key_2': node('b'), 'short_channel_id': channel(3), 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'len': 0, 'features': b'' }, trusted=True) self.cdb.add_channel_announcements({ 'node_id_1': node('c'), 'node_id_2': node('d'), 'bitcoin_key_1': node('c'), 'bitcoin_key_2': node('d'), 'short_channel_id': channel(4), 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'len': 0, 'features': b'' }, trusted=True) self.cdb.add_channel_announcements({ 'node_id_1': node('d'), 'node_id_2': node('e'), 'bitcoin_key_1': node('d'), 'bitcoin_key_2': node('e'), 'short_channel_id': channel(5), 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'len': 0, 'features': b'' }, trusted=True) self.cdb.add_channel_announcements({ 'node_id_1': node('a'), 'node_id_2': node('d'), 'bitcoin_key_1': node('a'), 'bitcoin_key_2': node('d'), 'short_channel_id': channel(6), 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'len': 0, 'features': b'' }, trusted=True) self.cdb.add_channel_announcements({ 'node_id_1': node('c'), 'node_id_2': node('e'), 'bitcoin_key_1': node('c'), 'bitcoin_key_2': node('e'), 'short_channel_id': channel(7), 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'len': 0, 'features': b'' }, trusted=True) def add_chan_upd(payload): self.cdb.add_channel_update(payload, verify=False) add_chan_upd({'short_channel_id': channel(1), 'message_flags': b'\x00', 'channel_flags': b'\x00', 'cltv_expiry_delta': 10, 'htlc_minimum_msat': 250, 'fee_base_msat': 100, 'fee_proportional_millionths': 150, 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'timestamp': 0}) add_chan_upd({'short_channel_id': channel(1), 'message_flags': b'\x00', 'channel_flags': b'\x01', 'cltv_expiry_delta': 10, 'htlc_minimum_msat': 250, 'fee_base_msat': 100, 'fee_proportional_millionths': 150, 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'timestamp': 0}) add_chan_upd({'short_channel_id': channel(2), 'message_flags': b'\x00', 'channel_flags': b'\x00', 'cltv_expiry_delta': 99, 'htlc_minimum_msat': 250, 'fee_base_msat': 100, 'fee_proportional_millionths': 150, 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'timestamp': 0}) add_chan_upd({'short_channel_id': channel(2), 'message_flags': b'\x00', 'channel_flags': b'\x01', 'cltv_expiry_delta': 10, 'htlc_minimum_msat': 250, 'fee_base_msat': 100, 'fee_proportional_millionths': 150, 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'timestamp': 0}) add_chan_upd({'short_channel_id': channel(3), 'message_flags': b'\x00', 'channel_flags': b'\x01', 'cltv_expiry_delta': 10, 'htlc_minimum_msat': 250, 'fee_base_msat': 100, 'fee_proportional_millionths': 150, 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'timestamp': 0}) add_chan_upd({'short_channel_id': channel(3), 'message_flags': b'\x00', 'channel_flags': b'\x00', 'cltv_expiry_delta': 10, 'htlc_minimum_msat': 250, 'fee_base_msat': 100, 'fee_proportional_millionths': 150, 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'timestamp': 0}) add_chan_upd({'short_channel_id': channel(4), 'message_flags': b'\x00', 'channel_flags': b'\x01', 'cltv_expiry_delta': 10, 'htlc_minimum_msat': 250, 'fee_base_msat': 100, 'fee_proportional_millionths': 150, 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'timestamp': 0}) add_chan_upd({'short_channel_id': channel(4), 'message_flags': b'\x00', 'channel_flags': b'\x00', 'cltv_expiry_delta': 10, 'htlc_minimum_msat': 250, 'fee_base_msat': 100, 'fee_proportional_millionths': 150, 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'timestamp': 0}) add_chan_upd({'short_channel_id': channel(5), 'message_flags': b'\x00', 'channel_flags': b'\x01', 'cltv_expiry_delta': 10, 'htlc_minimum_msat': 250, 'fee_base_msat': 100, 'fee_proportional_millionths': 150, 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'timestamp': 0}) add_chan_upd({'short_channel_id': channel(5), 'message_flags': b'\x00', 'channel_flags': b'\x00', 'cltv_expiry_delta': 10, 'htlc_minimum_msat': 250, 'fee_base_msat': 100, 'fee_proportional_millionths': 999, 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'timestamp': 0}) add_chan_upd({'short_channel_id': channel(6), 'message_flags': b'\x00', 'channel_flags': b'\x00', 'cltv_expiry_delta': 10, 'htlc_minimum_msat': 250, 'fee_base_msat': 100, 'fee_proportional_millionths': 200, 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'timestamp': 0}) add_chan_upd({'short_channel_id': channel(6), 'message_flags': b'\x00', 'channel_flags': b'\x01', 'cltv_expiry_delta': 10, 'htlc_minimum_msat': 250, 'fee_base_msat': 100, 'fee_proportional_millionths': 150, 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'timestamp': 0}) add_chan_upd({'short_channel_id': channel(7), 'message_flags': b'\x00', 'channel_flags': b'\x00', 'cltv_expiry_delta': 10, 'htlc_minimum_msat': 250, 'fee_base_msat': 100, 'fee_proportional_millionths': 150, 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'timestamp': 0}) add_chan_upd({'short_channel_id': channel(7), 'message_flags': b'\x00', 'channel_flags': b'\x01', 'cltv_expiry_delta': 10, 'htlc_minimum_msat': 250, 'fee_base_msat': 100, 'fee_proportional_millionths': 150, 'chain_hash': BitcoinTestnet.rev_genesis_bytes(), 'timestamp': 0}) def test_find_path_for_payment(self): self.prepare_graph() amount_to_send = 100000 path = self.path_finder.find_path_for_payment( nodeA=node('a'), nodeB=node('e'), invoice_amount_msat=amount_to_send) self.assertEqual([ PathEdge(start_node=node('a'), end_node=node('b'), short_channel_id=channel(3)), PathEdge(start_node=node('b'), end_node=node('e'), short_channel_id=channel(2)), ], path) route = self.path_finder.create_route_from_path(path) self.assertEqual(node('b'), route[0].node_id) self.assertEqual(channel(3), route[0].short_channel_id) def test_find_path_liquidity_hints(self): self.prepare_graph() amount_to_send = 100000 """ assume failure over channel 2, B -> E A -3-> B |-2-> E A -6-> D -5-> E <= chosen path A -6-> D -4-> C -7-> E A -3-> B -1-> C -7-> E A -6-> D -4-> C -1-> B -2-> E A -3-> B -1-> C -4-> D -5-> E """ self.path_finder.liquidity_hints.update_cannot_send(node('b'), node('e'), channel(2), amount_to_send - 1) path = self.path_finder.find_path_for_payment( nodeA=node('a'), nodeB=node('e'), invoice_amount_msat=amount_to_send) self.assertEqual(channel(6), path[0].short_channel_id) self.assertEqual(channel(5), path[1].short_channel_id) """ assume failure over channel 5, D -> E A -3-> B |-2-> E A -6-> D |-5-> E A -6-> D -4-> C -7-> E A -3-> B -1-> C -7-> E <= chosen path A -6-> D -4-> C -1-> B |-2-> E A -3-> B -1-> C -4-> D |-5-> E """ self.path_finder.liquidity_hints.update_cannot_send(node('d'), node('e'), channel(5), amount_to_send - 1) path = self.path_finder.find_path_for_payment( nodeA=node('a'), nodeB=node('e'), invoice_amount_msat=amount_to_send) self.assertEqual(channel(3), path[0].short_channel_id) self.assertEqual(channel(1), path[1].short_channel_id) self.assertEqual(channel(7), path[2].short_channel_id) """ assume success over channel 4, D -> C A -3-> B |-2-> E A -6-> D |-5-> E A -6-> D -4-> C -7-> E <= smaller penalty: chosen path A -3-> B -1-> C -7-> E A -6-> D -4-> C -1-> B |-2-> E A -3-> B -1-> C -4-> D |-5-> E """ self.path_finder.liquidity_hints.update_can_send(node('d'), node('c'), channel(4), amount_to_send + 1000) path = self.path_finder.find_path_for_payment( nodeA=node('a'), nodeB=node('e'), invoice_amount_msat=amount_to_send) self.assertEqual(channel(6), path[0].short_channel_id) self.assertEqual(channel(4), path[1].short_channel_id) self.assertEqual(channel(7), path[2].short_channel_id) def test_find_path_liquidity_hints_inflight_htlcs(self): self.prepare_graph() amount_to_send = 100000 """ add inflight htlc to channel 2, B -> E A -3-> B -2(1)-> E A -6-> D -5-> E <= chosen path A -6-> D -4-> C -7-> E A -3-> B -1-> C -7-> E A -6-> D -4-> C -1-> B -2-> E A -3-> B -1-> C -4-> D -5-> E """ self.path_finder.liquidity_hints.add_htlc(node('b'), node('e'), channel(2)) path = self.path_finder.find_path_for_payment( nodeA=node('a'), nodeB=node('e'), invoice_amount_msat=amount_to_send) self.assertEqual(channel(6), path[0].short_channel_id) self.assertEqual(channel(5), path[1].short_channel_id) """ remove inflight htlc from channel 2, B -> E A -3-> B -2(0)-> E <= chosen path A -6-> D -5-> E A -6-> D -4-> C -7-> E A -3-> B -1-> C -7-> E A -6-> D -4-> C -1-> B -2-> E A -3-> B -1-> C -4-> D -5-> E """ self.path_finder.liquidity_hints.remove_htlc(node('b'), node('e'), channel(2)) path = self.path_finder.find_path_for_payment( nodeA=node('a'), nodeB=node('e'), invoice_amount_msat=amount_to_send) self.assertEqual(channel(3), path[0].short_channel_id) self.assertEqual(channel(2), path[1].short_channel_id) def test_liquidity_hints(self): liquidity_hints = LiquidityHintMgr() node_from = bytes(0) node_to = bytes(1) channel_id = ShortChannelID.from_components(0, 0, 0) amount_to_send = 1_000_000 # check default penalty self.assertEqual( fee_for_edge_msat(amount_to_send, DEFAULT_PENALTY_BASE_MSAT, DEFAULT_PENALTY_PROPORTIONAL_MILLIONTH), liquidity_hints.penalty(node_from, node_to, channel_id, amount_to_send) ) liquidity_hints.update_can_send(node_from, node_to, channel_id, 1_000_000) liquidity_hints.update_cannot_send(node_from, node_to, channel_id, 2_000_000) hint = liquidity_hints.get_hint(channel_id) self.assertEqual(1_000_000, hint.can_send(node_from < node_to)) self.assertEqual(None, hint.cannot_send(node_to < node_from)) self.assertEqual(2_000_000, hint.cannot_send(node_from < node_to)) # the can_send backward hint is set automatically self.assertEqual(2_000_000, hint.can_send(node_to < node_from)) # check penalties self.assertEqual(0., liquidity_hints.penalty(node_from, node_to, channel_id, 1_000_000)) self.assertEqual(650, liquidity_hints.penalty(node_from, node_to, channel_id, 1_500_000)) self.assertEqual(inf, liquidity_hints.penalty(node_from, node_to, channel_id, 2_000_000)) # test that we don't overwrite significant info with less significant info liquidity_hints.update_can_send(node_from, node_to, channel_id, 500_000) hint = liquidity_hints.get_hint(channel_id) self.assertEqual(1_000_000, hint.can_send(node_from < node_to)) # test case when can_send > cannot_send liquidity_hints.update_can_send(node_from, node_to, channel_id, 3_000_000) hint = liquidity_hints.get_hint(channel_id) self.assertEqual(3_000_000, hint.can_send(node_from < node_to)) self.assertEqual(None, hint.cannot_send(node_from < node_to)) # test inflight htlc liquidity_hints.reset_liquidity_hints() liquidity_hints.add_htlc(node_from, node_to, channel_id) liquidity_hints.get_hint(channel_id) # we have got 600 (attempt) + 600 (inflight) penalty self.assertEqual(1200, liquidity_hints.penalty(node_from, node_to, channel_id, 1_000_000)) @needs_test_with_all_chacha20_implementations def test_new_onion_packet_legacy(self): # test vector from bolt-04 payment_path_pubkeys = [ bfh('02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619'), bfh('0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c'), bfh('027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007'), bfh('032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991'), bfh('02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145'), ] session_key = bfh('4141414141414141414141414141414141414141414141414141414141414141') associated_data = bfh('4242424242424242424242424242424242424242424242424242424242424242') hops_data = [ OnionHopsDataSingle(is_tlv_payload=False, payload={ "amt_to_forward": {"amt_to_forward": 0}, "outgoing_cltv_value": {"outgoing_cltv_value": 0}, "short_channel_id": {"short_channel_id": bfh('0000000000000000')}, }), OnionHopsDataSingle(is_tlv_payload=False, payload={ "amt_to_forward": {"amt_to_forward": 1}, "outgoing_cltv_value": {"outgoing_cltv_value": 1}, "short_channel_id": {"short_channel_id": bfh('0101010101010101')}, }), OnionHopsDataSingle(is_tlv_payload=False, payload={ "amt_to_forward": {"amt_to_forward": 2}, "outgoing_cltv_value": {"outgoing_cltv_value": 2}, "short_channel_id": {"short_channel_id": bfh('0202020202020202')}, }), OnionHopsDataSingle(is_tlv_payload=False, payload={ "amt_to_forward": {"amt_to_forward": 3}, "outgoing_cltv_value": {"outgoing_cltv_value": 3}, "short_channel_id": {"short_channel_id": bfh('0303030303030303')}, }), OnionHopsDataSingle(is_tlv_payload=False, payload={ "amt_to_forward": {"amt_to_forward": 4}, "outgoing_cltv_value": {"outgoing_cltv_value": 4}, "short_channel_id": {"short_channel_id": bfh('0404040404040404')}, }), ] packet = new_onion_packet(payment_path_pubkeys, session_key, hops_data, associated_data) self.assertEqual(bfh('0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a71e87f9aab8f6378c6ff744c1f34b393ad28d065b535c1a8668d85d3b34a1b3befd10f7d61ab590531cf08000178a333a347f8b4072e216400406bdf3bf038659793a1f9e7abc789266cc861cabd95818c0fc8efbdfdc14e3f7c2bc7eb8d6a79ef75ce721caad69320c3a469a202f3e468c67eaf7a7cda226d0fd32f7b48084dca885d014698cf05d742557763d9cb743faeae65dcc79dddaecf27fe5942be5380d15e9a1ec866abe044a9ad635778ba61fc0776dc832b39451bd5d35072d2269cf9b040a2a2fba158a0d8085926dc2e44f0c88bf487da56e13ef2d5e676a8589881b4869ed4c7f0218ff8c6c7dd7221d189c65b3b9aaa71a01484b122846c7c7b57e02e679ea8469b70e14fe4f70fee4d87b910cf144be6fe48eef24da475c0b0bcc6565a9f99728426ce2380a9580e2a9442481ceae7679906c30b1a0e21a10f26150e0645ab6edfdab1ce8f8bea7b1dee511c5fd38ac0e702c1c15bb86b52bca1b71e15b96982d262a442024c33ceb7dd8f949063c2e5e613e873250e2f8708bd4e1924abd45f65c2fa5617bfb10ee9e4a42d6b5811acc8029c16274f937dac9e8817c7e579fdb767ffe277f26d413ced06b620ede8362081da21cf67c2ca9d6f15fe5bc05f82f5bb93f8916bad3d63338ca824f3bbc11b57ce94a5fa1bc239533679903d6fec92a8c792fd86e2960188c14f21e399cfd72a50c620e10aefc6249360b463df9a89bf6836f4f26359207b765578e5ed76ae9f31b1cc48324be576e3d8e44d217445dba466f9b6293fdf05448584eb64f61e02903f834518622b7d4732471c6e0e22e22d1f45e31f0509eab39cdea5980a492a1da2aaac55a98a01216cd4bfe7abaa682af0fbff2dfed030ba28f1285df750e4d3477190dd193f8643b61d8ac1c427d590badb1f61a05d480908fbdc7c6f0502dd0c4abb51d725e92f95da2a8facb79881a844e2026911adcc659d1fb20a2fce63787c8bb0d9f6789c4b231c76da81c3f0718eb7156565a081d2be6b4170c0e0bcebddd459f53db2590c974bca0d705c055dee8c629bf854a5d58edc85228499ec6dde80cce4c8910b81b1e9e8b0f43bd39c8d69c3a80672729b7dc952dd9448688b6bd06afc2d2819cda80b66c57b52ccf7ac1a86601410d18d0c732f69de792e0894a9541684ef174de766fd4ce55efea8f53812867be6a391ac865802dbc26d93959df327ec2667c7256aa5a1d3c45a69a6158f285d6c97c3b8eedb09527848500517995a9eae4cd911df531544c77f5a9a2f22313e3eb72ca7a07dba243476bc926992e0d1e58b4a2fc8c7b01e0cad726237933ea319bad7537d39f3ed635d1e6c1d29e97b3d2160a09e30ee2b65ac5bce00996a73c008bcf351cecb97b6833b6d121dcf4644260b2946ea204732ac9954b228f0beaa15071930fd9583dfc466d12b5f0eeeba6dcf23d5ce8ae62ee5796359d97a4a15955c778d868d0ef9991d9f2833b5bb66119c5f8b396fd108baed7906cbb3cc376d13551caed97fece6f42a4c908ee279f1127fda1dd3ee77d8de0a6f3c135fa3f1cffe38591b6738dc97b55f0acc52be9753ce53e64d7e497bb00ca6123758df3b68fad99e35c04389f7514a8e36039f541598a417275e77869989782325a15b5342ac5011ff07af698584b476b35d941a4981eac590a07a092bb50342da5d3341f901aa07964a8d02b623c7b106dd0ae50bfa007a22d46c8772fa55558176602946cb1d11ea5460db7586fb89c6d3bcd3ab6dd20df4a4db63d2e7d52380800ad812b8640887e027e946df96488b47fbc4a4fadaa8beda4abe446fafea5403fae2ef'), packet.to_bytes()) @needs_test_with_all_chacha20_implementations def test_new_onion_packet_mixed_payloads(self): # test vector from bolt-04 payment_path_pubkeys = [ bfh('02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619'), bfh('0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c'), bfh('027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007'), bfh('032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991'), bfh('02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145'), ] session_key = bfh('4141414141414141414141414141414141414141414141414141414141414141') associated_data = bfh('4242424242424242424242424242424242424242424242424242424242424242') hops_data = [ OnionHopsDataSingle(is_tlv_payload=False, payload={ "amt_to_forward": {"amt_to_forward": 0}, "outgoing_cltv_value": {"outgoing_cltv_value": 0}, "short_channel_id": {"short_channel_id": bfh('0000000000000000')}, }), OnionHopsDataSingle(is_tlv_payload=True), OnionHopsDataSingle(is_tlv_payload=True), OnionHopsDataSingle(is_tlv_payload=True), OnionHopsDataSingle(is_tlv_payload=False, payload={ "amt_to_forward": {"amt_to_forward": 4}, "outgoing_cltv_value": {"outgoing_cltv_value": 4}, "short_channel_id": {"short_channel_id": bfh('0404040404040404')}, }), ] hops_data[1]._raw_bytes_payload = bfh("0101010101010101000000000000000100000001") hops_data[2]._raw_bytes_payload = bfh("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff") hops_data[3]._raw_bytes_payload = bfh("0303030303030303000000000000000300000003") packet = new_onion_packet(payment_path_pubkeys, session_key, hops_data, associated_data) self.assertEqual(bfh('0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a710f8eaf9ccc768f66bb5dec1f7827f33c43fe2ddd05614c8283aa78e9e7573f87c50f7d61ab590531cf08000178a333a347f8b4072e1cea42da7552402b10765adae3f581408f35ff0a71a34b78b1d8ecae77df96c6404bae9a8e8d7178977d7094a1ae549f89338c0777551f874159eb42d3a59fb9285ad4e24883f27de23942ec966611e99bee1cee503455be9e8e642cef6cef7b9864130f692283f8a973d47a8f1c1726b6e59969385975c766e35737c8d76388b64f748ee7943ffb0e2ee45c57a1abc40762ae598723d21bd184e2b338f68ebff47219357bd19cd7e01e2337b806ef4d717888e129e59cd3dc31e6201ccb2fd6d7499836f37a993262468bcb3a4dcd03a22818aca49c6b7b9b8e9e870045631d8e039b066ff86e0d1b7291f71cefa7264c70404a8e538b566c17ccc5feab231401e6c08a01bd5edfc1aa8e3e533b96e82d1f91118d508924b923531929aea889fcdf057f5995d9731c4bf796fb0e41c885d488dcbc68eb742e27f44310b276edc6f652658149e7e9ced4edde5d38c9b8f92e16f6b4ab13d710ee5c193921909bdd75db331cd9d7581a39fca50814ed8d9d402b86e7f8f6ac2f3bca8e6fe47eb45fbdd3be21a8a8d200797eae3c9a0497132f92410d804977408494dff49dd3d8bce248e0b74fd9e6f0f7102c25ddfa02bd9ad9f746abbfa3379834bc2380d58e9d23237821475a1874484783a15d68f47d3dc339f38d9bf925655d5c946778680fd6d1f062f84128895aff09d35d6c92cca63d3f95a9ee8f2a84f383b4d6a087533e65de12fc8dcaf85777736a2088ff4b22462265028695b37e70963c10df8ef2458756c73007dc3e544340927f9e9f5ea4816a9fd9832c311d122e9512739a6b4714bba590e31caa143ce83cb84b36c738c60c3190ff70cd9ac286a9fd2ab619399b68f1f7447be376ce884b5913c8496d01cbf7a44a60b6e6747513f69dc538f340bc1388e0fde5d0c1db50a4dcb9cc0576e0e2474e4853af9623212578d502757ffb2e0e749695ed70f61c116560d0d4154b64dcf3cbf3c91d89fb6dd004dc19588e3479fcc63c394a4f9e8a3b8b961fce8a532304f1337f1a697a1bb14b94d2953f39b73b6a3125d24f27fcd4f60437881185370bde68a5454d816e7a70d4cea582effab9a4f1b730437e35f7a5c4b769c7b72f0346887c1e63576b2f1e2b3706142586883f8cf3a23595cc8e35a52ad290afd8d2f8bcd5b4c1b891583a4159af7110ecde092079209c6ec46d2bda60b04c519bb8bc6dffb5c87f310814ef2f3003671b3c90ddf5d0173a70504c2280d31f17c061f4bb12a978122c8a2a618bb7d1edcf14f84bf0fa181798b826a254fca8b6d7c81e0beb01bd77f6461be3c8647301d02b04753b0771105986aa0cbc13f7718d64e1b3437e8eef1d319359914a7932548c91570ef3ea741083ca5be5ff43c6d9444d29df06f76ec3dc936e3d180f4b6d0fbc495487c7d44d7c8fe4a70d5ff1461d0d9593f3f898c919c363fa18341ce9dae54f898ccf3fe792136682272941563387263c51b2a2f32363b804672cc158c9230472b554090a661aa81525d11876eefdcc45442249e61e07284592f1606491de5c0324d3af4be035d7ede75b957e879e9770cdde2e1bbc1ef75d45fe555f1ff6ac296a2f648eeee59c7c08260226ea333c285bcf37a9bbfa57ba2ab8083c4be6fc2ebe279537d22da96a07392908cf22b233337a74fe5c603b51712b43c3ee55010ee3d44dd9ba82bba3145ec358f863e04bbfa53799a7a9216718fd5859da2f0deb77b8e315ad6868fdec9400f45a48e6dc8ddbaeb3'), packet.to_bytes()) @needs_test_with_all_chacha20_implementations def test_process_onion_packet_mixed_payloads(self): # this test is not from bolt-04, but is based on the one there; # here the TLV payloads are actually sane... payment_path_pubkeys = [ bfh('02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619'), bfh('0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c'), bfh('027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007'), bfh('032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991'), bfh('02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145'), ] payment_path_privkeys = [ bfh('4141414141414141414141414141414141414141414141414141414141414141'), bfh('4242424242424242424242424242424242424242424242424242424242424242'), bfh('4343434343434343434343434343434343434343434343434343434343434343'), bfh('4444444444444444444444444444444444444444444444444444444444444444'), bfh('4545454545454545454545454545454545454545454545454545454545454545'), ] session_key = bfh('4141414141414141414141414141414141414141414141414141414141414141') associated_data = bfh('4242424242424242424242424242424242424242424242424242424242424242') hops_data = [ OnionHopsDataSingle(is_tlv_payload=False, payload={ "amt_to_forward": {"amt_to_forward": 0}, "outgoing_cltv_value": {"outgoing_cltv_value": 0}, "short_channel_id": {"short_channel_id": bfh('0000000000000000')}, }), OnionHopsDataSingle(is_tlv_payload=True, payload={ "amt_to_forward": {"amt_to_forward": 1}, "outgoing_cltv_value": {"outgoing_cltv_value": 1}, "short_channel_id": {"short_channel_id": bfh('0101010101010101')}, }), OnionHopsDataSingle(is_tlv_payload=True, payload={ "amt_to_forward": {"amt_to_forward": 2}, "outgoing_cltv_value": {"outgoing_cltv_value": 2}, "short_channel_id": {"short_channel_id": bfh('0202020202020202')}, }), OnionHopsDataSingle(is_tlv_payload=True, payload={ "amt_to_forward": {"amt_to_forward": 3}, "outgoing_cltv_value": {"outgoing_cltv_value": 3}, "short_channel_id": {"short_channel_id": bfh('0303030303030303')}, }), OnionHopsDataSingle(is_tlv_payload=False, payload={ "amt_to_forward": {"amt_to_forward": 4}, "outgoing_cltv_value": {"outgoing_cltv_value": 4}, "short_channel_id": {"short_channel_id": bfh('0404040404040404')}, }), ] packet = new_onion_packet(payment_path_pubkeys, session_key, hops_data, associated_data) self.assertEqual(bfh('0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619e5f14350c2a76fc232b5e46d421e9615471ab9e0bc887beff8c95fdb878f7b3a71bde5adfa90b337f34616d8673d09dd055937273045566ce537ffbe3f9d1f263dc10c7d61ae590536c609010079a232a247922a5395359a63dfbefb85f40317e23254f3023f7d4a98f746c9ab06647645ce55c67308e3c77dc87a1caeac51b03b23c60f05e536e1d757c8c1093e34accfc4f97b5920f6dd2069d5b9ddbb384c3ac575e999a92a4434470ab0aa040c4c3cace3162a405842a88be783e64fad54bd6727c23fc446b7ec0dc3eec5a03eb6c70ec2784911c9e6d274322ec465f0972eb8e771b149f319582ba64dbc2b8e56a3ea79002801c09354f1541cf79bd1dccf5d6bd6b6bacc87a0f24ce497e14e8037e5a79fb4d9ca63fe47f17765963e8f17468a5eaec19a6cca2bfc4e4a366fea3a92112a945856be55e45197ecbab523025e7589529c30cc8addc8fa39d23ef64fa2e51a219c3bd4d3c484832f8e5af16bc46cdba0403991f4fc1b74beef857acf15fefed82ac8678ca66d26262c681beddfdb485aa498813b1a6c5833f1339c1a35244ab76baa0ccaf681ec1f54004e387063335648a77b65d90dde74f1c4b0a729ca25fa53256f7db6d35818b4e5910ba78ec69cf3646bf248ef46cf9cc33062662de2afe4dcf005951b85fd759429fa1ae490b78b14132ccb791232a6c680f03634c0136817f51bf9603a0dba405e7b347830be4327fceccd4734456842b82cf6275393b279bc6ac93d743e00a2d6042960089f70c782ce554b9f73eeeefeea50df7f6f80de1c4e869a7b502f9a5df30d1175402fa780812d35c6d489a30bb0cea53a1088669a238cccf416ecb37f8d8e6ea1327b64979d48e937db69a44a902923a75113685a4aca4a8d9c62b388b48d9c9e2ab9c2df4d529223144de6e16f2dd95a063da79163b3fe006a80263cde4410648f7c3e1f4a7707f82eb0e209002d972c7e57b4ff8ce063fa7b4140f52f569f0cc8793a97a170613efb6b27ba3a0370f8ea74fc0d6aabba54e0ee967abc70e87b580d2aac244236b7752db9d83b159afc1faf6b44b697643235bf59e99f43428caff409d26b9139538865b1f5cf4699f9296088aca461209024ad1dd00e3566e4fde2117b7b3ffced6696b735816a00199890056de86dcbb1b930228143dbf04f07c0eb34370089ea55c43b2c4546cbe1ff0c3a6217d994af9b4225f4b5acb1e3129f5f5b98d381a4692a8561c670b2ee95869f9614e76bb07f623c5194e1c9d26334026f8f5437ec1cde526f914fa094a465f0adcea32b79bfa44d2562536b0d8366da9ee577666c1d5e39615444ca5c900b8199fafac002b8235688eaa0c6887475a913b37d9a4ed43a894ea4576102e5d475ae0b962240ea95fc367b7ac214a4f8682448a9c0d2eea35727bdedc235a975ecc8148a5b03d6291a051dbefe19c8b344d2713c6664dd94ced53c6be39a837fbf1169cca6a12b0a2710f443ba1afeecb51e94236b2a6ed1c2f365b595443b1515de86dcb8c67282807789b47c331cde2fdd721262bef165fa96b7919d11bc5f2022f5affffdd747c7dbe3de8add829a0a8913519fdf7dba4e8a7a25456d2d559746d39ea6ffa31c7b904792fb734bba30f2e1adf7457a994513a1807785fe7b22bf419d1f407f8e2db8b22c0512b078c0cfdfd599e6c4a9d0cc624b9e24b87f30541c3248cd6643df15d251775cc457df4ea6b4e4c5990d87541028c6f0eb28502db1c11a92797168d0b68cb0a0d345b3a3ad05fc4016862f403c64670c41a2c0c6d4e384f5f7da6a204a24530a51182fd7164f120e74a78decb1ab6cda6b9cfc68ac0a35f7a57e750ead65a8e0429cc16e733b9e4feaea25d06c1a4768'), packet.to_bytes()) for i, privkey in enumerate(payment_path_privkeys): processed_packet = process_onion_packet(packet, associated_data, privkey) self.assertEqual(hops_data[i].to_bytes(), processed_packet.hop_data.to_bytes()) packet = processed_packet.next_packet @needs_test_with_all_chacha20_implementations def test_process_onion_packet_legacy(self): # this test is not from bolt-04, but is based on the one there; # except here we have the privkeys for these pubkeys payment_path_pubkeys = [ bfh('03d75c0ee70f68d73d7d13aeb6261d8ace11416800860c7e59407afe4e2e2d42bb'), bfh('03960a0b830c7b8e76de745b819f252c62508346196b916f5e813cdb0773283cce'), bfh('0385620e0a571cbc3552620f8bf1bdcdab2d1a4a59c36fa10b8249114ccbdda40d'), bfh('02ee242cf6c38b7285f0152c33804ff777f5c51fd352ca8132e845e2cf23b3d8ba'), bfh('025c585fd2e174bf8245b2b4a119e52a417688904228643ea3edaa1728bf2a258e'), ] payment_path_privkeys = [ bfh('3463a278617b3dd83f79bda7f97673f12609c54386e1f0d2b67b1c6354fda14e'), bfh('7e1255fddb52db1729fc3ceb21a46f95b8d9fe94cc83425e936a6c5223bb679d'), bfh('c7ce8c1462c311eec24dff9e2532ac6241e50ae57e7d1833af21942136972f23'), bfh('3d885f374d79a5e777459b083f7818cdc9493e5c4994ac9c7b843de8b70be661'), bfh('dd72ab44729527b7942e195e7a835e7c71f9c0ff61844eb21274d9c26166a8f8'), ] session_key = bfh('4141414141414141414141414141414141414141414141414141414141414141') associated_data = bfh('4242424242424242424242424242424242424242424242424242424242424242') hops_data = [ OnionHopsDataSingle(is_tlv_payload=False, payload={ "amt_to_forward": {"amt_to_forward": 0}, "outgoing_cltv_value": {"outgoing_cltv_value": 0}, "short_channel_id": {"short_channel_id": bfh('0000000000000000')}, }), OnionHopsDataSingle(is_tlv_payload=False, payload={ "amt_to_forward": {"amt_to_forward": 1}, "outgoing_cltv_value": {"outgoing_cltv_value": 1}, "short_channel_id": {"short_channel_id": bfh('0101010101010101')}, }), OnionHopsDataSingle(is_tlv_payload=False, payload={ "amt_to_forward": {"amt_to_forward": 2}, "outgoing_cltv_value": {"outgoing_cltv_value": 2}, "short_channel_id": {"short_channel_id": bfh('0202020202020202')}, }), OnionHopsDataSingle(is_tlv_payload=False, payload={ "amt_to_forward": {"amt_to_forward": 3}, "outgoing_cltv_value": {"outgoing_cltv_value": 3}, "short_channel_id": {"short_channel_id": bfh('0303030303030303')}, }), OnionHopsDataSingle(is_tlv_payload=False, payload={ "amt_to_forward": {"amt_to_forward": 4}, "outgoing_cltv_value": {"outgoing_cltv_value": 4}, "short_channel_id": {"short_channel_id": bfh('0404040404040404')}, }), ] packet = new_onion_packet(payment_path_pubkeys, session_key, hops_data, associated_data) self.assertEqual(bfh('0002eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f28368661954176cd9869da33d713aa219fcef1e5c806fef11e696bcc66844de8271c27974a049d041ffc5be934b8575c6ff4371f2f88d4edfd73e445534d3f6ae15b64b0d8308390bebf8d149002e31bdc283056477ba27c8054c248ad7306de31663a7c99ec65b251704041f7c4cc40a0016ba172fbf805ec59132a65a4c7eb1f41337931c5df0f840704535729262d30c6132d1b390f073edec8fa057176c6268b6ad06a82ff0229c3be444ee50b40686bc1306838b93c65771de1b6ca05dace1ff9814a6e58b2dd71e8244c83e28b2ed5a3b09e9e7df5c8c747e5765ba366a4f7407a6c6b0a32fb5521cce7cd668f7434c909c1be027d8595d85893e5f612c49a93eeeed80a78bab9c4a621ce0f6f5df7d64a9c8d435db19de192d9db522c7f7b4e201fc1b61a9bd3efd062ae24455d463818b01e2756c7d0691bc3ac4c017be34c9a8b2913bb1b94056bf7a21730afc3f254ffa41ca140a5d87ff470f536d08619e8004d50de2fe5954d6aa4a00570da397ba15ae9ea4d7d1f136256a9093f0a787a36cbb3520b6a3cf4d1b13b16bf399c4b0326da1382a90bd79cf92f4808c8c84eaa50a8ccf44acbde0e35b2e6b72858c8446d6a05f3ba70fb4adc70af27cea9bd1dc1ea35fb3cc236b8b9b69b614903db339b22ad5dc2ddda7ac65fd7de24e60b7dbba7aafc9d26c0f9fcb03f1bb85dfc21762f862620651db52ea703ae60aa7e07febf11caa95c4245a4b37eb9c233e1ab1604fb85849e7f49cb9f7c681c4d91b7c320eb4b89b9c6bcb636ceadda59f6ed47aa5b1ea0a946ea98f6ad2614e79e0d4ef96d6d65903adb0479709e03008bbdf3355dd87df7d68965fdf1ad5c68b6dc2761b96b10f8eb4c0329a646bf38cf4702002e61565231b4ac7a9cde63d23f7b24c9d42797b3c434558d71ed8bf9fcab2c2aee3e8b38c19f9edc3ad3dfe9ebba7387ce4764f97ed1c1a83552dff8315546761479a6f929c39bcca0891d4a967d1b77fa80feed6ae74ac82ed5fb7be225c3f2b0ebdc652afc2255c47bc318ac645bbf19c0819ff527ff6708a78e19c8ca3dc8087035e10d5ac976e84b71148586c8a5a7b26ed11b5b401ce7bb2ac532207eaa24d2f53aaa8024607da764d807c91489e82fcad04e6b8992a507119367f576ee5ffe6807d5723d60234d4c3f94adce0acfed9dba535ca375446a4e9b500b74ad2a66e1c6b0fc38933f282d3a4a877bceceeca52b46e731ca51a9534224a883c4a45587f973f73a22069a4154b1da03d307d8575c821bef0eef87165b9a1bbf902ecfca82ddd805d10fbb7147b496f6772f01e9bf542b00288f3a6efab32590c1f34535ece03a0587ca187d27a98d4c9aa7c044794baa43a81abbe307f51d0bda6e7b4cf62c4be553b176321777e7fd483d6cec16df137293aaf3ad53608e1c7831368675bb9608db04d5c859e7714edab3d2389837fa071f0795adfabc51507b1adbadc7f83e80bd4e4eb9ed1a89c9e0a6dc16f38d55181d5666b02150651961aab34faef97d80fa4e1960864dfec3b687fd4eadf7aa6c709cb4698ae86ae112f386f33731d996b9d41926a2e820c6ba483a61674a4bae03af37e872ffdc0a9a8a034327af17e13e9e7ac619c9188c2a5c12a6ebf887721455c0e2822e67a621ed49f1f50dfc38b71c29d0224954e84ced086c80de552cca3a14adbe43035901225bafc3db3b672c780e4fa12b59221f93690527efc16a28e7c63d1a99fc881f023b03a157076a7e999a715ed37521adb483e2477d75ba5a55d4abad22b024c5317334b6544f15971591c774d896229e4e668fc1c7958fbd76fa0b152a6f14c95692083badd066b6621367fd73d88ba8d860566e6d55b871d80c68296b80ae8847d'), packet.to_bytes()) for i, privkey in enumerate(payment_path_privkeys): processed_packet = process_onion_packet(packet, associated_data, privkey) self.assertEqual(hops_data[i].to_bytes(), processed_packet.hop_data.to_bytes()) packet = processed_packet.next_packet @needs_test_with_all_chacha20_implementations def test_decode_onion_error(self): # test vector from bolt-04 payment_path_pubkeys = [ bfh('02eec7245d6b7d2ccb30380bfbe2a3648cd7a942653f5aa340edcea1f283686619'), bfh('0324653eac434488002cc06bbfb7f10fe18991e35f9fe4302dbea6d2353dc0ab1c'), bfh('027f31ebc5462c1fdce1b737ecff52d37d75dea43ce11c74d25aa297165faa2007'), bfh('032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991'), bfh('02edabbd16b41c8371b92ef2f04c1185b4f03b6dcd52ba9b78d9d7c89c8f221145'), ] session_key = bfh('4141414141414141414141414141414141414141414141414141414141414141') error_packet_for_node_0 = bfh('9c5add3963fc7f6ed7f148623c84134b5647e1306419dbe2174e523fa9e2fbed3a06a19f899145610741c83ad40b7712aefaddec8c6baf7325d92ea4ca4d1df8bce517f7e54554608bf2bd8071a4f52a7a2f7ffbb1413edad81eeea5785aa9d990f2865dc23b4bc3c301a94eec4eabebca66be5cf638f693ec256aec514620cc28ee4a94bd9565bc4d4962b9d3641d4278fb319ed2b84de5b665f307a2db0f7fbb757366067d88c50f7e829138fde4f78d39b5b5802f1b92a8a820865af5cc79f9f30bc3f461c66af95d13e5e1f0381c184572a91dee1c849048a647a1158cf884064deddbf1b0b88dfe2f791428d0ba0f6fb2f04e14081f69165ae66d9297c118f0907705c9c4954a199bae0bb96fad763d690e7daa6cfda59ba7f2c8d11448b604d12d') decoded_error, index_of_sender = _decode_onion_error(error_packet_for_node_0, payment_path_pubkeys, session_key) self.assertEqual(bfh('4c2fc8bc08510334b6833ad9c3e79cd1b52ae59dfe5c2a4b23ead50f09f7ee0b0002200200fe0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'), decoded_error) self.assertEqual(4, index_of_sender) failure_msg, index_of_sender = decode_onion_error(error_packet_for_node_0, payment_path_pubkeys, session_key) self.assertEqual(4, index_of_sender) self.assertEqual(OnionFailureCode.TEMPORARY_NODE_FAILURE, failure_msg.code) self.assertEqual(b'', failure_msg.data)
mit
arnedesmedt/dotfiles
.config/sublime-text-3/Packages.symlinkfollow/pygments/all/pygments/formatters/rtf.py
50
5049
# -*- coding: utf-8 -*- """ pygments.formatters.rtf ~~~~~~~~~~~~~~~~~~~~~~~ A formatter that generates RTF files. :copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.formatter import Formatter from pygments.util import get_int_opt, _surrogatepair __all__ = ['RtfFormatter'] class RtfFormatter(Formatter): """ Format tokens as RTF markup. This formatter automatically outputs full RTF documents with color information and other useful stuff. Perfect for Copy and Paste into Microsoft(R) Word(R) documents. Please note that ``encoding`` and ``outencoding`` options are ignored. The RTF format is ASCII natively, but handles unicode characters correctly thanks to escape sequences. .. versionadded:: 0.6 Additional options accepted: `style` The style to use, can be a string or a Style subclass (default: ``'default'``). `fontface` The used font famliy, for example ``Bitstream Vera Sans``. Defaults to some generic font which is supposed to have fixed width. `fontsize` Size of the font used. Size is specified in half points. The default is 24 half-points, giving a size 12 font. .. versionadded:: 2.0 """ name = 'RTF' aliases = ['rtf'] filenames = ['*.rtf'] def __init__(self, **options): r""" Additional options accepted: ``fontface`` Name of the font used. Could for example be ``'Courier New'`` to further specify the default which is ``'\fmodern'``. The RTF specification claims that ``\fmodern`` are "Fixed-pitch serif and sans serif fonts". Hope every RTF implementation thinks the same about modern... """ Formatter.__init__(self, **options) self.fontface = options.get('fontface') or '' self.fontsize = get_int_opt(options, 'fontsize', 0) def _escape(self, text): return text.replace(u'\\', u'\\\\') \ .replace(u'{', u'\\{') \ .replace(u'}', u'\\}') def _escape_text(self, text): # empty strings, should give a small performance improvment if not text: return u'' # escape text text = self._escape(text) buf = [] for c in text: cn = ord(c) if cn < (2**7): # ASCII character buf.append(str(c)) elif (2**7) <= cn < (2**16): # single unicode escape sequence buf.append(u'{\\u%d}' % cn) elif (2**16) <= cn: # RTF limits unicode to 16 bits. # Force surrogate pairs buf.append(u'{\\u%d}{\\u%d}' % _surrogatepair(cn)) return u''.join(buf).replace(u'\n', u'\\par\n') def format_unencoded(self, tokensource, outfile): # rtf 1.8 header outfile.write(u'{\\rtf1\\ansi\\uc0\\deff0' u'{\\fonttbl{\\f0\\fmodern\\fprq1\\fcharset0%s;}}' u'{\\colortbl;' % (self.fontface and u' ' + self._escape(self.fontface) or u'')) # convert colors and save them in a mapping to access them later. color_mapping = {} offset = 1 for _, style in self.style: for color in style['color'], style['bgcolor'], style['border']: if color and color not in color_mapping: color_mapping[color] = offset outfile.write(u'\\red%d\\green%d\\blue%d;' % ( int(color[0:2], 16), int(color[2:4], 16), int(color[4:6], 16) )) offset += 1 outfile.write(u'}\\f0 ') if self.fontsize: outfile.write(u'\\fs%d' % (self.fontsize)) # highlight stream for ttype, value in tokensource: while not self.style.styles_token(ttype) and ttype.parent: ttype = ttype.parent style = self.style.style_for_token(ttype) buf = [] if style['bgcolor']: buf.append(u'\\cb%d' % color_mapping[style['bgcolor']]) if style['color']: buf.append(u'\\cf%d' % color_mapping[style['color']]) if style['bold']: buf.append(u'\\b') if style['italic']: buf.append(u'\\i') if style['underline']: buf.append(u'\\ul') if style['border']: buf.append(u'\\chbrdr\\chcfpat%d' % color_mapping[style['border']]) start = u''.join(buf) if start: outfile.write(u'{%s ' % start) outfile.write(self._escape_text(value)) if start: outfile.write(u'}') outfile.write(u'}')
mit
bbsan2k/nzbToMedia
libs/unidecode/x094.py
252
4661
data = ( 'Kui ', # 0x00 'Si ', # 0x01 'Liu ', # 0x02 'Nao ', # 0x03 'Heng ', # 0x04 'Pie ', # 0x05 'Sui ', # 0x06 'Fan ', # 0x07 'Qiao ', # 0x08 'Quan ', # 0x09 'Yang ', # 0x0a 'Tang ', # 0x0b 'Xiang ', # 0x0c 'Jue ', # 0x0d 'Jiao ', # 0x0e 'Zun ', # 0x0f 'Liao ', # 0x10 'Jie ', # 0x11 'Lao ', # 0x12 'Dui ', # 0x13 'Tan ', # 0x14 'Zan ', # 0x15 'Ji ', # 0x16 'Jian ', # 0x17 'Zhong ', # 0x18 'Deng ', # 0x19 'Ya ', # 0x1a 'Ying ', # 0x1b 'Dui ', # 0x1c 'Jue ', # 0x1d 'Nou ', # 0x1e 'Ti ', # 0x1f 'Pu ', # 0x20 'Tie ', # 0x21 '[?] ', # 0x22 '[?] ', # 0x23 'Ding ', # 0x24 'Shan ', # 0x25 'Kai ', # 0x26 'Jian ', # 0x27 'Fei ', # 0x28 'Sui ', # 0x29 'Lu ', # 0x2a 'Juan ', # 0x2b 'Hui ', # 0x2c 'Yu ', # 0x2d 'Lian ', # 0x2e 'Zhuo ', # 0x2f 'Qiao ', # 0x30 'Qian ', # 0x31 'Zhuo ', # 0x32 'Lei ', # 0x33 'Bi ', # 0x34 'Tie ', # 0x35 'Huan ', # 0x36 'Ye ', # 0x37 'Duo ', # 0x38 'Guo ', # 0x39 'Dang ', # 0x3a 'Ju ', # 0x3b 'Fen ', # 0x3c 'Da ', # 0x3d 'Bei ', # 0x3e 'Yi ', # 0x3f 'Ai ', # 0x40 'Zong ', # 0x41 'Xun ', # 0x42 'Diao ', # 0x43 'Zhu ', # 0x44 'Heng ', # 0x45 'Zhui ', # 0x46 'Ji ', # 0x47 'Nie ', # 0x48 'Ta ', # 0x49 'Huo ', # 0x4a 'Qing ', # 0x4b 'Bin ', # 0x4c 'Ying ', # 0x4d 'Kui ', # 0x4e 'Ning ', # 0x4f 'Xu ', # 0x50 'Jian ', # 0x51 'Jian ', # 0x52 'Yari ', # 0x53 'Cha ', # 0x54 'Zhi ', # 0x55 'Mie ', # 0x56 'Li ', # 0x57 'Lei ', # 0x58 'Ji ', # 0x59 'Zuan ', # 0x5a 'Kuang ', # 0x5b 'Shang ', # 0x5c 'Peng ', # 0x5d 'La ', # 0x5e 'Du ', # 0x5f 'Shuo ', # 0x60 'Chuo ', # 0x61 'Lu ', # 0x62 'Biao ', # 0x63 'Bao ', # 0x64 'Lu ', # 0x65 '[?] ', # 0x66 '[?] ', # 0x67 'Long ', # 0x68 'E ', # 0x69 'Lu ', # 0x6a 'Xin ', # 0x6b 'Jian ', # 0x6c 'Lan ', # 0x6d 'Bo ', # 0x6e 'Jian ', # 0x6f 'Yao ', # 0x70 'Chan ', # 0x71 'Xiang ', # 0x72 'Jian ', # 0x73 'Xi ', # 0x74 'Guan ', # 0x75 'Cang ', # 0x76 'Nie ', # 0x77 'Lei ', # 0x78 'Cuan ', # 0x79 'Qu ', # 0x7a 'Pan ', # 0x7b 'Luo ', # 0x7c 'Zuan ', # 0x7d 'Luan ', # 0x7e 'Zao ', # 0x7f 'Nie ', # 0x80 'Jue ', # 0x81 'Tang ', # 0x82 'Shu ', # 0x83 'Lan ', # 0x84 'Jin ', # 0x85 'Qiu ', # 0x86 'Yi ', # 0x87 'Zhen ', # 0x88 'Ding ', # 0x89 'Zhao ', # 0x8a 'Po ', # 0x8b 'Diao ', # 0x8c 'Tu ', # 0x8d 'Qian ', # 0x8e 'Chuan ', # 0x8f 'Shan ', # 0x90 'Ji ', # 0x91 'Fan ', # 0x92 'Diao ', # 0x93 'Men ', # 0x94 'Nu ', # 0x95 'Xi ', # 0x96 'Chai ', # 0x97 'Xing ', # 0x98 'Gai ', # 0x99 'Bu ', # 0x9a 'Tai ', # 0x9b 'Ju ', # 0x9c 'Dun ', # 0x9d 'Chao ', # 0x9e 'Zhong ', # 0x9f 'Na ', # 0xa0 'Bei ', # 0xa1 'Gang ', # 0xa2 'Ban ', # 0xa3 'Qian ', # 0xa4 'Yao ', # 0xa5 'Qin ', # 0xa6 'Jun ', # 0xa7 'Wu ', # 0xa8 'Gou ', # 0xa9 'Kang ', # 0xaa 'Fang ', # 0xab 'Huo ', # 0xac 'Tou ', # 0xad 'Niu ', # 0xae 'Ba ', # 0xaf 'Yu ', # 0xb0 'Qian ', # 0xb1 'Zheng ', # 0xb2 'Qian ', # 0xb3 'Gu ', # 0xb4 'Bo ', # 0xb5 'E ', # 0xb6 'Po ', # 0xb7 'Bu ', # 0xb8 'Ba ', # 0xb9 'Yue ', # 0xba 'Zuan ', # 0xbb 'Mu ', # 0xbc 'Dan ', # 0xbd 'Jia ', # 0xbe 'Dian ', # 0xbf 'You ', # 0xc0 'Tie ', # 0xc1 'Bo ', # 0xc2 'Ling ', # 0xc3 'Shuo ', # 0xc4 'Qian ', # 0xc5 'Liu ', # 0xc6 'Bao ', # 0xc7 'Shi ', # 0xc8 'Xuan ', # 0xc9 'She ', # 0xca 'Bi ', # 0xcb 'Ni ', # 0xcc 'Pi ', # 0xcd 'Duo ', # 0xce 'Xing ', # 0xcf 'Kao ', # 0xd0 'Lao ', # 0xd1 'Er ', # 0xd2 'Mang ', # 0xd3 'Ya ', # 0xd4 'You ', # 0xd5 'Cheng ', # 0xd6 'Jia ', # 0xd7 'Ye ', # 0xd8 'Nao ', # 0xd9 'Zhi ', # 0xda 'Dang ', # 0xdb 'Tong ', # 0xdc 'Lu ', # 0xdd 'Diao ', # 0xde 'Yin ', # 0xdf 'Kai ', # 0xe0 'Zha ', # 0xe1 'Zhu ', # 0xe2 'Xian ', # 0xe3 'Ting ', # 0xe4 'Diu ', # 0xe5 'Xian ', # 0xe6 'Hua ', # 0xe7 'Quan ', # 0xe8 'Sha ', # 0xe9 'Jia ', # 0xea 'Yao ', # 0xeb 'Ge ', # 0xec 'Ming ', # 0xed 'Zheng ', # 0xee 'Se ', # 0xef 'Jiao ', # 0xf0 'Yi ', # 0xf1 'Chan ', # 0xf2 'Chong ', # 0xf3 'Tang ', # 0xf4 'An ', # 0xf5 'Yin ', # 0xf6 'Ru ', # 0xf7 'Zhu ', # 0xf8 'Lao ', # 0xf9 'Pu ', # 0xfa 'Wu ', # 0xfb 'Lai ', # 0xfc 'Te ', # 0xfd 'Lian ', # 0xfe 'Keng ', # 0xff )
gpl-3.0
Shrhawk/edx-platform
lms/djangoapps/mobile_api/social_facebook/preferences/views.py
86
1597
""" Views for users sharing preferences """ from rest_framework import generics, status from rest_framework.response import Response from openedx.core.djangoapps.user_api.preferences.api import get_user_preferences, set_user_preference from ...utils import mobile_view from . import serializers @mobile_view() class UserSharing(generics.ListCreateAPIView): """ **Use Case** An API to retrieve or update the users social sharing settings **GET Example request**: GET /api/mobile/v0.5/settings/preferences/ **GET Response Values** {'share_with_facebook_friends': 'True'} **POST Example request**: POST /api/mobile/v0.5/settings/preferences/ paramters: share_with_facebook_friends : True **POST Response Values** {'share_with_facebook_friends': 'True'} """ serializer_class = serializers.UserSharingSerializar def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.DATA, files=request.FILES) if serializer.is_valid(): value = serializer.object['share_with_facebook_friends'] set_user_preference(request.user, "share_with_facebook_friends", value) return self.get(request, *args, **kwargs) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request, *args, **kwargs): preferences = get_user_preferences(request.user) response = {'share_with_facebook_friends': preferences.get('share_with_facebook_friends', 'False')} return Response(response)
agpl-3.0
batxes/4c2vhic
Six_zebra_models/Six_zebra_models_final_output_0.1_-0.1_13000/Six_zebra_models9343.py
2
13928
import _surface import chimera try: import chimera.runCommand except: pass from VolumePath import markerset as ms try: from VolumePath import Marker_Set, Link new_marker_set=Marker_Set except: from VolumePath import volume_path_dialog d= volume_path_dialog(True) new_marker_set= d.new_marker_set marker_sets={} surf_sets={} if "particle_0 geometry" not in marker_sets: s=new_marker_set('particle_0 geometry') marker_sets["particle_0 geometry"]=s s= marker_sets["particle_0 geometry"] mark=s.place_marker((4185.56, 12162.1, 14085.2), (0.7, 0.7, 0.7), 507.685) if "particle_1 geometry" not in marker_sets: s=new_marker_set('particle_1 geometry') marker_sets["particle_1 geometry"]=s s= marker_sets["particle_1 geometry"] mark=s.place_marker((3904.55, 13126, 13884.2), (0.7, 0.7, 0.7), 479.978) if "particle_2 geometry" not in marker_sets: s=new_marker_set('particle_2 geometry') marker_sets["particle_2 geometry"]=s s= marker_sets["particle_2 geometry"] mark=s.place_marker((4241.24, 11745.4, 12583.9), (0.7, 0.7, 0.7), 681.834) if "particle_3 geometry" not in marker_sets: s=new_marker_set('particle_3 geometry') marker_sets["particle_3 geometry"]=s s= marker_sets["particle_3 geometry"] mark=s.place_marker((4669.29, 10044.2, 11038.9), (0.7, 0.7, 0.7), 522.532) if "particle_4 geometry" not in marker_sets: s=new_marker_set('particle_4 geometry') marker_sets["particle_4 geometry"]=s s= marker_sets["particle_4 geometry"] mark=s.place_marker((4791.74, 9550.88, 10536.1), (0, 1, 0), 751.925) if "particle_5 geometry" not in marker_sets: s=new_marker_set('particle_5 geometry') marker_sets["particle_5 geometry"]=s s= marker_sets["particle_5 geometry"] mark=s.place_marker((3849.3, 11442.4, 10656.5), (0.7, 0.7, 0.7), 437.001) if "particle_6 geometry" not in marker_sets: s=new_marker_set('particle_6 geometry') marker_sets["particle_6 geometry"]=s s= marker_sets["particle_6 geometry"] mark=s.place_marker((3533.72, 10986.5, 8814.93), (0.7, 0.7, 0.7), 710.767) if "particle_7 geometry" not in marker_sets: s=new_marker_set('particle_7 geometry') marker_sets["particle_7 geometry"]=s s= marker_sets["particle_7 geometry"] mark=s.place_marker((2493.59, 12019, 7942.07), (0.7, 0.7, 0.7), 762.077) if "particle_8 geometry" not in marker_sets: s=new_marker_set('particle_8 geometry') marker_sets["particle_8 geometry"]=s s= marker_sets["particle_8 geometry"] mark=s.place_marker((1727.12, 11675.5, 6706.42), (0.7, 0.7, 0.7), 726.799) if "particle_9 geometry" not in marker_sets: s=new_marker_set('particle_9 geometry') marker_sets["particle_9 geometry"]=s s= marker_sets["particle_9 geometry"] mark=s.place_marker((866.892, 11247.1, 5069.8), (0.7, 0.7, 0.7), 885.508) if "particle_10 geometry" not in marker_sets: s=new_marker_set('particle_10 geometry') marker_sets["particle_10 geometry"]=s s= marker_sets["particle_10 geometry"] mark=s.place_marker((-71.7329, 9814.15, 5117.13), (0.7, 0.7, 0.7), 778.489) if "particle_11 geometry" not in marker_sets: s=new_marker_set('particle_11 geometry') marker_sets["particle_11 geometry"]=s s= marker_sets["particle_11 geometry"] mark=s.place_marker((-2170.94, 10122.1, 5041.11), (0.7, 0.7, 0.7), 790.333) if "particle_12 geometry" not in marker_sets: s=new_marker_set('particle_12 geometry') marker_sets["particle_12 geometry"]=s s= marker_sets["particle_12 geometry"] mark=s.place_marker((-4210.85, 10403.6, 5022.87), (0.7, 0.7, 0.7), 707.721) if "particle_13 geometry" not in marker_sets: s=new_marker_set('particle_13 geometry') marker_sets["particle_13 geometry"]=s s= marker_sets["particle_13 geometry"] mark=s.place_marker((-3517.89, 10374.1, 6478.29), (0.7, 0.7, 0.7), 651.166) if "particle_14 geometry" not in marker_sets: s=new_marker_set('particle_14 geometry') marker_sets["particle_14 geometry"]=s s= marker_sets["particle_14 geometry"] mark=s.place_marker((-3292.8, 10114.4, 4924.43), (0.7, 0.7, 0.7), 708.61) if "particle_15 geometry" not in marker_sets: s=new_marker_set('particle_15 geometry') marker_sets["particle_15 geometry"]=s s= marker_sets["particle_15 geometry"] mark=s.place_marker((-1971.35, 10112.1, 4138.5), (0.7, 0.7, 0.7), 490.595) if "particle_16 geometry" not in marker_sets: s=new_marker_set('particle_16 geometry') marker_sets["particle_16 geometry"]=s s= marker_sets["particle_16 geometry"] mark=s.place_marker((-618.486, 10102.3, 4423.5), (0.7, 0.7, 0.7), 591.565) if "particle_17 geometry" not in marker_sets: s=new_marker_set('particle_17 geometry') marker_sets["particle_17 geometry"]=s s= marker_sets["particle_17 geometry"] mark=s.place_marker((769.01, 10281.2, 4657.21), (0.7, 0.7, 0.7), 581.287) if "particle_18 geometry" not in marker_sets: s=new_marker_set('particle_18 geometry') marker_sets["particle_18 geometry"]=s s= marker_sets["particle_18 geometry"] mark=s.place_marker((695.681, 11773.9, 5639.78), (0.7, 0.7, 0.7), 789.529) if "particle_19 geometry" not in marker_sets: s=new_marker_set('particle_19 geometry') marker_sets["particle_19 geometry"]=s s= marker_sets["particle_19 geometry"] mark=s.place_marker((1962.12, 12441.9, 5095.03), (0.7, 0.7, 0.7), 623.587) if "particle_20 geometry" not in marker_sets: s=new_marker_set('particle_20 geometry') marker_sets["particle_20 geometry"]=s s= marker_sets["particle_20 geometry"] mark=s.place_marker((3182.88, 13235.1, 3996), (0.7, 0.7, 0.7), 1083.56) if "particle_21 geometry" not in marker_sets: s=new_marker_set('particle_21 geometry') marker_sets["particle_21 geometry"]=s s= marker_sets["particle_21 geometry"] mark=s.place_marker((3653.63, 14506.4, 2907.35), (0.7, 0.7, 0.7), 504.258) if "particle_22 geometry" not in marker_sets: s=new_marker_set('particle_22 geometry') marker_sets["particle_22 geometry"]=s s= marker_sets["particle_22 geometry"] mark=s.place_marker((4086.91, 13227.9, 3387.45), (0.7, 0.7, 0.7), 805.519) if "particle_23 geometry" not in marker_sets: s=new_marker_set('particle_23 geometry') marker_sets["particle_23 geometry"]=s s= marker_sets["particle_23 geometry"] mark=s.place_marker((3964.35, 11125.7, 3301.9), (0.7, 0.7, 0.7), 631.708) if "particle_24 geometry" not in marker_sets: s=new_marker_set('particle_24 geometry') marker_sets["particle_24 geometry"]=s s= marker_sets["particle_24 geometry"] mark=s.place_marker((3463.04, 9191.99, 2524.86), (0.7, 0.7, 0.7), 805.942) if "particle_25 geometry" not in marker_sets: s=new_marker_set('particle_25 geometry') marker_sets["particle_25 geometry"]=s s= marker_sets["particle_25 geometry"] mark=s.place_marker((3191.84, 8274.78, 2080.08), (1, 0.7, 0), 672.697) if "particle_26 geometry" not in marker_sets: s=new_marker_set('particle_26 geometry') marker_sets["particle_26 geometry"]=s s= marker_sets["particle_26 geometry"] mark=s.place_marker((5342.01, 7111.08, 3205.42), (0.7, 0.7, 0.7), 797.863) if "particle_27 geometry" not in marker_sets: s=new_marker_set('particle_27 geometry') marker_sets["particle_27 geometry"]=s s= marker_sets["particle_27 geometry"] mark=s.place_marker((6748.19, 5888.29, 3110.98), (1, 0.7, 0), 735.682) if "particle_28 geometry" not in marker_sets: s=new_marker_set('particle_28 geometry') marker_sets["particle_28 geometry"]=s s= marker_sets["particle_28 geometry"] mark=s.place_marker((7811.27, 6554.89, 3280.12), (0.7, 0.7, 0.7), 602.14) if "particle_29 geometry" not in marker_sets: s=new_marker_set('particle_29 geometry') marker_sets["particle_29 geometry"]=s s= marker_sets["particle_29 geometry"] mark=s.place_marker((9865.52, 7615.13, 2974.52), (0.7, 0.7, 0.7), 954.796) if "particle_30 geometry" not in marker_sets: s=new_marker_set('particle_30 geometry') marker_sets["particle_30 geometry"]=s s= marker_sets["particle_30 geometry"] mark=s.place_marker((9147.23, 7573.21, 3715.05), (0.7, 0.7, 0.7), 1021.88) if "particle_31 geometry" not in marker_sets: s=new_marker_set('particle_31 geometry') marker_sets["particle_31 geometry"]=s s= marker_sets["particle_31 geometry"] mark=s.place_marker((9880.49, 6287.82, 3364.74), (0.7, 0.7, 0.7), 909.323) if "particle_32 geometry" not in marker_sets: s=new_marker_set('particle_32 geometry') marker_sets["particle_32 geometry"]=s s= marker_sets["particle_32 geometry"] mark=s.place_marker((11883.4, 5374.2, 3932.73), (0.7, 0.7, 0.7), 621.049) if "particle_33 geometry" not in marker_sets: s=new_marker_set('particle_33 geometry') marker_sets["particle_33 geometry"]=s s= marker_sets["particle_33 geometry"] mark=s.place_marker((11842.1, 4832.05, 5281.18), (0.7, 0.7, 0.7), 525.154) if "particle_34 geometry" not in marker_sets: s=new_marker_set('particle_34 geometry') marker_sets["particle_34 geometry"]=s s= marker_sets["particle_34 geometry"] mark=s.place_marker((11749, 5181.08, 6743.55), (0.7, 0.7, 0.7), 890.246) if "particle_35 geometry" not in marker_sets: s=new_marker_set('particle_35 geometry') marker_sets["particle_35 geometry"]=s s= marker_sets["particle_35 geometry"] mark=s.place_marker((12654.9, 5517.78, 8223.46), (0.7, 0.7, 0.7), 671.216) if "particle_36 geometry" not in marker_sets: s=new_marker_set('particle_36 geometry') marker_sets["particle_36 geometry"]=s s= marker_sets["particle_36 geometry"] mark=s.place_marker((13417.6, 6785.87, 9037.71), (0.7, 0.7, 0.7), 662.672) if "particle_37 geometry" not in marker_sets: s=new_marker_set('particle_37 geometry') marker_sets["particle_37 geometry"]=s s= marker_sets["particle_37 geometry"] mark=s.place_marker((13100, 7660.29, 7728.67), (0.7, 0.7, 0.7), 646.682) if "particle_38 geometry" not in marker_sets: s=new_marker_set('particle_38 geometry') marker_sets["particle_38 geometry"]=s s= marker_sets["particle_38 geometry"] mark=s.place_marker((13591.6, 6665.47, 6673.14), (0.7, 0.7, 0.7), 769.945) if "particle_39 geometry" not in marker_sets: s=new_marker_set('particle_39 geometry') marker_sets["particle_39 geometry"]=s s= marker_sets["particle_39 geometry"] mark=s.place_marker((12023.1, 5646.28, 5969.3), (0.7, 0.7, 0.7), 606.92) if "particle_40 geometry" not in marker_sets: s=new_marker_set('particle_40 geometry') marker_sets["particle_40 geometry"]=s s= marker_sets["particle_40 geometry"] mark=s.place_marker((12346.8, 4467.46, 6252.34), (0.7, 0.7, 0.7), 622.571) if "particle_41 geometry" not in marker_sets: s=new_marker_set('particle_41 geometry') marker_sets["particle_41 geometry"]=s s= marker_sets["particle_41 geometry"] mark=s.place_marker((11294.2, 5307.45, 6034.37), (0.7, 0.7, 0.7), 466.865) if "particle_42 geometry" not in marker_sets: s=new_marker_set('particle_42 geometry') marker_sets["particle_42 geometry"]=s s= marker_sets["particle_42 geometry"] mark=s.place_marker((11203.4, 5691.81, 6690.46), (0.7, 0.7, 0.7), 682.933) if "particle_43 geometry" not in marker_sets: s=new_marker_set('particle_43 geometry') marker_sets["particle_43 geometry"]=s s= marker_sets["particle_43 geometry"] mark=s.place_marker((11369.6, 5235.94, 6343.95), (0.7, 0.7, 0.7), 809.326) if "particle_44 geometry" not in marker_sets: s=new_marker_set('particle_44 geometry') marker_sets["particle_44 geometry"]=s s= marker_sets["particle_44 geometry"] mark=s.place_marker((10836.2, 5312.76, 4580.26), (0.7, 0.7, 0.7), 796.72) if "particle_45 geometry" not in marker_sets: s=new_marker_set('particle_45 geometry') marker_sets["particle_45 geometry"]=s s= marker_sets["particle_45 geometry"] mark=s.place_marker((8018.51, 4948.65, 4035.09), (0.7, 0.7, 0.7), 870.026) if "particle_46 geometry" not in marker_sets: s=new_marker_set('particle_46 geometry') marker_sets["particle_46 geometry"]=s s= marker_sets["particle_46 geometry"] mark=s.place_marker((6696.09, 3654.72, 4325.29), (0.7, 0.7, 0.7), 909.577) if "particle_47 geometry" not in marker_sets: s=new_marker_set('particle_47 geometry') marker_sets["particle_47 geometry"]=s s= marker_sets["particle_47 geometry"] mark=s.place_marker((6204.48, 2973.07, 5117.74), (0, 1, 0), 500.536) if "particle_48 geometry" not in marker_sets: s=new_marker_set('particle_48 geometry') marker_sets["particle_48 geometry"]=s s= marker_sets["particle_48 geometry"] mark=s.place_marker((6718.77, 1223.9, 5894.49), (0.7, 0.7, 0.7), 725.276) if "particle_49 geometry" not in marker_sets: s=new_marker_set('particle_49 geometry') marker_sets["particle_49 geometry"]=s s= marker_sets["particle_49 geometry"] mark=s.place_marker((7640.25, -1272.89, 6048.18), (0.7, 0.7, 0.7), 570.331) if "particle_50 geometry" not in marker_sets: s=new_marker_set('particle_50 geometry') marker_sets["particle_50 geometry"]=s s= marker_sets["particle_50 geometry"] mark=s.place_marker((9225.35, -694.741, 5937.2), (0.7, 0.7, 0.7), 492.203) if "particle_51 geometry" not in marker_sets: s=new_marker_set('particle_51 geometry') marker_sets["particle_51 geometry"]=s s= marker_sets["particle_51 geometry"] mark=s.place_marker((8818.08, 1088.66, 3662.72), (0, 1, 0), 547.7) if "particle_52 geometry" not in marker_sets: s=new_marker_set('particle_52 geometry') marker_sets["particle_52 geometry"]=s s= marker_sets["particle_52 geometry"] mark=s.place_marker((8942.16, 1505.99, 4318.17), (0.7, 0.7, 0.7), 581.921) if "particle_53 geometry" not in marker_sets: s=new_marker_set('particle_53 geometry') marker_sets["particle_53 geometry"]=s s= marker_sets["particle_53 geometry"] mark=s.place_marker((10464.1, 1740.65, 5476.62), (0.7, 0.7, 0.7), 555.314) if "particle_54 geometry" not in marker_sets: s=new_marker_set('particle_54 geometry') marker_sets["particle_54 geometry"]=s s= marker_sets["particle_54 geometry"] mark=s.place_marker((11062.1, 2285.75, 6791.11), (0.7, 0.7, 0.7), 404.219) if "particle_55 geometry" not in marker_sets: s=new_marker_set('particle_55 geometry') marker_sets["particle_55 geometry"]=s s= marker_sets["particle_55 geometry"] mark=s.place_marker((10074.5, 3648.4, 7517.54), (0.7, 0.7, 0.7), 764.234) for k in surf_sets.keys(): chimera.openModels.add([surf_sets[k]])
gpl-3.0
ycaihua/scikit-learn
sklearn/preprocessing/tests/test_imputation.py
28
11950
import numpy as np from scipy import sparse from sklearn.utils.testing import assert_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_false from sklearn.utils.testing import assert_true from sklearn.preprocessing.imputation import Imputer from sklearn.pipeline import Pipeline from sklearn import grid_search from sklearn import tree from sklearn.random_projection import sparse_random_matrix def _check_statistics(X, X_true, strategy, statistics, missing_values): """Utility function for testing imputation for a given strategy. Test: - along the two axes - with dense and sparse arrays Check that: - the statistics (mean, median, mode) are correct - the missing values are imputed correctly""" err_msg = "Parameters: strategy = %s, missing_values = %s, " \ "axis = {0}, sparse = {1}" % (strategy, missing_values) # Normal matrix, axis = 0 imputer = Imputer(missing_values, strategy=strategy, axis=0) X_trans = imputer.fit(X).transform(X.copy()) assert_array_equal(imputer.statistics_, statistics, err_msg.format(0, False)) assert_array_equal(X_trans, X_true, err_msg.format(0, False)) # Normal matrix, axis = 1 imputer = Imputer(missing_values, strategy=strategy, axis=1) imputer.fit(X.transpose()) if np.isnan(statistics).any(): assert_raises(ValueError, imputer.transform, X.copy().transpose()) else: X_trans = imputer.transform(X.copy().transpose()) assert_array_equal(X_trans, X_true.transpose(), err_msg.format(1, False)) # Sparse matrix, axis = 0 imputer = Imputer(missing_values, strategy=strategy, axis=0) imputer.fit(sparse.csc_matrix(X)) X_trans = imputer.transform(sparse.csc_matrix(X.copy())) if sparse.issparse(X_trans): X_trans = X_trans.toarray() assert_array_equal(imputer.statistics_, statistics, err_msg.format(0, True)) assert_array_equal(X_trans, X_true, err_msg.format(0, True)) # Sparse matrix, axis = 1 imputer = Imputer(missing_values, strategy=strategy, axis=1) imputer.fit(sparse.csc_matrix(X.transpose())) if np.isnan(statistics).any(): assert_raises(ValueError, imputer.transform, sparse.csc_matrix(X.copy().transpose())) else: X_trans = imputer.transform(sparse.csc_matrix(X.copy().transpose())) if sparse.issparse(X_trans): X_trans = X_trans.toarray() assert_array_equal(X_trans, X_true.transpose(), err_msg.format(1, True)) def test_imputation_shape(): """Verify the shapes of the imputed matrix for different strategies.""" X = np.random.randn(10, 2) X[::2] = np.nan for strategy in ['mean', 'median', 'most_frequent']: imputer = Imputer(strategy=strategy) X_imputed = imputer.fit_transform(X) assert_equal(X_imputed.shape, (10, 2)) X_imputed = imputer.fit_transform(sparse.csr_matrix(X)) assert_equal(X_imputed.shape, (10, 2)) def test_imputation_mean_median_only_zero(): """Test imputation using the mean and median strategies, when missing_values == 0.""" X = np.array([ [np.nan, 0, 0, 0, 5], [np.nan, 1, 0, np.nan, 3], [np.nan, 2, 0, 0, 0], [np.nan, 6, 0, 5, 13], ]) X_imputed_mean = np.array([ [3, 5], [1, 3], [2, 7], [6, 13], ]) statistics_mean = [np.nan, 3, np.nan, np.nan, 7] # Behaviour of median with NaN is undefined, e.g. different results in # np.median and np.ma.median X_for_median = X[:, [0, 1, 2, 4]] X_imputed_median = np.array([ [2, 5], [1, 3], [2, 5], [6, 13], ]) statistics_median = [np.nan, 2, np.nan, 5] _check_statistics(X, X_imputed_mean, "mean", statistics_mean, 0) _check_statistics(X_for_median, X_imputed_median, "median", statistics_median, 0) def test_imputation_mean_median(): """Test imputation using the mean and median strategies, when missing_values != 0.""" rng = np.random.RandomState(0) dim = 10 dec = 10 shape = (dim * dim, dim + dec) zeros = np.zeros(shape[0]) values = np.arange(1, shape[0]+1) values[4::2] = - values[4::2] tests = [("mean", "NaN", lambda z, v, p: np.mean(np.hstack((z, v)))), ("mean", 0, lambda z, v, p: np.mean(v)), ("median", "NaN", lambda z, v, p: np.median(np.hstack((z, v)))), ("median", 0, lambda z, v, p: np.median(v))] for strategy, test_missing_values, true_value_fun in tests: X = np.empty(shape) X_true = np.empty(shape) true_statistics = np.empty(shape[1]) # Create a matrix X with columns # - with only zeros, # - with only missing values # - with zeros, missing values and values # And a matrix X_true containing all true values for j in range(shape[1]): nb_zeros = (j - dec + 1 > 0) * (j - dec + 1) * (j - dec + 1) nb_missing_values = max(shape[0] + dec * dec - (j + dec) * (j + dec), 0) nb_values = shape[0] - nb_zeros - nb_missing_values z = zeros[:nb_zeros] p = np.repeat(test_missing_values, nb_missing_values) v = values[rng.permutation(len(values))[:nb_values]] true_statistics[j] = true_value_fun(z, v, p) # Create the columns X[:, j] = np.hstack((v, z, p)) if 0 == test_missing_values: X_true[:, j] = np.hstack((v, np.repeat( true_statistics[j], nb_missing_values + nb_zeros))) else: X_true[:, j] = np.hstack((v, z, np.repeat(true_statistics[j], nb_missing_values))) # Shuffle them the same way np.random.RandomState(j).shuffle(X[:, j]) np.random.RandomState(j).shuffle(X_true[:, j]) # Mean doesn't support columns containing NaNs, median does if strategy == "median": cols_to_keep = ~np.isnan(X_true).any(axis=0) else: cols_to_keep = ~np.isnan(X_true).all(axis=0) X_true = X_true[:, cols_to_keep] _check_statistics(X, X_true, strategy, true_statistics, test_missing_values) def test_imputation_median_special_cases(): """Test median imputation with sparse boundary cases """ X = np.array([ [0, np.nan, np.nan], # odd: implicit zero [5, np.nan, np.nan], # odd: explicit nonzero [0, 0, np.nan], # even: average two zeros [-5, 0, np.nan], # even: avg zero and neg [0, 5, np.nan], # even: avg zero and pos [4, 5, np.nan], # even: avg nonzeros [-4, -5, np.nan], # even: avg negatives [-1, 2, np.nan], # even: crossing neg and pos ]).transpose() X_imputed_median = np.array([ [0, 0, 0], [5, 5, 5], [0, 0, 0], [-5, 0, -2.5], [0, 5, 2.5], [4, 5, 4.5], [-4, -5, -4.5], [-1, 2, .5], ]).transpose() statistics_median = [0, 5, 0, -2.5, 2.5, 4.5, -4.5, .5] _check_statistics(X, X_imputed_median, "median", statistics_median, 'NaN') def test_imputation_most_frequent(): """Test imputation using the most-frequent strategy.""" X = np.array([ [-1, -1, 0, 5], [-1, 2, -1, 3], [-1, 1, 3, -1], [-1, 2, 3, 7], ]) X_true = np.array([ [2, 0, 5], [2, 3, 3], [1, 3, 3], [2, 3, 7], ]) # scipy.stats.mode, used in Imputer, doesn't return the first most # frequent as promised in the doc but the lowest most frequent. When this # test will fail after an update of scipy, Imputer will need to be updated # to be consistent with the new (correct) behaviour _check_statistics(X, X_true, "most_frequent", [np.nan, 2, 3, 3], -1) def test_imputation_pipeline_grid_search(): """Test imputation within a pipeline + gridsearch.""" pipeline = Pipeline([('imputer', Imputer(missing_values=0)), ('tree', tree.DecisionTreeRegressor(random_state=0))]) parameters = { 'imputer__strategy': ["mean", "median", "most_frequent"], 'imputer__axis': [0, 1] } l = 100 X = sparse_random_matrix(l, l, density=0.10) Y = sparse_random_matrix(l, 1, density=0.10).toarray() gs = grid_search.GridSearchCV(pipeline, parameters) gs.fit(X, Y) def test_imputation_pickle(): """Test for pickling imputers.""" import pickle l = 100 X = sparse_random_matrix(l, l, density=0.10) for strategy in ["mean", "median", "most_frequent"]: imputer = Imputer(missing_values=0, strategy=strategy) imputer.fit(X) imputer_pickled = pickle.loads(pickle.dumps(imputer)) assert_array_equal(imputer.transform(X.copy()), imputer_pickled.transform(X.copy()), "Fail to transform the data after pickling " "(strategy = %s)" % (strategy)) def test_imputation_copy(): """Test imputation with copy""" X_orig = sparse_random_matrix(5, 5, density=0.75, random_state=0) # copy=True, dense => copy X = X_orig.copy().toarray() imputer = Imputer(missing_values=0, strategy="mean", copy=True) Xt = imputer.fit(X).transform(X) Xt[0, 0] = -1 assert_false(np.all(X == Xt)) # copy=True, sparse csr => copy X = X_orig.copy() imputer = Imputer(missing_values=X.data[0], strategy="mean", copy=True) Xt = imputer.fit(X).transform(X) Xt.data[0] = -1 assert_false(np.all(X.data == Xt.data)) # copy=False, dense => no copy X = X_orig.copy().toarray() imputer = Imputer(missing_values=0, strategy="mean", copy=False) Xt = imputer.fit(X).transform(X) Xt[0, 0] = -1 assert_true(np.all(X == Xt)) # copy=False, sparse csr, axis=1 => no copy X = X_orig.copy() imputer = Imputer(missing_values=X.data[0], strategy="mean", copy=False, axis=1) Xt = imputer.fit(X).transform(X) Xt.data[0] = -1 assert_true(np.all(X.data == Xt.data)) # copy=False, sparse csc, axis=0 => no copy X = X_orig.copy().tocsc() imputer = Imputer(missing_values=X.data[0], strategy="mean", copy=False, axis=0) Xt = imputer.fit(X).transform(X) Xt.data[0] = -1 assert_true(np.all(X.data == Xt.data)) # copy=False, sparse csr, axis=0 => copy X = X_orig.copy() imputer = Imputer(missing_values=X.data[0], strategy="mean", copy=False, axis=0) Xt = imputer.fit(X).transform(X) Xt.data[0] = -1 assert_false(np.all(X.data == Xt.data)) # copy=False, sparse csc, axis=1 => copy X = X_orig.copy().tocsc() imputer = Imputer(missing_values=X.data[0], strategy="mean", copy=False, axis=1) Xt = imputer.fit(X).transform(X) Xt.data[0] = -1 assert_false(np.all(X.data == Xt.data)) # copy=False, sparse csr, axis=1, missing_values=0 => copy X = X_orig.copy() imputer = Imputer(missing_values=0, strategy="mean", copy=False, axis=1) Xt = imputer.fit(X).transform(X) assert_false(sparse.issparse(Xt)) # Note: If X is sparse and if missing_values=0, then a (dense) copy of X is # made, even if copy=False.
bsd-3-clause
Sorsly/subtle
google-cloud-sdk/platform/gsutil/third_party/apitools/run_pylint.py
3
8173
# # Copyright 2015 Google 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. """Custom script to run PyLint on apitools codebase. "Inspired" by the similar script in gcloud-python. This runs pylint as a script via subprocess in two different subprocesses. The first lints the production/library code using the default rc file (PRODUCTION_RC). The second lints the demo/test code using an rc file (TEST_RC) which allows more style violations (hence it has a reduced number of style checks). """ import ConfigParser import copy import os import subprocess import sys IGNORED_DIRECTORIES = [ 'apitools/gen/testdata', 'samples/storage_sample/storage', 'venv', ] IGNORED_FILES = [ 'ez_setup.py', 'run_pylint.py', 'setup.py', ] PRODUCTION_RC = 'default.pylintrc' TEST_RC = 'reduced.pylintrc' TEST_DISABLED_MESSAGES = [ 'exec-used', 'invalid-name', 'missing-docstring', 'protected-access', ] TEST_RC_ADDITIONS = { 'MESSAGES CONTROL': { 'disable': ',\n'.join(TEST_DISABLED_MESSAGES), }, } def read_config(filename): """Reads pylintrc config onto native ConfigParser object.""" config = ConfigParser.ConfigParser() with open(filename, 'r') as file_obj: config.readfp(file_obj) return config def make_test_rc(base_rc_filename, additions_dict, target_filename): """Combines a base rc and test additions into single file.""" main_cfg = read_config(base_rc_filename) # Create fresh config for test, which must extend production. test_cfg = ConfigParser.ConfigParser() test_cfg._sections = copy.deepcopy(main_cfg._sections) for section, opts in additions_dict.items(): curr_section = test_cfg._sections.setdefault( section, test_cfg._dict()) for opt, opt_val in opts.items(): curr_val = curr_section.get(opt) if curr_val is None: raise KeyError('Expected to be adding to existing option.') curr_section[opt] = '%s\n%s' % (curr_val, opt_val) with open(target_filename, 'w') as file_obj: test_cfg.write(file_obj) def valid_filename(filename): """Checks if a file is a Python file and is not ignored.""" for directory in IGNORED_DIRECTORIES: if filename.startswith(directory): return False return (filename.endswith('.py') and filename not in IGNORED_FILES) def is_production_filename(filename): """Checks if the file contains production code. :rtype: boolean :returns: Boolean indicating production status. """ return not ('demo' in filename or 'test' in filename or filename.startswith('regression')) def get_files_for_linting(allow_limited=True, diff_base=None): """Gets a list of files in the repository. By default, returns all files via ``git ls-files``. However, in some cases uses a specific commit or branch (a so-called diff base) to compare against for changed files. (This requires ``allow_limited=True``.) To speed up linting on Travis pull requests against master, we manually set the diff base to origin/master. We don't do this on non-pull requests since origin/master will be equivalent to the currently checked out code. One could potentially use ${TRAVIS_COMMIT_RANGE} to find a diff base but this value is not dependable. :type allow_limited: boolean :param allow_limited: Boolean indicating if a reduced set of files can be used. :rtype: pair :returns: Tuple of the diff base using the the list of filenames to be linted. """ if os.getenv('TRAVIS') == 'true': # In travis, don't default to master. diff_base = None if (os.getenv('TRAVIS_BRANCH') == 'master' and os.getenv('TRAVIS_PULL_REQUEST') != 'false'): # In the case of a pull request into master, we want to # diff against HEAD in master. diff_base = 'origin/master' if diff_base is not None and allow_limited: result = subprocess.check_output(['git', 'diff', '--name-only', diff_base]) print 'Using files changed relative to %s:' % (diff_base,) print '-' * 60 print result.rstrip('\n') # Don't print trailing newlines. print '-' * 60 else: print 'Diff base not specified, listing all files in repository.' result = subprocess.check_output(['git', 'ls-files']) return result.rstrip('\n').split('\n'), diff_base def get_python_files(all_files=None, diff_base=None): """Gets a list of all Python files in the repository that need linting. Relies on :func:`get_files_for_linting()` to determine which files should be considered. NOTE: This requires ``git`` to be installed and requires that this is run within the ``git`` repository. :type all_files: list or ``NoneType`` :param all_files: Optional list of files to be linted. :rtype: tuple :returns: A tuple containing two lists and a boolean. The first list contains all production files, the next all test/demo files and the boolean indicates if a restricted fileset was used. """ using_restricted = False if all_files is None: all_files, diff_base = get_files_for_linting(diff_base=diff_base) using_restricted = diff_base is not None library_files = [] non_library_files = [] for filename in all_files: if valid_filename(filename): if is_production_filename(filename): library_files.append(filename) else: non_library_files.append(filename) return library_files, non_library_files, using_restricted def lint_fileset(filenames, rcfile, description): """Lints a group of files using a given rcfile.""" # Only lint filenames that exist. For example, 'git diff --name-only' # could spit out deleted / renamed files. Another alternative could # be to use 'git diff --name-status' and filter out files with a # status of 'D'. filenames = [filename for filename in filenames if os.path.exists(filename)] if filenames: rc_flag = '--rcfile=%s' % (rcfile,) pylint_shell_command = ['pylint', rc_flag] + filenames status_code = subprocess.call(pylint_shell_command) if status_code != 0: error_message = ('Pylint failed on %s with ' 'status %d.' % (description, status_code)) print >> sys.stderr, error_message sys.exit(status_code) else: print 'Skipping %s, no files to lint.' % (description,) def main(argv): """Script entry point. Lints both sets of files.""" diff_base = argv[1] if len(argv) > 1 else None make_test_rc(PRODUCTION_RC, TEST_RC_ADDITIONS, TEST_RC) library_files, non_library_files, using_restricted = get_python_files( diff_base=diff_base) try: lint_fileset(library_files, PRODUCTION_RC, 'library code') lint_fileset(non_library_files, TEST_RC, 'test and demo code') except SystemExit: if not using_restricted: raise message = 'Restricted lint failed, expanding to full fileset.' print >> sys.stderr, message all_files, _ = get_files_for_linting(allow_limited=False) library_files, non_library_files, _ = get_python_files( all_files=all_files) lint_fileset(library_files, PRODUCTION_RC, 'library code') lint_fileset(non_library_files, TEST_RC, 'test and demo code') if __name__ == '__main__': main(sys.argv)
mit
alexmogavero/home-assistant
homeassistant/components/device_tracker/mikrotik.py
4
5539
""" Support for Mikrotik routers as device tracker. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/device_tracker.mikrotik/ """ import logging import threading from datetime import timedelta import voluptuous as vol import homeassistant.helpers.config_validation as cv from homeassistant.components.device_tracker import ( DOMAIN, PLATFORM_SCHEMA, DeviceScanner) from homeassistant.const import (CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_PORT) from homeassistant.util import Throttle REQUIREMENTS = ['librouteros==1.0.2'] # Return cached results if last scan was less then this time ago. MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10) MTK_DEFAULT_API_PORT = '8728' _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_HOST): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_PORT, default=MTK_DEFAULT_API_PORT): cv.port }) def get_scanner(hass, config): """Validate the configuration and return MTikScanner.""" scanner = MikrotikScanner(config[DOMAIN]) return scanner if scanner.success_init else None class MikrotikScanner(DeviceScanner): """This class queries a Mikrotik router.""" def __init__(self, config): """Initialize the scanner.""" self.last_results = {} self.host = config[CONF_HOST] self.port = config[CONF_PORT] self.username = config[CONF_USERNAME] self.password = config[CONF_PASSWORD] self.lock = threading.Lock() self.connected = False self.success_init = False self.client = None self.wireless_exist = None self.success_init = self.connect_to_device() if self.success_init: _LOGGER.info( "Start polling Mikrotik (%s) router...", self.host ) self._update_info() else: _LOGGER.error( "Connection to Mikrotik (%s) failed", self.host ) def connect_to_device(self): """Connect to Mikrotik method.""" # pylint: disable=import-error import librouteros try: self.client = librouteros.connect( self.host, self.username, self.password, port=int(self.port) ) routerboard_info = self.client(cmd='/system/routerboard/getall') if routerboard_info: _LOGGER.info("Connected to Mikrotik %s with IP %s", routerboard_info[0].get('model', 'Router'), self.host) self.connected = True self.wireless_exist = self.client( cmd='/interface/wireless/getall' ) if not self.wireless_exist: _LOGGER.info( 'Mikrotik %s: Wireless adapters not found. Try to ' 'use DHCP lease table as presence tracker source. ' 'Please decrease lease time as much as possible.', self.host ) except (librouteros.exceptions.TrapError, librouteros.exceptions.ConnectionError) as api_error: _LOGGER.error("Connection error: %s", api_error) return self.connected def scan_devices(self): """Scan for new devices and return a list with found device MACs.""" self._update_info() return [device for device in self.last_results] def get_device_name(self, mac): """Return the name of the given device or None if we don't know.""" with self.lock: return self.last_results.get(mac) @Throttle(MIN_TIME_BETWEEN_SCANS) def _update_info(self): """Retrieve latest information from the Mikrotik box.""" with self.lock: if self.wireless_exist: devices_tracker = 'wireless' else: devices_tracker = 'ip' _LOGGER.info( "Loading %s devices from Mikrotik (%s) ...", devices_tracker, self.host ) device_names = self.client(cmd='/ip/dhcp-server/lease/getall') if self.wireless_exist: devices = self.client( cmd='/interface/wireless/registration-table/getall' ) else: devices = device_names if device_names is None and devices is None: return False mac_names = {device.get('mac-address'): device.get('host-name') for device in device_names if device.get('mac-address')} if self.wireless_exist: self.last_results = { device.get('mac-address'): mac_names.get(device.get('mac-address')) for device in devices } else: self.last_results = { device.get('mac-address'): mac_names.get(device.get('mac-address')) for device in device_names if device.get('active-address') } return True
apache-2.0
jkenn99/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/common/checkout/diff_parser_unittest.py
124
8145
# Copyright (C) 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. import cStringIO as StringIO import unittest2 as unittest import diff_parser import re from webkitpy.common.checkout.diff_test_data import DIFF_TEST_DATA class DiffParserTest(unittest.TestCase): maxDiff = None def test_diff_parser(self, parser = None): if not parser: parser = diff_parser.DiffParser(DIFF_TEST_DATA.splitlines()) self.assertEqual(3, len(parser.files)) self.assertTrue('WebCore/rendering/style/StyleFlexibleBoxData.h' in parser.files) diff = parser.files['WebCore/rendering/style/StyleFlexibleBoxData.h'] self.assertEqual(7, len(diff.lines)) # The first two unchaged lines. self.assertEqual((47, 47), diff.lines[0][0:2]) self.assertEqual('', diff.lines[0][2]) self.assertEqual((48, 48), diff.lines[1][0:2]) self.assertEqual(' unsigned align : 3; // EBoxAlignment', diff.lines[1][2]) # The deleted line self.assertEqual((50, 0), diff.lines[3][0:2]) self.assertEqual(' unsigned orient: 1; // EBoxOrient', diff.lines[3][2]) # The first file looks OK. Let's check the next, more complicated file. self.assertTrue('WebCore/rendering/style/StyleRareInheritedData.cpp' in parser.files) diff = parser.files['WebCore/rendering/style/StyleRareInheritedData.cpp'] # There are 3 chunks. self.assertEqual(7 + 7 + 9, len(diff.lines)) # Around an added line. self.assertEqual((60, 61), diff.lines[9][0:2]) self.assertEqual((0, 62), diff.lines[10][0:2]) self.assertEqual((61, 63), diff.lines[11][0:2]) # Look through the last chunk, which contains both add's and delete's. self.assertEqual((81, 83), diff.lines[14][0:2]) self.assertEqual((82, 84), diff.lines[15][0:2]) self.assertEqual((83, 85), diff.lines[16][0:2]) self.assertEqual((84, 0), diff.lines[17][0:2]) self.assertEqual((0, 86), diff.lines[18][0:2]) self.assertEqual((0, 87), diff.lines[19][0:2]) self.assertEqual((85, 88), diff.lines[20][0:2]) self.assertEqual((86, 89), diff.lines[21][0:2]) self.assertEqual((87, 90), diff.lines[22][0:2]) # Check if a newly added file is correctly handled. diff = parser.files['LayoutTests/platform/mac/fast/flexbox/box-orient-button-expected.checksum'] self.assertEqual(1, len(diff.lines)) self.assertEqual((0, 1), diff.lines[0][0:2]) def test_diff_converter(self): comment_lines = [ "Hey guys,\n", "\n", "See my awesome patch below!\n", "\n", " - Cool Hacker\n", "\n", ] revision_lines = [ "Subversion Revision 289799\n", ] svn_diff_lines = [ "Index: Tools/Scripts/webkitpy/common/checkout/diff_parser.py\n", "===================================================================\n", "--- Tools/Scripts/webkitpy/common/checkout/diff_parser.py\n", "+++ Tools/Scripts/webkitpy/common/checkout/diff_parser.py\n", "@@ -59,6 +59,7 @@ def git_diff_to_svn_diff(line):\n", ] self.assertEqual(diff_parser.get_diff_converter(svn_diff_lines), diff_parser.svn_diff_to_svn_diff) self.assertEqual(diff_parser.get_diff_converter(comment_lines + svn_diff_lines), diff_parser.svn_diff_to_svn_diff) self.assertEqual(diff_parser.get_diff_converter(revision_lines + svn_diff_lines), diff_parser.svn_diff_to_svn_diff) git_diff_lines = [ "diff --git a/Tools/Scripts/webkitpy/common/checkout/diff_parser.py b/Tools/Scripts/webkitpy/common/checkout/diff_parser.py\n", "index 3c5b45b..0197ead 100644\n", "--- a/Tools/Scripts/webkitpy/common/checkout/diff_parser.py\n", "+++ b/Tools/Scripts/webkitpy/common/checkout/diff_parser.py\n", "@@ -59,6 +59,7 @@ def git_diff_to_svn_diff(line):\n", ] self.assertEqual(diff_parser.get_diff_converter(git_diff_lines), diff_parser.git_diff_to_svn_diff) self.assertEqual(diff_parser.get_diff_converter(comment_lines + git_diff_lines), diff_parser.git_diff_to_svn_diff) self.assertEqual(diff_parser.get_diff_converter(revision_lines + git_diff_lines), diff_parser.git_diff_to_svn_diff) def test_git_mnemonicprefix(self): p = re.compile(r' ([a|b])/') prefixes = [ { 'a' : 'i', 'b' : 'w' }, # git-diff (compares the (i)ndex and the (w)ork tree) { 'a' : 'c', 'b' : 'w' }, # git-diff HEAD (compares a (c)ommit and the (w)ork tree) { 'a' : 'c', 'b' : 'i' }, # git diff --cached (compares a (c)ommit and the (i)ndex) { 'a' : 'o', 'b' : 'w' }, # git-diff HEAD:file1 file2 (compares an (o)bject and a (w)ork tree entity) { 'a' : '1', 'b' : '2' }, # git diff --no-index a b (compares two non-git things (1) and (2)) ] for prefix in prefixes: patch = p.sub(lambda x: " %s/" % prefix[x.group(1)], DIFF_TEST_DATA) self.test_diff_parser(diff_parser.DiffParser(patch.splitlines())) def test_git_diff_to_svn_diff(self): output = """\ Index: Tools/Scripts/webkitpy/common/checkout/diff_parser.py =================================================================== --- Tools/Scripts/webkitpy/common/checkout/diff_parser.py +++ Tools/Scripts/webkitpy/common/checkout/diff_parser.py @@ -59,6 +59,7 @@ def git_diff_to_svn_diff(line): A B C +D E F """ inputfmt = StringIO.StringIO("""\ diff --git a/Tools/Scripts/webkitpy/common/checkout/diff_parser.py b/Tools/Scripts/webkitpy/common/checkout/diff_parser.py index 2ed552c4555db72df16b212547f2c125ae301a04..72870482000c0dba64ce4300ed782c03ee79b74f 100644 --- a/Tools/Scripts/webkitpy/common/checkout/diff_parser.py +++ b/Tools/Scripts/webkitpy/common/checkout/diff_parser.py @@ -59,6 +59,7 @@ def git_diff_to_svn_diff(line): A B C +D E F """) shortfmt = StringIO.StringIO("""\ diff --git a/Tools/Scripts/webkitpy/common/checkout/diff_parser.py b/Tools/Scripts/webkitpy/common/checkout/diff_parser.py index b48b162..f300960 100644 --- a/Tools/Scripts/webkitpy/common/checkout/diff_parser.py +++ b/Tools/Scripts/webkitpy/common/checkout/diff_parser.py @@ -59,6 +59,7 @@ def git_diff_to_svn_diff(line): A B C +D E F """) self.assertMultiLineEqual(output, ''.join(diff_parser.git_diff_to_svn_diff(x) for x in shortfmt.readlines())) self.assertMultiLineEqual(output, ''.join(diff_parser.git_diff_to_svn_diff(x) for x in inputfmt.readlines()))
bsd-3-clause
SamStudio8/scikit-bio
skbio/sequence/tests/test_sequence.py
2
106092
# ---------------------------------------------------------------------------- # Copyright (c) 2013--, scikit-bio development team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with this software. # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function import six from six.moves import zip_longest import copy import re from types import GeneratorType from collections import Counter, defaultdict, Hashable from unittest import TestCase, main import numpy as np import numpy.testing as npt import pandas as pd from skbio import Sequence from skbio.util import assert_data_frame_almost_equal from skbio.sequence._sequence import (_single_index_to_slice, _is_single_index, _as_slice_if_single_index) class SequenceSubclass(Sequence): """Used for testing purposes.""" pass class TestSequence(TestCase): def setUp(self): self.lowercase_seq = Sequence('AAAAaaaa', lowercase='key') self.sequence_kinds = frozenset([ str, Sequence, lambda s: np.fromstring(s, dtype='|S1'), lambda s: np.fromstring(s, dtype=np.uint8)]) def empty_generator(): raise StopIteration() yield self.getitem_empty_indices = [ [], (), {}, empty_generator(), # ndarray of implicit float dtype np.array([]), np.array([], dtype=int)] def test_init_default_parameters(self): seq = Sequence('.ABC123xyz-') npt.assert_equal(seq.values, np.array('.ABC123xyz-', dtype='c')) self.assertEqual('.ABC123xyz-', str(seq)) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(11))) def test_init_nondefault_parameters(self): seq = Sequence('.ABC123xyz-', metadata={'id': 'foo', 'description': 'bar baz'}, positional_metadata={'quality': range(11)}) npt.assert_equal(seq.values, np.array('.ABC123xyz-', dtype='c')) self.assertEqual('.ABC123xyz-', str(seq)) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, {'id': 'foo', 'description': 'bar baz'}) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'quality': range(11)}, index=np.arange(11))) def test_init_handles_missing_metadata_efficiently(self): seq = Sequence('ACGT') # metadata attributes should be None and not initialized to a "missing" # representation self.assertIsNone(seq._metadata) self.assertIsNone(seq._positional_metadata) # initializing from an existing Sequence object should handle metadata # attributes efficiently on both objects new_seq = Sequence(seq) self.assertIsNone(seq._metadata) self.assertIsNone(seq._positional_metadata) self.assertIsNone(new_seq._metadata) self.assertIsNone(new_seq._positional_metadata) self.assertFalse(seq.has_metadata()) self.assertFalse(seq.has_positional_metadata()) self.assertFalse(new_seq.has_metadata()) self.assertFalse(new_seq.has_positional_metadata()) def test_init_empty_sequence(self): # Test constructing an empty sequence using each supported input type. for s in (b'', # bytes u'', # unicode np.array('', dtype='c'), # char vector np.fromstring('', dtype=np.uint8), # byte vec Sequence('')): # another Sequence object seq = Sequence(s) self.assertIsInstance(seq.values, np.ndarray) self.assertEqual(seq.values.dtype, '|S1') self.assertEqual(seq.values.shape, (0, )) npt.assert_equal(seq.values, np.array('', dtype='c')) self.assertEqual(str(seq), '') self.assertEqual(len(seq), 0) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(0))) def test_init_single_character_sequence(self): for s in (b'A', u'A', np.array('A', dtype='c'), np.fromstring('A', dtype=np.uint8), Sequence('A')): seq = Sequence(s) self.assertIsInstance(seq.values, np.ndarray) self.assertEqual(seq.values.dtype, '|S1') self.assertEqual(seq.values.shape, (1,)) npt.assert_equal(seq.values, np.array('A', dtype='c')) self.assertEqual(str(seq), 'A') self.assertEqual(len(seq), 1) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(1))) def test_init_multiple_character_sequence(self): for s in (b'.ABC\t123 xyz-', u'.ABC\t123 xyz-', np.array('.ABC\t123 xyz-', dtype='c'), np.fromstring('.ABC\t123 xyz-', dtype=np.uint8), Sequence('.ABC\t123 xyz-')): seq = Sequence(s) self.assertIsInstance(seq.values, np.ndarray) self.assertEqual(seq.values.dtype, '|S1') self.assertEqual(seq.values.shape, (14,)) npt.assert_equal(seq.values, np.array('.ABC\t123 xyz-', dtype='c')) self.assertEqual(str(seq), '.ABC\t123 xyz-') self.assertEqual(len(seq), 14) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(14))) def test_init_from_sequence_object(self): # We're testing this in its simplest form in other tests. This test # exercises more complicated cases of building a sequence from another # sequence. # just the sequence, no other metadata seq = Sequence('ACGT') self.assertEqual(Sequence(seq), seq) # sequence with metadata should have everything propagated seq = Sequence('ACGT', metadata={'id': 'foo', 'description': 'bar baz'}, positional_metadata={'quality': range(4)}) self.assertEqual(Sequence(seq), seq) # should be able to override metadata self.assertEqual( Sequence(seq, metadata={'id': 'abc', 'description': '123'}, positional_metadata={'quality': [42] * 4}), Sequence('ACGT', metadata={'id': 'abc', 'description': '123'}, positional_metadata={'quality': [42] * 4})) # subclasses work too seq = SequenceSubclass('ACGT', metadata={'id': 'foo', 'description': 'bar baz'}, positional_metadata={'quality': range(4)}) self.assertEqual( Sequence(seq), Sequence('ACGT', metadata={'id': 'foo', 'description': 'bar baz'}, positional_metadata={'quality': range(4)})) def test_init_from_contiguous_sequence_bytes_view(self): bytes = np.array([65, 42, 66, 42, 65], dtype=np.uint8) view = bytes[:3] seq = Sequence(view) # sequence should be what we'd expect self.assertEqual(seq, Sequence('A*B')) # we shouldn't own the memory because no copy should have been made self.assertFalse(seq._owns_bytes) # can't mutate view because it isn't writeable anymore with self.assertRaises(ValueError): view[1] = 100 # sequence shouldn't have changed self.assertEqual(seq, Sequence('A*B')) # mutate bytes (*not* the view) bytes[0] = 99 # Sequence changed because we are only able to make the view read-only, # not its source (bytes). This is somewhat inconsistent behavior that # is (to the best of our knowledge) outside our control. self.assertEqual(seq, Sequence('c*B')) def test_init_from_noncontiguous_sequence_bytes_view(self): bytes = np.array([65, 42, 66, 42, 65], dtype=np.uint8) view = bytes[::2] seq = Sequence(view) # sequence should be what we'd expect self.assertEqual(seq, Sequence('ABA')) # we should own the memory because a copy should have been made self.assertTrue(seq._owns_bytes) # mutate bytes and its view bytes[0] = 99 view[1] = 100 # sequence shouldn't have changed self.assertEqual(seq, Sequence('ABA')) def test_init_no_copy_of_sequence(self): bytes = np.array([65, 66, 65], dtype=np.uint8) seq = Sequence(bytes) # should share the same memory self.assertIs(seq._bytes, bytes) # shouldn't be able to mutate the Sequence object's internals by # mutating the shared memory with self.assertRaises(ValueError): bytes[1] = 42 def test_init_empty_metadata(self): for empty in None, {}: seq = Sequence('', metadata=empty) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) def test_init_empty_metadata_key(self): seq = Sequence('', metadata={'': ''}) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, {'': ''}) def test_init_empty_metadata_item(self): seq = Sequence('', metadata={'foo': ''}) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, {'foo': ''}) def test_init_single_character_metadata_item(self): seq = Sequence('', metadata={'foo': 'z'}) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, {'foo': 'z'}) def test_init_multiple_character_metadata_item(self): seq = Sequence('', metadata={'foo': '\nabc\tdef G123'}) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, {'foo': '\nabc\tdef G123'}) def test_init_metadata_multiple_keys(self): seq = Sequence('', metadata={'foo': 'abc', 42: {'nested': 'metadata'}}) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, {'foo': 'abc', 42: {'nested': 'metadata'}}) def test_init_empty_positional_metadata(self): # empty seq with missing/empty positional metadata for empty in None, {}, pd.DataFrame(): seq = Sequence('', positional_metadata=empty) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(0))) # non-empty seq with missing positional metadata seq = Sequence('xyz', positional_metadata=None) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(3))) def test_init_empty_positional_metadata_item(self): for item in ([], (), np.array([])): seq = Sequence('', positional_metadata={'foo': item}) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': item}, index=np.arange(0))) def test_init_single_positional_metadata_item(self): for item in ([2], (2, ), np.array([2])): seq = Sequence('G', positional_metadata={'foo': item}) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': item}, index=np.arange(1))) def test_init_multiple_positional_metadata_item(self): for item in ([0, 42, 42, 1, 0, 8, 100, 0, 0], (0, 42, 42, 1, 0, 8, 100, 0, 0), np.array([0, 42, 42, 1, 0, 8, 100, 0, 0])): seq = Sequence('G' * 9, positional_metadata={'foo': item}) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': item}, index=np.arange(9))) def test_init_positional_metadata_multiple_columns(self): seq = Sequence('^' * 5, positional_metadata={'foo': np.arange(5), 'bar': np.arange(5)[::-1]}) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': np.arange(5), 'bar': np.arange(5)[::-1]}, index=np.arange(5))) def test_init_positional_metadata_with_custom_index(self): df = pd.DataFrame({'foo': np.arange(5), 'bar': np.arange(5)[::-1]}, index=['a', 'b', 'c', 'd', 'e']) seq = Sequence('^' * 5, positional_metadata=df) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': np.arange(5), 'bar': np.arange(5)[::-1]}, index=np.arange(5))) def test_init_invalid_sequence(self): # invalid dtype (numpy.ndarray input) with self.assertRaises(TypeError): # int64 Sequence(np.array([1, 2, 3])) with self.assertRaises(TypeError): # |S21 Sequence(np.array([1, "23", 3])) with self.assertRaises(TypeError): # object Sequence(np.array([1, {}, ()])) # invalid input type (non-numpy.ndarray input) with six.assertRaisesRegex(self, TypeError, 'tuple'): Sequence(('a', 'b', 'c')) with six.assertRaisesRegex(self, TypeError, 'list'): Sequence(['a', 'b', 'c']) with six.assertRaisesRegex(self, TypeError, 'set'): Sequence({'a', 'b', 'c'}) with six.assertRaisesRegex(self, TypeError, 'dict'): Sequence({'a': 42, 'b': 43, 'c': 44}) with six.assertRaisesRegex(self, TypeError, 'int'): Sequence(42) with six.assertRaisesRegex(self, TypeError, 'float'): Sequence(4.2) with six.assertRaisesRegex(self, TypeError, 'int64'): Sequence(np.int_(50)) with six.assertRaisesRegex(self, TypeError, 'float64'): Sequence(np.float_(50)) with six.assertRaisesRegex(self, TypeError, 'Foo'): class Foo(object): pass Sequence(Foo()) # out of ASCII range with self.assertRaises(UnicodeEncodeError): Sequence(u'abc\u1F30') def test_init_invalid_metadata(self): for md in (0, 'a', ('f', 'o', 'o'), np.array([]), pd.DataFrame()): with six.assertRaisesRegex(self, TypeError, 'metadata must be a dict'): Sequence('abc', metadata=md) def test_init_invalid_positional_metadata(self): # not consumable by Pandas with six.assertRaisesRegex(self, TypeError, 'Positional metadata invalid. Must be ' 'consumable by pd.DataFrame. ' 'Original pandas error message: '): Sequence('ACGT', positional_metadata=2) # 0 elements with six.assertRaisesRegex(self, ValueError, '\(0\).*\(4\)'): Sequence('ACGT', positional_metadata=[]) # not enough elements with six.assertRaisesRegex(self, ValueError, '\(3\).*\(4\)'): Sequence('ACGT', positional_metadata=[2, 3, 4]) # too many elements with six.assertRaisesRegex(self, ValueError, '\(5\).*\(4\)'): Sequence('ACGT', positional_metadata=[2, 3, 4, 5, 6]) # Series not enough rows with six.assertRaisesRegex(self, ValueError, '\(3\).*\(4\)'): Sequence('ACGT', positional_metadata=pd.Series(range(3))) # Series too many rows with six.assertRaisesRegex(self, ValueError, '\(5\).*\(4\)'): Sequence('ACGT', positional_metadata=pd.Series(range(5))) # DataFrame not enough rows with six.assertRaisesRegex(self, ValueError, '\(3\).*\(4\)'): Sequence('ACGT', positional_metadata=pd.DataFrame({'quality': range(3)})) # DataFrame too many rows with six.assertRaisesRegex(self, ValueError, '\(5\).*\(4\)'): Sequence('ACGT', positional_metadata=pd.DataFrame({'quality': range(5)})) def test_values_property(self): # Property tests are only concerned with testing the interface # provided by the property: that it can be accessed, can't be # reassigned or mutated in place, and that the correct type is # returned. More extensive testing of border cases (e.g., different # sequence lengths or input types, odd characters, etc.) are performed # in Sequence.__init__ tests. seq = Sequence('ACGT') # should get back a numpy.ndarray of '|S1' dtype self.assertIsInstance(seq.values, np.ndarray) self.assertEqual(seq.values.dtype, '|S1') npt.assert_equal(seq.values, np.array('ACGT', dtype='c')) # test that we can't mutate the property with self.assertRaises(ValueError): seq.values[1] = 'A' # test that we can't set the property with self.assertRaises(AttributeError): seq.values = np.array("GGGG", dtype='c') def test_metadata_property_getter(self): md = {'foo': 'bar'} seq = Sequence('', metadata=md) self.assertIsInstance(seq.metadata, dict) self.assertEqual(seq.metadata, md) self.assertIsNot(seq.metadata, md) # update existing key seq.metadata['foo'] = 'baz' self.assertEqual(seq.metadata, {'foo': 'baz'}) # add new key seq.metadata['foo2'] = 'bar2' self.assertEqual(seq.metadata, {'foo': 'baz', 'foo2': 'bar2'}) def test_metadata_property_getter_missing(self): seq = Sequence('ACGT') self.assertIsNone(seq._metadata) self.assertEqual(seq.metadata, {}) self.assertIsNotNone(seq._metadata) def test_metadata_property_setter(self): md = {'foo': 'bar'} seq = Sequence('', metadata=md) self.assertEqual(seq.metadata, md) self.assertIsNot(seq.metadata, md) new_md = {'bar': 'baz', 42: 42} seq.metadata = new_md self.assertEqual(seq.metadata, new_md) self.assertIsNot(seq.metadata, new_md) seq.metadata = {} self.assertEqual(seq.metadata, {}) self.assertFalse(seq.has_metadata()) def test_metadata_property_setter_invalid_type(self): seq = Sequence('abc', metadata={123: 456}) for md in (None, 0, 'a', ('f', 'o', 'o'), np.array([]), pd.DataFrame()): with six.assertRaisesRegex(self, TypeError, 'metadata must be a dict'): seq.metadata = md # object should still be usable and its original metadata shouldn't # have changed self.assertEqual(seq.metadata, {123: 456}) def test_metadata_property_deleter(self): md = {'foo': 'bar'} seq = Sequence('CAT', metadata=md) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, md) self.assertIsNot(seq.metadata, md) del seq.metadata self.assertIsNone(seq._metadata) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) # test deleting again del seq.metadata self.assertIsNone(seq._metadata) self.assertFalse(seq.has_metadata()) self.assertEqual(seq.metadata, {}) # test deleting missing metadata immediately after instantiation seq = Sequence('ACGT') self.assertIsNone(seq._metadata) del seq.metadata self.assertIsNone(seq._metadata) def test_metadata_property_shallow_copy(self): md = {'key1': 'val1', 'key2': 'val2', 'key3': [1, 2]} seq = Sequence('CAT', metadata=md) self.assertTrue(seq.has_metadata()) self.assertEqual(seq.metadata, md) self.assertIsNot(seq.metadata, md) # updates to keys seq.metadata['key1'] = 'new val' self.assertEqual(seq.metadata, {'key1': 'new val', 'key2': 'val2', 'key3': [1, 2]}) # original metadata untouched self.assertEqual(md, {'key1': 'val1', 'key2': 'val2', 'key3': [1, 2]}) # updates to mutable value (by reference) seq.metadata['key3'].append(3) self.assertEqual( seq.metadata, {'key1': 'new val', 'key2': 'val2', 'key3': [1, 2, 3]}) # original metadata changed because we didn't deep copy self.assertEqual( md, {'key1': 'val1', 'key2': 'val2', 'key3': [1, 2, 3]}) def test_positional_metadata_property_getter(self): md = pd.DataFrame({'foo': [22, 22, 0]}) seq = Sequence('ACA', positional_metadata=md) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame({'foo': [22, 22, 0]})) self.assertIsNot(seq.positional_metadata, md) # update existing column seq.positional_metadata['foo'] = [42, 42, 43] assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame({'foo': [42, 42, 43]})) # add new column seq.positional_metadata['foo2'] = [True, False, True] assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': [42, 42, 43], 'foo2': [True, False, True]})) def test_positional_metadata_property_getter_missing(self): seq = Sequence('ACGT') self.assertIsNone(seq._positional_metadata) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame(index=np.arange(4))) self.assertIsNotNone(seq._positional_metadata) def test_positional_metadata_property_setter(self): md = pd.DataFrame({'foo': [22, 22, 0]}) seq = Sequence('ACA', positional_metadata=md) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame({'foo': [22, 22, 0]})) self.assertIsNot(seq.positional_metadata, md) new_md = pd.DataFrame({'bar': np.arange(3)}, index=['a', 'b', 'c']) seq.positional_metadata = new_md assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'bar': np.arange(3)}, index=np.arange(3))) self.assertIsNot(seq.positional_metadata, new_md) seq.positional_metadata = pd.DataFrame(index=np.arange(3)) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(3))) self.assertFalse(seq.has_positional_metadata()) def test_positional_metadata_property_setter_invalid_type(self): # More extensive tests for invalid input are on Sequence.__init__ tests seq = Sequence('abc', positional_metadata={'foo': [1, 2, 42]}) # not consumable by Pandas with six.assertRaisesRegex(self, TypeError, 'Positional metadata invalid. Must be ' 'consumable by pd.DataFrame. ' 'Original pandas error message: '): seq.positional_metadata = 2 # object should still be usable and its original metadata shouldn't # have changed assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame({'foo': [1, 2, 42]})) # wrong length with six.assertRaisesRegex(self, ValueError, '\(2\).*\(3\)'): seq.positional_metadata = {'foo': [1, 2]} assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame({'foo': [1, 2, 42]})) # None isn't valid when using setter (differs from constructor) with six.assertRaisesRegex(self, ValueError, '\(0\).*\(3\)'): seq.positional_metadata = None assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame({'foo': [1, 2, 42]})) def test_positional_metadata_property_deleter(self): md = pd.DataFrame({'foo': [22, 22, 0]}) seq = Sequence('ACA', positional_metadata=md) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame({'foo': [22, 22, 0]})) self.assertIsNot(seq.positional_metadata, md) del seq.positional_metadata self.assertIsNone(seq._positional_metadata) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(3))) # test deleting again del seq.positional_metadata self.assertIsNone(seq._positional_metadata) self.assertFalse(seq.has_positional_metadata()) assert_data_frame_almost_equal(seq.positional_metadata, pd.DataFrame(index=np.arange(3))) # test deleting missing positional metadata immediately after # instantiation seq = Sequence('ACGT') self.assertIsNone(seq._positional_metadata) del seq.positional_metadata self.assertIsNone(seq._positional_metadata) def test_positional_metadata_property_shallow_copy(self): # define metadata as a DataFrame because this has the potential to have # its underlying data shared md = pd.DataFrame({'foo': [22, 22, 0]}, index=['a', 'b', 'c']) seq = Sequence('ACA', positional_metadata=md) self.assertTrue(seq.has_positional_metadata()) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': [22, 22, 0]}, index=np.arange(3))) self.assertIsNot(seq.positional_metadata, md) # original metadata untouched orig_md = pd.DataFrame({'foo': [22, 22, 0]}, index=['a', 'b', 'c']) assert_data_frame_almost_equal(md, orig_md) # change values of column (using same dtype) seq.positional_metadata['foo'] = [42, 42, 42] assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': [42, 42, 42]}, index=np.arange(3))) # original metadata untouched assert_data_frame_almost_equal(md, orig_md) # change single value of underlying data seq.positional_metadata.values[0][0] = 10 assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'foo': [10, 42, 42]}, index=np.arange(3))) # original metadata untouched assert_data_frame_almost_equal(md, orig_md) # create column of object dtype -- these aren't deep copied md = pd.DataFrame({'obj': [[], [], []]}, index=['a', 'b', 'c']) seq = Sequence('ACA', positional_metadata=md) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'obj': [[], [], []]}, index=np.arange(3))) # mutate list seq.positional_metadata['obj'][0].append(42) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'obj': [[42], [], []]}, index=np.arange(3))) # original metadata changed because we didn't do a full deep copy assert_data_frame_almost_equal( md, pd.DataFrame({'obj': [[42], [], []]}, index=['a', 'b', 'c'])) def test_positional_metadata_property_set_column_series(self): seq_text = 'ACGTACGT' l = len(seq_text) seq = Sequence(seq_text, positional_metadata={'foo': range(l)}) seq.positional_metadata['bar'] = pd.Series(range(l-3)) # pandas.Series will be padded with NaN if too short npt.assert_equal(seq.positional_metadata['bar'], np.array(list(range(l-3)) + [np.NaN]*3)) seq.positional_metadata['baz'] = pd.Series(range(l+3)) # pandas.Series will be truncated if too long npt.assert_equal(seq.positional_metadata['baz'], np.array(range(l))) def test_positional_metadata_property_set_column_array(self): seq_text = 'ACGTACGT' l = len(seq_text) seq = Sequence(seq_text, positional_metadata={'foo': range(l)}) # array-like objects will fail if wrong size for array_like in (np.array(range(l-1)), range(l-1), np.array(range(l+1)), range(l+1)): with six.assertRaisesRegex(self, ValueError, "Length of values does not match " "length of index"): seq.positional_metadata['bar'] = array_like def test_eq_and_ne(self): seq_a = Sequence("A") seq_b = Sequence("B") self.assertTrue(seq_a == seq_a) self.assertTrue(Sequence("a") == Sequence("a")) self.assertTrue(Sequence("a", metadata={'id': 'b'}) == Sequence("a", metadata={'id': 'b'})) self.assertTrue(Sequence("a", metadata={'id': 'b', 'description': 'c'}) == Sequence("a", metadata={'id': 'b', 'description': 'c'})) self.assertTrue(Sequence("a", metadata={'id': 'b', 'description': 'c'}, positional_metadata={'quality': [1]}) == Sequence("a", metadata={'id': 'b', 'description': 'c'}, positional_metadata={'quality': [1]})) self.assertTrue(seq_a != seq_b) self.assertTrue(SequenceSubclass("a") != Sequence("a")) self.assertTrue(Sequence("a") != Sequence("b")) self.assertTrue(Sequence("a") != Sequence("a", metadata={'id': 'b'})) self.assertTrue(Sequence("a", metadata={'id': 'c'}) != Sequence("a", metadata={'id': 'c', 'description': 't'})) self.assertTrue(Sequence("a", positional_metadata={'quality': [1]}) != Sequence("a")) self.assertTrue(Sequence("a", positional_metadata={'quality': [1]}) != Sequence("a", positional_metadata={'quality': [2]})) self.assertTrue(Sequence("c", positional_metadata={'quality': [3]}) != Sequence("b", positional_metadata={'quality': [3]})) self.assertTrue(Sequence("a", metadata={'id': 'b'}) != Sequence("c", metadata={'id': 'b'})) def test_eq_sequences_without_metadata_compare_equal(self): self.assertTrue(Sequence('') == Sequence('')) self.assertTrue(Sequence('z') == Sequence('z')) self.assertTrue( Sequence('ACGT') == Sequence('ACGT')) def test_eq_sequences_with_metadata_compare_equal(self): seq1 = Sequence('ACGT', metadata={'id': 'foo', 'desc': 'abc'}, positional_metadata={'qual': [1, 2, 3, 4]}) seq2 = Sequence('ACGT', metadata={'id': 'foo', 'desc': 'abc'}, positional_metadata={'qual': [1, 2, 3, 4]}) self.assertTrue(seq1 == seq2) # order shouldn't matter self.assertTrue(seq2 == seq1) def test_eq_sequences_from_different_sources_compare_equal(self): # sequences that have the same data but are constructed from different # types of data should compare equal seq1 = Sequence('ACGT', metadata={'id': 'foo', 'desc': 'abc'}, positional_metadata={'quality': (1, 2, 3, 4)}) seq2 = Sequence(np.array([65, 67, 71, 84], dtype=np.uint8), metadata={'id': 'foo', 'desc': 'abc'}, positional_metadata={'quality': np.array([1, 2, 3, 4])}) self.assertTrue(seq1 == seq2) def test_eq_type_mismatch(self): seq1 = Sequence('ACGT') seq2 = SequenceSubclass('ACGT') self.assertFalse(seq1 == seq2) def test_eq_metadata_mismatch(self): # both provided seq1 = Sequence('ACGT', metadata={'id': 'foo'}) seq2 = Sequence('ACGT', metadata={'id': 'bar'}) self.assertFalse(seq1 == seq2) # one provided seq1 = Sequence('ACGT', metadata={'id': 'foo'}) seq2 = Sequence('ACGT') self.assertFalse(seq1 == seq2) def test_eq_positional_metadata_mismatch(self): # both provided seq1 = Sequence('ACGT', positional_metadata={'quality': [1, 2, 3, 4]}) seq2 = Sequence('ACGT', positional_metadata={'quality': [1, 2, 3, 5]}) self.assertFalse(seq1 == seq2) # one provided seq1 = Sequence('ACGT', positional_metadata={'quality': [1, 2, 3, 4]}) seq2 = Sequence('ACGT') self.assertFalse(seq1 == seq2) def test_eq_sequence_mismatch(self): seq1 = Sequence('ACGT') seq2 = Sequence('TGCA') self.assertFalse(seq1 == seq2) def test_eq_handles_missing_metadata_efficiently(self): seq1 = Sequence('ACGT') seq2 = Sequence('ACGT') self.assertTrue(seq1 == seq2) # metadata attributes should be None and not initialized to a "missing" # representation self.assertIsNone(seq1._metadata) self.assertIsNone(seq1._positional_metadata) self.assertIsNone(seq2._metadata) self.assertIsNone(seq2._positional_metadata) def test_getitem_gives_new_sequence(self): seq = Sequence("Sequence string !1@2#3?.,") self.assertFalse(seq is seq[:]) def test_getitem_with_int_has_positional_metadata(self): s = "Sequence string !1@2#3?.," length = len(s) seq = Sequence(s, metadata={'id': 'id', 'description': 'dsc'}, positional_metadata={'quality': np.arange(length)}) eseq = Sequence("S", {'id': 'id', 'description': 'dsc'}, positional_metadata={'quality': np.array([0])}) self.assertEqual(seq[0], eseq) eseq = Sequence(",", metadata={'id': 'id', 'description': 'dsc'}, positional_metadata={'quality': np.array([len(seq) - 1])}) self.assertEqual(seq[len(seq) - 1], eseq) eseq = Sequence("t", metadata={'id': 'id', 'description': 'dsc'}, positional_metadata={'quality': [10]}) self.assertEqual(seq[10], eseq) def test_single_index_to_slice(self): a = [1, 2, 3, 4] self.assertEqual(slice(0, 1), _single_index_to_slice(0)) self.assertEqual([1], a[_single_index_to_slice(0)]) self.assertEqual(slice(-1, None), _single_index_to_slice(-1)) self.assertEqual([4], a[_single_index_to_slice(-1)]) def test_is_single_index(self): self.assertTrue(_is_single_index(0)) self.assertFalse(_is_single_index(True)) self.assertFalse(_is_single_index(bool())) self.assertFalse(_is_single_index('a')) def test_as_slice_if_single_index(self): self.assertEqual(slice(0, 1), _as_slice_if_single_index(0)) slice_obj = slice(2, 3) self.assertIs(slice_obj, _as_slice_if_single_index(slice_obj)) def test_slice_positional_metadata(self): seq = Sequence('ABCDEFGHIJ', positional_metadata={'foo': np.arange(10), 'bar': np.arange(100, 110)}) self.assertTrue(pd.DataFrame({'foo': [0], 'bar': [100]}).equals( seq._slice_positional_metadata(0))) self.assertTrue(pd.DataFrame({'foo': [0], 'bar': [100]}).equals( seq._slice_positional_metadata(slice(0, 1)))) self.assertTrue(pd.DataFrame({'foo': [0, 1], 'bar': [100, 101]}).equals( seq._slice_positional_metadata(slice(0, 2)))) self.assertTrue(pd.DataFrame( {'foo': [9], 'bar': [109]}, index=[9]).equals( seq._slice_positional_metadata(9))) def test_getitem_with_int_no_positional_metadata(self): seq = Sequence("Sequence string !1@2#3?.,", metadata={'id': 'id2', 'description': 'no_qual'}) eseq = Sequence("t", metadata={'id': 'id2', 'description': 'no_qual'}) self.assertEqual(seq[10], eseq) def test_getitem_with_slice_has_positional_metadata(self): s = "0123456789abcdef" length = len(s) seq = Sequence(s, metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': np.arange(length)}) eseq = Sequence("012", metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': np.arange(3)}) self.assertEqual(seq[0:3], eseq) self.assertEqual(seq[:3], eseq) self.assertEqual(seq[:3:1], eseq) eseq = Sequence("def", metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': [13, 14, 15]}) self.assertEqual(seq[-3:], eseq) self.assertEqual(seq[-3::1], eseq) eseq = Sequence("02468ace", metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': [0, 2, 4, 6, 8, 10, 12, 14]}) self.assertEqual(seq[0:length:2], eseq) self.assertEqual(seq[::2], eseq) eseq = Sequence(s[::-1], metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': np.arange(length)[::-1]}) self.assertEqual(seq[length::-1], eseq) self.assertEqual(seq[::-1], eseq) eseq = Sequence('fdb97531', metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': [15, 13, 11, 9, 7, 5, 3, 1]}) self.assertEqual(seq[length::-2], eseq) self.assertEqual(seq[::-2], eseq) self.assertEqual(seq[0:500:], seq) eseq = Sequence('', metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': np.array([], dtype=np.int64)}) self.assertEqual(seq[length:0], eseq) self.assertEqual(seq[-length:0], eseq) self.assertEqual(seq[1:0], eseq) eseq = Sequence("0", metadata={'id': 'id3', 'description': 'dsc3'}, positional_metadata={'quality': [0]}) self.assertEqual(seq[0:1], eseq) self.assertEqual(seq[0:1:1], eseq) self.assertEqual(seq[-length::-1], eseq) def test_getitem_with_slice_no_positional_metadata(self): s = "0123456789abcdef" length = len(s) seq = Sequence(s, metadata={'id': 'id4', 'description': 'no_qual4'}) eseq = Sequence("02468ace", metadata={'id': 'id4', 'description': 'no_qual4'}) self.assertEqual(seq[0:length:2], eseq) self.assertEqual(seq[::2], eseq) def test_getitem_with_tuple_of_mixed_with_positional_metadata(self): s = "0123456789abcdef" length = len(s) seq = Sequence(s, metadata={'id': 'id5', 'description': 'dsc5'}, positional_metadata={'quality': np.arange(length)}) eseq = Sequence("00000", metadata={'id': 'id5', 'description': 'dsc5'}, positional_metadata={'quality': [0, 0, 0, 0, 0]}) self.assertEqual(seq[0, 0, 0, 0, 0], eseq) self.assertEqual(seq[0, 0:1, 0, 0, 0], eseq) self.assertEqual(seq[0, 0:1, 0, -length::-1, 0, 1:0], eseq) self.assertEqual(seq[0:1, 0:1, 0:1, 0:1, 0:1], eseq) self.assertEqual(seq[0:1, 0, 0, 0, 0], eseq) eseq = Sequence("0123fed9", metadata={'id': 'id5', 'description': 'dsc5'}, positional_metadata={'quality': [0, 1, 2, 3, 15, 14, 13, 9]}) self.assertEqual(seq[0, 1, 2, 3, 15, 14, 13, 9], eseq) self.assertEqual(seq[0, 1, 2, 3, :-4:-1, 9], eseq) self.assertEqual(seq[0:4, :-4:-1, 9, 1:0], eseq) self.assertEqual(seq[0:4, :-4:-1, 9:10], eseq) def test_getitem_with_tuple_of_mixed_no_positional_metadata(self): seq = Sequence("0123456789abcdef", metadata={'id': 'id6', 'description': 'no_qual6'}) eseq = Sequence("0123fed9", metadata={'id': 'id6', 'description': 'no_qual6'}) self.assertEqual(seq[0, 1, 2, 3, 15, 14, 13, 9], eseq) self.assertEqual(seq[0, 1, 2, 3, :-4:-1, 9], eseq) self.assertEqual(seq[0:4, :-4:-1, 9], eseq) self.assertEqual(seq[0:4, :-4:-1, 9:10], eseq) def test_getitem_with_iterable_of_mixed_has_positional_metadata(self): s = "0123456789abcdef" length = len(s) seq = Sequence(s, metadata={'id': 'id7', 'description': 'dsc7'}, positional_metadata={'quality': np.arange(length)}) def generator(): yield slice(0, 4) yield slice(200, 400) yield -1 yield slice(-2, -4, -1) yield 9 eseq = Sequence("0123fed9", metadata={'id': 'id7', 'description': 'dsc7'}, positional_metadata={'quality': [0, 1, 2, 3, 15, 14, 13, 9]}) self.assertEqual(seq[[0, 1, 2, 3, 15, 14, 13, 9]], eseq) self.assertEqual(seq[generator()], eseq) self.assertEqual(seq[[slice(0, 4), slice(None, -4, -1), 9]], eseq) self.assertEqual(seq[ [slice(0, 4), slice(None, -4, -1), slice(9, 10)]], eseq) def test_getitem_with_iterable_of_mixed_no_positional_metadata(self): s = "0123456789abcdef" seq = Sequence(s, metadata={'id': 'id7', 'description': 'dsc7'}) def generator(): yield slice(0, 4) yield slice(200, 400) yield slice(None, -4, -1) yield 9 eseq = Sequence("0123fed9", metadata={'id': 'id7', 'description': 'dsc7'}) self.assertEqual(seq[[0, 1, 2, 3, 15, 14, 13, 9]], eseq) self.assertEqual(seq[generator()], eseq) self.assertEqual(seq[[slice(0, 4), slice(None, -4, -1), 9]], eseq) self.assertEqual(seq[ [slice(0, 4), slice(None, -4, -1), slice(9, 10)]], eseq) def test_getitem_with_numpy_index_has_positional_metadata(self): s = "0123456789abcdef" length = len(s) seq = Sequence(s, metadata={'id': 'id9', 'description': 'dsc9'}, positional_metadata={'quality': np.arange(length)}) eseq = Sequence("0123fed9", metadata={'id': 'id9', 'description': 'dsc9'}, positional_metadata={'quality': [0, 1, 2, 3, 15, 14, 13, 9]}) self.assertEqual(seq[np.array([0, 1, 2, 3, 15, 14, 13, 9])], eseq) def test_getitem_with_numpy_index_no_positional_metadata(self): s = "0123456789abcdef" seq = Sequence(s, metadata={'id': 'id10', 'description': 'dsc10'}) eseq = Sequence("0123fed9", metadata={'id': 'id10', 'description': 'dsc10'}) self.assertEqual(seq[np.array([0, 1, 2, 3, 15, 14, 13, 9])], eseq) def test_getitem_with_empty_indices_empty_seq_no_pos_metadata(self): s = "" seq = Sequence(s, metadata={'id': 'id10', 'description': 'dsc10'}) eseq = Sequence('', metadata={'id': 'id10', 'description': 'dsc10'}) tested = 0 for index in self.getitem_empty_indices: tested += 1 self.assertEqual(seq[index], eseq) self.assertEqual(tested, 6) def test_getitem_with_empty_indices_non_empty_seq_no_pos_metadata(self): s = "0123456789abcdef" seq = Sequence(s, metadata={'id': 'id10', 'description': 'dsc10'}) eseq = Sequence('', metadata={'id': 'id10', 'description': 'dsc10'}) tested = 0 for index in self.getitem_empty_indices: tested += 1 self.assertEqual(seq[index], eseq) self.assertEqual(tested, 6) def test_getitem_with_boolean_vector_has_qual(self): s = "0123456789abcdef" length = len(s) seq = Sequence(s, metadata={'id': 'id11', 'description': 'dsc11'}, positional_metadata={'quality': np.arange(length)}) eseq = Sequence("13579bdf", metadata={'id': 'id11', 'description': 'dsc11'}, positional_metadata={'quality': [1, 3, 5, 7, 9, 11, 13, 15]}) self.assertEqual(seq[np.array([False, True] * 8)], eseq) self.assertEqual(seq[[False, True] * 8], eseq) def test_getitem_with_boolean_vector_no_positional_metadata(self): s = "0123456789abcdef" seq = Sequence(s, metadata={'id': 'id11', 'description': 'dsc11'}) eseq = Sequence("13579bdf", metadata={'id': 'id11', 'description': 'dsc11'}) self.assertEqual(seq[np.array([False, True] * 8)], eseq) def test_getitem_with_invalid(self): seq = Sequence("123456", metadata={'id': 'idm', 'description': 'description'}, positional_metadata={'quality': [1, 2, 3, 4, 5, 6]}) with self.assertRaises(IndexError): seq['not an index'] with self.assertRaises(IndexError): seq[['1', '2']] with self.assertRaises(IndexError): seq[[1, slice(1, 2), 'a']] with self.assertRaises(IndexError): seq[[1, slice(1, 2), True]] with self.assertRaises(IndexError): seq[True] with self.assertRaises(IndexError): seq[np.array([True, False])] with self.assertRaises(IndexError): seq[999] with self.assertRaises(IndexError): seq[0, 0, 999] # numpy 1.8.1 and 1.9.2 raise different error types # (ValueError, IndexError). with self.assertRaises(Exception): seq[100 * [True, False, True]] def test_getitem_handles_missing_metadata_efficiently(self): # there are two paths in __getitem__ we need to test for efficient # handling of missing metadata # path 1: mixed types seq = Sequence('ACGT') subseq = seq[1, 2:4] self.assertEqual(subseq, Sequence('CGT')) # metadata attributes should be None and not initialized to a "missing" # representation self.assertIsNone(seq._metadata) self.assertIsNone(seq._positional_metadata) self.assertIsNone(subseq._metadata) self.assertIsNone(subseq._positional_metadata) # path 2: uniform types seq = Sequence('ACGT') subseq = seq[1:3] self.assertEqual(subseq, Sequence('CG')) self.assertIsNone(seq._metadata) self.assertIsNone(seq._positional_metadata) self.assertIsNone(subseq._metadata) self.assertIsNone(subseq._positional_metadata) def test_len(self): self.assertEqual(len(Sequence("")), 0) self.assertEqual(len(Sequence("a")), 1) self.assertEqual(len(Sequence("abcdef")), 6) def test_nonzero(self): # blank self.assertFalse(Sequence("")) self.assertFalse(Sequence("", metadata={'id': 'foo'}, positional_metadata={'quality': range(0)})) # single self.assertTrue(Sequence("A")) self.assertTrue(Sequence("A", metadata={'id': 'foo'}, positional_metadata={'quality': range(1)})) # multi self.assertTrue(Sequence("ACGT")) self.assertTrue(Sequence("ACGT", metadata={'id': 'foo'}, positional_metadata={'quality': range(4)})) def test_contains(self): seq = Sequence("#@ACGT,24.13**02") tested = 0 for c in self.sequence_kinds: tested += 1 self.assertTrue(c(',24') in seq) self.assertTrue(c('*') in seq) self.assertTrue(c('') in seq) self.assertFalse(c("$") in seq) self.assertFalse(c("AGT") in seq) self.assertEqual(tested, 4) def test_contains_sequence_subclass(self): with self.assertRaises(TypeError): SequenceSubclass("A") in Sequence("AAA") self.assertTrue(SequenceSubclass("A").values in Sequence("AAA")) def test_hash(self): with self.assertRaises(TypeError): hash(Sequence("ABCDEFG")) self.assertNotIsInstance(Sequence("ABCDEFG"), Hashable) def test_iter_has_positional_metadata(self): tested = False seq = Sequence("0123456789", metadata={'id': 'a', 'desc': 'b'}, positional_metadata={'qual': np.arange(10)}) for i, s in enumerate(seq): tested = True self.assertEqual(s, Sequence(str(i), metadata={'id': 'a', 'desc': 'b'}, positional_metadata={'qual': [i]})) self.assertTrue(tested) def test_iter_no_positional_metadata(self): tested = False seq = Sequence("0123456789", metadata={'id': 'a', 'desc': 'b'}) for i, s in enumerate(seq): tested = True self.assertEqual(s, Sequence(str(i), metadata={'id': 'a', 'desc': 'b'})) self.assertTrue(tested) def test_reversed_has_positional_metadata(self): tested = False seq = Sequence("0123456789", metadata={'id': 'a', 'desc': 'b'}, positional_metadata={'qual': np.arange(10)}) for i, s in enumerate(reversed(seq)): tested = True self.assertEqual(s, Sequence(str(9 - i), metadata={'id': 'a', 'desc': 'b'}, positional_metadata={'qual': [9 - i]})) self.assertTrue(tested) def test_reversed_no_positional_metadata(self): tested = False seq = Sequence("0123456789", metadata={'id': 'a', 'desc': 'b'}) for i, s in enumerate(reversed(seq)): tested = True self.assertEqual(s, Sequence(str(9 - i), metadata={'id': 'a', 'desc': 'b'})) self.assertTrue(tested) def test_repr(self): # basic sanity checks -- more extensive testing of formatting and # special cases is performed in SequenceReprDoctests below. here we # only test that pieces of the repr are present. these tests also # exercise coverage for py2/3 since the doctests in # SequenceReprDoctests only currently run in py2. # minimal obs = repr(Sequence('')) self.assertEqual(obs.count('\n'), 4) self.assertTrue(obs.startswith('Sequence')) self.assertIn('length: 0', obs) self.assertTrue(obs.endswith('-')) # no metadata obs = repr(Sequence('ACGT')) self.assertEqual(obs.count('\n'), 5) self.assertTrue(obs.startswith('Sequence')) self.assertIn('length: 4', obs) self.assertTrue(obs.endswith('0 ACGT')) # metadata and positional metadata of mixed types obs = repr( Sequence( 'ACGT', metadata={'foo': 'bar', u'bar': 33.33, None: True, False: {}, (1, 2): 3, 'acb' * 100: "'", 10: 11}, positional_metadata={'foo': range(4), 42: ['a', 'b', [], 'c']})) self.assertEqual(obs.count('\n'), 16) self.assertTrue(obs.startswith('Sequence')) self.assertIn('None: True', obs) self.assertIn('\'foo\': \'bar\'', obs) self.assertIn('42: <dtype: object>', obs) self.assertIn('\'foo\': <dtype: int64>', obs) self.assertIn('length: 4', obs) self.assertTrue(obs.endswith('0 ACGT')) # sequence spanning > 5 lines obs = repr(Sequence('A' * 301)) self.assertEqual(obs.count('\n'), 9) self.assertTrue(obs.startswith('Sequence')) self.assertIn('length: 301', obs) self.assertIn('...', obs) self.assertTrue(obs.endswith('300 A')) def test_str(self): self.assertEqual(str(Sequence("GATTACA")), "GATTACA") self.assertEqual(str(Sequence("ACCGGTACC")), "ACCGGTACC") self.assertEqual(str(Sequence("GREG")), "GREG") self.assertEqual( str(Sequence("ABC", positional_metadata={'quality': [1, 2, 3]})), "ABC") self.assertIs(type(str(Sequence("A"))), str) def test_to_default_behavior(self): # minimal sequence, sequence with all optional attributes present, and # a subclass of Sequence for seq in (Sequence('ACGT'), Sequence('ACGT', metadata={'id': 'foo', 'desc': 'bar'}, positional_metadata={'quality': range(4)}), SequenceSubclass('ACGU', metadata={'id': 'rna seq'})): to = seq._to() self.assertEqual(seq, to) self.assertIsNot(seq, to) def test_to_update_single_attribute(self): seq = Sequence('HE..--..LLO', metadata={'id': 'hello', 'description': 'gapped hello'}, positional_metadata={'quality': range(11)}) to = seq._to(metadata={'id': 'new id'}) self.assertIsNot(seq, to) self.assertNotEqual(seq, to) self.assertEqual( to, Sequence('HE..--..LLO', metadata={'id': 'new id'}, positional_metadata={'quality': range(11)})) # metadata shouldn't have changed on the original sequence self.assertEqual(seq.metadata, {'id': 'hello', 'description': 'gapped hello'}) def test_to_update_multiple_attributes(self): seq = Sequence('HE..--..LLO', metadata={'id': 'hello', 'description': 'gapped hello'}, positional_metadata={'quality': range(11)}) to = seq._to(metadata={'id': 'new id', 'description': 'new desc'}, positional_metadata={'quality': range(20, 25)}, sequence='ACGTA') self.assertIsNot(seq, to) self.assertNotEqual(seq, to) # attributes should be what we specified in the _to call... self.assertEqual(to.metadata['id'], 'new id') npt.assert_array_equal(to.positional_metadata['quality'], np.array([20, 21, 22, 23, 24])) npt.assert_array_equal(to.values, np.array('ACGTA', dtype='c')) self.assertEqual(to.metadata['description'], 'new desc') # ...and shouldn't have changed on the original sequence self.assertEqual(seq.metadata['id'], 'hello') npt.assert_array_equal(seq.positional_metadata['quality'], range(11)) npt.assert_array_equal(seq.values, np.array('HE..--..LLO', dtype='c')) self.assertEqual(seq.metadata['description'], 'gapped hello') def test_to_invalid_kwargs(self): seq = Sequence('ACCGGTACC', metadata={'id': "test-seq", 'desc': "A test sequence"}) with self.assertRaises(TypeError): seq._to(metadata={'id': 'bar'}, unrecognized_kwarg='baz') def test_count(self): def construct_char_array(s): return np.fromstring(s, dtype='|S1') def construct_uint8_array(s): return np.fromstring(s, dtype=np.uint8) seq = Sequence("1234567899876555") tested = 0 for c in self.sequence_kinds: tested += 1 self.assertEqual(seq.count(c('4')), 1) self.assertEqual(seq.count(c('8')), 2) self.assertEqual(seq.count(c('5')), 4) self.assertEqual(seq.count(c('555')), 1) self.assertEqual(seq.count(c('555'), 0, 4), 0) self.assertEqual(seq.count(c('555'), start=0, end=4), 0) self.assertEqual(seq.count(c('5'), start=10), 3) self.assertEqual(seq.count(c('5'), end=10), 1) with self.assertRaises(ValueError): seq.count(c('')) self.assertEqual(tested, 4) def test_count_on_subclass(self): with self.assertRaises(TypeError) as cm: Sequence("abcd").count(SequenceSubclass("a")) self.assertIn("Sequence", str(cm.exception)) self.assertIn("SequenceSubclass", str(cm.exception)) def test_lowercase_mungeable_key(self): # NOTE: This test relies on Sequence._munge_to_index_array working # properly. If the internal implementation of the lowercase method # changes to no longer use _munge_to_index_array, this test may need # to be updated to cover cases currently covered by # _munge_to_index_array self.assertEqual('AAAAaaaa', self.lowercase_seq.lowercase('key')) def test_lowercase_array_key(self): # NOTE: This test relies on Sequence._munge_to_index_array working # properly. If the internal implementation of the lowercase method # changes to no longer use _munge_to_index_array, this test may need # to be updated to cover cases currently covered by # _munge_to_index_array self.assertEqual('aaAAaaaa', self.lowercase_seq.lowercase( np.array([True, True, False, False, True, True, True, True]))) self.assertEqual('AaAAaAAA', self.lowercase_seq.lowercase([1, 4])) def test_distance(self): tested = 0 for constructor in self.sequence_kinds: tested += 1 seq1 = Sequence("abcdef") seq2 = constructor("12bcef") self.assertIsInstance(seq1.distance(seq1), float) self.assertEqual(seq1.distance(seq2), 2.0/3.0) self.assertEqual(tested, 4) def test_distance_arbitrary_function(self): def metric(x, y): return len(x) ** 2 + len(y) ** 2 seq1 = Sequence("12345678") seq2 = Sequence("1234") result = seq1.distance(seq2, metric=metric) self.assertIsInstance(result, float) self.assertEqual(result, 80.0) def test_distance_default_metric(self): seq1 = Sequence("abcdef") seq2 = Sequence("12bcef") seq_wrong = Sequence("abcdefghijklmnop") self.assertIsInstance(seq1.distance(seq1), float) self.assertEqual(seq1.distance(seq1), 0.0) self.assertEqual(seq1.distance(seq2), 2.0/3.0) with self.assertRaises(ValueError): seq1.distance(seq_wrong) with self.assertRaises(ValueError): seq_wrong.distance(seq1) def test_distance_on_subclass(self): seq1 = Sequence("abcdef") seq2 = SequenceSubclass("12bcef") with self.assertRaises(TypeError): seq1.distance(seq2) def test_matches(self): tested = 0 for constructor in self.sequence_kinds: tested += 1 seq1 = Sequence("AACCEEGG") seq2 = constructor("ABCDEFGH") expected = np.array([True, False] * 4) npt.assert_equal(seq1.matches(seq2), expected) self.assertEqual(tested, 4) def test_matches_on_subclass(self): seq1 = Sequence("AACCEEGG") seq2 = SequenceSubclass("ABCDEFGH") with self.assertRaises(TypeError): seq1.matches(seq2) def test_matches_unequal_length(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("TOOLONGTOCOMPARE") with self.assertRaises(ValueError): seq1.matches(seq2) def test_mismatches(self): tested = 0 for constructor in self.sequence_kinds: tested += 1 seq1 = Sequence("AACCEEGG") seq2 = constructor("ABCDEFGH") expected = np.array([False, True] * 4) npt.assert_equal(seq1.mismatches(seq2), expected) self.assertEqual(tested, 4) def test_mismatches_on_subclass(self): seq1 = Sequence("AACCEEGG") seq2 = SequenceSubclass("ABCDEFGH") with self.assertRaises(TypeError): seq1.mismatches(seq2) def test_mismatches_unequal_length(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("TOOLONGTOCOMPARE") with self.assertRaises(ValueError): seq1.mismatches(seq2) def test_mismatch_frequency(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("ABCDEFGH") seq3 = Sequence("TTTTTTTT") self.assertIs(type(seq1.mismatch_frequency(seq1)), int) self.assertEqual(seq1.mismatch_frequency(seq1), 0) self.assertEqual(seq1.mismatch_frequency(seq2), 4) self.assertEqual(seq1.mismatch_frequency(seq3), 8) def test_mismatch_frequency_relative(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("ABCDEFGH") seq3 = Sequence("TTTTTTTT") self.assertIs(type(seq1.mismatch_frequency(seq1, relative=True)), float) self.assertEqual(seq1.mismatch_frequency(seq1, relative=True), 0.0) self.assertEqual(seq1.mismatch_frequency(seq2, relative=True), 0.5) self.assertEqual(seq1.mismatch_frequency(seq3, relative=True), 1.0) def test_mismatch_frequency_unequal_length(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("TOOLONGTOCOMPARE") with self.assertRaises(ValueError): seq1.mismatch_frequency(seq2) def test_mismatch_frequence_on_subclass(self): seq1 = Sequence("AACCEEGG") seq2 = SequenceSubclass("ABCDEFGH") with self.assertRaises(TypeError): seq1.mismatch_frequency(seq2) def test_match_frequency(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("ABCDEFGH") seq3 = Sequence("TTTTTTTT") self.assertIs(type(seq1.match_frequency(seq1)), int) self.assertEqual(seq1.match_frequency(seq1), 8) self.assertEqual(seq1.match_frequency(seq2), 4) self.assertEqual(seq1.match_frequency(seq3), 0) def test_match_frequency_relative(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("ABCDEFGH") seq3 = Sequence("TTTTTTTT") self.assertIs(type(seq1.match_frequency(seq1, relative=True)), float) self.assertEqual(seq1.match_frequency(seq1, relative=True), 1.0) self.assertEqual(seq1.match_frequency(seq2, relative=True), 0.5) self.assertEqual(seq1.match_frequency(seq3, relative=True), 0.0) def test_match_frequency_unequal_length(self): seq1 = Sequence("AACCEEGG") seq2 = Sequence("TOOLONGTOCOMPARE") with self.assertRaises(ValueError): seq1.match_frequency(seq2) def test_match_frequency_on_subclass(self): seq1 = Sequence("AACCEEGG") seq2 = SequenceSubclass("ABCDEFGH") with self.assertRaises(TypeError): seq1.match_frequency(seq2) def test_index(self): tested = 0 for c in self.sequence_kinds: tested += 1 seq = Sequence("ABCDEFG@@ABCDFOO") self.assertEqual(seq.index(c("A")), 0) self.assertEqual(seq.index(c("@")), 7) self.assertEqual(seq.index(c("@@")), 7) with self.assertRaises(ValueError): seq.index("A", start=1, end=5) self.assertEqual(tested, 4) def test_index_on_subclass(self): with self.assertRaises(TypeError): Sequence("ABCDEFG").index(SequenceSubclass("A")) self.assertEqual( SequenceSubclass("ABCDEFG").index(SequenceSubclass("A")), 0) def _compare_kmers_results(self, observed, expected): for obs, exp in zip_longest(observed, expected, fillvalue=None): self.assertEqual(obs, exp) def test_iter_kmers(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) expected = [ Sequence('G', positional_metadata={'quality': [0]}), Sequence('A', positional_metadata={'quality': [1]}), Sequence('T', positional_metadata={'quality': [2]}), Sequence('T', positional_metadata={'quality': [3]}), Sequence('A', positional_metadata={'quality': [4]}), Sequence('C', positional_metadata={'quality': [5]}), Sequence('A', positional_metadata={'quality': [6]}) ] self._compare_kmers_results( seq.iter_kmers(1, overlap=False), expected) expected = [ Sequence('GA', positional_metadata={'quality': [0, 1]}), Sequence('TT', positional_metadata={'quality': [2, 3]}), Sequence('AC', positional_metadata={'quality': [4, 5]}) ] self._compare_kmers_results( seq.iter_kmers(2, overlap=False), expected) expected = [ Sequence('GAT', positional_metadata={'quality': [0, 1, 2]}), Sequence('TAC', positional_metadata={'quality': [3, 4, 5]}) ] self._compare_kmers_results( seq.iter_kmers(3, overlap=False), expected) expected = [ Sequence('GATTACA', positional_metadata={'quality': [0, 1, 2, 3, 4, 5, 6]}) ] self._compare_kmers_results( seq.iter_kmers(7, overlap=False), expected) expected = [] self._compare_kmers_results( seq.iter_kmers(8, overlap=False), expected) self.assertIs(type(seq.iter_kmers(1)), GeneratorType) def test_iter_kmers_no_positional_metadata(self): seq = Sequence('GATTACA') expected = [ Sequence('G'), Sequence('A'), Sequence('T'), Sequence('T'), Sequence('A'), Sequence('C'), Sequence('A') ] self._compare_kmers_results( seq.iter_kmers(1, overlap=False), expected) expected = [ Sequence('GA'), Sequence('TT'), Sequence('AC') ] self._compare_kmers_results( seq.iter_kmers(2, overlap=False), expected) expected = [ Sequence('GAT'), Sequence('TAC') ] self._compare_kmers_results( seq.iter_kmers(3, overlap=False), expected) expected = [ Sequence('GATTACA') ] self._compare_kmers_results( seq.iter_kmers(7, overlap=False), expected) expected = [] self._compare_kmers_results( seq.iter_kmers(8, overlap=False), expected) self.assertIs(type(seq.iter_kmers(1)), GeneratorType) def test_iter_kmers_with_overlap(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) expected = [ Sequence('G', positional_metadata={'quality': [0]}), Sequence('A', positional_metadata={'quality': [1]}), Sequence('T', positional_metadata={'quality': [2]}), Sequence('T', positional_metadata={'quality': [3]}), Sequence('A', positional_metadata={'quality': [4]}), Sequence('C', positional_metadata={'quality': [5]}), Sequence('A', positional_metadata={'quality': [6]}) ] self._compare_kmers_results( seq.iter_kmers(1, overlap=True), expected) expected = [ Sequence('GA', positional_metadata={'quality': [0, 1]}), Sequence('AT', positional_metadata={'quality': [1, 2]}), Sequence('TT', positional_metadata={'quality': [2, 3]}), Sequence('TA', positional_metadata={'quality': [3, 4]}), Sequence('AC', positional_metadata={'quality': [4, 5]}), Sequence('CA', positional_metadata={'quality': [5, 6]}) ] self._compare_kmers_results( seq.iter_kmers(2, overlap=True), expected) expected = [ Sequence('GAT', positional_metadata={'quality': [0, 1, 2]}), Sequence('ATT', positional_metadata={'quality': [1, 2, 3]}), Sequence('TTA', positional_metadata={'quality': [2, 3, 4]}), Sequence('TAC', positional_metadata={'quality': [3, 4, 5]}), Sequence('ACA', positional_metadata={'quality': [4, 5, 6]}) ] self._compare_kmers_results( seq.iter_kmers(3, overlap=True), expected) expected = [ Sequence('GATTACA', positional_metadata={'quality': [0, 1, 2, 3, 4, 5, 6]}) ] self._compare_kmers_results( seq.iter_kmers(7, overlap=True), expected) expected = [] self._compare_kmers_results( seq.iter_kmers(8, overlap=True), expected) self.assertIs(type(seq.iter_kmers(1)), GeneratorType) def test_iter_kmers_with_overlap_no_positional_metadata(self): seq = Sequence('GATTACA') expected = [ Sequence('G'), Sequence('A'), Sequence('T'), Sequence('T'), Sequence('A'), Sequence('C'), Sequence('A') ] self._compare_kmers_results( seq.iter_kmers(1, overlap=True), expected) expected = [ Sequence('GA'), Sequence('AT'), Sequence('TT'), Sequence('TA'), Sequence('AC'), Sequence('CA') ] self._compare_kmers_results( seq.iter_kmers(2, overlap=True), expected) expected = [ Sequence('GAT'), Sequence('ATT'), Sequence('TTA'), Sequence('TAC'), Sequence('ACA') ] self._compare_kmers_results( seq.iter_kmers(3, overlap=True), expected) expected = [ Sequence('GATTACA') ] self._compare_kmers_results( seq.iter_kmers(7, overlap=True), expected) expected = [] self._compare_kmers_results( seq.iter_kmers(8, overlap=True), expected) self.assertIs(type(seq.iter_kmers(1)), GeneratorType) def test_iter_kmers_invalid_k(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) with self.assertRaises(ValueError): list(seq.iter_kmers(0)) with self.assertRaises(ValueError): list(seq.iter_kmers(-42)) def test_iter_kmers_invalid_k_no_positional_metadata(self): seq = Sequence('GATTACA') with self.assertRaises(ValueError): list(seq.iter_kmers(0)) with self.assertRaises(ValueError): list(seq.iter_kmers(-42)) def test_iter_kmers_different_sequences(self): seq = Sequence('HE..--..LLO', metadata={'id': 'hello', 'desc': 'gapped hello'}, positional_metadata={'quality': range(11)}) expected = [ Sequence('HE.', positional_metadata={'quality': [0, 1, 2]}, metadata={'id': 'hello', 'desc': 'gapped hello'}), Sequence('.--', positional_metadata={'quality': [3, 4, 5]}, metadata={'id': 'hello', 'desc': 'gapped hello'}), Sequence('..L', positional_metadata={'quality': [6, 7, 8]}, metadata={'id': 'hello', 'desc': 'gapped hello'}) ] self._compare_kmers_results(seq.iter_kmers(3, overlap=False), expected) def test_iter_kmers_different_sequences_no_positional_metadata(self): seq = Sequence('HE..--..LLO', metadata={'id': 'hello', 'desc': 'gapped hello'}) expected = [ Sequence('HE.', metadata={'id': 'hello', 'desc': 'gapped hello'}), Sequence('.--', metadata={'id': 'hello', 'desc': 'gapped hello'}), Sequence('..L', metadata={'id': 'hello', 'desc': 'gapped hello'}) ] self._compare_kmers_results(seq.iter_kmers(3, overlap=False), expected) def test_kmer_frequencies(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) # overlap = True expected = Counter('GATTACA') self.assertEqual(seq.kmer_frequencies(1, overlap=True), expected) expected = Counter(['GAT', 'ATT', 'TTA', 'TAC', 'ACA']) self.assertEqual(seq.kmer_frequencies(3, overlap=True), expected) expected = Counter([]) self.assertEqual(seq.kmer_frequencies(8, overlap=True), expected) # overlap = False expected = Counter(['GAT', 'TAC']) self.assertEqual(seq.kmer_frequencies(3, overlap=False), expected) expected = Counter(['GATTACA']) self.assertEqual(seq.kmer_frequencies(7, overlap=False), expected) expected = Counter([]) self.assertEqual(seq.kmer_frequencies(8, overlap=False), expected) def test_kmer_frequencies_relative(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) # overlap = True expected = defaultdict(float) expected['A'] = 3/7. expected['C'] = 1/7. expected['G'] = 1/7. expected['T'] = 2/7. self.assertEqual(seq.kmer_frequencies(1, overlap=True, relative=True), expected) expected = defaultdict(float) expected['GAT'] = 1/5. expected['ATT'] = 1/5. expected['TTA'] = 1/5. expected['TAC'] = 1/5. expected['ACA'] = 1/5. self.assertEqual(seq.kmer_frequencies(3, overlap=True, relative=True), expected) expected = defaultdict(float) self.assertEqual(seq.kmer_frequencies(8, overlap=True, relative=True), expected) # overlap = False expected = defaultdict(float) expected['GAT'] = 1/2. expected['TAC'] = 1/2. self.assertEqual(seq.kmer_frequencies(3, overlap=False, relative=True), expected) expected = defaultdict(float) expected['GATTACA'] = 1.0 self.assertEqual(seq.kmer_frequencies(7, overlap=False, relative=True), expected) expected = defaultdict(float) self.assertEqual(seq.kmer_frequencies(8, overlap=False, relative=True), expected) def test_kmer_frequencies_floating_point_precision(self): # Test that a sequence having no variation in k-words yields a # frequency of exactly 1.0. Note that it is important to use # self.assertEqual here instead of self.assertAlmostEqual because we # want to test for exactly 1.0. A previous implementation of # Sequence.kmer_frequencies(relative=True) added (1 / num_words) for # each occurrence of a k-word to compute the frequencies (see # https://github.com/biocore/scikit-bio/issues/801). In certain cases, # this yielded a frequency slightly less than 1.0 due to roundoff # error. The test case here uses a sequence with 10 characters that are # all identical and computes k-word frequencies with k=1. This test # case exposes the roundoff error present in the previous # implementation because there are 10 k-words (which are all # identical), so 1/10 added 10 times yields a number slightly less than # 1.0. This occurs because 1/10 cannot be represented exactly as a # floating point number. seq = Sequence('AAAAAAAAAA') self.assertEqual(seq.kmer_frequencies(1, relative=True), defaultdict(float, {'A': 1.0})) def test_find_with_regex(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) pat = re.compile('(T+A)(CA)') obs = list(seq.find_with_regex(pat)) exp = [slice(2, 5), slice(5, 7)] self.assertEqual(obs, exp) self.assertIs(type(seq.find_with_regex(pat)), GeneratorType) def test_find_with_regex_string_as_input(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) pat = '(T+A)(CA)' obs = list(seq.find_with_regex(pat)) exp = [slice(2, 5), slice(5, 7)] self.assertEqual(obs, exp) self.assertIs(type(seq.find_with_regex(pat)), GeneratorType) def test_find_with_regex_no_groups(self): seq = Sequence('GATTACA', positional_metadata={'quality': range(7)}) pat = re.compile('(FOO)') self.assertEqual(list(seq.find_with_regex(pat)), []) def test_find_with_regex_ignore_no_difference(self): seq = Sequence('..ABCDEFG..') pat = "([A-Z]+)" exp = [slice(2, 9)] self.assertEqual(list(seq.find_with_regex(pat)), exp) obs = seq.find_with_regex( pat, ignore=np.array([1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1], dtype=bool)) self.assertEqual(list(obs), exp) def test_find_with_regex_ignore(self): obs = Sequence('A..A..BBAAB.A..AB..A.').find_with_regex( "(A+)", ignore=np.array([0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1], dtype=bool)) self.assertEqual(list(obs), [slice(0, 4), slice(8, 10), slice(12, 16), slice(19, 20)]) def test_find_with_regex_ignore_index_array(self): obs = Sequence('A..A..BBAAB.A..AB..A.').find_with_regex( "(A+)", ignore=np.array([1, 2, 4, 5, 11, 13, 14, 17, 18, 20])) self.assertEqual(list(obs), [slice(0, 4), slice(8, 10), slice(12, 16), slice(19, 20)]) def test_iter_contiguous_index_array(self): s = Sequence("0123456789abcdef") for c in list, tuple, np.array, pd.Series: exp = [Sequence("0123"), Sequence("89ab")] obs = s.iter_contiguous(c([0, 1, 2, 3, 8, 9, 10, 11])) self.assertEqual(list(obs), exp) def test_iter_contiguous_boolean_vector(self): s = Sequence("0123456789abcdef") for c in list, tuple, np.array, pd.Series: exp = [Sequence("0123"), Sequence("89ab")] obs = s.iter_contiguous(c(([True] * 4 + [False] * 4) * 2)) self.assertEqual(list(obs), exp) def test_iter_contiguous_iterable_slices(self): def spaced_out(): yield slice(0, 4) yield slice(8, 12) def contiguous(): yield slice(0, 4) yield slice(4, 8) yield slice(12, 16) s = Sequence("0123456789abcdef") for c in (lambda x: x, list, tuple, lambda x: np.array(tuple(x)), lambda x: pd.Series(tuple(x))): exp = [Sequence("0123"), Sequence("89ab")] obs = s.iter_contiguous(c(spaced_out())) self.assertEqual(list(obs), exp) exp = [Sequence("01234567"), Sequence("cdef")] obs = s.iter_contiguous(c(contiguous())) self.assertEqual(list(obs), exp) def test_iter_contiguous_with_max_length(self): s = Sequence("0123456789abcdef") for c in list, tuple, np.array, pd.Series: exp = [Sequence("234"), Sequence("678"), Sequence("abc")] obs = s.iter_contiguous(c([True, False, True, True] * 4), min_length=3) self.assertEqual(list(obs), exp) exp = [Sequence("0"), Sequence("234"), Sequence("678"), Sequence("abc"), Sequence("ef")] obs1 = list(s.iter_contiguous(c([True, False, True, True] * 4), min_length=1)) obs2 = list(s.iter_contiguous(c([True, False, True, True] * 4))) self.assertEqual(obs1, obs2) self.assertEqual(obs1, exp) def test_iter_contiguous_with_invert(self): def spaced_out(): yield slice(0, 4) yield slice(8, 12) def contiguous(): yield slice(0, 4) yield slice(4, 8) yield slice(12, 16) s = Sequence("0123456789abcdef") for c in (lambda x: x, list, tuple, lambda x: np.array(tuple(x)), lambda x: pd.Series(tuple(x))): exp = [Sequence("4567"), Sequence("cdef")] obs = s.iter_contiguous(c(spaced_out()), invert=True) self.assertEqual(list(obs), exp) exp = [Sequence("89ab")] obs = s.iter_contiguous(c(contiguous()), invert=True) self.assertEqual(list(obs), exp) def test_has_metadata(self): # truly missing seq = Sequence('ACGT') self.assertFalse(seq.has_metadata()) # metadata attribute should be None and not initialized to a "missing" # representation self.assertIsNone(seq._metadata) # looks empty seq = Sequence('ACGT', metadata={}) self.assertFalse(seq.has_metadata()) # metadata is present seq = Sequence('ACGT', metadata={'foo': 42}) self.assertTrue(seq.has_metadata()) def test_has_positional_metadata(self): # truly missing seq = Sequence('ACGT') self.assertFalse(seq.has_positional_metadata()) # positional metadata attribute should be None and not initialized to a # "missing" representation self.assertIsNone(seq._positional_metadata) # looks empty seq = Sequence('ACGT', positional_metadata=pd.DataFrame(index=np.arange(4))) self.assertFalse(seq.has_positional_metadata()) # positional metadata is present seq = Sequence('ACGT', positional_metadata={'foo': [1, 2, 3, 4]}) self.assertTrue(seq.has_positional_metadata()) def test_copy_without_metadata(self): # shallow vs deep copy with sequence only should be equivalent. thus, # copy.copy, copy.deepcopy, and Sequence.copy(deep=True|False) should # all be equivalent for copy_method in (lambda seq: seq.copy(deep=False), lambda seq: seq.copy(deep=True), copy.copy, copy.deepcopy): seq = Sequence('ACGT') seq_copy = copy_method(seq) self.assertEqual(seq_copy, seq) self.assertIsNot(seq_copy, seq) self.assertIsNot(seq_copy._bytes, seq._bytes) # metadata attributes should be None and not initialized to a # "missing" representation self.assertIsNone(seq._metadata) self.assertIsNone(seq._positional_metadata) self.assertIsNone(seq_copy._metadata) self.assertIsNone(seq_copy._positional_metadata) def test_copy_with_metadata_shallow(self): # copy.copy and Sequence.copy should behave identically for copy_method in lambda seq: seq.copy(), copy.copy: seq = Sequence('ACGT', metadata={'foo': [1]}, positional_metadata={'bar': [[], [], [], []], 'baz': [42, 42, 42, 42]}) seq_copy = copy_method(seq) self.assertEqual(seq_copy, seq) self.assertIsNot(seq_copy, seq) self.assertIsNot(seq_copy._bytes, seq._bytes) self.assertIsNot(seq_copy._metadata, seq._metadata) self.assertIsNot(seq_copy._positional_metadata, seq._positional_metadata) self.assertIsNot(seq_copy._positional_metadata.values, seq._positional_metadata.values) self.assertIs(seq_copy._metadata['foo'], seq._metadata['foo']) self.assertIs(seq_copy._positional_metadata.loc[0, 'bar'], seq._positional_metadata.loc[0, 'bar']) seq_copy.metadata['foo'].append(2) seq_copy.metadata['foo2'] = 42 self.assertEqual(seq_copy.metadata, {'foo': [1, 2], 'foo2': 42}) self.assertEqual(seq.metadata, {'foo': [1, 2]}) seq_copy.positional_metadata.loc[0, 'bar'].append(1) seq_copy.positional_metadata.loc[0, 'baz'] = 43 assert_data_frame_almost_equal( seq_copy.positional_metadata, pd.DataFrame({'bar': [[1], [], [], []], 'baz': [43, 42, 42, 42]})) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'bar': [[1], [], [], []], 'baz': [42, 42, 42, 42]})) def test_copy_with_metadata_deep(self): # copy.deepcopy and Sequence.copy(deep=True) should behave identically for copy_method in lambda seq: seq.copy(deep=True), copy.deepcopy: seq = Sequence('ACGT', metadata={'foo': [1]}, positional_metadata={'bar': [[], [], [], []], 'baz': [42, 42, 42, 42]}) seq_copy = copy_method(seq) self.assertEqual(seq_copy, seq) self.assertIsNot(seq_copy, seq) self.assertIsNot(seq_copy._bytes, seq._bytes) self.assertIsNot(seq_copy._metadata, seq._metadata) self.assertIsNot(seq_copy._positional_metadata, seq._positional_metadata) self.assertIsNot(seq_copy._positional_metadata.values, seq._positional_metadata.values) self.assertIsNot(seq_copy._metadata['foo'], seq._metadata['foo']) self.assertIsNot(seq_copy._positional_metadata.loc[0, 'bar'], seq._positional_metadata.loc[0, 'bar']) seq_copy.metadata['foo'].append(2) seq_copy.metadata['foo2'] = 42 self.assertEqual(seq_copy.metadata, {'foo': [1, 2], 'foo2': 42}) self.assertEqual(seq.metadata, {'foo': [1]}) seq_copy.positional_metadata.loc[0, 'bar'].append(1) seq_copy.positional_metadata.loc[0, 'baz'] = 43 assert_data_frame_almost_equal( seq_copy.positional_metadata, pd.DataFrame({'bar': [[1], [], [], []], 'baz': [43, 42, 42, 42]})) assert_data_frame_almost_equal( seq.positional_metadata, pd.DataFrame({'bar': [[], [], [], []], 'baz': [42, 42, 42, 42]})) def test_deepcopy_memo_is_respected(self): # basic test to ensure deepcopy's memo is passed through to recursive # deepcopy calls seq = Sequence('ACGT', metadata={'foo': 'bar'}) memo = {} copy.deepcopy(seq, memo) self.assertGreater(len(memo), 2) def test_munge_to_index_array_valid_index_array(self): s = Sequence('123456') for c in list, tuple, np.array, pd.Series: exp = np.array([1, 2, 3], dtype=int) obs = s._munge_to_index_array(c([1, 2, 3])) npt.assert_equal(obs, exp) exp = np.array([1, 3, 5], dtype=int) obs = s._munge_to_index_array(c([1, 3, 5])) npt.assert_equal(obs, exp) def test_munge_to_index_array_invalid_index_array(self): s = Sequence("12345678") for c in list, tuple, np.array, pd.Series: with self.assertRaises(ValueError): s._munge_to_index_array(c([3, 2, 1])) with self.assertRaises(ValueError): s._munge_to_index_array(c([5, 6, 7, 2])) with self.assertRaises(ValueError): s._munge_to_index_array(c([0, 1, 2, 1])) def test_munge_to_index_array_valid_bool_array(self): s = Sequence('123456') for c in list, tuple, np.array, pd.Series: exp = np.array([2, 3, 5], dtype=int) obs = s._munge_to_index_array( c([False, False, True, True, False, True])) npt.assert_equal(obs, exp) exp = np.array([], dtype=int) obs = s._munge_to_index_array( c([False] * 6)) npt.assert_equal(obs, exp) exp = np.arange(6) obs = s._munge_to_index_array( c([True] * 6)) npt.assert_equal(obs, exp) def test_munge_to_index_array_invalid_bool_array(self): s = Sequence('123456') for c in (list, tuple, lambda x: np.array(x, dtype=bool), lambda x: pd.Series(x, dtype=bool)): with self.assertRaises(ValueError): s._munge_to_index_array(c([])) with self.assertRaises(ValueError): s._munge_to_index_array(c([True])) with self.assertRaises(ValueError): s._munge_to_index_array(c([True] * 10)) def test_munge_to_index_array_valid_iterable(self): s = Sequence('') def slices_only(): return (slice(i, i+1) for i in range(0, 10, 2)) def mixed(): return (slice(i, i+1) if i % 2 == 0 else i for i in range(10)) def unthinkable(): for i in range(10): if i % 3 == 0: yield slice(i, i+1) elif i % 3 == 1: yield i else: yield np.array([i], dtype=int) for c in (lambda x: x, list, tuple, lambda x: np.array(tuple(x)), lambda x: pd.Series(tuple(x))): exp = np.arange(10, dtype=int) obs = s._munge_to_index_array(c(mixed())) npt.assert_equal(obs, exp) exp = np.arange(10, dtype=int) obs = s._munge_to_index_array(c(unthinkable())) npt.assert_equal(obs, exp) exp = np.arange(10, step=2, dtype=int) obs = s._munge_to_index_array(c(slices_only())) npt.assert_equal(obs, exp) def test_munge_to_index_array_invalid_iterable(self): s = Sequence('') def bad1(): yield "r" yield [1, 2, 3] def bad2(): yield 1 yield 'str' def bad3(): yield False yield True yield 2 def bad4(): yield np.array([False, True]) yield slice(2, 5) for c in (lambda x: x, list, tuple, lambda x: np.array(tuple(x)), lambda x: pd.Series(tuple(x))): with self.assertRaises(TypeError): s._munge_to_index_array(bad1()) with self.assertRaises(TypeError): s._munge_to_index_array(bad2()) with self.assertRaises(TypeError): s._munge_to_index_array(bad3()) with self.assertRaises(TypeError): s._munge_to_index_array(bad4()) def test_munge_to_index_array_valid_string(self): seq = Sequence('ACGTACGT', positional_metadata={'introns': [False, True, True, False, False, True, False, False]}) npt.assert_equal(np.array([1, 2, 5]), seq._munge_to_index_array('introns')) seq.positional_metadata['exons'] = ~seq.positional_metadata['introns'] npt.assert_equal(np.array([0, 3, 4, 6, 7]), seq._munge_to_index_array('exons')) def test_munge_to_index_array_invalid_string(self): seq_str = 'ACGT' seq = Sequence(seq_str, positional_metadata={'quality': range(len(seq_str))}) with six.assertRaisesRegex(self, ValueError, "No positional metadata associated with " "key 'introns'"): seq._munge_to_index_array('introns') with six.assertRaisesRegex(self, TypeError, "Column 'quality' in positional metadata " "does not correspond to a boolean " "vector"): seq._munge_to_index_array('quality') def test_munge_to_bytestring_return_bytes(self): seq = Sequence('') m = 'dummy_method' str_inputs = ('', 'a', 'acgt') unicode_inputs = (u'', u'a', u'acgt') byte_inputs = (b'', b'a', b'acgt') seq_inputs = (Sequence(''), Sequence('a'), Sequence('acgt')) all_inputs = str_inputs + unicode_inputs + byte_inputs + seq_inputs all_expected = [b'', b'a', b'acgt'] * 4 for input_, expected in zip(all_inputs, all_expected): observed = seq._munge_to_bytestring(input_, m) self.assertEqual(observed, expected) self.assertIs(type(observed), bytes) def test_munge_to_bytestring_unicode_out_of_ascii_range(self): seq = Sequence('') all_inputs = (u'\x80', u'abc\x80', u'\x80abc') for input_ in all_inputs: with six.assertRaisesRegex(self, UnicodeEncodeError, "'ascii' codec can't encode character" ".*in position.*: ordinal not in" " range\(128\)"): seq._munge_to_bytestring(input_, 'dummy_method') # NOTE: this must be a *separate* class for doctests only (no unit tests). nose # will not run the unit tests otherwise # # these doctests exercise the correct formatting of Sequence's repr in a # variety of situations. they are more extensive than the unit tests above # (TestSequence.test_repr) but are only currently run in py2. thus, they cannot # be relied upon for coverage (the unit tests take care of this) class SequenceReprDoctests(object): r""" >>> import pandas as pd >>> from skbio import Sequence Empty (minimal) sequence: >>> Sequence('') Sequence ------------- Stats: length: 0 ------------- Single character sequence: >>> Sequence('G') Sequence ------------- Stats: length: 1 ------------- 0 G Multicharacter sequence: >>> Sequence('ACGT') Sequence ------------- Stats: length: 4 ------------- 0 ACGT Full single line: >>> Sequence('A' * 60) Sequence ------------------------------------------------------------------- Stats: length: 60 ------------------------------------------------------------------- 0 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA Full single line with 1 character overflow: >>> Sequence('A' * 61) Sequence -------------------------------------------------------------------- Stats: length: 61 -------------------------------------------------------------------- 0 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 60 A Two full lines: >>> Sequence('T' * 120) Sequence -------------------------------------------------------------------- Stats: length: 120 -------------------------------------------------------------------- 0 TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT 60 TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT Two full lines with 1 character overflow: >>> Sequence('T' * 121) Sequence --------------------------------------------------------------------- Stats: length: 121 --------------------------------------------------------------------- 0 TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT 60 TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT TTTTTTTTTT 120 T Five full lines (maximum amount of information): >>> Sequence('A' * 300) Sequence --------------------------------------------------------------------- Stats: length: 300 --------------------------------------------------------------------- 0 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 60 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 120 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 180 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 240 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA Six lines starts "summarized" output: >>> Sequence('A' * 301) Sequence --------------------------------------------------------------------- Stats: length: 301 --------------------------------------------------------------------- 0 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 60 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA ... 240 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 300 A A naive algorithm would assume the width of the first column (noting position) based on the sequence's length alone. This can be off by one if the last position (in the last line) has a shorter width than the width calculated from the sequence's length. This test case ensures that only a single space is inserted between position 99960 and the first sequence chunk: >>> Sequence('A' * 100000) Sequence ----------------------------------------------------------------------- Stats: length: 100000 ----------------------------------------------------------------------- 0 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 60 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA ... 99900 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 99960 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA The largest sequence that can be displayed using six chunks per line: >>> Sequence('A' * 100020) Sequence ----------------------------------------------------------------------- Stats: length: 100020 ----------------------------------------------------------------------- 0 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 60 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA ... 99900 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 99960 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA A single character longer than the previous sequence causes the optimal number of chunks per line to be 5: >>> Sequence('A' * 100021) Sequence ------------------------------------------------------------- Stats: length: 100021 ------------------------------------------------------------- 0 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 50 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA ... 99950 AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA AAAAAAAAAA 100000 AAAAAAAAAA AAAAAAAAAA A Wide range of characters (locale-independent): >>> import string >>> Sequence((string.ascii_letters + string.punctuation + string.digits + ... 'a space') * 567) Sequence ----------------------------------------------------------------------- Stats: length: 57267 ----------------------------------------------------------------------- 0 abcdefghij klmnopqrst uvwxyzABCD EFGHIJKLMN OPQRSTUVWX YZ!"#$%&'( 60 )*+,-./:;< =>?@[\]^_` {|}~012345 6789a spac eabcdefghi jklmnopqrs ... 57180 opqrstuvwx yzABCDEFGH IJKLMNOPQR STUVWXYZ!" #$%&'()*+, -./:;<=>?@ 57240 [\]^_`{|}~ 0123456789 a space Supply horrendous metadata and positional metadata to exercise a variety of metadata formatting cases and rules. Sorting should be by type, then by value within each type (Python 3 doesn't allow sorting of mixed types): >>> metadata = { ... # str key, str value ... 'abc': 'some description', ... # int value ... 'foo': 42, ... # unsupported type (dict) value ... 'bar': {}, ... # int key, wrapped str (single line) ... 42: 'some words to test text wrapping and such... yada yada yada ' ... 'yada yada yada yada yada.', ... # bool key, wrapped str (multi-line) ... True: 'abc ' * 34, ... # float key, truncated str (too long) ... 42.5: 'abc ' * 200, ... # unsupported type (tuple) key, unsupported type (list) value ... ('foo', 'bar'): [1, 2, 3], ... # bytes key, single long word that wraps ... b'long word': 'abc' * 30, ... # truncated key (too long), None value ... 'too long of a key name to display in repr': None, ... # wrapped bytes value (has b'' prefix) ... 'bytes wrapped value': b'abcd' * 25, ... # float value ... 0.1: 99.9999, ... # bool value ... 43: False, ... # None key, complex value ... None: complex(-1.0, 0.0), ... # nested quotes ... 10: '"\'' ... } >>> positional_metadata = pd.DataFrame.from_items([ ... # str key, int list value ... ('foo', [1, 2, 3, 4]), ... # float key, float list value ... (42.5, [2.5, 3.0, 4.2, -0.00001]), ... # int key, object list value ... (42, [[], 4, 5, {}]), ... # truncated key (too long), bool list value ... ('abc' * 90, [True, False, False, True]), ... # None key ... (None, range(4))]) >>> Sequence('ACGT', metadata=metadata, ... positional_metadata=positional_metadata) Sequence ----------------------------------------------------------------------- Metadata: None: (-1+0j) True: 'abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc ' b'long word': 'abcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabcabca bcabcabcabcabcabcabcabcabcabcabcabcabc' 0.1: 99.9999 42.5: <class 'str'> 10: '"\'' 42: 'some words to test text wrapping and such... yada yada yada yada yada yada yada yada.' 43: False 'abc': 'some description' 'bar': <class 'dict'> 'bytes wrapped value': b'abcdabcdabcdabcdabcdabcdabcdabcdabcdabcdab cdabcdabcdabcdabcdabcdabcdabcdabcdabcdabcd abcdabcdabcdabcd' 'foo': 42 <class 'str'>: None <class 'tuple'>: <class 'list'> Positional metadata: 'foo': <dtype: int64> 42.5: <dtype: float64> 42: <dtype: object> <class 'str'>: <dtype: bool> None: <dtype: int64> Stats: length: 4 ----------------------------------------------------------------------- 0 ACGT """ pass if __name__ == "__main__": main()
bsd-3-clause
angr/angr
angr/analyses/decompiler/optimization_passes/mod_simplifier.py
1
2880
import logging from ailment import Expr from ... import AnalysesHub from .engine_base import SimplifierAILEngine, SimplifierAILState from .optimization_pass import OptimizationPass, OptimizationPassStage _l = logging.getLogger(name=__name__) class ModSimplifierAILEngine(SimplifierAILEngine): def _ail_handle_Sub(self, expr): operand_0 = self._expr(expr.operands[0]) operand_1 = self._expr(expr.operands[1]) x_0, c_0, x_1, c_1 = None, None, None, None if isinstance(operand_1, Expr.BinaryOp) \ and isinstance(operand_1.operands[1], Expr.Const) \ and operand_1.op == 'Mul': if isinstance(operand_1.operands[0], Expr.BinaryOp) \ and isinstance(operand_1.operands[0].operands[1], Expr.Const) \ and operand_1.operands[0].op in ['Div', 'DivMod']: x_0 = operand_1.operands[0].operands[0] x_1 = operand_0 c_0 = operand_1.operands[1] c_1 = operand_1.operands[0].operands[1] elif isinstance(operand_1.operands[0], Expr.Convert) \ and isinstance(operand_1.operands[0].operand, Expr.BinaryOp) \ and operand_1.operands[0].operand.op in ['Div', 'DivMod']: x_0 = operand_1.operands[0].operand.operands[0] x_1 = operand_0 c_0 = operand_1.operands[1] c_1 = operand_1.operands[0].operand.operands[1] if x_0 is not None and x_1 is not None and x_0 == x_1 and c_0.value == c_1.value: return Expr.BinaryOp(expr.idx, 'Mod', [x_0, c_0], expr.signed, **expr.tags) if (operand_0, operand_1) != (expr.operands[0], expr.operands[1]): return Expr.BinaryOp(expr.idx, 'Sub', [operand_0, operand_1], expr.signed, **expr.tags) return expr def _ail_handle_Mod(self, expr): #pylint: disable=no-self-use return expr class ModSimplifier(OptimizationPass): ARCHES = ["X86", "AMD64"] PLATFORMS = ["linux", "windows"] STAGE = OptimizationPassStage.AFTER_GLOBAL_SIMPLIFICATION def __init__(self, func, **kwargs): super().__init__(func, **kwargs) self.state = SimplifierAILState(self.project.arch) self.engine = ModSimplifierAILEngine() self.analyze() def _check(self): return True, None def _analyze(self, cache=None): for block in list(self._graph.nodes()): new_block = block old_block = None while new_block != old_block: old_block = new_block new_block = self.engine.process(state=self.state.copy(), block=old_block.copy()) _l.debug("new block: %s", new_block.statements) self._update_block(block, new_block) AnalysesHub.register_default("ModSimplifier", ModSimplifier)
bsd-2-clause
Team-Blackout/EvilZ.213.BLACKOUT_edition
tools/perf/scripts/python/check-perf-trace.py
11214
2503
# perf script event handlers, generated by perf script -g python # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # This script tests basic functionality such as flag and symbol # strings, common_xxx() calls back into perf, begin, end, unhandled # events, etc. Basically, if this script runs successfully and # displays expected results, Python scripting support should be ok. import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from Core import * from perf_trace_context import * unhandled = autodict() def trace_begin(): print "trace_begin" pass def trace_end(): print_unhandled() def irq__softirq_entry(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, vec): print_header(event_name, common_cpu, common_secs, common_nsecs, common_pid, common_comm) print_uncommon(context) print "vec=%s\n" % \ (symbol_str("irq__softirq_entry", "vec", vec)), def kmem__kmalloc(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, call_site, ptr, bytes_req, bytes_alloc, gfp_flags): print_header(event_name, common_cpu, common_secs, common_nsecs, common_pid, common_comm) print_uncommon(context) print "call_site=%u, ptr=%u, bytes_req=%u, " \ "bytes_alloc=%u, gfp_flags=%s\n" % \ (call_site, ptr, bytes_req, bytes_alloc, flag_str("kmem__kmalloc", "gfp_flags", gfp_flags)), def trace_unhandled(event_name, context, event_fields_dict): try: unhandled[event_name] += 1 except TypeError: unhandled[event_name] = 1 def print_header(event_name, cpu, secs, nsecs, pid, comm): print "%-20s %5u %05u.%09u %8u %-20s " % \ (event_name, cpu, secs, nsecs, pid, comm), # print trace fields not included in handler args def print_uncommon(context): print "common_preempt_count=%d, common_flags=%s, common_lock_depth=%d, " \ % (common_pc(context), trace_flag_str(common_flags(context)), \ common_lock_depth(context)) def print_unhandled(): keys = unhandled.keys() if not keys: return print "\nunhandled events:\n\n", print "%-40s %10s\n" % ("event", "count"), print "%-40s %10s\n" % ("----------------------------------------", \ "-----------"), for event_name in keys: print "%-40s %10d\n" % (event_name, unhandled[event_name])
gpl-2.0
WhireCrow/openwrt-mt7620
staging_dir/target-mipsel_r2_uClibc-0.9.33.2/usr/lib/python2.7/lib2to3/tests/test_pytree.py
131
17346
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Unit tests for pytree.py. NOTE: Please *don't* add doc strings to individual test methods! In verbose mode, printing of the module, class and method name is much more helpful than printing of (the first line of) the docstring, especially when debugging a test. """ from __future__ import with_statement import sys import warnings # Testing imports from . import support from lib2to3 import pytree try: sorted except NameError: def sorted(lst): l = list(lst) l.sort() return l class TestNodes(support.TestCase): """Unit tests for nodes (Base, Leaf, Node).""" if sys.version_info >= (2,6): # warnings.catch_warnings is new in 2.6. def test_deprecated_prefix_methods(self): l = pytree.Leaf(100, "foo") with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always", DeprecationWarning) self.assertEqual(l.get_prefix(), "") l.set_prefix("hi") self.assertEqual(l.prefix, "hi") self.assertEqual(len(w), 2) for warning in w: self.assertTrue(warning.category is DeprecationWarning) self.assertEqual(str(w[0].message), "get_prefix() is deprecated; " \ "use the prefix property") self.assertEqual(str(w[1].message), "set_prefix() is deprecated; " \ "use the prefix property") def test_instantiate_base(self): if __debug__: # Test that instantiating Base() raises an AssertionError self.assertRaises(AssertionError, pytree.Base) def test_leaf(self): l1 = pytree.Leaf(100, "foo") self.assertEqual(l1.type, 100) self.assertEqual(l1.value, "foo") def test_leaf_repr(self): l1 = pytree.Leaf(100, "foo") self.assertEqual(repr(l1), "Leaf(100, 'foo')") def test_leaf_str(self): l1 = pytree.Leaf(100, "foo") self.assertEqual(str(l1), "foo") l2 = pytree.Leaf(100, "foo", context=(" ", (10, 1))) self.assertEqual(str(l2), " foo") def test_leaf_str_numeric_value(self): # Make sure that the Leaf's value is stringified. Failing to # do this can cause a TypeError in certain situations. l1 = pytree.Leaf(2, 5) l1.prefix = "foo_" self.assertEqual(str(l1), "foo_5") def test_leaf_equality(self): l1 = pytree.Leaf(100, "foo") l2 = pytree.Leaf(100, "foo", context=(" ", (1, 0))) self.assertEqual(l1, l2) l3 = pytree.Leaf(101, "foo") l4 = pytree.Leaf(100, "bar") self.assertNotEqual(l1, l3) self.assertNotEqual(l1, l4) def test_leaf_prefix(self): l1 = pytree.Leaf(100, "foo") self.assertEqual(l1.prefix, "") self.assertFalse(l1.was_changed) l1.prefix = " ##\n\n" self.assertEqual(l1.prefix, " ##\n\n") self.assertTrue(l1.was_changed) def test_node(self): l1 = pytree.Leaf(100, "foo") l2 = pytree.Leaf(200, "bar") n1 = pytree.Node(1000, [l1, l2]) self.assertEqual(n1.type, 1000) self.assertEqual(n1.children, [l1, l2]) def test_node_repr(self): l1 = pytree.Leaf(100, "foo") l2 = pytree.Leaf(100, "bar", context=(" ", (1, 0))) n1 = pytree.Node(1000, [l1, l2]) self.assertEqual(repr(n1), "Node(1000, [%s, %s])" % (repr(l1), repr(l2))) def test_node_str(self): l1 = pytree.Leaf(100, "foo") l2 = pytree.Leaf(100, "bar", context=(" ", (1, 0))) n1 = pytree.Node(1000, [l1, l2]) self.assertEqual(str(n1), "foo bar") def test_node_prefix(self): l1 = pytree.Leaf(100, "foo") self.assertEqual(l1.prefix, "") n1 = pytree.Node(1000, [l1]) self.assertEqual(n1.prefix, "") n1.prefix = " " self.assertEqual(n1.prefix, " ") self.assertEqual(l1.prefix, " ") def test_get_suffix(self): l1 = pytree.Leaf(100, "foo", prefix="a") l2 = pytree.Leaf(100, "bar", prefix="b") n1 = pytree.Node(1000, [l1, l2]) self.assertEqual(l1.get_suffix(), l2.prefix) self.assertEqual(l2.get_suffix(), "") self.assertEqual(n1.get_suffix(), "") l3 = pytree.Leaf(100, "bar", prefix="c") n2 = pytree.Node(1000, [n1, l3]) self.assertEqual(n1.get_suffix(), l3.prefix) self.assertEqual(l3.get_suffix(), "") self.assertEqual(n2.get_suffix(), "") def test_node_equality(self): n1 = pytree.Node(1000, ()) n2 = pytree.Node(1000, [], context=(" ", (1, 0))) self.assertEqual(n1, n2) n3 = pytree.Node(1001, ()) self.assertNotEqual(n1, n3) def test_node_recursive_equality(self): l1 = pytree.Leaf(100, "foo") l2 = pytree.Leaf(100, "foo") n1 = pytree.Node(1000, [l1]) n2 = pytree.Node(1000, [l2]) self.assertEqual(n1, n2) l3 = pytree.Leaf(100, "bar") n3 = pytree.Node(1000, [l3]) self.assertNotEqual(n1, n3) def test_replace(self): l1 = pytree.Leaf(100, "foo") l2 = pytree.Leaf(100, "+") l3 = pytree.Leaf(100, "bar") n1 = pytree.Node(1000, [l1, l2, l3]) self.assertEqual(n1.children, [l1, l2, l3]) self.assertTrue(isinstance(n1.children, list)) self.assertFalse(n1.was_changed) l2new = pytree.Leaf(100, "-") l2.replace(l2new) self.assertEqual(n1.children, [l1, l2new, l3]) self.assertTrue(isinstance(n1.children, list)) self.assertTrue(n1.was_changed) def test_replace_with_list(self): l1 = pytree.Leaf(100, "foo") l2 = pytree.Leaf(100, "+") l3 = pytree.Leaf(100, "bar") n1 = pytree.Node(1000, [l1, l2, l3]) l2.replace([pytree.Leaf(100, "*"), pytree.Leaf(100, "*")]) self.assertEqual(str(n1), "foo**bar") self.assertTrue(isinstance(n1.children, list)) def test_leaves(self): l1 = pytree.Leaf(100, "foo") l2 = pytree.Leaf(100, "bar") l3 = pytree.Leaf(100, "fooey") n2 = pytree.Node(1000, [l1, l2]) n3 = pytree.Node(1000, [l3]) n1 = pytree.Node(1000, [n2, n3]) self.assertEqual(list(n1.leaves()), [l1, l2, l3]) def test_depth(self): l1 = pytree.Leaf(100, "foo") l2 = pytree.Leaf(100, "bar") n2 = pytree.Node(1000, [l1, l2]) n3 = pytree.Node(1000, []) n1 = pytree.Node(1000, [n2, n3]) self.assertEqual(l1.depth(), 2) self.assertEqual(n3.depth(), 1) self.assertEqual(n1.depth(), 0) def test_post_order(self): l1 = pytree.Leaf(100, "foo") l2 = pytree.Leaf(100, "bar") l3 = pytree.Leaf(100, "fooey") c1 = pytree.Node(1000, [l1, l2]) n1 = pytree.Node(1000, [c1, l3]) self.assertEqual(list(n1.post_order()), [l1, l2, c1, l3, n1]) def test_pre_order(self): l1 = pytree.Leaf(100, "foo") l2 = pytree.Leaf(100, "bar") l3 = pytree.Leaf(100, "fooey") c1 = pytree.Node(1000, [l1, l2]) n1 = pytree.Node(1000, [c1, l3]) self.assertEqual(list(n1.pre_order()), [n1, c1, l1, l2, l3]) def test_changed(self): l1 = pytree.Leaf(100, "f") self.assertFalse(l1.was_changed) l1.changed() self.assertTrue(l1.was_changed) l1 = pytree.Leaf(100, "f") n1 = pytree.Node(1000, [l1]) self.assertFalse(n1.was_changed) n1.changed() self.assertTrue(n1.was_changed) l1 = pytree.Leaf(100, "foo") l2 = pytree.Leaf(100, "+") l3 = pytree.Leaf(100, "bar") n1 = pytree.Node(1000, [l1, l2, l3]) n2 = pytree.Node(1000, [n1]) self.assertFalse(l1.was_changed) self.assertFalse(n1.was_changed) self.assertFalse(n2.was_changed) n1.changed() self.assertTrue(n1.was_changed) self.assertTrue(n2.was_changed) self.assertFalse(l1.was_changed) def test_leaf_constructor_prefix(self): for prefix in ("xyz_", ""): l1 = pytree.Leaf(100, "self", prefix=prefix) self.assertTrue(str(l1), prefix + "self") self.assertEqual(l1.prefix, prefix) def test_node_constructor_prefix(self): for prefix in ("xyz_", ""): l1 = pytree.Leaf(100, "self") l2 = pytree.Leaf(100, "foo", prefix="_") n1 = pytree.Node(1000, [l1, l2], prefix=prefix) self.assertTrue(str(n1), prefix + "self_foo") self.assertEqual(n1.prefix, prefix) self.assertEqual(l1.prefix, prefix) self.assertEqual(l2.prefix, "_") def test_remove(self): l1 = pytree.Leaf(100, "foo") l2 = pytree.Leaf(100, "foo") n1 = pytree.Node(1000, [l1, l2]) n2 = pytree.Node(1000, [n1]) self.assertEqual(n1.remove(), 0) self.assertEqual(n2.children, []) self.assertEqual(l1.parent, n1) self.assertEqual(n1.parent, None) self.assertEqual(n2.parent, None) self.assertFalse(n1.was_changed) self.assertTrue(n2.was_changed) self.assertEqual(l2.remove(), 1) self.assertEqual(l1.remove(), 0) self.assertEqual(n1.children, []) self.assertEqual(l1.parent, None) self.assertEqual(n1.parent, None) self.assertEqual(n2.parent, None) self.assertTrue(n1.was_changed) self.assertTrue(n2.was_changed) def test_remove_parentless(self): n1 = pytree.Node(1000, []) n1.remove() self.assertEqual(n1.parent, None) l1 = pytree.Leaf(100, "foo") l1.remove() self.assertEqual(l1.parent, None) def test_node_set_child(self): l1 = pytree.Leaf(100, "foo") n1 = pytree.Node(1000, [l1]) l2 = pytree.Leaf(100, "bar") n1.set_child(0, l2) self.assertEqual(l1.parent, None) self.assertEqual(l2.parent, n1) self.assertEqual(n1.children, [l2]) n2 = pytree.Node(1000, [l1]) n2.set_child(0, n1) self.assertEqual(l1.parent, None) self.assertEqual(n1.parent, n2) self.assertEqual(n2.parent, None) self.assertEqual(n2.children, [n1]) self.assertRaises(IndexError, n1.set_child, 4, l2) # I don't care what it raises, so long as it's an exception self.assertRaises(Exception, n1.set_child, 0, list) def test_node_insert_child(self): l1 = pytree.Leaf(100, "foo") n1 = pytree.Node(1000, [l1]) l2 = pytree.Leaf(100, "bar") n1.insert_child(0, l2) self.assertEqual(l2.parent, n1) self.assertEqual(n1.children, [l2, l1]) l3 = pytree.Leaf(100, "abc") n1.insert_child(2, l3) self.assertEqual(n1.children, [l2, l1, l3]) # I don't care what it raises, so long as it's an exception self.assertRaises(Exception, n1.insert_child, 0, list) def test_node_append_child(self): n1 = pytree.Node(1000, []) l1 = pytree.Leaf(100, "foo") n1.append_child(l1) self.assertEqual(l1.parent, n1) self.assertEqual(n1.children, [l1]) l2 = pytree.Leaf(100, "bar") n1.append_child(l2) self.assertEqual(l2.parent, n1) self.assertEqual(n1.children, [l1, l2]) # I don't care what it raises, so long as it's an exception self.assertRaises(Exception, n1.append_child, list) def test_node_next_sibling(self): n1 = pytree.Node(1000, []) n2 = pytree.Node(1000, []) p1 = pytree.Node(1000, [n1, n2]) self.assertTrue(n1.next_sibling is n2) self.assertEqual(n2.next_sibling, None) self.assertEqual(p1.next_sibling, None) def test_leaf_next_sibling(self): l1 = pytree.Leaf(100, "a") l2 = pytree.Leaf(100, "b") p1 = pytree.Node(1000, [l1, l2]) self.assertTrue(l1.next_sibling is l2) self.assertEqual(l2.next_sibling, None) self.assertEqual(p1.next_sibling, None) def test_node_prev_sibling(self): n1 = pytree.Node(1000, []) n2 = pytree.Node(1000, []) p1 = pytree.Node(1000, [n1, n2]) self.assertTrue(n2.prev_sibling is n1) self.assertEqual(n1.prev_sibling, None) self.assertEqual(p1.prev_sibling, None) def test_leaf_prev_sibling(self): l1 = pytree.Leaf(100, "a") l2 = pytree.Leaf(100, "b") p1 = pytree.Node(1000, [l1, l2]) self.assertTrue(l2.prev_sibling is l1) self.assertEqual(l1.prev_sibling, None) self.assertEqual(p1.prev_sibling, None) class TestPatterns(support.TestCase): """Unit tests for tree matching patterns.""" def test_basic_patterns(self): # Build a tree l1 = pytree.Leaf(100, "foo") l2 = pytree.Leaf(100, "bar") l3 = pytree.Leaf(100, "foo") n1 = pytree.Node(1000, [l1, l2]) n2 = pytree.Node(1000, [l3]) root = pytree.Node(1000, [n1, n2]) # Build a pattern matching a leaf pl = pytree.LeafPattern(100, "foo", name="pl") r = {} self.assertFalse(pl.match(root, results=r)) self.assertEqual(r, {}) self.assertFalse(pl.match(n1, results=r)) self.assertEqual(r, {}) self.assertFalse(pl.match(n2, results=r)) self.assertEqual(r, {}) self.assertTrue(pl.match(l1, results=r)) self.assertEqual(r, {"pl": l1}) r = {} self.assertFalse(pl.match(l2, results=r)) self.assertEqual(r, {}) # Build a pattern matching a node pn = pytree.NodePattern(1000, [pl], name="pn") self.assertFalse(pn.match(root, results=r)) self.assertEqual(r, {}) self.assertFalse(pn.match(n1, results=r)) self.assertEqual(r, {}) self.assertTrue(pn.match(n2, results=r)) self.assertEqual(r, {"pn": n2, "pl": l3}) r = {} self.assertFalse(pn.match(l1, results=r)) self.assertEqual(r, {}) self.assertFalse(pn.match(l2, results=r)) self.assertEqual(r, {}) def test_wildcard(self): # Build a tree for testing l1 = pytree.Leaf(100, "foo") l2 = pytree.Leaf(100, "bar") l3 = pytree.Leaf(100, "foo") n1 = pytree.Node(1000, [l1, l2]) n2 = pytree.Node(1000, [l3]) root = pytree.Node(1000, [n1, n2]) # Build a pattern pl = pytree.LeafPattern(100, "foo", name="pl") pn = pytree.NodePattern(1000, [pl], name="pn") pw = pytree.WildcardPattern([[pn], [pl, pl]], name="pw") r = {} self.assertFalse(pw.match_seq([root], r)) self.assertEqual(r, {}) self.assertFalse(pw.match_seq([n1], r)) self.assertEqual(r, {}) self.assertTrue(pw.match_seq([n2], r)) # These are easier to debug self.assertEqual(sorted(r.keys()), ["pl", "pn", "pw"]) self.assertEqual(r["pl"], l1) self.assertEqual(r["pn"], n2) self.assertEqual(r["pw"], [n2]) # But this is equivalent self.assertEqual(r, {"pl": l1, "pn": n2, "pw": [n2]}) r = {} self.assertTrue(pw.match_seq([l1, l3], r)) self.assertEqual(r, {"pl": l3, "pw": [l1, l3]}) self.assertTrue(r["pl"] is l3) r = {} def test_generate_matches(self): la = pytree.Leaf(1, "a") lb = pytree.Leaf(1, "b") lc = pytree.Leaf(1, "c") ld = pytree.Leaf(1, "d") le = pytree.Leaf(1, "e") lf = pytree.Leaf(1, "f") leaves = [la, lb, lc, ld, le, lf] root = pytree.Node(1000, leaves) pa = pytree.LeafPattern(1, "a", "pa") pb = pytree.LeafPattern(1, "b", "pb") pc = pytree.LeafPattern(1, "c", "pc") pd = pytree.LeafPattern(1, "d", "pd") pe = pytree.LeafPattern(1, "e", "pe") pf = pytree.LeafPattern(1, "f", "pf") pw = pytree.WildcardPattern([[pa, pb, pc], [pd, pe], [pa, pb], [pc, pd], [pe, pf]], min=1, max=4, name="pw") self.assertEqual([x[0] for x in pw.generate_matches(leaves)], [3, 5, 2, 4, 6]) pr = pytree.NodePattern(type=1000, content=[pw], name="pr") matches = list(pytree.generate_matches([pr], [root])) self.assertEqual(len(matches), 1) c, r = matches[0] self.assertEqual(c, 1) self.assertEqual(str(r["pr"]), "abcdef") self.assertEqual(r["pw"], [la, lb, lc, ld, le, lf]) for c in "abcdef": self.assertEqual(r["p" + c], pytree.Leaf(1, c)) def test_has_key_example(self): pattern = pytree.NodePattern(331, (pytree.LeafPattern(7), pytree.WildcardPattern(name="args"), pytree.LeafPattern(8))) l1 = pytree.Leaf(7, "(") l2 = pytree.Leaf(3, "x") l3 = pytree.Leaf(8, ")") node = pytree.Node(331, [l1, l2, l3]) r = {} self.assertTrue(pattern.match(node, r)) self.assertEqual(r["args"], [l2])
gpl-2.0
nash-x/hws
neutron/db/migration/alembic_migrations/agent_init_ops.py
17
1725
# Copyright 2014 OpenStack Foundation # # 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. # # Initial operations for agent management extension # This module only manages the 'agents' table. Binding tables are created # in the modules for relevant resources from alembic import op import sqlalchemy as sa def upgrade(): op.create_table( 'agents', sa.Column('id', sa.String(length=36), nullable=False), sa.Column('agent_type', sa.String(length=255), nullable=False), sa.Column('binary', sa.String(length=255), nullable=False), sa.Column('topic', sa.String(length=255), nullable=False), sa.Column('host', sa.String(length=255), nullable=False), sa.Column('admin_state_up', sa.Boolean(), nullable=False), sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('started_at', sa.DateTime(), nullable=False), sa.Column('heartbeat_timestamp', sa.DateTime(), nullable=False), sa.Column('description', sa.String(length=255), nullable=True), sa.Column('configurations', sa.String(length=4095), nullable=False), sa.PrimaryKeyConstraint('id')) def downgrade(): op.drop_table('agents')
apache-2.0
mark-adams/python-social-auth
social/backends/mineid.py
72
1257
from social.backends.oauth import BaseOAuth2 class MineIDOAuth2(BaseOAuth2): """MineID OAuth2 authentication backend""" name = 'mineid' _AUTHORIZATION_URL = '%(scheme)s://%(host)s/oauth/authorize' _ACCESS_TOKEN_URL = '%(scheme)s://%(host)s/oauth/access_token' ACCESS_TOKEN_METHOD = 'POST' SCOPE_SEPARATOR = ',' EXTRA_DATA = [ ] def get_user_details(self, response): """Return user details""" return {'email': response.get('email'), 'username': response.get('email')} def user_data(self, access_token, *args, **kwargs): return self._user_data(access_token) def _user_data(self, access_token, path=None): url = '%(scheme)s://%(host)s/api/user' % self.get_mineid_url_params() return self.get_json(url, params={'access_token': access_token}) @property def AUTHORIZATION_URL(self): return self._AUTHORIZATION_URL % self.get_mineid_url_params() @property def ACCESS_TOKEN_URL(self): return self._ACCESS_TOKEN_URL % self.get_mineid_url_params() def get_mineid_url_params(self): return { 'host': self.setting('HOST', 'www.mineid.org'), 'scheme': self.setting('SCHEME', 'https'), }
bsd-3-clause
sajuptpm/murano
murano/dsl/typespec.py
3
2113
# Copyright (c) 2014 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 murano.dsl import exceptions import murano.dsl.type_scheme as type_scheme class PropertyUsages(object): In = 'In' Out = 'Out' InOut = 'InOut' Runtime = 'Runtime' Const = 'Const' Config = 'Config' All = set([In, Out, InOut, Runtime, Const, Config]) Writable = set([Out, InOut, Runtime]) class Spec(object): def __init__(self, declaration, owner_class): self._namespace_resolver = owner_class.namespace_resolver self._contract = type_scheme.TypeScheme(declaration['Contract']) self._usage = declaration.get('Usage') or 'In' self._default = declaration.get('Default') self._has_default = 'Default' in declaration if self._usage not in PropertyUsages.All: raise exceptions.DslSyntaxError( 'Unknown type {0}. Must be one of ({1})'.format( self._usage, ', '.join(PropertyUsages.All))) def validate(self, value, this, owner, context, object_store, default=None): if default is None: default = self.default return self._contract(value, context, this, owner, object_store, self._namespace_resolver, default) @property def default(self): return self._default @property def has_default(self): return self._has_default @property def usage(self): return self._usage class PropertySpec(Spec): pass class ArgumentSpec(Spec): pass
apache-2.0
jpburstrom/sampleman
mutagen/ogg.py
5
17692
# Copyright 2006 Joe Wreschnig # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # $Id: ogg.py 3975 2007-01-13 21:51:17Z piman $ """Read and write Ogg bitstreams and pages. This module reads and writes a subset of the Ogg bitstream format version 0. It does *not* read or write Ogg Vorbis files! For that, you should use mutagen.oggvorbis. This implementation is based on the RFC 3533 standard found at http://www.xiph.org/ogg/doc/rfc3533.txt. """ import struct import sys import zlib from cStringIO import StringIO from mutagen import FileType from mutagen._util import cdata, insert_bytes, delete_bytes class error(IOError): """Ogg stream parsing errors.""" pass class OggPage(object): """A single Ogg page (not necessarily a single encoded packet). A page is a header of 26 bytes, followed by the length of the data, followed by the data. The constructor is givin a file-like object pointing to the start of an Ogg page. After the constructor is finished it is pointing to the start of the next page. Attributes: version -- stream structure version (currently always 0) position -- absolute stream position (default -1) serial -- logical stream serial number (default 0) sequence -- page sequence number within logical stream (default 0) offset -- offset this page was read from (default None) complete -- if the last packet on this page is complete (default True) packets -- list of raw packet data (default []) Note that if 'complete' is false, the next page's 'continued' property must be true (so set both when constructing pages). If a file-like object is supplied to the constructor, the above attributes will be filled in based on it. """ version = 0 __type_flags = 0 position = 0L serial = 0 sequence = 0 offset = None complete = True def __init__(self, fileobj=None): self.packets = [] if fileobj is None: return self.offset = fileobj.tell() header = fileobj.read(27) if len(header) == 0: raise EOFError try: (oggs, self.version, self.__type_flags, self.position, self.serial, self.sequence, crc, segments) = struct.unpack( "<4sBBqIIiB", header) except struct.error: raise error("unable to read full header; got %r" % header) if oggs != "OggS": raise error("read %r, expected %r, at 0x%x" % ( oggs, "OggS", fileobj.tell() - 27)) if self.version != 0: raise error("version %r unsupported" % self.version) total = 0 lacings = [] lacing_bytes = fileobj.read(segments) if len(lacing_bytes) != segments: raise error("unable to read %r lacing bytes" % segments) for c in map(ord, lacing_bytes): total += c if c < 255: lacings.append(total) total = 0 if total: lacings.append(total) self.complete = False self.packets = map(fileobj.read, lacings) if map(len, self.packets) != lacings: raise error("unable to read full data") def __eq__(self, other): """Two Ogg pages are the same if they write the same data.""" try: return (self.write() == other.write()) except AttributeError: return False def __repr__(self): attrs = ['version', 'position', 'serial', 'sequence', 'offset', 'complete', 'continued', 'first', 'last'] values = ["%s=%r" % (attr, getattr(self, attr)) for attr in attrs] return "<%s %s, %d bytes in %d packets>" % ( type(self).__name__, " ".join(values), sum(map(len, self.packets)), len(self.packets)) def write(self): """Return a string encoding of the page header and data. A ValueError is raised if the data is too big to fit in a single page. """ data = [ struct.pack("<4sBBqIIi", "OggS", self.version, self.__type_flags, self.position, self.serial, self.sequence, 0) ] lacing_data = [] for datum in self.packets: quot, rem = divmod(len(datum), 255) lacing_data.append("\xff" * quot + chr(rem)) lacing_data = "".join(lacing_data) if not self.complete and lacing_data.endswith("\x00"): lacing_data = lacing_data[:-1] data.append(chr(len(lacing_data))) data.append(lacing_data) data.extend(self.packets) data = "".join(data) # Python's CRC is swapped relative to Ogg's needs. crc = ~zlib.crc32(data.translate(cdata.bitswap), -1) # Although we're using to_int_be, this actually makes the CRC # a proper le integer, since Python's CRC is byteswapped. crc = cdata.to_int_be(crc).translate(cdata.bitswap) data = data[:22] + crc + data[26:] return data def __size(self): size = 27 # Initial header size for datum in self.packets: quot, rem = divmod(len(datum), 255) size += quot + 1 if not self.complete and rem == 0: # Packet contains a multiple of 255 bytes and is not # terminated, so we don't have a \x00 at the end. size -= 1 size += sum(map(len, self.packets)) return size size = property(__size, doc="Total frame size.") def __set_flag(self, bit, val): mask = 1 << bit if val: self.__type_flags |= mask else: self.__type_flags &= ~mask continued = property( lambda self: cdata.test_bit(self.__type_flags, 0), lambda self, v: self.__set_flag(0, v), doc="The first packet is continued from the previous page.") first = property( lambda self: cdata.test_bit(self.__type_flags, 1), lambda self, v: self.__set_flag(1, v), doc="This is the first page of a logical bitstream.") last = property( lambda self: cdata.test_bit(self.__type_flags, 2), lambda self, v: self.__set_flag(2, v), doc="This is the last page of a logical bitstream.") def renumber(klass, fileobj, serial, start): """Renumber pages belonging to a specified logical stream. fileobj must be opened with mode r+b or w+b. Starting at page number 'start', renumber all pages belonging to logical stream 'serial'. Other pages will be ignored. fileobj must point to the start of a valid Ogg page; any occuring after it and part of the specified logical stream will be numbered. No adjustment will be made to the data in the pages nor the granule position; only the page number, and so also the CRC. If an error occurs (e.g. non-Ogg data is found), fileobj will be left pointing to the place in the stream the error occured, but the invalid data will be left intact (since this function does not change the total file size). """ number = start while True: try: page = OggPage(fileobj) except EOFError: break else: if page.serial != serial: # Wrong stream, skip this page. continue # Changing the number can't change the page size, # so seeking back based on the current size is safe. fileobj.seek(-page.size, 1) page.sequence = number fileobj.write(page.write()) fileobj.seek(page.offset + page.size, 0) number += 1 renumber = classmethod(renumber) def to_packets(klass, pages, strict=False): """Construct a list of packet data from a list of Ogg pages. If strict is true, the first page must start a new packet, and the last page must end the last packet. """ serial = pages[0].serial sequence = pages[0].sequence packets = [] if strict: if pages[0].continued: raise ValueError("first packet is continued") if not pages[-1].complete: raise ValueError("last packet does not complete") elif pages and pages[0].continued: packets.append("") for page in pages: if serial != page.serial: raise ValueError("invalid serial number in %r" % page) elif sequence != page.sequence: raise ValueError("bad sequence number in %r" % page) else: sequence += 1 if page.continued: packets[-1] += page.packets[0] else: packets.append(page.packets[0]) packets.extend(page.packets[1:]) return packets to_packets = classmethod(to_packets) def from_packets(klass, packets, sequence=0, default_size=4096, wiggle_room=2048): """Construct a list of Ogg pages from a list of packet data. The algorithm will generate pages of approximately default_size in size (rounded down to the nearest multiple of 255). However, it will also allow pages to increase to approximately default_size + wiggle_room if allowing the wiggle room would finish a packet (only one packet will be finished in this way per page; if the next packet would fit into the wiggle room, it still starts on a new page). This method reduces packet fragmentation when packet sizes are slightly larger than the default page size, while still ensuring most pages are of the average size. Pages are numbered started at 'sequence'; other information is uninitialized. """ chunk_size = (default_size // 255) * 255 pages = [] page = OggPage() page.sequence = sequence for packet in packets: page.packets.append("") while packet: data, packet = packet[:chunk_size], packet[chunk_size:] if page.size < default_size and len(page.packets) < 255: page.packets[-1] += data else: # If we've put any packet data into this page yet, # we need to mark it incomplete. However, we can # also have just started this packet on an already # full page, in which case, just start the new # page with this packet. if page.packets[-1]: page.complete = False if len(page.packets) == 1: page.position = -1L else: page.packets.pop(-1) pages.append(page) page = OggPage() page.continued = not pages[-1].complete page.sequence = pages[-1].sequence + 1 page.packets.append(data) if len(packet) < wiggle_room: page.packets[-1] += packet packet = "" if page.packets: pages.append(page) return pages from_packets = classmethod(from_packets) def replace(klass, fileobj, old_pages, new_pages): """Replace old_pages with new_pages within fileobj. old_pages must have come from reading fileobj originally. new_pages are assumed to have the 'same' data as old_pages, and so the serial and sequence numbers will be copied, as will the flags for the first and last pages. fileobj will be resized and pages renumbered as necessary. As such, it must be opened r+b or w+b. """ # Number the new pages starting from the first old page. first = old_pages[0].sequence for page, seq in zip(new_pages, range(first, first + len(new_pages))): page.sequence = seq page.serial = old_pages[0].serial new_pages[0].first = old_pages[0].first new_pages[0].last = old_pages[0].last new_pages[0].continued = old_pages[0].continued new_pages[-1].first = old_pages[-1].first new_pages[-1].last = old_pages[-1].last new_pages[-1].complete = old_pages[-1].complete if not new_pages[-1].complete and len(new_pages[-1].packets) == 1: new_pages[-1].position = -1L new_data = "".join(map(klass.write, new_pages)) # Make room in the file for the new data. delta = len(new_data) fileobj.seek(old_pages[0].offset, 0) insert_bytes(fileobj, delta, old_pages[0].offset) fileobj.seek(old_pages[0].offset, 0) fileobj.write(new_data) new_data_end = old_pages[0].offset + delta # Go through the old pages and delete them. Since we shifted # the data down the file, we need to adjust their offsets. We # also need to go backwards, so we don't adjust the deltas of # the other pages. old_pages.reverse() for old_page in old_pages: adj_offset = old_page.offset + delta delete_bytes(fileobj, old_page.size, adj_offset) # Finally, if there's any discrepency in length, we need to # renumber the pages for the logical stream. if len(old_pages) != len(new_pages): fileobj.seek(new_data_end, 0) serial = new_pages[-1].serial sequence = new_pages[-1].sequence + 1 klass.renumber(fileobj, serial, sequence) replace = classmethod(replace) def find_last(klass, fileobj, serial): """Find the last page of the stream 'serial'. If the file is not multiplexed this function is fast. If it is, it must read the whole the stream. This finds the last page in the actual file object, or the last page in the stream (with eos set), whichever comes first. """ # For non-muxed streams, look at the last page. try: fileobj.seek(-256*256, 2) except IOError: # The file is less than 64k in length. fileobj.seek(0) data = fileobj.read() try: index = data.rindex("OggS") except ValueError: raise error("unable to find final Ogg header") stringobj = StringIO(data[index:]) best_page = None try: page = OggPage(stringobj) except error: pass else: if page.serial == serial: if page.last: return page else: best_page = page else: best_page = None # The stream is muxed, so use the slow way. fileobj.seek(0) try: page = OggPage(fileobj) while not page.last: page = OggPage(fileobj) while page.serial != serial: page = OggPage(fileobj) best_page = page return page except error: return best_page except EOFError: return best_page find_last = classmethod(find_last) class OggFileType(FileType): """An generic Ogg file.""" _Info = None _Tags = None _Error = None _mimes = ["application/ogg", "application/x-ogg"] def load(self, filename): """Load file information from a filename.""" self.filename = filename fileobj = file(filename, "rb") try: try: self.info = self._Info(fileobj) self.tags = self._Tags(fileobj, self.info) if self.info.length: # The streaminfo gave us real length information, # don't waste time scanning the Ogg. return last_page = OggPage.find_last(fileobj, self.info.serial) samples = last_page.position try: denom = self.info.sample_rate except AttributeError: denom = self.info.fps self.info.length = samples / float(denom) except error, e: raise self._Error, e, sys.exc_info()[2] except EOFError: raise self._Error, "no appropriate stream found" finally: fileobj.close() def delete(self, filename=None): """Remove tags from a file. If no filename is given, the one most recently loaded is used. """ if filename is None: filename = self.filename self.tags.clear() fileobj = file(filename, "rb+") try: try: self.tags._inject(fileobj) except error, e: raise self._Error, e, sys.exc_info()[2] except EOFError: raise self._Error, "no appropriate stream found" finally: fileobj.close() def save(self, filename=None): """Save a tag to a file. If no filename is given, the one most recently loaded is used. """ if filename is None: filename = self.filename fileobj = file(filename, "rb+") try: try: self.tags._inject(fileobj) except error, e: raise self._Error, e, sys.exc_info()[2] except EOFError: raise self._Error, "no appropriate stream found" finally: fileobj.close()
gpl-3.0
d40223223/2015cd_midterm
static/Brython3.1.1-20150328-091302/Lib/_csv.py
639
21705
"""CSV parsing and writing. [Copied from PyPy https://bitbucket-assetroot.s3.amazonaws.com/pypy/pypy/1400171824.19/641/_csv.py?Signature=cc%2Bc8m06cBMbsxt2e15XXXUDACk%3D&Expires=1404136251&AWSAccessKeyId=0EMWEFSGA12Z1HF1TZ82 and adapted to Python 3 syntax for Brython] This module provides classes that assist in the reading and writing of Comma Separated Value (CSV) files, and implements the interface described by PEP 305. Although many CSV files are simple to parse, the format is not formally defined by a stable specification and is subtle enough that parsing lines of a CSV file with something like line.split(\",\") is bound to fail. The module supports three basic APIs: reading, writing, and registration of dialects. DIALECT REGISTRATION: Readers and writers support a dialect argument, which is a convenient handle on a group of settings. When the dialect argument is a string, it identifies one of the dialects previously registered with the module. If it is a class or instance, the attributes of the argument are used as the settings for the reader or writer: class excel: delimiter = ',' quotechar = '\"' escapechar = None doublequote = True skipinitialspace = False lineterminator = '\\r\\n' quoting = QUOTE_MINIMAL SETTINGS: * quotechar - specifies a one-character string to use as the quoting character. It defaults to '\"'. * delimiter - specifies a one-character string to use as the field separator. It defaults to ','. * skipinitialspace - specifies how to interpret whitespace which immediately follows a delimiter. It defaults to False, which means that whitespace immediately following a delimiter is part of the following field. * lineterminator - specifies the character sequence which should terminate rows. * quoting - controls when quotes should be generated by the writer. It can take on any of the following module constants: csv.QUOTE_MINIMAL means only when required, for example, when a field contains either the quotechar or the delimiter csv.QUOTE_ALL means that quotes are always placed around fields. csv.QUOTE_NONNUMERIC means that quotes are always placed around fields which do not parse as integers or floating point numbers. csv.QUOTE_NONE means that quotes are never placed around fields. * escapechar - specifies a one-character string used to escape the delimiter when quoting is set to QUOTE_NONE. * doublequote - controls the handling of quotes inside fields. When True, two consecutive quotes are interpreted as one during read, and when writing, each quote character embedded in the data is written as two quotes. """ __version__ = "1.0" QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE = range(4) _dialects = {} _field_limit = 128 * 1024 # max parsed field size class Error(Exception): pass class Dialect(object): """CSV dialect The Dialect type records CSV parsing and generation options.""" __slots__ = ["_delimiter", "_doublequote", "_escapechar", "_lineterminator", "_quotechar", "_quoting", "_skipinitialspace", "_strict"] def __new__(cls, dialect, **kwargs): for name in kwargs: if '_' + name not in Dialect.__slots__: raise TypeError("unexpected keyword argument '%s'" % (name,)) if dialect is not None: if isinstance(dialect, str): dialect = get_dialect(dialect) # Can we reuse this instance? if (isinstance(dialect, Dialect) and all(value is None for value in kwargs.values())): return dialect self = object.__new__(cls) def set_char(x): if x is None: return None if isinstance(x, str) and len(x) <= 1: return x raise TypeError("%r must be a 1-character string" % (name,)) def set_str(x): if isinstance(x, str): return x raise TypeError("%r must be a string" % (name,)) def set_quoting(x): if x in range(4): return x raise TypeError("bad 'quoting' value") attributes = {"delimiter": (',', set_char), "doublequote": (True, bool), "escapechar": (None, set_char), "lineterminator": ("\r\n", set_str), "quotechar": ('"', set_char), "quoting": (QUOTE_MINIMAL, set_quoting), "skipinitialspace": (False, bool), "strict": (False, bool), } # Copy attributes notset = object() for name in Dialect.__slots__: name = name[1:] value = notset if name in kwargs: value = kwargs[name] elif dialect is not None: value = getattr(dialect, name, notset) # mapping by name: (default, converter) if value is notset: value = attributes[name][0] if name == 'quoting' and not self.quotechar: value = QUOTE_NONE else: converter = attributes[name][1] if converter: value = converter(value) setattr(self, '_' + name, value) if not self.delimiter: raise TypeError("delimiter must be set") if self.quoting != QUOTE_NONE and not self.quotechar: raise TypeError("quotechar must be set if quoting enabled") if not self.lineterminator: raise TypeError("lineterminator must be set") return self delimiter = property(lambda self: self._delimiter) doublequote = property(lambda self: self._doublequote) escapechar = property(lambda self: self._escapechar) lineterminator = property(lambda self: self._lineterminator) quotechar = property(lambda self: self._quotechar) quoting = property(lambda self: self._quoting) skipinitialspace = property(lambda self: self._skipinitialspace) strict = property(lambda self: self._strict) def _call_dialect(dialect_inst, kwargs): return Dialect(dialect_inst, **kwargs) def register_dialect(name, dialect=None, **kwargs): """Create a mapping from a string name to a dialect class. dialect = csv.register_dialect(name, dialect)""" if not isinstance(name, str): raise TypeError("dialect name must be a string or unicode") dialect = _call_dialect(dialect, kwargs) _dialects[name] = dialect def unregister_dialect(name): """Delete the name/dialect mapping associated with a string name.\n csv.unregister_dialect(name)""" try: del _dialects[name] except KeyError: raise Error("unknown dialect") def get_dialect(name): """Return the dialect instance associated with name. dialect = csv.get_dialect(name)""" try: return _dialects[name] except KeyError: raise Error("unknown dialect") def list_dialects(): """Return a list of all know dialect names names = csv.list_dialects()""" return list(_dialects) class Reader(object): """CSV reader Reader objects are responsible for reading and parsing tabular data in CSV format.""" (START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD, IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD, EAT_CRNL) = range(8) def __init__(self, iterator, dialect=None, **kwargs): self.dialect = _call_dialect(dialect, kwargs) # null characters are not allowed to be in the string so we can use # it as a fall back self._delimiter = self.dialect.delimiter if self.dialect.delimiter else '\0' self._quotechar = self.dialect.quotechar if self.dialect.quotechar else '\0' self._escapechar = self.dialect.escapechar if self.dialect.escapechar else '\0' self._doublequote = self.dialect.doublequote self._quoting = self.dialect.quoting self._skipinitialspace = self.dialect.skipinitialspace self._strict = self.dialect.strict self.input_iter = iter(iterator) self.line_num = 0 self._parse_reset() def _parse_reset(self): self.field = '' self.fields = [] self.state = self.START_RECORD self.numeric_field = False def __iter__(self): return self def __next__(self): self._parse_reset() while True: try: line = next(self.input_iter) except StopIteration: # End of input OR exception if len(self.field) > 0: raise Error("newline inside string") raise self.line_num += 1 if '\0' in line: raise Error("line contains NULL byte") self._parse_process_char(line) self._parse_eol() if self.state == self.START_RECORD: break fields = self.fields self.fields = [] return fields def _parse_process_char(self, line): pos = 0 while pos < len(line): if self.state == self.IN_FIELD: # in unquoted field and have already found one character when starting the field pos2 = pos while pos2 < len(line): if line[pos2] == '\n' or line[pos2] == '\r': # end of line - return [fields] if pos2 > pos: self._parse_add_str(line[pos:pos2]) pos = pos2 self._parse_save_field() self.state = self.EAT_CRNL break elif line[pos2] == self._escapechar[0]: # possible escaped character if pos2 > pos: self._parse_add_str(line[pos:pos2]) pos = pos2 self.state = self.ESCAPED_CHAR break elif line[pos2] == self._delimiter[0]: # save field - wait for new field if pos2 > pos: self._parse_add_str(line[pos:pos2]) pos = pos2 self._parse_save_field() self.state = self.START_FIELD break # normal character - save in field pos2 += 1 else: if pos2 > pos: self._parse_add_str(line[pos:pos2]) pos = pos2 continue elif self.state == self.START_RECORD: if line[pos] == '\n' or line[pos] == '\r': self.state = self.EAT_CRNL else: self.state = self.START_FIELD # restart process continue elif self.state == self.START_FIELD: if line[pos] == '\n' or line[pos] == '\r': # save empty field - return [fields] self._parse_save_field() self.state = self.EAT_CRNL elif (line[pos] == self._quotechar[0] and self._quoting != QUOTE_NONE): # start quoted field self.state = self.IN_QUOTED_FIELD elif line[pos] == self._escapechar[0]: # possible escaped character self.state = self.ESCAPED_CHAR elif self._skipinitialspace and line[pos] == ' ': # ignore space at start of field pass elif line[pos] == self._delimiter[0]: # save empty field self._parse_save_field() else: # begin new unquoted field if self._quoting == QUOTE_NONNUMERIC: self.numeric_field = True self.state = self.IN_FIELD continue elif self.state == self.ESCAPED_CHAR: self._parse_add_char(line[pos]) self.state = self.IN_FIELD elif self.state == self.IN_QUOTED_FIELD: if line[pos] == self._escapechar: # possible escape character self.state = self.ESCAPE_IN_QUOTED_FIELD elif (line[pos] == self._quotechar and self._quoting != QUOTE_NONE): if self._doublequote: # doublequote; " represented by "" self.state = self.QUOTE_IN_QUOTED_FIELD else: #end of quote part of field self.state = self.IN_FIELD else: # normal character - save in field self._parse_add_char(line[pos]) elif self.state == self.ESCAPE_IN_QUOTED_FIELD: self._parse_add_char(line[pos]) self.state = self.IN_QUOTED_FIELD elif self.state == self.QUOTE_IN_QUOTED_FIELD: # doublequote - seen a quote in a quoted field if (line[pos] == self._quotechar and self._quoting != QUOTE_NONE): # save "" as " self._parse_add_char(line[pos]) self.state = self.IN_QUOTED_FIELD elif line[pos] == self._delimiter[0]: # save field - wait for new field self._parse_save_field() self.state = self.START_FIELD elif line[pos] == '\r' or line[pos] == '\n': # end of line - return [fields] self._parse_save_field() self.state = self.EAT_CRNL elif not self._strict: self._parse_add_char(line[pos]) self.state = self.IN_FIELD else: raise Error("'%c' expected after '%c'" % (self._delimiter, self._quotechar)) elif self.state == self.EAT_CRNL: if line[pos] == '\r' or line[pos] == '\n': pass else: raise Error("new-line character seen in unquoted field - " "do you need to open the file " "in universal-newline mode?") else: raise RuntimeError("unknown state: %r" % (self.state,)) pos += 1 def _parse_eol(self): if self.state == self.EAT_CRNL: self.state = self.START_RECORD elif self.state == self.START_RECORD: # empty line - return [] pass elif self.state == self.IN_FIELD: # in unquoted field # end of line - return [fields] self._parse_save_field() self.state = self.START_RECORD elif self.state == self.START_FIELD: # save empty field - return [fields] self._parse_save_field() self.state = self.START_RECORD elif self.state == self.ESCAPED_CHAR: self._parse_add_char('\n') self.state = self.IN_FIELD elif self.state == self.IN_QUOTED_FIELD: pass elif self.state == self.ESCAPE_IN_QUOTED_FIELD: self._parse_add_char('\n') self.state = self.IN_QUOTED_FIELD elif self.state == self.QUOTE_IN_QUOTED_FIELD: # end of line - return [fields] self._parse_save_field() self.state = self.START_RECORD else: raise RuntimeError("unknown state: %r" % (self.state,)) def _parse_save_field(self): field, self.field = self.field, '' if self.numeric_field: self.numeric_field = False field = float(field) self.fields.append(field) def _parse_add_char(self, c): if len(self.field) + 1 > _field_limit: raise Error("field larget than field limit (%d)" % (_field_limit)) self.field += c def _parse_add_str(self, s): if len(self.field) + len(s) > _field_limit: raise Error("field larget than field limit (%d)" % (_field_limit)) self.field += s class Writer(object): """CSV writer Writer objects are responsible for generating tabular data in CSV format from sequence input.""" def __init__(self, file, dialect=None, **kwargs): if not (hasattr(file, 'write') and callable(file.write)): raise TypeError("argument 1 must have a 'write' method") self.writeline = file.write self.dialect = _call_dialect(dialect, kwargs) def _join_reset(self): self.rec = [] self.num_fields = 0 def _join_append(self, field, quoted, quote_empty): dialect = self.dialect # If this is not the first field we need a field separator if self.num_fields > 0: self.rec.append(dialect.delimiter) if dialect.quoting == QUOTE_NONE: need_escape = tuple(dialect.lineterminator) + ( dialect.escapechar, # escapechar always first dialect.delimiter, dialect.quotechar) else: for c in tuple(dialect.lineterminator) + ( dialect.delimiter, dialect.escapechar): if c and c in field: quoted = True need_escape = () if dialect.quotechar in field: if dialect.doublequote: field = field.replace(dialect.quotechar, dialect.quotechar * 2) quoted = True else: need_escape = (dialect.quotechar,) for c in need_escape: if c and c in field: if not dialect.escapechar: raise Error("need to escape, but no escapechar set") field = field.replace(c, dialect.escapechar + c) # If field is empty check if it needs to be quoted if field == '' and quote_empty: if dialect.quoting == QUOTE_NONE: raise Error("single empty field record must be quoted") quoted = 1 if quoted: field = dialect.quotechar + field + dialect.quotechar self.rec.append(field) self.num_fields += 1 def writerow(self, row): dialect = self.dialect try: rowlen = len(row) except TypeError: raise Error("sequence expected") # join all fields in internal buffer self._join_reset() for field in row: quoted = False if dialect.quoting == QUOTE_NONNUMERIC: try: float(field) except: quoted = True # This changed since 2.5: # quoted = not isinstance(field, (int, long, float)) elif dialect.quoting == QUOTE_ALL: quoted = True if field is None: self._join_append("", quoted, rowlen == 1) else: self._join_append(str(field), quoted, rowlen == 1) # add line terminator self.rec.append(dialect.lineterminator) self.writeline(''.join(self.rec)) def writerows(self, rows): for row in rows: self.writerow(row) def reader(*args, **kwargs): """ csv_reader = reader(iterable [, dialect='excel'] [optional keyword args]) for row in csv_reader: process(row) The "iterable" argument can be any object that returns a line of input for each iteration, such as a file object or a list. The optional \"dialect\" parameter is discussed below. The function also accepts optional keyword arguments which override settings provided by the dialect. The returned object is an iterator. Each iteration returns a row of the CSV file (which can span multiple input lines)""" return Reader(*args, **kwargs) def writer(*args, **kwargs): """ csv_writer = csv.writer(fileobj [, dialect='excel'] [optional keyword args]) for row in sequence: csv_writer.writerow(row) [or] csv_writer = csv.writer(fileobj [, dialect='excel'] [optional keyword args]) csv_writer.writerows(rows) The \"fileobj\" argument can be any object that supports the file API.""" return Writer(*args, **kwargs) undefined = object() def field_size_limit(limit=undefined): """Sets an upper limit on parsed fields. csv.field_size_limit([limit]) Returns old limit. If limit is not given, no new limit is set and the old limit is returned""" global _field_limit old_limit = _field_limit if limit is not undefined: if not isinstance(limit, (int, long)): raise TypeError("int expected, got %s" % (limit.__class__.__name__,)) _field_limit = limit return old_limit
gpl-3.0
hassanabidpk/django
django/conf/locale/eo/formats.py
504
2335
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'j\-\a \d\e F Y' # '26-a de julio 1887' TIME_FORMAT = 'H:i' # '18:59' DATETIME_FORMAT = r'j\-\a \d\e F Y\, \j\e H:i' # '26-a de julio 1887, je 18:59' YEAR_MONTH_FORMAT = r'F \d\e Y' # 'julio de 1887' MONTH_DAY_FORMAT = r'j\-\a \d\e F' # '26-a de julio' SHORT_DATE_FORMAT = 'Y-m-d' # '1887-07-26' SHORT_DATETIME_FORMAT = 'Y-m-d H:i' # '1887-07-26 18:59' FIRST_DAY_OF_WEEK = 1 # Monday (lundo) # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%Y-%m-%d', # '1887-07-26' '%y-%m-%d', # '87-07-26' '%Y %m %d', # '1887 07 26' '%d-a de %b %Y', # '26-a de jul 1887' '%d %b %Y', # '26 jul 1887' '%d-a de %B %Y', # '26-a de julio 1887' '%d %B %Y', # '26 julio 1887' '%d %m %Y', # '26 07 1887' ] TIME_INPUT_FORMATS = [ '%H:%M:%S', # '18:59:00' '%H:%M', # '18:59' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '1887-07-26 18:59:00' '%Y-%m-%d %H:%M', # '1887-07-26 18:59' '%Y-%m-%d', # '1887-07-26' '%Y.%m.%d %H:%M:%S', # '1887.07.26 18:59:00' '%Y.%m.%d %H:%M', # '1887.07.26 18:59' '%Y.%m.%d', # '1887.07.26' '%d/%m/%Y %H:%M:%S', # '26/07/1887 18:59:00' '%d/%m/%Y %H:%M', # '26/07/1887 18:59' '%d/%m/%Y', # '26/07/1887' '%y-%m-%d %H:%M:%S', # '87-07-26 18:59:00' '%y-%m-%d %H:%M', # '87-07-26 18:59' '%y-%m-%d', # '87-07-26' ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '\xa0' # non-breaking space NUMBER_GROUPING = 3
bsd-3-clause
BeyondTheClouds/nova
nova/tests/unit/api/openstack/compute/test_shelve.py
8
6956
# 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 uuid from oslo_policy import policy as oslo_policy import webob from nova.api.openstack.compute.legacy_v2.contrib import shelve as shelve_v2 from nova.api.openstack.compute import shelve as shelve_v21 from nova.compute import api as compute_api from nova import exception from nova import policy from nova import test from nova.tests.unit.api.openstack import fakes from nova.tests.unit import fake_instance def fake_instance_get_by_uuid(context, instance_id, columns_to_join=None, use_slave=False): return fake_instance.fake_db_instance( **{'name': 'fake', 'project_id': '%s_unequal' % context.project_id}) class ShelvePolicyTestV21(test.NoDBTestCase): plugin = shelve_v21 prefix = 'os_compute_api:os-shelve' offload = 'shelve_offload' def setUp(self): super(ShelvePolicyTestV21, self).setUp() self.controller = self.plugin.ShelveController() self.req = fakes.HTTPRequest.blank('') def test_shelve_restricted_by_role(self): rules = {'compute_extension:%sshelve' % self.prefix: 'role:admin'} policy.set_rules(oslo_policy.Rules.from_dict(rules)) self.assertRaises(exception.Forbidden, self.controller._shelve, self.req, str(uuid.uuid4()), {}) def test_shelve_locked_server(self): self.stub_out('nova.db.instance_get_by_uuid', fake_instance_get_by_uuid) self.stubs.Set(compute_api.API, 'shelve', fakes.fake_actions_to_locked_server) self.assertRaises(webob.exc.HTTPConflict, self.controller._shelve, self.req, str(uuid.uuid4()), {}) def test_unshelve_restricted_by_role(self): rules = {'compute_extension:%sunshelve' % self.prefix: 'role:admin'} policy.set_rules(oslo_policy.Rules.from_dict(rules)) self.assertRaises(exception.Forbidden, self.controller._unshelve, self.req, str(uuid.uuid4()), {}) def test_unshelve_locked_server(self): self.stub_out('nova.db.instance_get_by_uuid', fake_instance_get_by_uuid) self.stubs.Set(compute_api.API, 'unshelve', fakes.fake_actions_to_locked_server) self.assertRaises(webob.exc.HTTPConflict, self.controller._unshelve, self.req, str(uuid.uuid4()), {}) def test_shelve_offload_restricted_by_role(self): rules = {'compute_extension:%s%s' % (self.prefix, self.offload): 'role:admin'} policy.set_rules(oslo_policy.Rules.from_dict(rules)) self.assertRaises(exception.Forbidden, self.controller._shelve_offload, self.req, str(uuid.uuid4()), {}) def test_shelve_offload_locked_server(self): self.stub_out('nova.db.instance_get_by_uuid', fake_instance_get_by_uuid) self.stubs.Set(compute_api.API, 'shelve_offload', fakes.fake_actions_to_locked_server) self.assertRaises(webob.exc.HTTPConflict, self.controller._shelve_offload, self.req, str(uuid.uuid4()), {}) class ShelvePolicyTestV2(ShelvePolicyTestV21): plugin = shelve_v2 prefix = '' offload = 'shelveOffload' # These 3 cases are covered in ShelvePolicyEnforcementV21 def test_shelve_allowed(self): rules = {'compute:get': '', 'compute_extension:%sshelve' % self.prefix: ''} policy.set_rules(oslo_policy.Rules.from_dict(rules)) self.stub_out('nova.db.instance_get_by_uuid', fake_instance_get_by_uuid) self.assertRaises(exception.Forbidden, self.controller._shelve, self.req, str(uuid.uuid4()), {}) def test_unshelve_allowed(self): rules = {'compute:get': '', 'compute_extension:%sunshelve' % self.prefix: ''} policy.set_rules(oslo_policy.Rules.from_dict(rules)) self.stub_out('nova.db.instance_get_by_uuid', fake_instance_get_by_uuid) self.assertRaises(exception.Forbidden, self.controller._unshelve, self.req, str(uuid.uuid4()), {}) def test_shelve_offload_allowed(self): rules = {'compute:get': '', 'compute_extension:%s%s' % (self.prefix, self.offload): ''} policy.set_rules(oslo_policy.Rules.from_dict(rules)) self.stub_out('nova.db.instance_get_by_uuid', fake_instance_get_by_uuid) self.assertRaises(exception.Forbidden, self.controller._shelve_offload, self.req, str(uuid.uuid4()), {}) class ShelvePolicyEnforcementV21(test.NoDBTestCase): def setUp(self): super(ShelvePolicyEnforcementV21, self).setUp() self.controller = shelve_v21.ShelveController() self.req = fakes.HTTPRequest.blank('') def test_shelve_policy_failed(self): rule_name = "os_compute_api:os-shelve:shelve" self.policy.set_rules({rule_name: "project:non_fake"}) exc = self.assertRaises( exception.PolicyNotAuthorized, self.controller._shelve, self.req, fakes.FAKE_UUID, body={'shelve': {}}) self.assertEqual( "Policy doesn't allow %s to be performed." % rule_name, exc.format_message()) def test_shelve_offload_policy_failed(self): rule_name = "os_compute_api:os-shelve:shelve_offload" self.policy.set_rules({rule_name: "project:non_fake"}) exc = self.assertRaises( exception.PolicyNotAuthorized, self.controller._shelve_offload, self.req, fakes.FAKE_UUID, body={'shelve_offload': {}}) self.assertEqual( "Policy doesn't allow %s to be performed." % rule_name, exc.format_message()) def test_unshelve_policy_failed(self): rule_name = "os_compute_api:os-shelve:unshelve" self.policy.set_rules({rule_name: "project:non_fake"}) exc = self.assertRaises( exception.PolicyNotAuthorized, self.controller._unshelve, self.req, fakes.FAKE_UUID, body={'unshelve': {}}) self.assertEqual( "Policy doesn't allow %s to be performed." % rule_name, exc.format_message())
apache-2.0
saurabh6790/medsynaptic1-app
patches/may_2013/p02_update_valuation_rate.py
30
1376
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import webnotes def execute(): from stock.stock_ledger import update_entries_after item_warehouse = [] # update valuation_rate in transaction doctypes = {"Purchase Receipt": "purchase_receipt_details", "Purchase Invoice": "entries"} for dt in doctypes: for d in webnotes.conn.sql("""select name from `tab%s` where modified >= '2013-05-09' and docstatus=1""" % dt): rec = webnotes.get_obj(dt, d[0]) rec.update_valuation_rate(doctypes[dt]) for item in rec.doclist.get({"parentfield": doctypes[dt]}): webnotes.conn.sql("""update `tab%s Item` set valuation_rate = %s where name = %s"""% (dt, '%s', '%s'), tuple([item.valuation_rate, item.name])) if dt == "Purchase Receipt": webnotes.conn.sql("""update `tabStock Ledger Entry` set incoming_rate = %s where voucher_detail_no = %s""", (item.valuation_rate, item.name)) if [item.item_code, item.warehouse] not in item_warehouse: item_warehouse.append([item.item_code, item.warehouse]) for d in item_warehouse: try: update_entries_after({"item_code": d[0], "warehouse": d[1], "posting_date": "2013-01-01", "posting_time": "00:05:00"}) webnotes.conn.commit() except: pass
agpl-3.0
ThirdProject/android_external_chromium_org
components/policy/tools/syntax_check_policy_template_json.py
51
18860
#!/usr/bin/env python # Copyright (c) 2012 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. ''' Checks a policy_templates.json file for conformity to its syntax specification. ''' import json import optparse import os import re import sys LEADING_WHITESPACE = re.compile('^([ \t]*)') TRAILING_WHITESPACE = re.compile('.*?([ \t]+)$') # Matches all non-empty strings that contain no whitespaces. NO_WHITESPACE = re.compile('[^\s]+$') # Convert a 'type' to its corresponding schema type. TYPE_TO_SCHEMA = { 'int': 'integer', 'list': 'array', 'dict': 'object', 'main': 'boolean', 'string': 'string', 'int-enum': 'integer', 'string-enum': 'string', 'external': 'object', } # List of boolean policies that have been introduced with negative polarity in # the past and should not trigger the negative polarity check. LEGACY_INVERTED_POLARITY_WHITELIST = [ 'DeveloperToolsDisabled', 'DeviceAutoUpdateDisabled', 'Disable3DAPIs', 'DisableAuthNegotiateCnameLookup', 'DisablePluginFinder', 'DisablePrintPreview', 'DisableSafeBrowsingProceedAnyway', 'DisableScreenshots', 'DisableSpdy', 'DisableSSLRecordSplitting', 'DriveDisabled', 'DriveDisabledOverCellular', 'ExternalStorageDisabled', 'SavingBrowserHistoryDisabled', 'SyncDisabled', ] class PolicyTemplateChecker(object): def __init__(self): self.error_count = 0 self.warning_count = 0 self.num_policies = 0 self.num_groups = 0 self.num_policies_in_groups = 0 self.options = None self.features = [] def _Error(self, message, parent_element=None, identifier=None, offending_snippet=None): self.error_count += 1 error = '' if identifier is not None and parent_element is not None: error += 'In %s %s: ' % (parent_element, identifier) print error + 'Error: ' + message if offending_snippet is not None: print ' Offending:', json.dumps(offending_snippet, indent=2) def _CheckContains(self, container, key, value_type, optional=False, parent_element='policy', container_name=None, identifier=None, offending='__CONTAINER__', regexp_check=None): ''' Checks |container| for presence of |key| with value of type |value_type|. If |value_type| is string and |regexp_check| is specified, then an error is reported when the value does not match the regular expression object. The other parameters are needed to generate, if applicable, an appropriate human-readable error message of the following form: In |parent_element| |identifier|: (if the key is not present): Error: |container_name| must have a |value_type| named |key|. Offending snippet: |offending| (if specified; defaults to |container|) (if the value does not have the required type): Error: Value of |key| must be a |value_type|. Offending snippet: |container[key]| Returns: |container[key]| if the key is present, None otherwise. ''' if identifier is None: identifier = container.get('name') if container_name is None: container_name = parent_element if offending == '__CONTAINER__': offending = container if key not in container: if optional: return else: self._Error('%s must have a %s "%s".' % (container_name.title(), value_type.__name__, key), container_name, identifier, offending) return None value = container[key] if not isinstance(value, value_type): self._Error('Value of "%s" must be a %s.' % (key, value_type.__name__), container_name, identifier, value) if value_type == str and regexp_check and not regexp_check.match(value): self._Error('Value of "%s" must match "%s".' % (key, regexp_check.pattern), container_name, identifier, value) return value def _AddPolicyID(self, id, policy_ids, policy): ''' Adds |id| to |policy_ids|. Generates an error message if the |id| exists already; |policy| is needed for this message. ''' if id in policy_ids: self._Error('Duplicate id', 'policy', policy.get('name'), id) else: policy_ids.add(id) def _CheckPolicyIDs(self, policy_ids): ''' Checks a set of policy_ids to make sure it contains a continuous range of entries (i.e. no holes). Holes would not be a technical problem, but we want to ensure that nobody accidentally omits IDs. ''' for i in range(len(policy_ids)): if (i + 1) not in policy_ids: self._Error('No policy with id: %s' % (i + 1)) def _CheckPolicySchema(self, policy, policy_type): '''Checks that the 'schema' field matches the 'type' field.''' self._CheckContains(policy, 'schema', dict) if isinstance(policy.get('schema'), dict): self._CheckContains(policy['schema'], 'type', str) schema_type = policy['schema'].get('type') if schema_type != TYPE_TO_SCHEMA[policy_type]: self._Error('Schema type must match the existing type for policy %s' % policy.get('name')) # Checks that boolean policies are not negated (which makes them harder to # reason about). if (schema_type == 'boolean' and 'disable' in policy.get('name').lower() and policy.get('name') not in LEGACY_INVERTED_POLARITY_WHITELIST): self._Error(('Boolean policy %s uses negative polarity, please make ' + 'new boolean policies follow the XYZEnabled pattern. ' + 'See also http://crbug.com/85687') % policy.get('name')) def _CheckPolicy(self, policy, is_in_group, policy_ids): if not isinstance(policy, dict): self._Error('Each policy must be a dictionary.', 'policy', None, policy) return # There should not be any unknown keys in |policy|. for key in policy: if key not in ('name', 'type', 'caption', 'desc', 'device_only', 'supported_on', 'label', 'policies', 'items', 'example_value', 'features', 'deprecated', 'future', 'id', 'schema', 'max_size'): self.warning_count += 1 print ('In policy %s: Warning: Unknown key: %s' % (policy.get('name'), key)) # Each policy must have a name. self._CheckContains(policy, 'name', str, regexp_check=NO_WHITESPACE) # Each policy must have a type. policy_types = ('group', 'main', 'string', 'int', 'list', 'int-enum', 'string-enum', 'dict', 'external') policy_type = self._CheckContains(policy, 'type', str) if policy_type not in policy_types: self._Error('Policy type must be one of: ' + ', '.join(policy_types), 'policy', policy.get('name'), policy_type) return # Can't continue for unsupported type. # Each policy must have a caption message. self._CheckContains(policy, 'caption', str) # Each policy must have a description message. self._CheckContains(policy, 'desc', str) # If 'label' is present, it must be a string. self._CheckContains(policy, 'label', str, True) # If 'deprecated' is present, it must be a bool. self._CheckContains(policy, 'deprecated', bool, True) # If 'future' is present, it must be a bool. self._CheckContains(policy, 'future', bool, True) if policy_type == 'group': # Groups must not be nested. if is_in_group: self._Error('Policy groups must not be nested.', 'policy', policy) # Each policy group must have a list of policies. policies = self._CheckContains(policy, 'policies', list) # Check sub-policies. if policies is not None: for nested_policy in policies: self._CheckPolicy(nested_policy, True, policy_ids) # Groups must not have an |id|. if 'id' in policy: self._Error('Policies of type "group" must not have an "id" field.', 'policy', policy) # Statistics. self.num_groups += 1 else: # policy_type != group # Each policy must have a protobuf ID. id = self._CheckContains(policy, 'id', int) self._AddPolicyID(id, policy_ids, policy) # 'schema' is the new 'type'. # TODO(joaodasilva): remove the 'type' checks once 'schema' is used # everywhere. self._CheckPolicySchema(policy, policy_type) # Each policy must have a supported_on list. supported_on = self._CheckContains(policy, 'supported_on', list) if supported_on is not None: for s in supported_on: if not isinstance(s, str): self._Error('Entries in "supported_on" must be strings.', 'policy', policy, supported_on) # Each policy must have a 'features' dict. features = self._CheckContains(policy, 'features', dict) # All the features must have a documenting message. if features: for feature in features: if not feature in self.features: self._Error('Unknown feature "%s". Known features must have a ' 'documentation string in the messages dictionary.' % feature, 'policy', policy.get('name', policy)) # All user policies must have a per_profile feature flag. if (not policy.get('device_only', False) and not policy.get('deprecated', False) and not filter(re.compile('^chrome_frame:.*').match, supported_on)): self._CheckContains(features, 'per_profile', bool, container_name='features', identifier=policy.get('name')) # All policies must declare whether they allow changes at runtime. self._CheckContains(features, 'dynamic_refresh', bool, container_name='features', identifier=policy.get('name')) # Each policy must have an 'example_value' of appropriate type. if policy_type == 'main': value_type = bool elif policy_type in ('string', 'string-enum'): value_type = str elif policy_type in ('int', 'int-enum'): value_type = int elif policy_type == 'list': value_type = list elif policy_type in ('dict', 'external'): value_type = dict else: raise NotImplementedError('Unimplemented policy type: %s' % policy_type) self._CheckContains(policy, 'example_value', value_type) # Statistics. self.num_policies += 1 if is_in_group: self.num_policies_in_groups += 1 if policy_type in ('int-enum', 'string-enum'): # Enums must contain a list of items. items = self._CheckContains(policy, 'items', list) if items is not None: if len(items) < 1: self._Error('"items" must not be empty.', 'policy', policy, items) for item in items: # Each item must have a name. # Note: |policy.get('name')| is used instead of |policy['name']| # because it returns None rather than failing when no key called # 'name' exists. self._CheckContains(item, 'name', str, container_name='item', identifier=policy.get('name'), regexp_check=NO_WHITESPACE) # Each item must have a value of the correct type. self._CheckContains(item, 'value', value_type, container_name='item', identifier=policy.get('name')) # Each item must have a caption. self._CheckContains(item, 'caption', str, container_name='item', identifier=policy.get('name')) if policy_type == 'external': # Each policy referencing external data must specify a maximum data size. self._CheckContains(policy, 'max_size', int) def _CheckMessage(self, key, value): # |key| must be a string, |value| a dict. if not isinstance(key, str): self._Error('Each message key must be a string.', 'message', key, key) return if not isinstance(value, dict): self._Error('Each message must be a dictionary.', 'message', key, value) return # Each message must have a desc. self._CheckContains(value, 'desc', str, parent_element='message', identifier=key) # Each message must have a text. self._CheckContains(value, 'text', str, parent_element='message', identifier=key) # There should not be any unknown keys in |value|. for vkey in value: if vkey not in ('desc', 'text'): self.warning_count += 1 print 'In message %s: Warning: Unknown key: %s' % (key, vkey) def _LeadingWhitespace(self, line): match = LEADING_WHITESPACE.match(line) if match: return match.group(1) return '' def _TrailingWhitespace(self, line): match = TRAILING_WHITESPACE.match(line) if match: return match.group(1) return '' def _LineError(self, message, line_number): self.error_count += 1 print 'In line %d: Error: %s' % (line_number, message) def _LineWarning(self, message, line_number): self.warning_count += 1 print ('In line %d: Warning: Automatically fixing formatting: %s' % (line_number, message)) def _CheckFormat(self, filename): if self.options.fix: fixed_lines = [] with open(filename) as f: indent = 0 line_number = 0 for line in f: line_number += 1 line = line.rstrip('\n') # Check for trailing whitespace. trailing_whitespace = self._TrailingWhitespace(line) if len(trailing_whitespace) > 0: if self.options.fix: line = line.rstrip() self._LineWarning('Trailing whitespace.', line_number) else: self._LineError('Trailing whitespace.', line_number) if self.options.fix: if len(line) == 0: fixed_lines += ['\n'] continue else: if line == trailing_whitespace: # This also catches the case of an empty line. continue # Check for correct amount of leading whitespace. leading_whitespace = self._LeadingWhitespace(line) if leading_whitespace.count('\t') > 0: if self.options.fix: leading_whitespace = leading_whitespace.replace('\t', ' ') line = leading_whitespace + line.lstrip() self._LineWarning('Tab character found.', line_number) else: self._LineError('Tab character found.', line_number) if line[len(leading_whitespace)] in (']', '}'): indent -= 2 if line[0] != '#': # Ignore 0-indented comments. if len(leading_whitespace) != indent: if self.options.fix: line = ' ' * indent + line.lstrip() self._LineWarning('Indentation should be ' + str(indent) + ' spaces.', line_number) else: self._LineError('Bad indentation. Should be ' + str(indent) + ' spaces.', line_number) if line[-1] in ('[', '{'): indent += 2 if self.options.fix: fixed_lines.append(line + '\n') # If --fix is specified: backup the file (deleting any existing backup), # then write the fixed version with the old filename. if self.options.fix: if self.options.backup: backupfilename = filename + '.bak' if os.path.exists(backupfilename): os.remove(backupfilename) os.rename(filename, backupfilename) with open(filename, 'w') as f: f.writelines(fixed_lines) def Main(self, filename, options): try: with open(filename) as f: data = eval(f.read()) except: import traceback traceback.print_exc(file=sys.stdout) self._Error('Invalid JSON syntax.') return if data == None: self._Error('Invalid JSON syntax.') return self.options = options # First part: check JSON structure. # Check (non-policy-specific) message definitions. messages = self._CheckContains(data, 'messages', dict, parent_element=None, container_name='The root element', offending=None) if messages is not None: for message in messages: self._CheckMessage(message, messages[message]) if message.startswith('doc_feature_'): self.features.append(message[12:]) # Check policy definitions. policy_definitions = self._CheckContains(data, 'policy_definitions', list, parent_element=None, container_name='The root element', offending=None) if policy_definitions is not None: policy_ids = set() for policy in policy_definitions: self._CheckPolicy(policy, False, policy_ids) self._CheckPolicyIDs(policy_ids) # Second part: check formatting. self._CheckFormat(filename) # Third part: summary and exit. print ('Finished checking %s. %d errors, %d warnings.' % (filename, self.error_count, self.warning_count)) if self.options.stats: if self.num_groups > 0: print ('%d policies, %d of those in %d groups (containing on ' 'average %.1f policies).' % (self.num_policies, self.num_policies_in_groups, self.num_groups, (1.0 * self.num_policies_in_groups / self.num_groups))) else: print self.num_policies, 'policies, 0 policy groups.' if self.error_count > 0: return 1 return 0 def Run(self, argv, filename=None): parser = optparse.OptionParser( usage='usage: %prog [options] filename', description='Syntax check a policy_templates.json file.') parser.add_option('--fix', action='store_true', help='Automatically fix formatting.') parser.add_option('--backup', action='store_true', help='Create backup of original file (before fixing).') parser.add_option('--stats', action='store_true', help='Generate statistics.') (options, args) = parser.parse_args(argv) if filename is None: if len(args) != 2: parser.print_help() sys.exit(1) filename = args[1] return self.Main(filename, options) if __name__ == '__main__': sys.exit(PolicyTemplateChecker().Run(sys.argv))
bsd-3-clause
resmo/ansible
lib/ansible/plugins/connection/lxd.py
74
4629
# (c) 2016 Matt Clay <matt@mystile.com> # (c) 2017 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 DOCUMENTATION = """ author: Matt Clay <matt@mystile.com> connection: lxd short_description: Run tasks in lxc containers via lxc CLI description: - Run commands or put/fetch files to an existing lxc container using lxc CLI version_added: "2.0" options: remote_addr: description: - Container identifier default: inventory_hostname vars: - name: ansible_host - name: ansible_lxd_host executable: description: - shell to use for execution inside container default: /bin/sh vars: - name: ansible_executable - name: ansible_lxd_executable """ import os from distutils.spawn import find_executable from subprocess import Popen, PIPE from ansible.errors import AnsibleError, AnsibleConnectionFailure, AnsibleFileNotFound from ansible.module_utils._text import to_bytes, to_text from ansible.plugins.connection import ConnectionBase class Connection(ConnectionBase): """ lxd based connections """ transport = "lxd" has_pipelining = True default_user = 'root' def __init__(self, play_context, new_stdin, *args, **kwargs): super(Connection, self).__init__(play_context, new_stdin, *args, **kwargs) self._host = self._play_context.remote_addr self._lxc_cmd = find_executable("lxc") if not self._lxc_cmd: raise AnsibleError("lxc command not found in PATH") if self._play_context.remote_user is not None and self._play_context.remote_user != 'root': self._display.warning('lxd does not support remote_user, using container default: root') def _connect(self): """connect to lxd (nothing to do here) """ super(Connection, self)._connect() if not self._connected: self._display.vvv(u"ESTABLISH LXD CONNECTION FOR USER: root", host=self._host) self._connected = True def exec_command(self, cmd, in_data=None, sudoable=True): """ execute a command on the lxd host """ super(Connection, self).exec_command(cmd, in_data=in_data, sudoable=sudoable) self._display.vvv(u"EXEC {0}".format(cmd), host=self._host) local_cmd = [self._lxc_cmd, "exec", self._host, "--", self._play_context.executable, "-c", cmd] local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd] in_data = to_bytes(in_data, errors='surrogate_or_strict', nonstring='passthru') process = Popen(local_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate(in_data) stdout = to_text(stdout) stderr = to_text(stderr) if stderr == "error: Container is not running.\n": raise AnsibleConnectionFailure("container not running: %s" % self._host) if stderr == "error: not found\n": raise AnsibleConnectionFailure("container not found: %s" % self._host) return process.returncode, stdout, stderr def put_file(self, in_path, out_path): """ put a file from local to lxd """ super(Connection, self).put_file(in_path, out_path) self._display.vvv(u"PUT {0} TO {1}".format(in_path, out_path), host=self._host) if not os.path.isfile(to_bytes(in_path, errors='surrogate_or_strict')): raise AnsibleFileNotFound("input path is not a file: %s" % in_path) local_cmd = [self._lxc_cmd, "file", "push", in_path, self._host + "/" + out_path] local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd] process = Popen(local_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) process.communicate() def fetch_file(self, in_path, out_path): """ fetch a file from lxd to local """ super(Connection, self).fetch_file(in_path, out_path) self._display.vvv(u"FETCH {0} TO {1}".format(in_path, out_path), host=self._host) local_cmd = [self._lxc_cmd, "file", "pull", self._host + "/" + in_path, out_path] local_cmd = [to_bytes(i, errors='surrogate_or_strict') for i in local_cmd] process = Popen(local_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) process.communicate() def close(self): """ close the connection (nothing to do here) """ super(Connection, self).close() self._connected = False
gpl-3.0