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
dhruvagarwal/django
tests/template_tests/filter_tests/test_pluralize.py
430
1200
from decimal import Decimal from django.template.defaultfilters import pluralize from django.test import SimpleTestCase class FunctionTests(SimpleTestCase): def test_integers(self): self.assertEqual(pluralize(1), '') self.assertEqual(pluralize(0), 's') self.assertEqual(pluralize(2), 's') def test_floats(self): self.assertEqual(pluralize(0.5), 's') self.assertEqual(pluralize(1.5), 's') def test_decimals(self): self.assertEqual(pluralize(Decimal(1)), '') self.assertEqual(pluralize(Decimal(0)), 's') self.assertEqual(pluralize(Decimal(2)), 's') def test_lists(self): self.assertEqual(pluralize([1]), '') self.assertEqual(pluralize([]), 's') self.assertEqual(pluralize([1, 2, 3]), 's') def test_suffixes(self): self.assertEqual(pluralize(1, 'es'), '') self.assertEqual(pluralize(0, 'es'), 'es') self.assertEqual(pluralize(2, 'es'), 'es') self.assertEqual(pluralize(1, 'y,ies'), 'y') self.assertEqual(pluralize(0, 'y,ies'), 'ies') self.assertEqual(pluralize(2, 'y,ies'), 'ies') self.assertEqual(pluralize(0, 'y,ies,error'), '')
bsd-3-clause
mapseed/api
src/sa_api_v2/management/commands/updateDatasetDevCreds.py
3
3486
from __future__ import print_function from django.core.management.base import BaseCommand import os import re # for manually testing with `./manage.py shell` commandline: # from ... import models as sa_models # from ... import forms from sa_api_v2 import models as sa_models import logging # display our logs to console with StreamHandler: console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(console_handler) # The name of our file containing our dev key values, # located in our project root. DATASET_ENV_FILE = '.dataset-env' # The suffix of our dev key variables in our .env file: DEV_KEY_SUFFIX = '_DEV_KEY' def parse_env(dict): """ Parses variables from a .env file located in the project root directory and loads them into the dictionary. """ try: file_path = os.path.join( os.path.dirname(__file__), '..', '..', '..', DATASET_ENV_FILE) with open(file_path) as f: content = f.read() except IOError: content = '' for line in content.splitlines(): m1 = re.match(r'\A([A-Za-z_0-9]+){}=(.*)\Z'.format(DEV_KEY_SUFFIX), line) if m1: key, val = m1.group(1), m1.group(2) m2 = re.match(r"\A'(.*)'\Z", val) if m2: val = m2.group(1) m3 = re.match(r'\A"(.*)"\Z', val) if m3: val = re.sub(r'\\(.)', r'\1', m3.group(1)) logger.info('parsing key from environment file: {}={}' .format(key, val)) dict.setdefault('{}{}'.format(key, DEV_KEY_SUFFIX), val) class Command(BaseCommand): help = """ For our dev api, update the api key value of all our datasets to the constants defined in our .env file This command is idempotent. """ def handle(self, *args, **options): logger.info('parsing environment variables...') api_key_values = {} parse_env(api_key_values) logger.info('environment variables: {}'.format(api_key_values)) logger.info('starting dataset key migration...') datasets = sa_models.DataSet.objects.all() logger.info('fetching matching...') logger.info('') for dataset in datasets: api_key_value = api_key_values.get('{}{}'.format( dataset.display_name.upper(), DEV_KEY_SUFFIX), None) # handle case when we have a dataset but no dev key: if api_key_value is None: logger.error('No matching key found for dataset: {}' .format(dataset.display_name)) logger.error('perhaps we should create a key for it?\n') continue # handle case when we have a dataset with no key: if dataset.keys is None or len(dataset.keys.all()) < 1: logger.error('Skipping dataset because it has no api key: {}\n' .format(dataset.display_name)) continue logger.info('setting key for datset name: {} to value: {}' .format(dataset.display_name, api_key_value)) # save the new value to our dataset's key: key = dataset.keys.all()[0] key.key = api_key_value key.save() dataset.key = key dataset.save()
gpl-3.0
hargup/sympy
sympy/polys/domains/tests/test_polynomialring.py
99
3314
"""Tests for the PolynomialRing classes. """ from sympy.polys.domains import QQ, ZZ from sympy.polys.polyerrors import ExactQuotientFailed, CoercionFailed, NotReversible from sympy.abc import x, y from sympy.utilities.pytest import raises def test_build_order(): R = QQ.old_poly_ring(x, y, order=(("lex", x), ("ilex", y))) assert R.order((1, 5)) == ((1,), (-5,)) def test_globalring(): Qxy = QQ.old_frac_field(x, y) R = QQ.old_poly_ring(x, y) X = R.convert(x) Y = R.convert(y) assert x in R assert 1/x not in R assert 1/(1 + x) not in R assert Y in R assert X.ring == R assert X * (Y**2 + 1) == R.convert(x * (y**2 + 1)) assert X * y == X * Y == R.convert(x * y) == x * Y assert X + y == X + Y == R.convert(x + y) == x + Y assert X - y == X - Y == R.convert(x - y) == x - Y assert X + 1 == R.convert(x + 1) raises(ExactQuotientFailed, lambda: X/Y) raises(ExactQuotientFailed, lambda: x/Y) raises(ExactQuotientFailed, lambda: X/y) assert X**2 / X == X assert R.from_GlobalPolynomialRing(ZZ.old_poly_ring(x, y).convert(x), ZZ.old_poly_ring(x, y)) == X assert R.from_FractionField(Qxy.convert(x), Qxy) == X assert R.from_FractionField(Qxy.convert(x)/y, Qxy) is None assert R._sdm_to_vector(R._vector_to_sdm([X, Y], R.order), 2) == [X, Y] def test_localring(): Qxy = QQ.old_frac_field(x, y) R = QQ.old_poly_ring(x, y, order="ilex") X = R.convert(x) Y = R.convert(y) assert x in R assert 1/x not in R assert 1/(1 + x) in R assert Y in R assert X.ring == R assert X*(Y**2 + 1)/(1 + X) == R.convert(x*(y**2 + 1)/(1 + x)) assert X*y == X*Y raises(ExactQuotientFailed, lambda: X/Y) raises(ExactQuotientFailed, lambda: x/Y) raises(ExactQuotientFailed, lambda: X/y) assert X + y == X + Y == R.convert(x + y) == x + Y assert X - y == X - Y == R.convert(x - y) == x - Y assert X + 1 == R.convert(x + 1) assert X**2 / X == X assert R.from_GlobalPolynomialRing(ZZ.old_poly_ring(x, y).convert(x), ZZ.old_poly_ring(x, y)) == X assert R.from_FractionField(Qxy.convert(x), Qxy) == X raises(CoercionFailed, lambda: R.from_FractionField(Qxy.convert(x)/y, Qxy)) raises(ExactQuotientFailed, lambda: X/Y) raises(NotReversible, lambda: X.invert()) assert R._sdm_to_vector( R._vector_to_sdm([X/(X + 1), Y/(1 + X*Y)], R.order), 2) == \ [X*(1 + X*Y), Y*(1 + X)] def test_conversion(): L = QQ.old_poly_ring(x, y, order="ilex") G = QQ.old_poly_ring(x, y) assert L.convert(x) == L.convert(G.convert(x), G) assert G.convert(x) == G.convert(L.convert(x), L) raises(CoercionFailed, lambda: G.convert(L.convert(1/(1 + x)), L)) def test_units(): R = QQ.old_poly_ring(x) assert R.is_unit(R.convert(1)) assert R.is_unit(R.convert(2)) assert not R.is_unit(R.convert(x)) assert not R.is_unit(R.convert(1 + x)) R = QQ.old_poly_ring(x, order='ilex') assert R.is_unit(R.convert(1)) assert R.is_unit(R.convert(2)) assert not R.is_unit(R.convert(x)) assert R.is_unit(R.convert(1 + x)) R = ZZ.old_poly_ring(x) assert R.is_unit(R.convert(1)) assert not R.is_unit(R.convert(2)) assert not R.is_unit(R.convert(x)) assert not R.is_unit(R.convert(1 + x))
bsd-3-clause
britcey/ansible
test/runner/lib/target.py
28
16080
"""Test target identification, iteration and inclusion/exclusion.""" from __future__ import absolute_import, print_function import os import re import errno import itertools import abc from lib.util import ApplicationError MODULE_EXTENSIONS = '.py', '.ps1' def find_target_completion(target_func, prefix): """ :type target_func: () -> collections.Iterable[CompletionTarget] :type prefix: unicode :rtype: list[str] """ try: targets = target_func() prefix = prefix.encode() short = os.environ.get('COMP_TYPE') == '63' # double tab completion from bash matches = walk_completion_targets(targets, prefix, short) return matches except Exception as ex: # pylint: disable=locally-disabled, broad-except return [str(ex)] def walk_completion_targets(targets, prefix, short=False): """ :type targets: collections.Iterable[CompletionTarget] :type prefix: str :type short: bool :rtype: tuple[str] """ aliases = set(alias for target in targets for alias in target.aliases) if prefix.endswith('/') and prefix in aliases: aliases.remove(prefix) matches = [alias for alias in aliases if alias.startswith(prefix) and '/' not in alias[len(prefix):-1]] if short: offset = len(os.path.dirname(prefix)) if offset: offset += 1 relative_matches = [match[offset:] for match in matches if len(match) > offset] if len(relative_matches) > 1: matches = relative_matches return tuple(sorted(matches)) def walk_internal_targets(targets, includes=None, excludes=None, requires=None): """ :type targets: collections.Iterable[T <= CompletionTarget] :type includes: list[str] :type excludes: list[str] :type requires: list[str] :rtype: tuple[T <= CompletionTarget] """ targets = tuple(targets) include_targets = sorted(filter_targets(targets, includes, errors=True, directories=False), key=lambda t: t.name) if requires: require_targets = set(filter_targets(targets, requires, errors=True, directories=False)) include_targets = [target for target in include_targets if target in require_targets] if excludes: list(filter_targets(targets, excludes, errors=True, include=False, directories=False)) internal_targets = set(filter_targets(include_targets, excludes, errors=False, include=False, directories=False)) return tuple(sorted(internal_targets, key=lambda t: t.name)) def walk_external_targets(targets, includes=None, excludes=None, requires=None): """ :type targets: collections.Iterable[CompletionTarget] :type includes: list[str] :type excludes: list[str] :type requires: list[str] :rtype: tuple[CompletionTarget], tuple[CompletionTarget] """ targets = tuple(targets) if requires: include_targets = list(filter_targets(targets, includes, errors=True, directories=False)) require_targets = set(filter_targets(targets, requires, errors=True, directories=False)) includes = [target.name for target in include_targets if target in require_targets] if includes: include_targets = sorted(filter_targets(targets, includes, errors=True), key=lambda t: t.name) else: include_targets = [] else: include_targets = sorted(filter_targets(targets, includes, errors=True), key=lambda t: t.name) if excludes: exclude_targets = sorted(filter_targets(targets, excludes, errors=True), key=lambda t: t.name) else: exclude_targets = [] previous = None include = [] for target in include_targets: if isinstance(previous, DirectoryTarget) and isinstance(target, DirectoryTarget) \ and previous.name == target.name: previous.modules = tuple(set(previous.modules) | set(target.modules)) else: include.append(target) previous = target previous = None exclude = [] for target in exclude_targets: if isinstance(previous, DirectoryTarget) and isinstance(target, DirectoryTarget) \ and previous.name == target.name: previous.modules = tuple(set(previous.modules) | set(target.modules)) else: exclude.append(target) previous = target return tuple(include), tuple(exclude) def filter_targets(targets, patterns, include=True, directories=True, errors=True): """ :type targets: collections.Iterable[CompletionTarget] :type patterns: list[str] :type include: bool :type directories: bool :type errors: bool :rtype: collections.Iterable[CompletionTarget] """ unmatched = set(patterns or ()) compiled_patterns = dict((p, re.compile('^%s$' % p)) for p in patterns) if patterns else None for target in targets: matched_directories = set() match = False if patterns: for alias in target.aliases: for pattern in patterns: if compiled_patterns[pattern].match(alias): match = True try: unmatched.remove(pattern) except KeyError: pass if alias.endswith('/'): if target.base_path and len(target.base_path) > len(alias): matched_directories.add(target.base_path) else: matched_directories.add(alias) elif include: match = True if not target.base_path: matched_directories.add('.') for alias in target.aliases: if alias.endswith('/'): if target.base_path and len(target.base_path) > len(alias): matched_directories.add(target.base_path) else: matched_directories.add(alias) if match != include: continue if directories and matched_directories: yield DirectoryTarget(sorted(matched_directories, key=len)[0], target.modules) else: yield target if errors: if unmatched: raise TargetPatternsNotMatched(unmatched) def walk_module_targets(): """ :rtype: collections.Iterable[TestTarget] """ path = 'lib/ansible/modules' for target in walk_test_targets(path, path + '/', extensions=MODULE_EXTENSIONS): if not target.module: continue yield target def walk_units_targets(): """ :rtype: collections.Iterable[TestTarget] """ return walk_test_targets(path='test/units', module_path='test/units/modules/', extensions=('.py',), prefix='test_') def walk_compile_targets(): """ :rtype: collections.Iterable[TestTarget] """ return walk_test_targets(module_path='lib/ansible/modules/', extensions=('.py',)) def walk_sanity_targets(): """ :rtype: collections.Iterable[TestTarget] """ return walk_test_targets(module_path='lib/ansible/modules/') def walk_posix_integration_targets(): """ :rtype: collections.Iterable[IntegrationTarget] """ for target in walk_integration_targets(): if 'posix/' in target.aliases: yield target def walk_network_integration_targets(): """ :rtype: collections.Iterable[IntegrationTarget] """ for target in walk_integration_targets(): if 'network/' in target.aliases: yield target def walk_windows_integration_targets(): """ :rtype: collections.Iterable[IntegrationTarget] """ for target in walk_integration_targets(): if 'windows/' in target.aliases: yield target def walk_integration_targets(): """ :rtype: collections.Iterable[IntegrationTarget] """ path = 'test/integration/targets' modules = frozenset(t.module for t in walk_module_targets()) paths = sorted(os.path.join(path, p) for p in os.listdir(path)) prefixes = load_integration_prefixes() for path in paths: yield IntegrationTarget(path, modules, prefixes) def load_integration_prefixes(): """ :rtype: dict[str, str] """ path = 'test/integration' names = sorted(f for f in os.listdir(path) if os.path.splitext(f)[0] == 'target-prefixes') prefixes = {} for name in names: prefix = os.path.splitext(name)[1][1:] with open(os.path.join(path, name), 'r') as prefix_fd: prefixes.update(dict((k, prefix) for k in prefix_fd.read().splitlines())) return prefixes def walk_test_targets(path=None, module_path=None, extensions=None, prefix=None): """ :type path: str | None :type module_path: str | None :type extensions: tuple[str] | None :type prefix: str | None :rtype: collections.Iterable[TestTarget] """ for root, _, file_names in os.walk(path or '.', topdown=False): if root.endswith('/__pycache__'): continue if '/.tox/' in root: continue if path is None: root = root[2:] if root.startswith('.'): continue for file_name in file_names: name, ext = os.path.splitext(os.path.basename(file_name)) if name.startswith('.'): continue if extensions and ext not in extensions: continue if prefix and not name.startswith(prefix): continue yield TestTarget(os.path.join(root, file_name), module_path, prefix, path) class CompletionTarget(object): """Command-line argument completion target base class.""" __metaclass__ = abc.ABCMeta def __init__(self): self.name = None self.path = None self.base_path = None self.modules = tuple() self.aliases = tuple() def __eq__(self, other): if isinstance(other, CompletionTarget): return self.__repr__() == other.__repr__() return False def __ne__(self, other): return not self.__eq__(other) def __lt__(self, other): return self.name.__lt__(other.name) def __gt__(self, other): return self.name.__gt__(other.name) def __hash__(self): return hash(self.__repr__()) def __repr__(self): if self.modules: return '%s (%s)' % (self.name, ', '.join(self.modules)) return self.name class DirectoryTarget(CompletionTarget): """Directory target.""" def __init__(self, path, modules): """ :type path: str :type modules: tuple[str] """ super(DirectoryTarget, self).__init__() self.name = path self.path = path self.modules = modules class TestTarget(CompletionTarget): """Generic test target.""" def __init__(self, path, module_path, module_prefix, base_path): """ :type path: str :type module_path: str | None :type module_prefix: str | None :type base_path: str """ super(TestTarget, self).__init__() self.name = path self.path = path self.base_path = base_path + '/' if base_path else None name, ext = os.path.splitext(os.path.basename(self.path)) if module_path and path.startswith(module_path) and name != '__init__' and ext in MODULE_EXTENSIONS: self.module = name[len(module_prefix or ''):].lstrip('_') self.modules = self.module, else: self.module = None self.modules = tuple() aliases = [self.path, self.module] parts = self.path.split('/') for i in range(1, len(parts)): alias = '%s/' % '/'.join(parts[:i]) aliases.append(alias) aliases = [a for a in aliases if a] self.aliases = tuple(sorted(aliases)) class IntegrationTarget(CompletionTarget): """Integration test target.""" non_posix = frozenset(( 'network', 'windows', )) categories = frozenset(non_posix | frozenset(( 'posix', 'module', 'needs', 'skip', ))) def __init__(self, path, modules, prefixes): """ :type path: str :type modules: frozenset[str] :type prefixes: dict[str, str] """ super(IntegrationTarget, self).__init__() self.name = os.path.basename(path) self.path = path # script_path and type contents = sorted(os.listdir(path)) runme_files = tuple(c for c in contents if os.path.splitext(c)[0] == 'runme') test_files = tuple(c for c in contents if os.path.splitext(c)[0] == 'test') self.script_path = None if runme_files: self.type = 'script' self.script_path = os.path.join(path, runme_files[0]) elif test_files: self.type = 'special' elif os.path.isdir(os.path.join(path, 'tasks')): self.type = 'role' else: self.type = 'unknown' # static_aliases try: with open(os.path.join(path, 'aliases'), 'r') as aliases_file: static_aliases = tuple(aliases_file.read().splitlines()) except IOError as ex: if ex.errno != errno.ENOENT: raise static_aliases = tuple() # modules if self.name in modules: module = self.name elif self.name.startswith('win_') and self.name[4:] in modules: module = self.name[4:] else: module = None self.modules = tuple(sorted(a for a in static_aliases + tuple([module]) if a in modules)) # groups groups = [self.type] groups += [a for a in static_aliases if a not in modules] groups += ['module/%s' % m for m in self.modules] if not self.modules: groups.append('non_module') if 'destructive' not in groups: groups.append('non_destructive') if '_' in self.name: prefix = self.name[:self.name.find('_')] else: prefix = None if prefix in prefixes: group = prefixes[prefix] if group != prefix: group = '%s/%s' % (group, prefix) groups.append(group) if self.name.startswith('win_'): groups.append('windows') if self.name.startswith('connection_'): groups.append('connection') if self.name.startswith('setup_') or self.name.startswith('prepare_'): groups.append('hidden') if self.type not in ('script', 'role'): groups.append('hidden') for group in itertools.islice(groups, 0, len(groups)): if '/' in group: parts = group.split('/') for i in range(1, len(parts)): groups.append('/'.join(parts[:i])) if not any(g in self.non_posix for g in groups): groups.append('posix') # aliases aliases = [self.name] + \ ['%s/' % g for g in groups] + \ ['%s/%s' % (g, self.name) for g in groups if g not in self.categories] if 'hidden/' in aliases: aliases = ['hidden/'] + ['hidden/%s' % a for a in aliases if not a.startswith('hidden/')] self.aliases = tuple(sorted(set(aliases))) class TargetPatternsNotMatched(ApplicationError): """One or more targets were not matched when a match was required.""" def __init__(self, patterns): """ :type patterns: set[str] """ self.patterns = sorted(patterns) if len(patterns) > 1: message = 'Target patterns not matched:\n%s' % '\n'.join(self.patterns) else: message = 'Target pattern not matched: %s' % self.patterns[0] super(TargetPatternsNotMatched, self).__init__(message)
gpl-3.0
frost-nzcr4/djangocms-installer
docs/conf.py
3
8439
#!/usr/bin/env python # -*- coding: utf-8 -*- # # complexity documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its containing dir. # # 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 extensions (or modules to document with 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.insert(0, os.path.abspath('.')) cwd = os.getcwd() parent = os.path.dirname(cwd) sys.path.append(parent) import djangocms_installer # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # 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', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig', 'sphinx.ext.viewcode'] # 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-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'django CMS Installer' copyright = u'2013, Iacopo Spalletti' # 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 = djangocms_installer.__version__ # The full version, including alpha/beta/rc tags. release = djangocms_installer.__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 patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_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' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # 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_domain_indices = 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, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = 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 = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'djangocms_installerdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'djangocms_installer.tex', u'django CMS Installer Documentation', u'Iacopo Spalletti', '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 # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'djangocms_installer', u'django CMS Installer Documentation', [u'Iacopo Spalletti'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'djangocms_installer', u'django CMS Installer Documentation', u'Iacopo Spalletti', 'djangocms_installer', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
bsd-3-clause
amerlyq/airy
vim/res/ycm_extra_conf.py
1
5213
# SEE: CACHE/bundle/YouCompleteMe/cpp/ycm/.ycm_extra_conf.py import os import ycm_core # These are the compilation flags that will be used in case there's no # compilation database set (by default, one is not set). # CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR. flags = [ '-Wall', '-Wextra', '-Werror', '-Wc++98-compat', '-Wno-long-long', '-Wno-variadic-macros', '-fexceptions', '-DNDEBUG', # You 100% do NOT need -DUSE_CLANG_COMPLETER in your flags; only the YCM # source code needs it. #'-DUSE_CLANG_COMPLETER', # THIS IS IMPORTANT! Without a "-std=<something>" flag, clang won't know which # language to use when compiling headers. So it will guess. Badly. So C++ # headers will be compiled as C headers. You don't want that so ALWAYS specify # a "-std=<something>". # For a C project, you would set this to something like 'c99' instead of # 'c++11'. '-std=c++11', # ...and the same thing goes for the magic -x option which specifies the # language that the files to be compiled are written in. This is mostly # relevant for c++ headers. # For a C project, you would set this to 'c' instead of 'c++'. '-x', 'c++', '-isystem', '../BoostParts', # This path will only work on OS X, but extra paths that don't exist are not harmful '-isystem', '/System/Library/Frameworks/Python.framework/Headers', '-isystem', '../llvm/include', '-isystem', '../llvm/tools/clang/include', '-I', '.', '-I', './ClangCompleter', '-isystem', './tests/gmock/gtest', '-isystem', './tests/gmock/gtest/include', '-isystem', './tests/gmock', '-isystem', './tests/gmock/include', '-isystem', '/usr/include', '-isystem', '/usr/local/include', '-isystem', '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../lib/c++/v1', '-isystem', '/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include', ] # Set this to the absolute path to the folder (NOT the file!) containing the # compile_commands.json file to use that instead of 'flags'. See here for # more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html # # Most projects will NOT need to set this to anything; you can just change the # 'flags' list of compilation flags. Notice that YCM itself uses that approach. compilation_database_folder = os.path.abspath( '~/aura/pdrm/gerrit/build' ) if os.path.exists( compilation_database_folder ): database = ycm_core.CompilationDatabase( compilation_database_folder ) else: database = None SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ] def DirectoryOfThisScript(): return os.path.dirname( os.path.abspath( __file__ ) ) def MakeRelativePathsInFlagsAbsolute( flags, working_directory ): if not working_directory: return list( flags ) new_flags = [] make_next_absolute = False path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ] for flag in flags: new_flag = flag if make_next_absolute: make_next_absolute = False if not flag.startswith( '/' ): new_flag = os.path.join( working_directory, flag ) for path_flag in path_flags: if flag == path_flag: make_next_absolute = True break if flag.startswith( path_flag ): path = flag[ len( path_flag ): ] new_flag = path_flag + os.path.join( working_directory, path ) break if new_flag: new_flags.append( new_flag ) return new_flags def IsHeaderFile( filename ): extension = os.path.splitext( filename )[ 1 ] return extension in [ '.h', '.hxx', '.hpp', '.hh' ] def GetCompilationInfoForFile( filename ): # The compilation_commands.json file generated by CMake does not have entries # for header files. So we do our best by asking the db for flags for a # corresponding source file, if any. If one exists, the flags for that file # should be good enough. if IsHeaderFile( filename ): basename = os.path.splitext( filename )[ 0 ] for extension in SOURCE_EXTENSIONS: replacement_file = basename + extension if os.path.exists( replacement_file ): compilation_info = database.GetCompilationInfoForFile( replacement_file ) if compilation_info.compiler_flags_: return compilation_info return None return database.GetCompilationInfoForFile( filename ) def FlagsForFile( filename, **kwargs ): if database: # Bear in mind that compilation_info.compiler_flags_ does NOT return a # python list, but a "list-like" StringVec object compilation_info = GetCompilationInfoForFile( filename ) if not compilation_info: return None final_flags = MakeRelativePathsInFlagsAbsolute( compilation_info.compiler_flags_, compilation_info.compiler_working_dir_ ) # NOTE: This is just for YouCompleteMe; it's highly likely that your project # does NOT need to remove the stdlib flag. DO NOT USE THIS IN YOUR # ycm_extra_conf IF YOU'RE NOT 100% SURE YOU NEED IT. #try: # final_flags.remove( '-stdlib=libc++' ) #except ValueError: # pass else: relative_to = DirectoryOfThisScript() final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to ) return { 'flags': final_flags, 'do_cache': True }
mit
rdo-management/ironic
ironic/tests/drivers/test_virtualbox.py
4
18456
# 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. """Test class for VirtualBox Driver Modules.""" import mock from oslo_config import cfg from pyremotevbox import exception as pyremotevbox_exc from pyremotevbox import vbox as pyremotevbox_vbox from ironic.common import boot_devices from ironic.common import exception from ironic.common import states from ironic.conductor import task_manager from ironic.drivers.modules import virtualbox from ironic.tests.conductor import utils as mgr_utils from ironic.tests.db import base as db_base from ironic.tests.objects import utils as obj_utils INFO_DICT = { 'virtualbox_vmname': 'baremetal1', 'virtualbox_host': '10.0.2.2', 'virtualbox_username': 'username', 'virtualbox_password': 'password', 'virtualbox_port': 12345, } CONF = cfg.CONF class VirtualBoxMethodsTestCase(db_base.DbTestCase): def setUp(self): super(VirtualBoxMethodsTestCase, self).setUp() driver_info = INFO_DICT.copy() mgr_utils.mock_the_extension_manager(driver="fake_vbox") self.node = obj_utils.create_test_node(self.context, driver='fake_vbox', driver_info=driver_info) def test__parse_driver_info(self): info = virtualbox._parse_driver_info(self.node) self.assertEqual('baremetal1', info['vmname']) self.assertEqual('10.0.2.2', info['host']) self.assertEqual('username', info['username']) self.assertEqual('password', info['password']) self.assertEqual(12345, info['port']) def test__parse_driver_info_missing_vmname(self): del self.node.driver_info['virtualbox_vmname'] self.assertRaises(exception.MissingParameterValue, virtualbox._parse_driver_info, self.node) def test__parse_driver_info_missing_host(self): del self.node.driver_info['virtualbox_host'] self.assertRaises(exception.MissingParameterValue, virtualbox._parse_driver_info, self.node) def test__parse_driver_info_invalid_port(self): self.node.driver_info['virtualbox_port'] = 'invalid-port' self.assertRaises(exception.InvalidParameterValue, virtualbox._parse_driver_info, self.node) def test__parse_driver_info_missing_port(self): del self.node.driver_info['virtualbox_port'] info = virtualbox._parse_driver_info(self.node) self.assertEqual(18083, info['port']) @mock.patch.object(pyremotevbox_vbox, 'VirtualBoxHost') def test__run_virtualbox_method(self, host_mock): host_object_mock = mock.MagicMock() func_mock = mock.MagicMock() vm_object_mock = mock.MagicMock(foo=func_mock) host_mock.return_value = host_object_mock host_object_mock.find_vm.return_value = vm_object_mock func_mock.return_value = 'return-value' return_value = virtualbox._run_virtualbox_method(self.node, 'some-ironic-method', 'foo', 'args', kwarg='kwarg') host_mock.assert_called_once_with(vmname='baremetal1', host='10.0.2.2', username='username', password='password', port=12345) host_object_mock.find_vm.assert_called_once_with('baremetal1') func_mock.assert_called_once_with('args', kwarg='kwarg') self.assertEqual('return-value', return_value) @mock.patch.object(pyremotevbox_vbox, 'VirtualBoxHost') def test__run_virtualbox_method_get_host_fails(self, host_mock): host_mock.side_effect = pyremotevbox_exc.PyRemoteVBoxException self.assertRaises(exception.VirtualBoxOperationFailed, virtualbox._run_virtualbox_method, self.node, 'some-ironic-method', 'foo', 'args', kwarg='kwarg') @mock.patch.object(pyremotevbox_vbox, 'VirtualBoxHost') def test__run_virtualbox_method_find_vm_fails(self, host_mock): host_object_mock = mock.MagicMock() host_mock.return_value = host_object_mock exc = pyremotevbox_exc.PyRemoteVBoxException host_object_mock.find_vm.side_effect = exc self.assertRaises(exception.VirtualBoxOperationFailed, virtualbox._run_virtualbox_method, self.node, 'some-ironic-method', 'foo', 'args', kwarg='kwarg') host_mock.assert_called_once_with(vmname='baremetal1', host='10.0.2.2', username='username', password='password', port=12345) host_object_mock.find_vm.assert_called_once_with('baremetal1') @mock.patch.object(pyremotevbox_vbox, 'VirtualBoxHost') def test__run_virtualbox_method_func_fails(self, host_mock): host_object_mock = mock.MagicMock() host_mock.return_value = host_object_mock func_mock = mock.MagicMock() vm_object_mock = mock.MagicMock(foo=func_mock) host_object_mock.find_vm.return_value = vm_object_mock func_mock.side_effect = pyremotevbox_exc.PyRemoteVBoxException self.assertRaises(exception.VirtualBoxOperationFailed, virtualbox._run_virtualbox_method, self.node, 'some-ironic-method', 'foo', 'args', kwarg='kwarg') host_mock.assert_called_once_with(vmname='baremetal1', host='10.0.2.2', username='username', password='password', port=12345) host_object_mock.find_vm.assert_called_once_with('baremetal1') func_mock.assert_called_once_with('args', kwarg='kwarg') @mock.patch.object(pyremotevbox_vbox, 'VirtualBoxHost') def test__run_virtualbox_method_invalid_method(self, host_mock): host_object_mock = mock.MagicMock() host_mock.return_value = host_object_mock vm_object_mock = mock.MagicMock() host_object_mock.find_vm.return_value = vm_object_mock del vm_object_mock.foo self.assertRaises(exception.InvalidParameterValue, virtualbox._run_virtualbox_method, self.node, 'some-ironic-method', 'foo', 'args', kwarg='kwarg') host_mock.assert_called_once_with(vmname='baremetal1', host='10.0.2.2', username='username', password='password', port=12345) host_object_mock.find_vm.assert_called_once_with('baremetal1') @mock.patch.object(pyremotevbox_vbox, 'VirtualBoxHost') def test__run_virtualbox_method_vm_wrong_power_state(self, host_mock): host_object_mock = mock.MagicMock() host_mock.return_value = host_object_mock func_mock = mock.MagicMock() vm_object_mock = mock.MagicMock(foo=func_mock) host_object_mock.find_vm.return_value = vm_object_mock func_mock.side_effect = pyremotevbox_exc.VmInWrongPowerState # _run_virtualbox_method() doesn't catch VmInWrongPowerState and # lets caller handle it. self.assertRaises(pyremotevbox_exc.VmInWrongPowerState, virtualbox._run_virtualbox_method, self.node, 'some-ironic-method', 'foo', 'args', kwarg='kwarg') host_mock.assert_called_once_with(vmname='baremetal1', host='10.0.2.2', username='username', password='password', port=12345) host_object_mock.find_vm.assert_called_once_with('baremetal1') func_mock.assert_called_once_with('args', kwarg='kwarg') class VirtualBoxPowerTestCase(db_base.DbTestCase): def setUp(self): super(VirtualBoxPowerTestCase, self).setUp() driver_info = INFO_DICT.copy() mgr_utils.mock_the_extension_manager(driver="fake_vbox") self.node = obj_utils.create_test_node(self.context, driver='fake_vbox', driver_info=driver_info) def test_get_properties(self): with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: properties = task.driver.power.get_properties() self.assertIn('virtualbox_vmname', properties) self.assertIn('virtualbox_host', properties) @mock.patch.object(virtualbox, '_parse_driver_info') def test_validate(self, parse_info_mock): with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: task.driver.power.validate(task) parse_info_mock.assert_called_once_with(task.node) @mock.patch.object(virtualbox, '_run_virtualbox_method') def test_get_power_state(self, run_method_mock): run_method_mock.return_value = 'PoweredOff' with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: power_state = task.driver.power.get_power_state(task) run_method_mock.assert_called_once_with(task.node, 'get_power_state', 'get_power_status') self.assertEqual(states.POWER_OFF, power_state) @mock.patch.object(virtualbox, '_run_virtualbox_method') def test_get_power_state_invalid_state(self, run_method_mock): run_method_mock.return_value = 'invalid-state' with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: power_state = task.driver.power.get_power_state(task) run_method_mock.assert_called_once_with(task.node, 'get_power_state', 'get_power_status') self.assertEqual(states.ERROR, power_state) @mock.patch.object(virtualbox, '_run_virtualbox_method') def test_set_power_state_off(self, run_method_mock): with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: task.driver.power.set_power_state(task, states.POWER_OFF) run_method_mock.assert_called_once_with(task.node, 'set_power_state', 'stop') @mock.patch.object(virtualbox, '_run_virtualbox_method') def test_set_power_state_on(self, run_method_mock): with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: task.driver.power.set_power_state(task, states.POWER_ON) run_method_mock.assert_called_once_with(task.node, 'set_power_state', 'start') @mock.patch.object(virtualbox, '_run_virtualbox_method') def test_set_power_state_reboot(self, run_method_mock): with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: task.driver.power.set_power_state(task, states.REBOOT) run_method_mock.assert_any_call(task.node, 'reboot', 'stop') run_method_mock.assert_any_call(task.node, 'reboot', 'start') def test_set_power_state_invalid_state(self): with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: self.assertRaises(exception.InvalidParameterValue, task.driver.power.set_power_state, task, 'invalid-state') @mock.patch.object(virtualbox, '_run_virtualbox_method') def test_reboot(self, run_method_mock): with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: task.driver.power.reboot(task) run_method_mock.assert_any_call(task.node, 'reboot', 'stop') run_method_mock.assert_any_call(task.node, 'reboot', 'start') class VirtualBoxManagementTestCase(db_base.DbTestCase): def setUp(self): super(VirtualBoxManagementTestCase, self).setUp() driver_info = INFO_DICT.copy() mgr_utils.mock_the_extension_manager(driver="fake_vbox") self.node = obj_utils.create_test_node(self.context, driver='fake_vbox', driver_info=driver_info) def test_get_properties(self): with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: properties = task.driver.management.get_properties() self.assertIn('virtualbox_vmname', properties) self.assertIn('virtualbox_host', properties) @mock.patch.object(virtualbox, '_parse_driver_info') def test_validate(self, parse_info_mock): with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: task.driver.management.validate(task) parse_info_mock.assert_called_once_with(task.node) def test_get_supported_boot_devices(self): with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: devices = task.driver.management.get_supported_boot_devices() self.assertIn(boot_devices.PXE, devices) self.assertIn(boot_devices.DISK, devices) self.assertIn(boot_devices.CDROM, devices) @mock.patch.object(virtualbox, '_run_virtualbox_method') def test_get_boot_device_ok(self, run_method_mock): run_method_mock.return_value = 'Network' with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: ret_val = task.driver.management.get_boot_device(task) run_method_mock.assert_called_once_with(task.node, 'get_boot_device', 'get_boot_device') self.assertEqual(boot_devices.PXE, ret_val['boot_device']) self.assertTrue(ret_val['persistent']) @mock.patch.object(virtualbox, '_run_virtualbox_method') def test_get_boot_device_invalid(self, run_method_mock): run_method_mock.return_value = 'invalid-boot-device' with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: ret_val = task.driver.management.get_boot_device(task) self.assertIsNone(ret_val['boot_device']) self.assertIsNone(ret_val['persistent']) @mock.patch.object(virtualbox, '_run_virtualbox_method') def test_set_boot_device_ok(self, run_method_mock): with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: task.driver.management.set_boot_device(task, boot_devices.PXE) run_method_mock.assert_called_once_with(task.node, 'set_boot_device', 'set_boot_device', 'Network') @mock.patch.object(virtualbox, 'LOG') @mock.patch.object(virtualbox, '_run_virtualbox_method') def test_set_boot_device_wrong_power_state(self, run_method_mock, log_mock): run_method_mock.side_effect = pyremotevbox_exc.VmInWrongPowerState with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: task.driver.management.set_boot_device(task, boot_devices.PXE) log_mock.error.assert_called_once_with(mock.ANY, mock.ANY) @mock.patch.object(virtualbox, '_run_virtualbox_method') def test_set_boot_device_invalid(self, run_method_mock): with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: self.assertRaises(exception.InvalidParameterValue, task.driver.management.set_boot_device, task, 'invalid-boot-device') def test_get_sensors_data(self): with task_manager.acquire(self.context, self.node.uuid, shared=False) as task: self.assertRaises(NotImplementedError, task.driver.management.get_sensors_data, task)
apache-2.0
mjirayu/sit_academy
common/test/acceptance/tests/studio/test_studio_rerun.py
122
4166
""" Acceptance tests for Studio related to course reruns. """ import random from bok_choy.promise import EmptyPromise from nose.tools import assert_in from ...pages.studio.index import DashboardPage from ...pages.studio.course_rerun import CourseRerunPage from ...pages.studio.overview import CourseOutlinePage from ...pages.lms.courseware import CoursewarePage from ...fixtures.course import XBlockFixtureDesc from base_studio_test import StudioCourseTest class CourseRerunTest(StudioCourseTest): """ Feature: Courses can be rerun """ __test__ = True SECTION_NAME = 'Rerun Section' SUBSECITON_NAME = 'Rerun Subsection' UNIT_NAME = 'Rerun Unit' COMPONENT_NAME = 'Rerun Component' COMPONENT_CONTENT = 'Test Content' def setUp(self): """ Login as global staff because that's the only way to rerun a course. """ super(CourseRerunTest, self).setUp(is_staff=True) self.dashboard_page = DashboardPage(self.browser) def populate_course_fixture(self, course_fixture): """ Create a sample course with one section, one subsection, one unit, and one component. """ course_fixture.add_children( XBlockFixtureDesc('chapter', self.SECTION_NAME).add_children( XBlockFixtureDesc('sequential', self.SUBSECITON_NAME).add_children( XBlockFixtureDesc('vertical', self.UNIT_NAME).add_children( XBlockFixtureDesc('html', self.COMPONENT_NAME, self.COMPONENT_CONTENT) ) ) ) ) def test_course_rerun(self): """ Scenario: Courses can be rerun Given I have a course with a section, subsesction, vertical, and html component with content 'Test Content' When I visit the course rerun page And I type 'test_rerun' in the course run field And I click Create Rerun And I visit the course listing page And I wait for all courses to finish processing And I click on the course with run 'test_rerun' Then I see a rerun notification on the course outline page And when I click 'Dismiss' on the notification Then I do not see a rerun notification And when I expand the subsection and click on the unit And I click 'View Live Version' Then I see one html component with the content 'Test Content' """ course_info = (self.course_info['org'], self.course_info['number'], self.course_info['run']) self.dashboard_page.visit() self.dashboard_page.create_rerun(self.course_info['display_name']) rerun_page = CourseRerunPage(self.browser, *course_info) rerun_page.wait_for_page() course_run = 'test_rerun_' + str(random.randrange(1000000, 9999999)) rerun_page.course_run = course_run rerun_page.create_rerun() def finished_processing(): self.dashboard_page.visit() return not self.dashboard_page.has_processing_courses EmptyPromise(finished_processing, "Rerun finished processing", try_interval=5, timeout=60).fulfill() assert_in(course_run, self.dashboard_page.course_runs) self.dashboard_page.click_course_run(course_run) outline_page = CourseOutlinePage(self.browser, *course_info) outline_page.wait_for_page() self.assertTrue(outline_page.has_rerun_notification) outline_page.dismiss_rerun_notification() EmptyPromise(lambda: not outline_page.has_rerun_notification, "Rerun notification dismissed").fulfill() subsection = outline_page.section(self.SECTION_NAME).subsection(self.SUBSECITON_NAME) subsection.expand_subsection() unit_page = subsection.unit(self.UNIT_NAME).go_to() unit_page.view_published_version() courseware = CoursewarePage(self.browser, self.course_id) courseware.wait_for_page() self.assertEqual(courseware.num_xblock_components, 1) self.assertEqual(courseware.xblock_component_html_content(), self.COMPONENT_CONTENT)
agpl-3.0
vnsofthe/odoo-dev
openerp/addons/base/tests/test_res_lang.py
384
2104
import unittest2 import openerp.tests.common as common class test_res_lang(common.TransactionCase): def test_00_intersperse(self): from openerp.addons.base.res.res_lang import intersperse assert intersperse("", []) == ("", 0) assert intersperse("0", []) == ("0", 0) assert intersperse("012", []) == ("012", 0) assert intersperse("1", []) == ("1", 0) assert intersperse("12", []) == ("12", 0) assert intersperse("123", []) == ("123", 0) assert intersperse("1234", []) == ("1234", 0) assert intersperse("123456789", []) == ("123456789", 0) assert intersperse("&ab%#@1", []) == ("&ab%#@1", 0) assert intersperse("0", []) == ("0", 0) assert intersperse("0", [1]) == ("0", 0) assert intersperse("0", [2]) == ("0", 0) assert intersperse("0", [200]) == ("0", 0) assert intersperse("12345678", [1], '.') == ('1234567.8', 1) assert intersperse("12345678", [1], '.') == ('1234567.8', 1) assert intersperse("12345678", [2], '.') == ('123456.78', 1) assert intersperse("12345678", [2,1], '.') == ('12345.6.78', 2) assert intersperse("12345678", [2,0], '.') == ('12.34.56.78', 3) assert intersperse("12345678", [-1,2], '.') == ('12345678', 0) assert intersperse("12345678", [2,-1], '.') == ('123456.78', 1) assert intersperse("12345678", [2,0,1], '.') == ('12.34.56.78', 3) assert intersperse("12345678", [2,0,0], '.') == ('12.34.56.78', 3) assert intersperse("12345678", [2,0,-1], '.') == ('12.34.56.78', 3) assert intersperse("12345678", [3,3,3,3], '.') == ('12.345.678', 2) assert intersperse("abc1234567xy", [2], '.') == ('abc1234567.xy', 1) assert intersperse("abc1234567xy8", [2], '.') == ('abc1234567x.y8', 1) # ... w.r.t. here. assert intersperse("abc12", [3], '.') == ('abc12', 0) assert intersperse("abc12", [2], '.') == ('abc12', 0) assert intersperse("abc12", [1], '.') == ('abc1.2', 1) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
Russell-IO/ansible
lib/ansible/modules/network/slxos/slxos_command.py
25
7951
#!/usr/bin/python # # (c) 2018 Extreme Networks Inc. # # 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/>. # from __future__ import (absolute_import, division, print_function) ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = """ --- module: slxos_command version_added: "2.6" author: "Lindsay Hill (@LindsayHill)" short_description: Run commands on remote devices running Extreme Networks SLX-OS description: - Sends arbitrary commands to an SLX node and returns the results read from the device. This module includes an argument that will cause the module to wait for a specific condition before returning or timing out if the condition is not met. - This module does not support running commands in configuration mode. Please use M(slxos_config) to configure SLX-OS devices. notes: - Tested against SLX-OS 17s.1.02 - If a command sent to the device requires answering a prompt, it is possible to pass a dict containing I(command), I(answer) and I(prompt). See examples. options: commands: description: - List of commands to send to the remote SLX-OS device over the configured provider. The resulting output from the command is returned. If the I(wait_for) argument is provided, the module is not returned until the condition is satisfied or the number of retries has expired. required: true wait_for: description: - List of conditions to evaluate against the output of the command. The task will wait for each condition to be true before moving forward. If the conditional is not true within the configured number of retries, the task fails. See examples. default: null match: description: - The I(match) argument is used in conjunction with the I(wait_for) argument to specify the match policy. Valid values are C(all) or C(any). If the value is set to C(all) then all conditionals in the wait_for must be satisfied. If the value is set to C(any) then only one of the values must be satisfied. required: false default: all choices: ['any', 'all'] retries: description: - Specifies the number of retries a command should by tried before it is considered failed. The command is run on the target device every retry and evaluated against the I(wait_for) conditions. required: false default: 10 interval: description: - Configures the interval in seconds to wait between retries of the command. If the command does not pass the specified conditions, the interval indicates how long to wait before trying the command again. required: false default: 1 """ EXAMPLES = """ tasks: - name: run show version on remote devices slxos_command: commands: show version - name: run show version and check to see if output contains SLX slxos_command: commands: show version wait_for: result[0] contains SLX - name: run multiple commands on remote nodes slxos_command: commands: - show version - show interfaces - name: run multiple commands and evaluate the output slxos_command: commands: - show version - show interface status wait_for: - result[0] contains SLX - result[1] contains Eth - name: run command that requires answering a prompt slxos_command: commands: - command: 'clear sessions' prompt: 'This operation will logout all the user sessions. Do you want to continue (yes/no)?:' answer: y """ RETURN = """ stdout: description: The set of responses from the commands returned: always apart from low level errors (such as action plugin) type: list sample: ['...', '...'] stdout_lines: description: The value of stdout split into a list returned: always apart from low level errors (such as action plugin) type: list sample: [['...', '...'], ['...'], ['...']] failed_conditions: description: The list of conditionals that have failed returned: failed type: list sample: ['...', '...'] """ import re import time from ansible.module_utils.network.slxos.slxos import run_commands from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.common.utils import ComplexList from ansible.module_utils.network.common.parsing import Conditional from ansible.module_utils.six import string_types __metaclass__ = type def to_lines(stdout): for item in stdout: if isinstance(item, string_types): item = str(item).split('\n') yield item def parse_commands(module, warnings): command = ComplexList(dict( command=dict(key=True), prompt=dict(), answer=dict() ), module) commands = command(module.params['commands']) for item in list(commands): configure_type = re.match(r'conf(?:\w*)(?:\s+(\w+))?', item['command']) if module.check_mode: if configure_type and configure_type.group(1) not in ('confirm', 'replace', 'revert', 'network'): module.fail_json( msg='slxos_command does not support running config mode ' 'commands. Please use slxos_config instead' ) if not item['command'].startswith('show'): warnings.append( 'only show commands are supported when using check mode, not ' 'executing `%s`' % item['command'] ) commands.remove(item) return commands def main(): """main entry point for module execution """ argument_spec = dict( commands=dict(type='list', required=True), wait_for=dict(type='list'), match=dict(default='all', choices=['all', 'any']), retries=dict(default=10, type='int'), interval=dict(default=1, type='int') ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) result = {'changed': False} warnings = list() commands = parse_commands(module, warnings) result['warnings'] = warnings wait_for = module.params['wait_for'] or list() conditionals = [Conditional(c) for c in wait_for] retries = module.params['retries'] interval = module.params['interval'] match = module.params['match'] while retries > 0: responses = run_commands(module, commands) for item in list(conditionals): if item(responses): if match == 'any': conditionals = list() break conditionals.remove(item) if not conditionals: break time.sleep(interval) retries -= 1 if conditionals: failed_conditions = [item.raw for item in conditionals] msg = 'One or more conditional statements have not been satisfied' module.fail_json(msg=msg, failed_conditions=failed_conditions) result.update({ 'changed': False, 'stdout': responses, 'stdout_lines': list(to_lines(responses)) }) module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
niteshch207/universe
scripts/generate-config-reference.py
3
3017
#!/usr/bin/env python3 """This script builds a Markdown file containing configuration references for all packages (and all package versions) contained in the Mesosphere DC/OS Universe repository. It outputs a single file, 'config-reference.md' in the current working directory. Usage: ./generate-config-reference.py [/path/to/universe/repo/packages] """ import json import os import sys def find_config_files(path): config_files = [] for root, dirs, files in os.walk(path): for f in files: if f == 'config.json': config_files.append(os.path.join(root, f)) return config_files def main(path): files = find_config_files(path) outfile = open(os.path.join(os.getcwd(), 'config-reference.md'), 'w') outfile.write("# DC/OS Universe Package Configuration Reference\n\n") for f in files: with open(f, 'r') as config: package_name = f.split('/')[-3] package_version = f.split('/')[-2] outfile.write("## {} version {}\n\n".format(package_name, package_version)) props = json.loads(config.read())['properties'] for key, value in props.items(): if key == "properties": outfile.write("*Errors encountered when processing config properties. Not all properties may be listed here. Please verify the structure of this package and package version.*\n\n") continue outfile.write("### {} configuration properties\n\n".format(key)) outfile.write("| Property | Type | Description | Default Value |\n") outfile.write("|----------|------|-------------|---------------|\n") for _, prop in value.items(): if type(prop) is not dict: continue for key, details in prop.items(): prop = key try: typ = details['type'] except KeyError: typ = "*No type provided.*" try: desc = details['description'] except KeyError: desc = "*No description provided.*" try: default = "`{}`".format(details['default']) if default == "``": default = "*Empty string.*" except KeyError: default = "*No default.*" outfile.write("| {prop} | {typ} | {desc} | {default} |\n".format( prop=prop, desc=desc, typ=typ, default=default)) outfile.write("\n") outfile.close() if __name__ == '__main__': if len(sys.argv) == 2: path = sys.argv[1] else: path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../repo/packages') main(path)
apache-2.0
kamcpp/tensorflow
tensorflow/contrib/opt/__init__.py
11
1119
# 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. # ============================================================================== """opt: A module containing optimization routines.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=wildcard-import from tensorflow.contrib.opt.python.training.external_optimizer import * from tensorflow.contrib.opt.python.training.moving_average_optimizer import * from tensorflow.contrib.opt.python.training.variable_clipping_optimizer import *
apache-2.0
LarsFronius/ansible
lib/ansible/modules/cloud/ovirt/ovirt_external_providers_facts.py
7
5916
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2016 Red Hat, Inc. # # 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/>. # ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ovirt_external_providers_facts short_description: Retrieve facts about one or more oVirt/RHV external providers author: "Ondra Machacek (@machacekondra)" version_added: "2.3" description: - "Retrieve facts about one or more oVirt/RHV external providers." notes: - "This module creates a new top-level C(ovirt_external_providers) fact, which contains a list of external_providers." options: type: description: - "Type of the external provider." choices: ['os_image', 'os_network', 'os_volume', 'foreman'] required: true name: description: - "Name of the external provider, can be used as glob expression." extends_documentation_fragment: ovirt_facts ''' EXAMPLES = ''' # Examples don't contain auth parameter for simplicity, # look at ovirt_auth module to see how to reuse authentication: # Gather facts about all image external providers named C<glance>: - ovirt_external_providers_facts: type: os_image name: glance - debug: var: ovirt_external_providers ''' RETURN = ''' external_host_providers: description: "List of dictionaries of all the external_host_provider attributes. External provider attributes can be found on your oVirt/RHV instance at following url: https://ovirt.example.com/ovirt-engine/api/model#types/external_host_provider." returned: "On success and if parameter 'type: foreman' is used." type: list openstack_image_providers: description: "List of dictionaries of all the openstack_image_provider attributes. External provider attributes can be found on your oVirt/RHV instance at following url: https://ovirt.example.com/ovirt-engine/api/model#types/openstack_image_provider." returned: "On success and if parameter 'type: os_image' is used." type: list openstack_volume_providers: description: "List of dictionaries of all the openstack_volume_provider attributes. External provider attributes can be found on your oVirt/RHV instance at following url: https://ovirt.example.com/ovirt-engine/api/model#types/openstack_volume_provider." returned: "On success and if parameter 'type: os_volume' is used." type: list openstack_network_providers: description: "List of dictionaries of all the openstack_network_provider attributes. External provider attributes can be found on your oVirt/RHV instance at following url: https://ovirt.example.com/ovirt-engine/api/model#types/openstack_network_provider." returned: "On success and if parameter 'type: os_network' is used." type: list ''' import fnmatch import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ovirt import ( check_sdk, create_connection, get_dict_of_struct, ovirt_facts_full_argument_spec, ) def _external_provider_service(provider_type, system_service): if provider_type == 'os_image': return system_service.openstack_image_providers_service() elif provider_type == 'os_network': return system_service.openstack_network_providers_service() elif provider_type == 'os_volume': return system_service.openstack_volume_providers_service() elif provider_type == 'foreman': return system_service.external_host_providers_service() def main(): argument_spec = ovirt_facts_full_argument_spec( name=dict(default=None, required=False), type=dict( default=None, required=True, choices=[ 'os_image', 'os_network', 'os_volume', 'foreman', ], aliases=['provider'], ), ) module = AnsibleModule(argument_spec) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) external_providers_service = _external_provider_service( provider_type=module.params.pop('type'), system_service=connection.system_service(), ) if module.params['name']: external_providers = [ e for e in external_providers_service.list() if fnmatch.fnmatch(e.name, module.params['name']) ] else: external_providers = external_providers_service.list() module.exit_json( changed=False, ansible_facts=dict( ovirt_external_providers=[ get_dict_of_struct( struct=c, connection=connection, fetch_nested=module.params.get('fetch_nested'), attributes=module.params.get('nested_attributes'), ) for c in external_providers ], ), ) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None) if __name__ == '__main__': main()
gpl-3.0
jeffery-do/Vizdoombot
doom/lib/python3.5/site-packages/scipy/optimize/nnls.py
116
1423
from __future__ import division, print_function, absolute_import from . import _nnls from numpy import asarray_chkfinite, zeros, double __all__ = ['nnls'] def nnls(A, b): """ Solve ``argmin_x || Ax - b ||_2`` for ``x>=0``. This is a wrapper for a FORTAN non-negative least squares solver. Parameters ---------- A : ndarray Matrix ``A`` as shown above. b : ndarray Right-hand side vector. Returns ------- x : ndarray Solution vector. rnorm : float The residual, ``|| Ax-b ||_2``. Notes ----- The FORTRAN code was published in the book below. The algorithm is an active set method. It solves the KKT (Karush-Kuhn-Tucker) conditions for the non-negative least squares problem. References ---------- Lawson C., Hanson R.J., (1987) Solving Least Squares Problems, SIAM """ A, b = map(asarray_chkfinite, (A, b)) if len(A.shape) != 2: raise ValueError("expected matrix") if len(b.shape) != 1: raise ValueError("expected vector") m, n = A.shape if m != b.shape[0]: raise ValueError("incompatible dimensions") w = zeros((n,), dtype=double) zz = zeros((m,), dtype=double) index = zeros((n,), dtype=int) x, rnorm, mode = _nnls.nnls(A, m, n, b, w, zz, index) if mode != 1: raise RuntimeError("too many iterations") return x, rnorm
mit
nugget/home-assistant
tests/components/frontend/test_storage.py
10
4742
"""The tests for frontend storage.""" import pytest from homeassistant.setup import async_setup_component from homeassistant.components.frontend import storage @pytest.fixture(autouse=True) def setup_frontend(hass): """Fixture to setup the frontend.""" hass.loop.run_until_complete(async_setup_component(hass, 'frontend', {})) async def test_get_user_data_empty(hass, hass_ws_client, hass_storage): """Test get_user_data command.""" client = await hass_ws_client(hass) await client.send_json({ 'id': 5, 'type': 'frontend/get_user_data', 'key': 'non-existing-key', }) res = await client.receive_json() assert res['success'], res assert res['result']['value'] is None async def test_get_user_data(hass, hass_ws_client, hass_admin_user, hass_storage): """Test get_user_data command.""" storage_key = storage.STORAGE_KEY_USER_DATA.format(hass_admin_user.id) hass_storage[storage_key] = { 'key': storage_key, 'version': 1, 'data': { 'test-key': 'test-value', 'test-complex': [{'foo': 'bar'}] } } client = await hass_ws_client(hass) # Get a simple string key await client.send_json({ 'id': 6, 'type': 'frontend/get_user_data', 'key': 'test-key', }) res = await client.receive_json() assert res['success'], res assert res['result']['value'] == 'test-value' # Get a more complex key await client.send_json({ 'id': 7, 'type': 'frontend/get_user_data', 'key': 'test-complex', }) res = await client.receive_json() assert res['success'], res assert res['result']['value'][0]['foo'] == 'bar' # Get all data (no key) await client.send_json({ 'id': 8, 'type': 'frontend/get_user_data', }) res = await client.receive_json() assert res['success'], res assert res['result']['value']['test-key'] == 'test-value' assert res['result']['value']['test-complex'][0]['foo'] == 'bar' async def test_set_user_data_empty(hass, hass_ws_client, hass_storage): """Test set_user_data command.""" client = await hass_ws_client(hass) # test creating await client.send_json({ 'id': 6, 'type': 'frontend/get_user_data', 'key': 'test-key', }) res = await client.receive_json() assert res['success'], res assert res['result']['value'] is None await client.send_json({ 'id': 7, 'type': 'frontend/set_user_data', 'key': 'test-key', 'value': 'test-value' }) res = await client.receive_json() assert res['success'], res await client.send_json({ 'id': 8, 'type': 'frontend/get_user_data', 'key': 'test-key', }) res = await client.receive_json() assert res['success'], res assert res['result']['value'] == 'test-value' async def test_set_user_data(hass, hass_ws_client, hass_storage, hass_admin_user): """Test set_user_data command with initial data.""" storage_key = storage.STORAGE_KEY_USER_DATA.format(hass_admin_user.id) hass_storage[storage_key] = { 'version': 1, 'data': { 'test-key': 'test-value', 'test-complex': 'string', } } client = await hass_ws_client(hass) # test creating await client.send_json({ 'id': 5, 'type': 'frontend/set_user_data', 'key': 'test-non-existent-key', 'value': 'test-value-new' }) res = await client.receive_json() assert res['success'], res await client.send_json({ 'id': 6, 'type': 'frontend/get_user_data', 'key': 'test-non-existent-key', }) res = await client.receive_json() assert res['success'], res assert res['result']['value'] == 'test-value-new' # test updating with complex data await client.send_json({ 'id': 7, 'type': 'frontend/set_user_data', 'key': 'test-complex', 'value': [{'foo': 'bar'}] }) res = await client.receive_json() assert res['success'], res await client.send_json({ 'id': 8, 'type': 'frontend/get_user_data', 'key': 'test-complex', }) res = await client.receive_json() assert res['success'], res assert res['result']['value'][0]['foo'] == 'bar' # ensure other existing key was not modified await client.send_json({ 'id': 9, 'type': 'frontend/get_user_data', 'key': 'test-key', }) res = await client.receive_json() assert res['success'], res assert res['result']['value'] == 'test-value'
apache-2.0
mdanielwork/intellij-community
python/testData/MockSdk2.7/python_stubs/__builtin__.py
19
174731
# encoding: utf-8 # module __builtin__ # from (built-in) # by generator 1.145 from __future__ import print_function """ Built-in functions, exceptions, and other objects. Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices. """ # imports from exceptions import (ArithmeticError, AssertionError, AttributeError, BaseException, BufferError, BytesWarning, DeprecationWarning, EOFError, EnvironmentError, Exception, FloatingPointError, FutureWarning, GeneratorExit, IOError, ImportError, ImportWarning, IndentationError, IndexError, KeyError, KeyboardInterrupt, LookupError, MemoryError, NameError, NotImplementedError, OSError, OverflowError, PendingDeprecationWarning, ReferenceError, RuntimeError, RuntimeWarning, StandardError, StopIteration, SyntaxError, SyntaxWarning, SystemError, SystemExit, TabError, TypeError, UnboundLocalError, UnicodeDecodeError, UnicodeEncodeError, UnicodeError, UnicodeTranslateError, UnicodeWarning, UserWarning, ValueError, Warning, ZeroDivisionError) # Variables with simple values False = False None = object() # real value of type <type 'NoneType'> replaced True = True __debug__ = True # functions def abs(number): # real signature unknown; restored from __doc__ """ abs(number) -> number Return the absolute value of the argument. """ return 0 def all(iterable): # real signature unknown; restored from __doc__ """ all(iterable) -> bool Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True. """ return False def any(iterable): # real signature unknown; restored from __doc__ """ any(iterable) -> bool Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False. """ return False def apply(p_object, args=None, kwargs=None): # real signature unknown; restored from __doc__ """ apply(object[, args[, kwargs]]) -> value Call a callable object with positional arguments taken from the tuple args, and keyword arguments taken from the optional dictionary kwargs. Note that classes are callable, as are instances with a __call__() method. Deprecated since release 2.3. Instead, use the extended call syntax: function(*args, **keywords). """ pass def bin(number): # real signature unknown; restored from __doc__ """ bin(number) -> string Return the binary representation of an integer or long integer. """ return "" def callable(p_object): # real signature unknown; restored from __doc__ """ callable(object) -> bool Return whether the object is callable (i.e., some kind of function). Note that classes are callable, as are instances with a __call__() method. """ return False def chr(i): # real signature unknown; restored from __doc__ """ chr(i) -> character Return a string of one character with ordinal i; 0 <= i < 256. """ return "" def cmp(x, y): # real signature unknown; restored from __doc__ """ cmp(x, y) -> integer Return negative if x<y, zero if x==y, positive if x>y. """ return 0 def coerce(x, y): # real signature unknown; restored from __doc__ """ coerce(x, y) -> (x1, y1) Return a tuple consisting of the two numeric arguments converted to a common type, using the same rules as used by arithmetic operations. If coercion is not possible, raise TypeError. """ pass def compile(source, filename, mode, flags=None, dont_inherit=None): # real signature unknown; restored from __doc__ """ compile(source, filename, mode[, flags[, dont_inherit]]) -> code object Compile the source string (a Python module, statement or expression) into a code object that can be executed by the exec statement or eval(). The filename will be used for run-time error messages. The mode must be 'exec' to compile a module, 'single' to compile a single (interactive) statement, or 'eval' to compile an expression. The flags argument, if present, controls which future statements influence the compilation of the code. The dont_inherit argument, if non-zero, stops the compilation inheriting the effects of any future statements in effect in the code calling compile; if absent or zero these statements do influence the compilation, in addition to any features explicitly specified. """ pass def copyright(*args, **kwargs): # real signature unknown """ interactive prompt objects for printing the license text, a list of contributors and the copyright notice. """ pass def credits(*args, **kwargs): # real signature unknown """ interactive prompt objects for printing the license text, a list of contributors and the copyright notice. """ pass def delattr(p_object, name): # real signature unknown; restored from __doc__ """ delattr(object, name) Delete a named attribute on an object; delattr(x, 'y') is equivalent to ``del x.y''. """ pass def dir(p_object=None): # real signature unknown; restored from __doc__ """ dir([object]) -> list of strings If called without an argument, return the names in the current scope. Else, return an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it. If the object supplies a method named __dir__, it will be used; otherwise the default dir() logic is used and returns: for a module object: the module's attributes. for a class object: its attributes, and recursively the attributes of its bases. for any other object: its attributes, its class's attributes, and recursively the attributes of its class's base classes. """ return [] def divmod(x, y): # known case of __builtin__.divmod """ divmod(x, y) -> (quotient, remainder) Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x. """ return (0, 0) def eval(source, globals=None, locals=None): # real signature unknown; restored from __doc__ """ eval(source[, globals[, locals]]) -> value Evaluate the source in the context of globals and locals. The source may be a string representing a Python expression or a code object as returned by compile(). The globals must be a dictionary and locals can be any mapping, defaulting to the current globals and locals. If only globals is given, locals defaults to it. """ pass def execfile(filename, globals=None, locals=None): # real signature unknown; restored from __doc__ """ execfile(filename[, globals[, locals]]) Read and execute a Python script from a file. The globals and locals are dictionaries, defaulting to the current globals and locals. If only globals is given, locals defaults to it. """ pass def exit(*args, **kwargs): # real signature unknown pass def filter(function_or_none, sequence): # known special case of filter """ filter(function or None, sequence) -> list, tuple, or string Return those items of sequence for which function(item) is true. If function is None, return the items that are true. If sequence is a tuple or string, return the same type, else return a list. """ pass def format(value, format_spec=None): # real signature unknown; restored from __doc__ """ format(value[, format_spec]) -> string Returns value.__format__(format_spec) format_spec defaults to "" """ return "" def getattr(object, name, default=None): # known special case of getattr """ getattr(object, name[, default]) -> value Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y. When a default argument is given, it is returned when the attribute doesn't exist; without it, an exception is raised in that case. """ pass def globals(): # real signature unknown; restored from __doc__ """ globals() -> dictionary Return the dictionary containing the current scope's global variables. """ return {} def hasattr(p_object, name): # real signature unknown; restored from __doc__ """ hasattr(object, name) -> bool Return whether the object has an attribute with the given name. (This is done by calling getattr(object, name) and catching exceptions.) """ return False def hash(p_object): # real signature unknown; restored from __doc__ """ hash(object) -> integer Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely. """ return 0 def help(with_a_twist): # real signature unknown; restored from __doc__ """ Define the built-in 'help'. This is a wrapper around pydoc.help (with a twist). """ pass def hex(number): # real signature unknown; restored from __doc__ """ hex(number) -> string Return the hexadecimal representation of an integer or long integer. """ return "" def id(p_object): # real signature unknown; restored from __doc__ """ id(object) -> integer Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.) """ return 0 def input(prompt=None): # real signature unknown; restored from __doc__ """ input([prompt]) -> value Equivalent to eval(raw_input(prompt)). """ pass def intern(string): # real signature unknown; restored from __doc__ """ intern(string) -> string ``Intern'' the given string. This enters the string in the (global) table of interned strings whose purpose is to speed up dictionary lookups. Return the string itself or the previously interned string object with the same value. """ return "" def isinstance(p_object, class_or_type_or_tuple): # real signature unknown; restored from __doc__ """ isinstance(object, class-or-type-or-tuple) -> bool Return whether an object is an instance of a class or of a subclass thereof. With a type as second argument, return whether that is the object's type. The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for isinstance(x, A) or isinstance(x, B) or ... (etc.). """ return False def issubclass(C, B): # real signature unknown; restored from __doc__ """ issubclass(C, B) -> bool Return whether class C is a subclass (i.e., a derived class) of class B. When using a tuple as the second argument issubclass(X, (A, B, ...)), is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.). """ return False def iter(source, sentinel=None): # known special case of iter """ iter(collection) -> iterator iter(callable, sentinel) -> iterator Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence. In the second form, the callable is called until it returns the sentinel. """ pass def len(p_object): # real signature unknown; restored from __doc__ """ len(object) -> integer Return the number of items of a sequence or collection. """ return 0 def license(*args, **kwargs): # real signature unknown """ interactive prompt objects for printing the license text, a list of contributors and the copyright notice. """ pass def locals(): # real signature unknown; restored from __doc__ """ locals() -> dictionary Update and return a dictionary containing the current scope's local variables. """ return {} def map(function, sequence, *sequence_1): # real signature unknown; restored from __doc__ """ map(function, sequence[, sequence, ...]) -> list Return a list of the results of applying the function to the items of the argument sequence(s). If more than one sequence is given, the function is called with an argument list consisting of the corresponding item of each sequence, substituting None for missing values when not all sequences have the same length. If the function is None, return a list of the items of the sequence (or a list of tuples if more than one sequence). """ return [] def max(*args, **kwargs): # known special case of max """ max(iterable[, key=func]) -> value max(a, b, c, ...[, key=func]) -> value With a single iterable argument, return its largest item. With two or more arguments, return the largest argument. """ pass def min(*args, **kwargs): # known special case of min """ min(iterable[, key=func]) -> value min(a, b, c, ...[, key=func]) -> value With a single iterable argument, return its smallest item. With two or more arguments, return the smallest argument. """ pass def next(iterator, default=None): # real signature unknown; restored from __doc__ """ next(iterator[, default]) Return the next item from the iterator. If default is given and the iterator is exhausted, it is returned instead of raising StopIteration. """ pass def oct(number): # real signature unknown; restored from __doc__ """ oct(number) -> string Return the octal representation of an integer or long integer. """ return "" def open(name, mode=None, buffering=None): # real signature unknown; restored from __doc__ """ open(name[, mode[, buffering]]) -> file object Open a file using the file() type, returns a file object. This is the preferred way to open a file. See file.__doc__ for further information. """ return file('/dev/null') def ord(c): # real signature unknown; restored from __doc__ """ ord(c) -> integer Return the integer ordinal of a one-character string. """ return 0 def pow(x, y, z=None): # real signature unknown; restored from __doc__ """ pow(x, y[, z]) -> number With two arguments, equivalent to x**y. With three arguments, equivalent to (x**y) % z, but may be more efficient (e.g. for longs). """ return 0 def print(*args, **kwargs): # known special case of print """ print(value, ..., sep=' ', end='\n', file=sys.stdout) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. """ pass def quit(*args, **kwargs): # real signature unknown pass def range(start=None, stop=None, step=None): # known special case of range """ range(stop) -> list of integers range(start, stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. """ pass def raw_input(prompt=None): # real signature unknown; restored from __doc__ """ raw_input([prompt]) -> string Read a string from standard input. The trailing newline is stripped. If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError. On Unix, GNU readline is used if enabled. The prompt string, if given, is printed without a trailing newline before reading. """ return "" def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__ """ reduce(function, sequence[, initial]) -> value Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty. """ pass def reload(module): # real signature unknown; restored from __doc__ """ reload(module) -> module Reload the module. The module must have been successfully imported before. """ pass def repr(p_object): # real signature unknown; restored from __doc__ """ repr(object) -> string Return the canonical string representation of the object. For most object types, eval(repr(object)) == object. """ return "" def round(number, ndigits=None): # real signature unknown; restored from __doc__ """ round(number[, ndigits]) -> floating point number Round a number to a given precision in decimal digits (default 0 digits). This always returns a floating point number. Precision may be negative. """ return 0.0 def setattr(p_object, name, value): # real signature unknown; restored from __doc__ """ setattr(object, name, value) Set a named attribute on an object; setattr(x, 'y', v) is equivalent to ``x.y = v''. """ pass def sorted(iterable, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__ """ sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list """ pass def sum(sequence, start=None): # real signature unknown; restored from __doc__ """ sum(sequence[, start]) -> value Return the sum of a sequence of numbers (NOT strings) plus the value of parameter 'start' (which defaults to 0). When the sequence is empty, return start. """ pass def unichr(i): # real signature unknown; restored from __doc__ """ unichr(i) -> Unicode character Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. """ return u"" def vars(p_object=None): # real signature unknown; restored from __doc__ """ vars([object]) -> dictionary Without arguments, equivalent to locals(). With an argument, equivalent to object.__dict__. """ return {} def zip(seq1, seq2, *more_seqs): # known special case of zip """ zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] Return a list of tuples, where each tuple contains the i-th element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument sequence. """ pass def __import__(name, globals={}, locals={}, fromlist=[], level=-1): # real signature unknown; restored from __doc__ """ __import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module Import a module. Because this function is meant for use by the Python interpreter and not for general use it is better to use importlib.import_module() to programmatically import a module. The globals argument is only used to determine the context; they are not modified. The locals argument is unused. The fromlist should be a list of names to emulate ``from name import ...'', or an empty list to emulate ``import name''. When importing a module from a package, note that __import__('A.B', ...) returns package A when fromlist is empty, but its submodule B when fromlist is not empty. Level is used to determine whether to perform absolute or relative imports. -1 is the original strategy of attempting both absolute and relative imports, 0 is absolute, a positive number is the number of parent directories to search relative to the current module. """ pass # classes class ___Classobj: '''A mock class representing the old style class base.''' __module__ = '' __class__ = None def __init__(self): pass __dict__ = {} __doc__ = '' class __generator(object): '''A mock class representing the generator function type.''' def __init__(self): self.gi_code = None self.gi_frame = None self.gi_running = 0 def __iter__(self): '''Defined to support iteration over container.''' pass def next(self): '''Return the next item from the container.''' pass def close(self): '''Raises new GeneratorExit exception inside the generator to terminate the iteration.''' pass def send(self, value): '''Resumes the generator and "sends" a value that becomes the result of the current yield-expression.''' pass def throw(self, type, value=None, traceback=None): '''Used to raise an exception inside the generator.''' pass class __function(object): '''A mock class representing function type.''' def __init__(self): self.__name__ = '' self.__doc__ = '' self.__dict__ = '' self.__module__ = '' self.func_defaults = {} self.func_globals = {} self.func_closure = None self.func_code = None self.func_name = '' self.func_doc = '' self.func_dict = '' self.__defaults__ = {} self.__globals__ = {} self.__closure__ = None self.__code__ = None self.__name__ = '' class __method(object): '''A mock class representing method type.''' def __init__(self): self.im_class = None self.im_self = None self.im_func = None self.__func__ = None self.__self__ = None class __namedtuple(tuple): '''A mock base class for named tuples.''' __slots__ = () _fields = () def __new__(cls, *args, **kwargs): 'Create a new instance of the named tuple.' return tuple.__new__(cls, *args) @classmethod def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new named tuple object from a sequence or iterable.' return new(cls, iterable) def __repr__(self): return '' def _asdict(self): 'Return a new dict which maps field types to their values.' return {} def _replace(self, **kwargs): 'Return a new named tuple object replacing specified fields with new values.' return self def __getnewargs__(self): return tuple(self) class object: """ The most base type """ def __delattr__(self, name): # real signature unknown; restored from __doc__ """ x.__delattr__('name') <==> del x.name """ pass def __format__(self, *args, **kwargs): # real signature unknown """ default object formatter """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self): # known special case of object.__init__ """ x.__init__(...) initializes x; see help(type(x)) for signature """ pass @staticmethod # known case of __new__ def __new__(cls, *more): # known special case of object.__new__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __reduce_ex__(self, *args, **kwargs): # real signature unknown """ helper for pickle """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ helper for pickle """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setattr__(self, name, value): # real signature unknown; restored from __doc__ """ x.__setattr__('name', value) <==> x.name = value """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ __sizeof__() -> int size of object in memory, in bytes """ return 0 def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass @classmethod # known case def __subclasshook__(cls, subclass): # known special case of object.__subclasshook__ """ Abstract classes can override this to customize issubclass(). This is invoked early on by abc.ABCMeta.__subclasscheck__(). It should return True, False or NotImplemented. If it returns NotImplemented, the normal algorithm is used. Otherwise, it overrides the normal algorithm (and the outcome is cached). """ pass __class__ = None # (!) forward: type, real value is '' __dict__ = {} __doc__ = '' __module__ = '' class basestring(object): """ Type basestring cannot be instantiated; it is the base for str and unicode. """ def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass class int(object): """ int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) 4 """ def bit_length(self): # real signature unknown; restored from __doc__ """ int.bit_length() -> int Number of bits necessary to represent self in binary. >>> bin(37) '0b100101' >>> (37).bit_length() 6 """ return 0 def conjugate(self, *args, **kwargs): # real signature unknown """ Returns self, the complex conjugate of any int. """ pass def __abs__(self): # real signature unknown; restored from __doc__ """ x.__abs__() <==> abs(x) """ pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __and__(self, y): # real signature unknown; restored from __doc__ """ x.__and__(y) <==> x&y """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __coerce__(self, y): # real signature unknown; restored from __doc__ """ x.__coerce__(y) <==> coerce(x, y) """ pass def __divmod__(self, y): # real signature unknown; restored from __doc__ """ x.__divmod__(y) <==> divmod(x, y) """ pass def __div__(self, y): # real signature unknown; restored from __doc__ """ x.__div__(y) <==> x/y """ pass def __float__(self): # real signature unknown; restored from __doc__ """ x.__float__() <==> float(x) """ pass def __floordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__floordiv__(y) <==> x//y """ pass def __format__(self, *args, **kwargs): # real signature unknown pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __hex__(self): # real signature unknown; restored from __doc__ """ x.__hex__() <==> hex(x) """ pass def __index__(self): # real signature unknown; restored from __doc__ """ x[y:z] <==> x[y.__index__():z.__index__()] """ pass def __init__(self, x, base=10): # known special case of int.__init__ """ int(x=0) -> int or long int(x, base=10) -> int or long Convert a number or string to an integer, or return 0 if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is outside the integer range, the function returns a long instead. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) 4 # (copied from class doc) """ pass def __int__(self): # real signature unknown; restored from __doc__ """ x.__int__() <==> int(x) """ pass def __invert__(self): # real signature unknown; restored from __doc__ """ x.__invert__() <==> ~x """ pass def __long__(self): # real signature unknown; restored from __doc__ """ x.__long__() <==> long(x) """ pass def __lshift__(self, y): # real signature unknown; restored from __doc__ """ x.__lshift__(y) <==> x<<y """ pass def __mod__(self, y): # real signature unknown; restored from __doc__ """ x.__mod__(y) <==> x%y """ pass def __mul__(self, y): # real signature unknown; restored from __doc__ """ x.__mul__(y) <==> x*y """ pass def __neg__(self): # real signature unknown; restored from __doc__ """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __nonzero__(self): # real signature unknown; restored from __doc__ """ x.__nonzero__() <==> x != 0 """ pass def __oct__(self): # real signature unknown; restored from __doc__ """ x.__oct__() <==> oct(x) """ pass def __or__(self, y): # real signature unknown; restored from __doc__ """ x.__or__(y) <==> x|y """ pass def __pos__(self): # real signature unknown; restored from __doc__ """ x.__pos__() <==> +x """ pass def __pow__(self, y, z=None): # real signature unknown; restored from __doc__ """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ pass def __radd__(self, y): # real signature unknown; restored from __doc__ """ x.__radd__(y) <==> y+x """ pass def __rand__(self, y): # real signature unknown; restored from __doc__ """ x.__rand__(y) <==> y&x """ pass def __rdivmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rdivmod__(y) <==> divmod(y, x) """ pass def __rdiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rdiv__(y) <==> y/x """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rfloordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rfloordiv__(y) <==> y//x """ pass def __rlshift__(self, y): # real signature unknown; restored from __doc__ """ x.__rlshift__(y) <==> y<<x """ pass def __rmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, y): # real signature unknown; restored from __doc__ """ x.__rmul__(y) <==> y*x """ pass def __ror__(self, y): # real signature unknown; restored from __doc__ """ x.__ror__(y) <==> y|x """ pass def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__ """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ pass def __rrshift__(self, y): # real signature unknown; restored from __doc__ """ x.__rrshift__(y) <==> y>>x """ pass def __rshift__(self, y): # real signature unknown; restored from __doc__ """ x.__rshift__(y) <==> x>>y """ pass def __rsub__(self, y): # real signature unknown; restored from __doc__ """ x.__rsub__(y) <==> y-x """ pass def __rtruediv__(self, y): # real signature unknown; restored from __doc__ """ x.__rtruediv__(y) <==> y/x """ pass def __rxor__(self, y): # real signature unknown; restored from __doc__ """ x.__rxor__(y) <==> y^x """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass def __sub__(self, y): # real signature unknown; restored from __doc__ """ x.__sub__(y) <==> x-y """ pass def __truediv__(self, y): # real signature unknown; restored from __doc__ """ x.__truediv__(y) <==> x/y """ pass def __trunc__(self, *args, **kwargs): # real signature unknown """ Truncating an Integral returns itself. """ pass def __xor__(self, y): # real signature unknown; restored from __doc__ """ x.__xor__(y) <==> x^y """ pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the real part of a complex number""" class bool(int): """ bool(x) -> bool Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed. """ def __and__(self, y): # real signature unknown; restored from __doc__ """ x.__and__(y) <==> x&y """ pass def __init__(self, x): # real signature unknown; restored from __doc__ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __or__(self, y): # real signature unknown; restored from __doc__ """ x.__or__(y) <==> x|y """ pass def __rand__(self, y): # real signature unknown; restored from __doc__ """ x.__rand__(y) <==> y&x """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __ror__(self, y): # real signature unknown; restored from __doc__ """ x.__ror__(y) <==> y|x """ pass def __rxor__(self, y): # real signature unknown; restored from __doc__ """ x.__rxor__(y) <==> y^x """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass def __xor__(self, y): # real signature unknown; restored from __doc__ """ x.__xor__(y) <==> x^y """ pass class buffer(object): """ buffer(object [, offset[, size]]) Create a new buffer object which references the given object. The buffer will reference a slice of the target object from the start of the object (or at the specified offset). The slice will extend to the end of the target object (or with the specified size). """ def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __delslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__delslice__(i, j) <==> del x[i:j] Use of negative indices is not supported. """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, p_object, offset=None, size=None): # real signature unknown; restored from __doc__ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __mul__(self, n): # real signature unknown; restored from __doc__ """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__ """ x.__setslice__(i, j, y) <==> x[i:j]=y Use of negative indices is not supported. """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass class bytearray(object): """ bytearray(iterable_of_ints) -> bytearray. bytearray(string, encoding[, errors]) -> bytearray. bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray. bytearray(memory_view) -> bytearray. Construct an mutable bytearray object from: - an iterable yielding integers in range(256) - a text string encoded using the specified encoding - a bytes or a bytearray object - any object implementing the buffer API. bytearray(int) -> bytearray. Construct a zero-initialized bytearray of the given length. """ def append(self, p_int): # real signature unknown; restored from __doc__ """ B.append(int) -> None Append a single item to the end of B. """ pass def capitalize(self): # real signature unknown; restored from __doc__ """ B.capitalize() -> copy of B Return a copy of B with only its first character capitalized (ASCII) and the rest lower-cased. """ pass def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ B.center(width[, fillchar]) -> copy of B Return B centered in a string of length width. Padding is done using the specified fill character (default is a space). """ pass def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ B.count(sub [,start [,end]]) -> int Return the number of non-overlapping occurrences of subsection sub in bytes B[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return 0 def decode(self, encoding=None, errors=None): # real signature unknown; restored from __doc__ """ B.decode([encoding[, errors]]) -> unicode object. Decodes B using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. """ return u"" def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """ B.endswith(suffix [,start [,end]]) -> bool Return True if B ends with the specified suffix, False otherwise. With optional start, test B beginning at that position. With optional end, stop comparing B at that position. suffix can also be a tuple of strings to try. """ return False def expandtabs(self, tabsize=None): # real signature unknown; restored from __doc__ """ B.expandtabs([tabsize]) -> copy of B Return a copy of B where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ pass def extend(self, iterable_int): # real signature unknown; restored from __doc__ """ B.extend(iterable int) -> None Append all the elements from the iterator or sequence to the end of B. """ pass def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ B.find(sub [,start [,end]]) -> int Return the lowest index in B where subsection sub is found, such that sub is contained within B[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 @classmethod # known case def fromhex(cls, string): # real signature unknown; restored from __doc__ """ bytearray.fromhex(string) -> bytearray Create a bytearray object from a string of hexadecimal numbers. Spaces between two numbers are accepted. Example: bytearray.fromhex('B9 01EF') -> bytearray(b'\xb9\x01\xef'). """ return bytearray def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ B.index(sub [,start [,end]]) -> int Like B.find() but raise ValueError when the subsection is not found. """ return 0 def insert(self, index, p_int): # real signature unknown; restored from __doc__ """ B.insert(index, int) -> None Insert a single item into the bytearray before the given index. """ pass def isalnum(self): # real signature unknown; restored from __doc__ """ B.isalnum() -> bool Return True if all characters in B are alphanumeric and there is at least one character in B, False otherwise. """ return False def isalpha(self): # real signature unknown; restored from __doc__ """ B.isalpha() -> bool Return True if all characters in B are alphabetic and there is at least one character in B, False otherwise. """ return False def isdigit(self): # real signature unknown; restored from __doc__ """ B.isdigit() -> bool Return True if all characters in B are digits and there is at least one character in B, False otherwise. """ return False def islower(self): # real signature unknown; restored from __doc__ """ B.islower() -> bool Return True if all cased characters in B are lowercase and there is at least one cased character in B, False otherwise. """ return False def isspace(self): # real signature unknown; restored from __doc__ """ B.isspace() -> bool Return True if all characters in B are whitespace and there is at least one character in B, False otherwise. """ return False def istitle(self): # real signature unknown; restored from __doc__ """ B.istitle() -> bool Return True if B is a titlecased string and there is at least one character in B, i.e. uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. """ return False def isupper(self): # real signature unknown; restored from __doc__ """ B.isupper() -> bool Return True if all cased characters in B are uppercase and there is at least one cased character in B, False otherwise. """ return False def join(self, iterable_of_bytes): # real signature unknown; restored from __doc__ """ B.join(iterable_of_bytes) -> bytes Concatenates any number of bytearray objects, with B in between each pair. """ return "" def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ B.ljust(width[, fillchar]) -> copy of B Return B left justified in a string of length width. Padding is done using the specified fill character (default is a space). """ pass def lower(self): # real signature unknown; restored from __doc__ """ B.lower() -> copy of B Return a copy of B with all ASCII characters converted to lowercase. """ pass def lstrip(self, bytes=None): # real signature unknown; restored from __doc__ """ B.lstrip([bytes]) -> bytearray Strip leading bytes contained in the argument. If the argument is omitted, strip leading ASCII whitespace. """ return bytearray def partition(self, sep): # real signature unknown; restored from __doc__ """ B.partition(sep) -> (head, sep, tail) Searches for the separator sep in B, and returns the part before it, the separator itself, and the part after it. If the separator is not found, returns B and two empty bytearray objects. """ pass def pop(self, index=None): # real signature unknown; restored from __doc__ """ B.pop([index]) -> int Remove and return a single item from B. If no index argument is given, will pop the last value. """ return 0 def remove(self, p_int): # real signature unknown; restored from __doc__ """ B.remove(int) -> None Remove the first occurance of a value in B. """ pass def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ """ B.replace(old, new[, count]) -> bytes Return a copy of B with all occurrences of subsection old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. """ return "" def reverse(self): # real signature unknown; restored from __doc__ """ B.reverse() -> None Reverse the order of the values in B in place. """ pass def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ B.rfind(sub [,start [,end]]) -> int Return the highest index in B where subsection sub is found, such that sub is contained within B[start,end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ B.rindex(sub [,start [,end]]) -> int Like B.rfind() but raise ValueError when the subsection is not found. """ return 0 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ B.rjust(width[, fillchar]) -> copy of B Return B right justified in a string of length width. Padding is done using the specified fill character (default is a space) """ pass def rpartition(self, sep): # real signature unknown; restored from __doc__ """ B.rpartition(sep) -> (head, sep, tail) Searches for the separator sep in B, starting at the end of B, and returns the part before it, the separator itself, and the part after it. If the separator is not found, returns two empty bytearray objects and B. """ pass def rsplit(self, sep, maxsplit=None): # real signature unknown; restored from __doc__ """ B.rsplit(sep[, maxsplit]) -> list of bytearray Return a list of the sections in B, using sep as the delimiter, starting at the end of B and working to the front. If sep is not given, B is split on ASCII whitespace characters (space, tab, return, newline, formfeed, vertical tab). If maxsplit is given, at most maxsplit splits are done. """ return [] def rstrip(self, bytes=None): # real signature unknown; restored from __doc__ """ B.rstrip([bytes]) -> bytearray Strip trailing bytes contained in the argument. If the argument is omitted, strip trailing ASCII whitespace. """ return bytearray def split(self, sep=None, maxsplit=None): # real signature unknown; restored from __doc__ """ B.split([sep[, maxsplit]]) -> list of bytearray Return a list of the sections in B, using sep as the delimiter. If sep is not given, B is split on ASCII whitespace characters (space, tab, return, newline, formfeed, vertical tab). If maxsplit is given, at most maxsplit splits are done. """ return [] def splitlines(self, keepends=False): # real signature unknown; restored from __doc__ """ B.splitlines(keepends=False) -> list of lines Return a list of the lines in B, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ return [] def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ """ B.startswith(prefix [,start [,end]]) -> bool Return True if B starts with the specified prefix, False otherwise. With optional start, test B beginning at that position. With optional end, stop comparing B at that position. prefix can also be a tuple of strings to try. """ return False def strip(self, bytes=None): # real signature unknown; restored from __doc__ """ B.strip([bytes]) -> bytearray Strip leading and trailing bytes contained in the argument. If the argument is omitted, strip ASCII whitespace. """ return bytearray def swapcase(self): # real signature unknown; restored from __doc__ """ B.swapcase() -> copy of B Return a copy of B with uppercase ASCII characters converted to lowercase ASCII and vice versa. """ pass def title(self): # real signature unknown; restored from __doc__ """ B.title() -> copy of B Return a titlecased version of B, i.e. ASCII words start with uppercase characters, all remaining cased characters have lowercase. """ pass def translate(self, table, deletechars=None): # real signature unknown; restored from __doc__ """ B.translate(table[, deletechars]) -> bytearray Return a copy of B, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a bytes object of length 256. """ return bytearray def upper(self): # real signature unknown; restored from __doc__ """ B.upper() -> copy of B Return a copy of B with all ASCII characters converted to uppercase. """ pass def zfill(self, width): # real signature unknown; restored from __doc__ """ B.zfill(width) -> copy of B Pad a numeric string B with zeros on the left, to fill a field of the specified width. B is never truncated. """ pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __alloc__(self): # real signature unknown; restored from __doc__ """ B.__alloc__() -> int Returns the number of bytes actually allocated. """ return 0 def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x """ pass def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __iadd__(self, y): # real signature unknown; restored from __doc__ """ x.__iadd__(y) <==> x+=y """ pass def __imul__(self, y): # real signature unknown; restored from __doc__ """ x.__imul__(y) <==> x*=y """ pass def __init__(self, source=None, encoding=None, errors='strict'): # known special case of bytearray.__init__ """ bytearray(iterable_of_ints) -> bytearray. bytearray(string, encoding[, errors]) -> bytearray. bytearray(bytes_or_bytearray) -> mutable copy of bytes_or_bytearray. bytearray(memory_view) -> bytearray. Construct an mutable bytearray object from: - an iterable yielding integers in range(256) - a text string encoded using the specified encoding - a bytes or a bytearray object - any object implementing the buffer API. bytearray(int) -> bytearray. Construct a zero-initialized bytearray of the given length. # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass def __mul__(self, n): # real signature unknown; restored from __doc__ """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ Return state information for pickling. """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ B.__sizeof__() -> int Returns the size of B in memory, in bytes """ return 0 def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass class str(basestring): """ str(object='') -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object. """ def capitalize(self): # real signature unknown; restored from __doc__ """ S.capitalize() -> string Return a copy of the string S with only its first character capitalized. """ return "" def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.center(width[, fillchar]) -> string Return S centered in a string of length width. Padding is done using the specified fill character (default is a space) """ return "" def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return 0 def decode(self, encoding=None, errors=None): # real signature unknown; restored from __doc__ """ S.decode([encoding[,errors]]) -> object Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. """ return object() def encode(self, encoding=None, errors=None): # real signature unknown; restored from __doc__ """ S.encode([encoding[,errors]]) -> object Encodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that is able to handle UnicodeEncodeErrors. """ return object() def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. """ return False def expandtabs(self, tabsize=None): # real signature unknown; restored from __doc__ """ S.expandtabs([tabsize]) -> string Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ return "" def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def format(self, *args, **kwargs): # known special case of str.format """ S.format(*args, **kwargs) -> string Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). """ pass def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.index(sub [,start [,end]]) -> int Like S.find() but raise ValueError when the substring is not found. """ return 0 def isalnum(self): # real signature unknown; restored from __doc__ """ S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise. """ return False def isalpha(self): # real signature unknown; restored from __doc__ """ S.isalpha() -> bool Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise. """ return False def isdigit(self): # real signature unknown; restored from __doc__ """ S.isdigit() -> bool Return True if all characters in S are digits and there is at least one character in S, False otherwise. """ return False def islower(self): # real signature unknown; restored from __doc__ """ S.islower() -> bool Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise. """ return False def isspace(self): # real signature unknown; restored from __doc__ """ S.isspace() -> bool Return True if all characters in S are whitespace and there is at least one character in S, False otherwise. """ return False def istitle(self): # real signature unknown; restored from __doc__ """ S.istitle() -> bool Return True if S is a titlecased string and there is at least one character in S, i.e. uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. """ return False def isupper(self): # real signature unknown; restored from __doc__ """ S.isupper() -> bool Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise. """ return False def join(self, iterable): # real signature unknown; restored from __doc__ """ S.join(iterable) -> string Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. """ return "" def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.ljust(width[, fillchar]) -> string Return S left-justified in a string of length width. Padding is done using the specified fill character (default is a space). """ return "" def lower(self): # real signature unknown; restored from __doc__ """ S.lower() -> string Return a copy of the string S converted to lowercase. """ return "" def lstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.lstrip([chars]) -> string or unicode Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping """ return "" def partition(self, sep): # real signature unknown; restored from __doc__ """ S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings. """ pass def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ """ S.replace(old, new[, count]) -> string Return a copy of string S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. """ return "" def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rfind(sub [,start [,end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rindex(sub [,start [,end]]) -> int Like S.rfind() but raise ValueError when the substring is not found. """ return 0 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.rjust(width[, fillchar]) -> string Return S right-justified in a string of length width. Padding is done using the specified fill character (default is a space) """ return "" def rpartition(self, sep): # real signature unknown; restored from __doc__ """ S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S. """ pass def rsplit(self, sep=None, maxsplit=None): # real signature unknown; restored from __doc__ """ S.rsplit([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator. """ return [] def rstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.rstrip([chars]) -> string or unicode Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping """ return "" def split(self, sep=None, maxsplit=None): # real signature unknown; restored from __doc__ """ S.split([sep [,maxsplit]]) -> list of strings Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. """ return [] def splitlines(self, keepends=False): # real signature unknown; restored from __doc__ """ S.splitlines(keepends=False) -> list of strings Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ return [] def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. """ return False def strip(self, chars=None): # real signature unknown; restored from __doc__ """ S.strip([chars]) -> string or unicode Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is unicode, S will be converted to unicode before stripping """ return "" def swapcase(self): # real signature unknown; restored from __doc__ """ S.swapcase() -> string Return a copy of the string S with uppercase characters converted to lowercase and vice versa. """ return "" def title(self): # real signature unknown; restored from __doc__ """ S.title() -> string Return a titlecased version of S, i.e. words start with uppercase characters, all remaining cased characters have lowercase. """ return "" def translate(self, table, deletechars=None): # real signature unknown; restored from __doc__ """ S.translate(table [,deletechars]) -> string Return a copy of the string S, where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256 or None. If the table argument is None, no translation is applied and the operation simply removes the characters in deletechars. """ return "" def upper(self): # real signature unknown; restored from __doc__ """ S.upper() -> string Return a copy of the string S converted to uppercase. """ return "" def zfill(self, width): # real signature unknown; restored from __doc__ """ S.zfill(width) -> string Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated. """ return "" def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown pass def _formatter_parser(self, *args, **kwargs): # real signature unknown pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __format__(self, format_spec): # real signature unknown; restored from __doc__ """ S.__format__(format_spec) -> string Return a formatted version of S as described by format_spec. """ return "" def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, string=''): # known special case of str.__init__ """ str(object='') -> string Return a nice string representation of the object. If the argument is a string, the return value is the same object. # (copied from class doc) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass def __mod__(self, y): # real signature unknown; restored from __doc__ """ x.__mod__(y) <==> x%y """ pass def __mul__(self, n): # real signature unknown; restored from __doc__ """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass bytes = str class classmethod(object): """ classmethod(function) -> method Convert a function to be a class method. A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom: class C: def f(cls, arg1, arg2, ...): ... f = classmethod(f) It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument. Class methods are different than C++ or Java static methods. If you want those, see the staticmethod builtin. """ def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __get__(self, obj, type=None): # real signature unknown; restored from __doc__ """ descr.__get__(obj[, type]) -> value """ pass def __init__(self, function): # real signature unknown; restored from __doc__ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass __func__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default class complex(object): """ complex(real[, imag]) -> complex number Create a complex number from a real part and an optional imaginary part. This is equivalent to (real + imag*1j) where imag defaults to 0. """ def conjugate(self): # real signature unknown; restored from __doc__ """ complex.conjugate() -> complex Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j. """ return complex def __abs__(self): # real signature unknown; restored from __doc__ """ x.__abs__() <==> abs(x) """ pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __coerce__(self, y): # real signature unknown; restored from __doc__ """ x.__coerce__(y) <==> coerce(x, y) """ pass def __divmod__(self, y): # real signature unknown; restored from __doc__ """ x.__divmod__(y) <==> divmod(x, y) """ pass def __div__(self, y): # real signature unknown; restored from __doc__ """ x.__div__(y) <==> x/y """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __float__(self): # real signature unknown; restored from __doc__ """ x.__float__() <==> float(x) """ pass def __floordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__floordiv__(y) <==> x//y """ pass def __format__(self): # real signature unknown; restored from __doc__ """ complex.__format__() -> str Convert to a string according to format_spec. """ return "" def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, real, imag=None): # real signature unknown; restored from __doc__ pass def __int__(self): # real signature unknown; restored from __doc__ """ x.__int__() <==> int(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __long__(self): # real signature unknown; restored from __doc__ """ x.__long__() <==> long(x) """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass def __mod__(self, y): # real signature unknown; restored from __doc__ """ x.__mod__(y) <==> x%y """ pass def __mul__(self, y): # real signature unknown; restored from __doc__ """ x.__mul__(y) <==> x*y """ pass def __neg__(self): # real signature unknown; restored from __doc__ """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __nonzero__(self): # real signature unknown; restored from __doc__ """ x.__nonzero__() <==> x != 0 """ pass def __pos__(self): # real signature unknown; restored from __doc__ """ x.__pos__() <==> +x """ pass def __pow__(self, y, z=None): # real signature unknown; restored from __doc__ """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ pass def __radd__(self, y): # real signature unknown; restored from __doc__ """ x.__radd__(y) <==> y+x """ pass def __rdivmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rdivmod__(y) <==> divmod(y, x) """ pass def __rdiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rdiv__(y) <==> y/x """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rfloordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rfloordiv__(y) <==> y//x """ pass def __rmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, y): # real signature unknown; restored from __doc__ """ x.__rmul__(y) <==> y*x """ pass def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__ """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ pass def __rsub__(self, y): # real signature unknown; restored from __doc__ """ x.__rsub__(y) <==> y-x """ pass def __rtruediv__(self, y): # real signature unknown; restored from __doc__ """ x.__rtruediv__(y) <==> y/x """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass def __sub__(self, y): # real signature unknown; restored from __doc__ """ x.__sub__(y) <==> x-y """ pass def __truediv__(self, y): # real signature unknown; restored from __doc__ """ x.__truediv__(y) <==> x/y """ pass imag = property(lambda self: 0.0) """the imaginary part of a complex number :type: float """ real = property(lambda self: 0.0) """the real part of a complex number :type: float """ class dict(object): """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) """ def clear(self): # real signature unknown; restored from __doc__ """ D.clear() -> None. Remove all items from D. """ pass def copy(self): # real signature unknown; restored from __doc__ """ D.copy() -> a shallow copy of D """ pass @staticmethod # known case def fromkeys(S, v=None): # real signature unknown; restored from __doc__ """ dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. v defaults to None. """ pass def get(self, k, d=None): # real signature unknown; restored from __doc__ """ D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None. """ pass def has_key(self, k): # real signature unknown; restored from __doc__ """ D.has_key(k) -> True if D has a key k, else False """ return False def items(self): # real signature unknown; restored from __doc__ """ D.items() -> list of D's (key, value) pairs, as 2-tuples """ return [] def iteritems(self): # real signature unknown; restored from __doc__ """ D.iteritems() -> an iterator over the (key, value) items of D """ pass def iterkeys(self): # real signature unknown; restored from __doc__ """ D.iterkeys() -> an iterator over the keys of D """ pass def itervalues(self): # real signature unknown; restored from __doc__ """ D.itervalues() -> an iterator over the values of D """ pass def keys(self): # real signature unknown; restored from __doc__ """ D.keys() -> list of D's keys """ return [] def pop(self, k, d=None): # real signature unknown; restored from __doc__ """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass def popitem(self): # real signature unknown; restored from __doc__ """ D.popitem() -> (k, v), remove and return some (key, value) pair as a 2-tuple; but raise KeyError if D is empty. """ pass def setdefault(self, k, d=None): # real signature unknown; restored from __doc__ """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """ pass def update(self, E=None, **F): # known special case of dict.update """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass def values(self): # real signature unknown; restored from __doc__ """ D.values() -> list of D's values """ return [] def viewitems(self): # real signature unknown; restored from __doc__ """ D.viewitems() -> a set-like object providing a view on D's items """ pass def viewkeys(self): # real signature unknown; restored from __doc__ """ D.viewkeys() -> a set-like object providing a view on D's keys """ pass def viewvalues(self): # real signature unknown; restored from __doc__ """ D.viewvalues() -> an object providing a view on D's values """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __contains__(self, k): # real signature unknown; restored from __doc__ """ D.__contains__(k) -> True if D has a key k, else False """ return False def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __init__(self, seq=None, **kwargs): # known special case of dict.__init__ """ dict() -> new empty dictionary dict(mapping) -> new dictionary initialized from a mapping object's (key, value) pairs dict(iterable) -> new dictionary initialized as if via: d = {} for k, v in iterable: d[k] = v dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ D.__sizeof__() -> size of D in memory, in bytes """ pass __hash__ = None class enumerate(object): """ enumerate(iterable[, start]) -> iterator for index, value of iterable Return an enumerate object. iterable must be another object that supports iteration. The enumerate object yields pairs containing a count (from start, which defaults to zero) and a value yielded by the iterable argument. enumerate is useful for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ... """ def next(self): # real signature unknown; restored from __doc__ """ x.next() -> the next value, or raise StopIteration """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __init__(self, iterable, start=0): # known special case of enumerate.__init__ """ x.__init__(...) initializes x; see help(type(x)) for signature """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass class file(object): """ file(name[, mode[, buffering]]) -> file object Open a file. The mode can be 'r', 'w' or 'a' for reading (default), writing or appending. The file will be created if it doesn't exist when opened for writing or appending; it will be truncated when opened for writing. Add a 'b' to the mode for binary files. Add a '+' to the mode to allow simultaneous reading and writing. If the buffering argument is given, 0 means unbuffered, 1 means line buffered, and larger numbers specify the buffer size. The preferred way to open a file is with the builtin open() function. Add a 'U' to mode to open the file for input with universal newline support. Any line ending in the input file will be seen as a '\n' in Python. Also, a file so opened gains the attribute 'newlines'; the value for this attribute is one of None (no newline read yet), '\r', '\n', '\r\n' or a tuple containing all the newline types seen. 'U' cannot be combined with 'w' or '+' mode. """ def close(self): # real signature unknown; restored from __doc__ """ close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for further I/O operations. close() may be called more than once without error. Some kinds of file objects (for example, opened by popen()) may return an exit status upon closing. """ pass def fileno(self): # real signature unknown; restored from __doc__ """ fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read(). """ return 0 def flush(self): # real signature unknown; restored from __doc__ """ flush() -> None. Flush the internal I/O buffer. """ pass def isatty(self): # real signature unknown; restored from __doc__ """ isatty() -> true or false. True if the file is connected to a tty device. """ return False def next(self): # real signature unknown; restored from __doc__ """ x.next() -> the next value, or raise StopIteration """ pass def read(self, size=None): # real signature unknown; restored from __doc__ """ read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. """ pass def readinto(self): # real signature unknown; restored from __doc__ """ readinto() -> Undocumented. Don't use this; it may go away. """ pass def readline(self, size=None): # real signature unknown; restored from __doc__ """ readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. """ pass def readlines(self, size=None): # real signature unknown; restored from __doc__ """ readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned. """ return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__ """ seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to 0 (offset from start of file, offset should be >= 0); other values are 1 (move relative to current position, positive or negative), and 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are seekable. """ pass def tell(self): # real signature unknown; restored from __doc__ """ tell() -> current file position, an integer (may be a long integer). """ pass def truncate(self, size=None): # real signature unknown; restored from __doc__ """ truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell(). """ pass def write(self, p_str): # real signature unknown; restored from __doc__ """ write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written. """ pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__ """ writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string. """ pass def xreadlines(self): # real signature unknown; restored from __doc__ """ xreadlines() -> returns self. For backward compatibility. File objects now include the performance optimizations previously implemented in the xreadlines module. """ pass def __delattr__(self, name): # real signature unknown; restored from __doc__ """ x.__delattr__('name') <==> del x.name """ pass def __enter__(self): # real signature unknown; restored from __doc__ """ __enter__() -> self. """ return self def __exit__(self, *excinfo): # real signature unknown; restored from __doc__ """ __exit__(*excinfo) -> None. Closes the file. """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __init__(self, name, mode=None, buffering=None): # real signature unknown; restored from __doc__ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setattr__(self, name, value): # real signature unknown; restored from __doc__ """ x.__setattr__('name', value) <==> x.name = value """ pass closed = property(lambda self: True) """True if the file is closed :type: bool """ encoding = property(lambda self: '') """file encoding :type: string """ errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """Unicode error handler""" mode = property(lambda self: '') """file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added) :type: string """ name = property(lambda self: '') """file name :type: string """ newlines = property(lambda self: '') """end-of-line convention used in this file :type: string """ softspace = property(lambda self: True) """flag indicating that a space needs to be printed; used by print :type: bool """ class float(object): """ float(x) -> floating point number Convert a string or number to a floating point number, if possible. """ def as_integer_ratio(self): # real signature unknown; restored from __doc__ """ float.as_integer_ratio() -> (int, int) Return a pair of integers, whose ratio is exactly equal to the original float and with a positive denominator. Raise OverflowError on infinities and a ValueError on NaNs. >>> (10.0).as_integer_ratio() (10, 1) >>> (0.0).as_integer_ratio() (0, 1) >>> (-.25).as_integer_ratio() (-1, 4) """ pass def conjugate(self, *args, **kwargs): # real signature unknown """ Return self, the complex conjugate of any float. """ pass @staticmethod # known case def fromhex(string): # real signature unknown; restored from __doc__ """ float.fromhex(string) -> float Create a floating-point number from a hexadecimal string. >>> float.fromhex('0x1.ffffp10') 2047.984375 >>> float.fromhex('-0x1p-1074') -4.9406564584124654e-324 """ return 0.0 def hex(self): # real signature unknown; restored from __doc__ """ float.hex() -> string Return a hexadecimal representation of a floating-point number. >>> (-0.1).hex() '-0x1.999999999999ap-4' >>> 3.14159.hex() '0x1.921f9f01b866ep+1' """ return "" def is_integer(self, *args, **kwargs): # real signature unknown """ Return True if the float is an integer. """ pass def __abs__(self): # real signature unknown; restored from __doc__ """ x.__abs__() <==> abs(x) """ pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __coerce__(self, y): # real signature unknown; restored from __doc__ """ x.__coerce__(y) <==> coerce(x, y) """ pass def __divmod__(self, y): # real signature unknown; restored from __doc__ """ x.__divmod__(y) <==> divmod(x, y) """ pass def __div__(self, y): # real signature unknown; restored from __doc__ """ x.__div__(y) <==> x/y """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __float__(self): # real signature unknown; restored from __doc__ """ x.__float__() <==> float(x) """ pass def __floordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__floordiv__(y) <==> x//y """ pass def __format__(self, format_spec): # real signature unknown; restored from __doc__ """ float.__format__(format_spec) -> string Formats the float according to format_spec. """ return "" def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getformat__(self, typestr): # real signature unknown; restored from __doc__ """ float.__getformat__(typestr) -> string You probably don't want to use this function. It exists mainly to be used in Python's test suite. typestr must be 'double' or 'float'. This function returns whichever of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian' best describes the format of floating point numbers used by the C type named by typestr. """ return "" def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, x): # real signature unknown; restored from __doc__ pass def __int__(self): # real signature unknown; restored from __doc__ """ x.__int__() <==> int(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __long__(self): # real signature unknown; restored from __doc__ """ x.__long__() <==> long(x) """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass def __mod__(self, y): # real signature unknown; restored from __doc__ """ x.__mod__(y) <==> x%y """ pass def __mul__(self, y): # real signature unknown; restored from __doc__ """ x.__mul__(y) <==> x*y """ pass def __neg__(self): # real signature unknown; restored from __doc__ """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __nonzero__(self): # real signature unknown; restored from __doc__ """ x.__nonzero__() <==> x != 0 """ pass def __pos__(self): # real signature unknown; restored from __doc__ """ x.__pos__() <==> +x """ pass def __pow__(self, y, z=None): # real signature unknown; restored from __doc__ """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ pass def __radd__(self, y): # real signature unknown; restored from __doc__ """ x.__radd__(y) <==> y+x """ pass def __rdivmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rdivmod__(y) <==> divmod(y, x) """ pass def __rdiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rdiv__(y) <==> y/x """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rfloordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rfloordiv__(y) <==> y//x """ pass def __rmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, y): # real signature unknown; restored from __doc__ """ x.__rmul__(y) <==> y*x """ pass def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__ """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ pass def __rsub__(self, y): # real signature unknown; restored from __doc__ """ x.__rsub__(y) <==> y-x """ pass def __rtruediv__(self, y): # real signature unknown; restored from __doc__ """ x.__rtruediv__(y) <==> y/x """ pass def __setformat__(self, typestr, fmt): # real signature unknown; restored from __doc__ """ float.__setformat__(typestr, fmt) -> None You probably don't want to use this function. It exists mainly to be used in Python's test suite. typestr must be 'double' or 'float'. fmt must be one of 'unknown', 'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be one of the latter two if it appears to match the underlying C reality. Override the automatic determination of C-level floating point type. This affects how floats are converted to and from binary strings. """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass def __sub__(self, y): # real signature unknown; restored from __doc__ """ x.__sub__(y) <==> x-y """ pass def __truediv__(self, y): # real signature unknown; restored from __doc__ """ x.__truediv__(y) <==> x/y """ pass def __trunc__(self, *args, **kwargs): # real signature unknown """ Return the Integral closest to x between 0 and x. """ pass imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the imaginary part of a complex number""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the real part of a complex number""" class frozenset(object): """ frozenset() -> empty frozenset object frozenset(iterable) -> frozenset object Build an immutable unordered collection of unique elements. """ def copy(self, *args, **kwargs): # real signature unknown """ Return a shallow copy of a set. """ pass def difference(self, *args, **kwargs): # real signature unknown """ Return the difference of two or more sets as a new set. (i.e. all elements that are in this set but not the others.) """ pass def intersection(self, *args, **kwargs): # real signature unknown """ Return the intersection of two or more sets as a new set. (i.e. elements that are common to all of the sets.) """ pass def isdisjoint(self, *args, **kwargs): # real signature unknown """ Return True if two sets have a null intersection. """ pass def issubset(self, *args, **kwargs): # real signature unknown """ Report whether another set contains this set. """ pass def issuperset(self, *args, **kwargs): # real signature unknown """ Report whether this set contains another set. """ pass def symmetric_difference(self, *args, **kwargs): # real signature unknown """ Return the symmetric difference of two sets as a new set. (i.e. all elements that are in exactly one of the sets.) """ pass def union(self, *args, **kwargs): # real signature unknown """ Return the union of sets as a new set. (i.e. all elements that are in either set.) """ pass def __and__(self, y): # real signature unknown; restored from __doc__ """ x.__and__(y) <==> x&y """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x. """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, seq=()): # known special case of frozenset.__init__ """ x.__init__(...) initializes x; see help(type(x)) for signature """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __or__(self, y): # real signature unknown; restored from __doc__ """ x.__or__(y) <==> x|y """ pass def __rand__(self, y): # real signature unknown; restored from __doc__ """ x.__rand__(y) <==> y&x """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ Return state information for pickling. """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __ror__(self, y): # real signature unknown; restored from __doc__ """ x.__ror__(y) <==> y|x """ pass def __rsub__(self, y): # real signature unknown; restored from __doc__ """ x.__rsub__(y) <==> y-x """ pass def __rxor__(self, y): # real signature unknown; restored from __doc__ """ x.__rxor__(y) <==> y^x """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __sub__(self, y): # real signature unknown; restored from __doc__ """ x.__sub__(y) <==> x-y """ pass def __xor__(self, y): # real signature unknown; restored from __doc__ """ x.__xor__(y) <==> x^y """ pass class list(object): """ list() -> new empty list list(iterable) -> new list initialized from iterable's items """ def append(self, p_object): # real signature unknown; restored from __doc__ """ L.append(object) -- append object to end """ pass def count(self, value): # real signature unknown; restored from __doc__ """ L.count(value) -> integer -- return number of occurrences of value """ return 0 def extend(self, iterable): # real signature unknown; restored from __doc__ """ L.extend(iterable) -- extend list by appending elements from the iterable """ pass def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ """ L.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. """ return 0 def insert(self, index, p_object): # real signature unknown; restored from __doc__ """ L.insert(index, object) -- insert object before index """ pass def pop(self, index=None): # real signature unknown; restored from __doc__ """ L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range. """ pass def remove(self, value): # real signature unknown; restored from __doc__ """ L.remove(value) -- remove first occurrence of value. Raises ValueError if the value is not present. """ pass def reverse(self): # real signature unknown; restored from __doc__ """ L.reverse() -- reverse *IN PLACE* """ pass def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__ """ L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; cmp(x, y) -> -1, 0, 1 """ pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x """ pass def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __delslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__delslice__(i, j) <==> del x[i:j] Use of negative indices is not supported. """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __iadd__(self, y): # real signature unknown; restored from __doc__ """ x.__iadd__(y) <==> x+=y """ pass def __imul__(self, y): # real signature unknown; restored from __doc__ """ x.__imul__(y) <==> x*=y """ pass def __init__(self, seq=()): # known special case of list.__init__ """ list() -> new empty list list(iterable) -> new list initialized from iterable's items # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass def __mul__(self, n): # real signature unknown; restored from __doc__ """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __reversed__(self): # real signature unknown; restored from __doc__ """ L.__reversed__() -- return a reverse iterator over the list """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__ """ x.__setslice__(i, j, y) <==> x[i:j]=y Use of negative indices is not supported. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ L.__sizeof__() -- size of L in memory, in bytes """ pass __hash__ = None class long(object): """ long(x=0) -> long long(x, base=10) -> long Convert a number or string to a long integer, or return 0L if no arguments are given. If x is floating point, the conversion truncates towards zero. If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) 4L """ def bit_length(self): # real signature unknown; restored from __doc__ """ long.bit_length() -> int or long Number of bits necessary to represent self in binary. >>> bin(37L) '0b100101' >>> (37L).bit_length() 6 """ return 0 def conjugate(self, *args, **kwargs): # real signature unknown """ Returns self, the complex conjugate of any long. """ pass def __abs__(self): # real signature unknown; restored from __doc__ """ x.__abs__() <==> abs(x) """ pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __and__(self, y): # real signature unknown; restored from __doc__ """ x.__and__(y) <==> x&y """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __coerce__(self, y): # real signature unknown; restored from __doc__ """ x.__coerce__(y) <==> coerce(x, y) """ pass def __divmod__(self, y): # real signature unknown; restored from __doc__ """ x.__divmod__(y) <==> divmod(x, y) """ pass def __div__(self, y): # real signature unknown; restored from __doc__ """ x.__div__(y) <==> x/y """ pass def __float__(self): # real signature unknown; restored from __doc__ """ x.__float__() <==> float(x) """ pass def __floordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__floordiv__(y) <==> x//y """ pass def __format__(self, *args, **kwargs): # real signature unknown pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __hex__(self): # real signature unknown; restored from __doc__ """ x.__hex__() <==> hex(x) """ pass def __index__(self): # real signature unknown; restored from __doc__ """ x[y:z] <==> x[y.__index__():z.__index__()] """ pass def __init__(self, x=0): # real signature unknown; restored from __doc__ pass def __int__(self): # real signature unknown; restored from __doc__ """ x.__int__() <==> int(x) """ pass def __invert__(self): # real signature unknown; restored from __doc__ """ x.__invert__() <==> ~x """ pass def __long__(self): # real signature unknown; restored from __doc__ """ x.__long__() <==> long(x) """ pass def __lshift__(self, y): # real signature unknown; restored from __doc__ """ x.__lshift__(y) <==> x<<y """ pass def __mod__(self, y): # real signature unknown; restored from __doc__ """ x.__mod__(y) <==> x%y """ pass def __mul__(self, y): # real signature unknown; restored from __doc__ """ x.__mul__(y) <==> x*y """ pass def __neg__(self): # real signature unknown; restored from __doc__ """ x.__neg__() <==> -x """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __nonzero__(self): # real signature unknown; restored from __doc__ """ x.__nonzero__() <==> x != 0 """ pass def __oct__(self): # real signature unknown; restored from __doc__ """ x.__oct__() <==> oct(x) """ pass def __or__(self, y): # real signature unknown; restored from __doc__ """ x.__or__(y) <==> x|y """ pass def __pos__(self): # real signature unknown; restored from __doc__ """ x.__pos__() <==> +x """ pass def __pow__(self, y, z=None): # real signature unknown; restored from __doc__ """ x.__pow__(y[, z]) <==> pow(x, y[, z]) """ pass def __radd__(self, y): # real signature unknown; restored from __doc__ """ x.__radd__(y) <==> y+x """ pass def __rand__(self, y): # real signature unknown; restored from __doc__ """ x.__rand__(y) <==> y&x """ pass def __rdivmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rdivmod__(y) <==> divmod(y, x) """ pass def __rdiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rdiv__(y) <==> y/x """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rfloordiv__(self, y): # real signature unknown; restored from __doc__ """ x.__rfloordiv__(y) <==> y//x """ pass def __rlshift__(self, y): # real signature unknown; restored from __doc__ """ x.__rlshift__(y) <==> y<<x """ pass def __rmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, y): # real signature unknown; restored from __doc__ """ x.__rmul__(y) <==> y*x """ pass def __ror__(self, y): # real signature unknown; restored from __doc__ """ x.__ror__(y) <==> y|x """ pass def __rpow__(self, x, z=None): # real signature unknown; restored from __doc__ """ y.__rpow__(x[, z]) <==> pow(x, y[, z]) """ pass def __rrshift__(self, y): # real signature unknown; restored from __doc__ """ x.__rrshift__(y) <==> y>>x """ pass def __rshift__(self, y): # real signature unknown; restored from __doc__ """ x.__rshift__(y) <==> x>>y """ pass def __rsub__(self, y): # real signature unknown; restored from __doc__ """ x.__rsub__(y) <==> y-x """ pass def __rtruediv__(self, y): # real signature unknown; restored from __doc__ """ x.__rtruediv__(y) <==> y/x """ pass def __rxor__(self, y): # real signature unknown; restored from __doc__ """ x.__rxor__(y) <==> y^x """ pass def __sizeof__(self, *args, **kwargs): # real signature unknown """ Returns size in memory, in bytes """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass def __sub__(self, y): # real signature unknown; restored from __doc__ """ x.__sub__(y) <==> x-y """ pass def __truediv__(self, y): # real signature unknown; restored from __doc__ """ x.__truediv__(y) <==> x/y """ pass def __trunc__(self, *args, **kwargs): # real signature unknown """ Truncating an Integral returns itself. """ pass def __xor__(self, y): # real signature unknown; restored from __doc__ """ x.__xor__(y) <==> x^y """ pass denominator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the denominator of a rational number in lowest terms""" imag = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the imaginary part of a complex number""" numerator = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the numerator of a rational number in lowest terms""" real = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """the real part of a complex number""" class memoryview(object): """ memoryview(object) Create a new memoryview object which references the given object. """ def tobytes(self, *args, **kwargs): # real signature unknown pass def tolist(self, *args, **kwargs): # real signature unknown pass def __delitem__(self, y): # real signature unknown; restored from __doc__ """ x.__delitem__(y) <==> del x[y] """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __init__(self, p_object): # real signature unknown; restored from __doc__ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setitem__(self, i, y): # real signature unknown; restored from __doc__ """ x.__setitem__(i, y) <==> x[i]=y """ pass format = property(lambda self: object(), lambda self, v: None, lambda self: None) # default itemsize = property(lambda self: object(), lambda self, v: None, lambda self: None) # default ndim = property(lambda self: object(), lambda self, v: None, lambda self: None) # default readonly = property(lambda self: object(), lambda self, v: None, lambda self: None) # default shape = property(lambda self: object(), lambda self, v: None, lambda self: None) # default strides = property(lambda self: object(), lambda self, v: None, lambda self: None) # default suboffsets = property(lambda self: object(), lambda self, v: None, lambda self: None) # default class property(object): """ property(fget=None, fset=None, fdel=None, doc=None) -> property attribute fget is a function to be used for getting an attribute value, and likewise fset is a function for setting, and fdel a function for del'ing, an attribute. Typical use is to define a managed attribute x: class C(object): def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") Decorators make defining new properties or modifying existing ones easy: class C(object): @property def x(self): "I am the 'x' property." return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x """ def deleter(self, *args, **kwargs): # real signature unknown """ Descriptor to change the deleter on a property. """ pass def getter(self, *args, **kwargs): # real signature unknown """ Descriptor to change the getter on a property. """ pass def setter(self, *args, **kwargs): # real signature unknown """ Descriptor to change the setter on a property. """ pass def __delete__(self, obj): # real signature unknown; restored from __doc__ """ descr.__delete__(obj) """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __get__(self, obj, type=None): # real signature unknown; restored from __doc__ """ descr.__get__(obj[, type]) -> value """ pass def __init__(self, fget=None, fset=None, fdel=None, doc=None): # known special case of property.__init__ """ property(fget=None, fset=None, fdel=None, doc=None) -> property attribute fget is a function to be used for getting an attribute value, and likewise fset is a function for setting, and fdel a function for del'ing, an attribute. Typical use is to define a managed attribute x: class C(object): def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") Decorators make defining new properties or modifying existing ones easy: class C(object): @property def x(self): "I am the 'x' property." return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x # (copied from class doc) """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __set__(self, obj, value): # real signature unknown; restored from __doc__ """ descr.__set__(obj, value) """ pass fdel = property(lambda self: object(), lambda self, v: None, lambda self: None) # default fget = property(lambda self: object(), lambda self, v: None, lambda self: None) # default fset = property(lambda self: object(), lambda self, v: None, lambda self: None) # default class reversed(object): """ reversed(sequence) -> reverse iterator over values of the sequence Return a reverse iterator """ def next(self): # real signature unknown; restored from __doc__ """ x.next() -> the next value, or raise StopIteration """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __init__(self, sequence): # real signature unknown; restored from __doc__ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __length_hint__(self, *args, **kwargs): # real signature unknown """ Private method returning an estimate of len(list(it)). """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass class set(object): """ set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. """ def add(self, *args, **kwargs): # real signature unknown """ Add an element to a set. This has no effect if the element is already present. """ pass def clear(self, *args, **kwargs): # real signature unknown """ Remove all elements from this set. """ pass def copy(self, *args, **kwargs): # real signature unknown """ Return a shallow copy of a set. """ pass def difference(self, *args, **kwargs): # real signature unknown """ Return the difference of two or more sets as a new set. (i.e. all elements that are in this set but not the others.) """ pass def difference_update(self, *args, **kwargs): # real signature unknown """ Remove all elements of another set from this set. """ pass def discard(self, *args, **kwargs): # real signature unknown """ Remove an element from a set if it is a member. If the element is not a member, do nothing. """ pass def intersection(self, *args, **kwargs): # real signature unknown """ Return the intersection of two or more sets as a new set. (i.e. elements that are common to all of the sets.) """ pass def intersection_update(self, *args, **kwargs): # real signature unknown """ Update a set with the intersection of itself and another. """ pass def isdisjoint(self, *args, **kwargs): # real signature unknown """ Return True if two sets have a null intersection. """ pass def issubset(self, *args, **kwargs): # real signature unknown """ Report whether another set contains this set. """ pass def issuperset(self, *args, **kwargs): # real signature unknown """ Report whether this set contains another set. """ pass def pop(self, *args, **kwargs): # real signature unknown """ Remove and return an arbitrary set element. Raises KeyError if the set is empty. """ pass def remove(self, *args, **kwargs): # real signature unknown """ Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. """ pass def symmetric_difference(self, *args, **kwargs): # real signature unknown """ Return the symmetric difference of two sets as a new set. (i.e. all elements that are in exactly one of the sets.) """ pass def symmetric_difference_update(self, *args, **kwargs): # real signature unknown """ Update a set with the symmetric difference of itself and another. """ pass def union(self, *args, **kwargs): # real signature unknown """ Return the union of sets as a new set. (i.e. all elements that are in either set.) """ pass def update(self, *args, **kwargs): # real signature unknown """ Update a set with the union of itself and others. """ pass def __and__(self, y): # real signature unknown; restored from __doc__ """ x.__and__(y) <==> x&y """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x. """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __iand__(self, y): # real signature unknown; restored from __doc__ """ x.__iand__(y) <==> x&=y """ pass def __init__(self, seq=()): # known special case of set.__init__ """ set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. # (copied from class doc) """ pass def __ior__(self, y): # real signature unknown; restored from __doc__ """ x.__ior__(y) <==> x|=y """ pass def __isub__(self, y): # real signature unknown; restored from __doc__ """ x.__isub__(y) <==> x-=y """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __ixor__(self, y): # real signature unknown; restored from __doc__ """ x.__ixor__(y) <==> x^=y """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __or__(self, y): # real signature unknown; restored from __doc__ """ x.__or__(y) <==> x|y """ pass def __rand__(self, y): # real signature unknown; restored from __doc__ """ x.__rand__(y) <==> y&x """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ Return state information for pickling. """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __ror__(self, y): # real signature unknown; restored from __doc__ """ x.__ror__(y) <==> y|x """ pass def __rsub__(self, y): # real signature unknown; restored from __doc__ """ x.__rsub__(y) <==> y-x """ pass def __rxor__(self, y): # real signature unknown; restored from __doc__ """ x.__rxor__(y) <==> y^x """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __sub__(self, y): # real signature unknown; restored from __doc__ """ x.__sub__(y) <==> x-y """ pass def __xor__(self, y): # real signature unknown; restored from __doc__ """ x.__xor__(y) <==> x^y """ pass __hash__ = None class slice(object): """ slice(stop) slice(start, stop[, step]) Create a slice object. This is used for extended slicing (e.g. a[0:10:2]). """ def indices(self, len): # real signature unknown; restored from __doc__ """ S.indices(len) -> (start, stop, stride) Assuming a sequence of length len, calculate the start and stop indices, and the stride length of the extended slice described by S. Out of bounds indices are clipped in a manner consistent with the handling of normal slices. """ pass def __cmp__(self, y): # real signature unknown; restored from __doc__ """ x.__cmp__(y) <==> cmp(x,y) """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, stop): # real signature unknown; restored from __doc__ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ Return state information for pickling. """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass start = property(lambda self: 0) """:type: int""" step = property(lambda self: 0) """:type: int""" stop = property(lambda self: 0) """:type: int""" class staticmethod(object): """ staticmethod(function) -> method Convert a function to be a static method. A static method does not receive an implicit first argument. To declare a static method, use this idiom: class C: def f(arg1, arg2, ...): ... f = staticmethod(f) It can be called either on the class (e.g. C.f()) or on an instance (e.g. C().f()). The instance is ignored except for its class. Static methods in Python are similar to those found in Java or C++. For a more advanced concept, see the classmethod builtin. """ def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __get__(self, obj, type=None): # real signature unknown; restored from __doc__ """ descr.__get__(obj[, type]) -> value """ pass def __init__(self, function): # real signature unknown; restored from __doc__ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass __func__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default class super(object): """ super(type, obj) -> bound super object; requires isinstance(obj, type) super(type) -> unbound super object super(type, type2) -> bound super object; requires issubclass(type2, type) Typical use to call a cooperative superclass method: class C(B): def meth(self, arg): super(C, self).meth(arg) """ def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __get__(self, obj, type=None): # real signature unknown; restored from __doc__ """ descr.__get__(obj[, type]) -> value """ pass def __init__(self, type1, type2=None): # known special case of super.__init__ """ super(type, obj) -> bound super object; requires isinstance(obj, type) super(type) -> unbound super object super(type, type2) -> bound super object; requires issubclass(type2, type) Typical use to call a cooperative superclass method: class C(B): def meth(self, arg): super(C, self).meth(arg) # (copied from class doc) """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass __self_class__ = property(lambda self: type(object)) """the type of the instance invoking super(); may be None :type: type """ __self__ = property(lambda self: type(object)) """the instance invoking super(); may be None :type: type """ __thisclass__ = property(lambda self: type(object)) """the class invoking super() :type: type """ class tuple(object): """ tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. """ def count(self, value): # real signature unknown; restored from __doc__ """ T.count(value) -> integer -- return number of occurrences of value """ return 0 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ """ T.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. """ return 0 def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, seq=()): # known special case of tuple.__init__ """ tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. # (copied from class doc) """ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass def __mul__(self, n): # real signature unknown; restored from __doc__ """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass class type(object): """ type(object) -> the object's type type(name, bases, dict) -> a new type """ def mro(self): # real signature unknown; restored from __doc__ """ mro() -> list return a type's method resolution order """ return [] def __call__(self, *more): # real signature unknown; restored from __doc__ """ x.__call__(...) <==> x(...) """ pass def __delattr__(self, name): # real signature unknown; restored from __doc__ """ x.__delattr__('name') <==> del x.name """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(cls, what, bases=None, dict=None): # known special case of type.__init__ """ type(object) -> the object's type type(name, bases, dict) -> a new type # (copied from class doc) """ pass def __instancecheck__(self): # real signature unknown; restored from __doc__ """ __instancecheck__() -> bool check if an object is an instance """ return False def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __setattr__(self, name, value): # real signature unknown; restored from __doc__ """ x.__setattr__('name', value) <==> x.name = value """ pass def __subclasscheck__(self): # real signature unknown; restored from __doc__ """ __subclasscheck__() -> bool check if a class is a subclass """ return False def __subclasses__(self): # real signature unknown; restored from __doc__ """ __subclasses__() -> list of immediate subclasses """ return [] __abstractmethods__ = property(lambda self: object(), lambda self, v: None, lambda self: None) # default __bases__ = ( object, ) __base__ = object __basicsize__ = 872 __dictoffset__ = 264 __dict__ = None # (!) real value is '' __flags__ = 2148423147 __itemsize__ = 40 __mro__ = ( None, # (!) forward: type, real value is '' object, ) __name__ = 'type' __weakrefoffset__ = 368 class unicode(basestring): """ unicode(object='') -> unicode object unicode(string[, encoding[, errors]]) -> unicode object Create a new Unicode object from the given encoded string. encoding defaults to the current default string encoding. errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'. """ def capitalize(self): # real signature unknown; restored from __doc__ """ S.capitalize() -> unicode Return a capitalized version of S, i.e. make the first character have upper case and the rest lower case. """ return u"" def center(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.center(width[, fillchar]) -> unicode Return S centered in a Unicode string of length width. Padding is done using the specified fill character (default is a space) """ return u"" def count(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.count(sub[, start[, end]]) -> int Return the number of non-overlapping occurrences of substring sub in Unicode string S[start:end]. Optional arguments start and end are interpreted as in slice notation. """ return 0 def decode(self, encoding=None, errors=None): # real signature unknown; restored from __doc__ """ S.decode([encoding[,errors]]) -> string or unicode Decodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeDecodeError. Other possible values are 'ignore' and 'replace' as well as any other name registered with codecs.register_error that is able to handle UnicodeDecodeErrors. """ return "" def encode(self, encoding=None, errors=None): # real signature unknown; restored from __doc__ """ S.encode([encoding[,errors]]) -> string or unicode Encodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors. """ return "" def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. """ return False def expandtabs(self, tabsize=None): # real signature unknown; restored from __doc__ """ S.expandtabs([tabsize]) -> unicode Return a copy of S where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. """ return u"" def find(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.find(sub [,start [,end]]) -> int Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def format(self, *args, **kwargs): # known special case of unicode.format """ S.format(*args, **kwargs) -> unicode Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces ('{' and '}'). """ pass def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.index(sub [,start [,end]]) -> int Like S.find() but raise ValueError when the substring is not found. """ return 0 def isalnum(self): # real signature unknown; restored from __doc__ """ S.isalnum() -> bool Return True if all characters in S are alphanumeric and there is at least one character in S, False otherwise. """ return False def isalpha(self): # real signature unknown; restored from __doc__ """ S.isalpha() -> bool Return True if all characters in S are alphabetic and there is at least one character in S, False otherwise. """ return False def isdecimal(self): # real signature unknown; restored from __doc__ """ S.isdecimal() -> bool Return True if there are only decimal characters in S, False otherwise. """ return False def isdigit(self): # real signature unknown; restored from __doc__ """ S.isdigit() -> bool Return True if all characters in S are digits and there is at least one character in S, False otherwise. """ return False def islower(self): # real signature unknown; restored from __doc__ """ S.islower() -> bool Return True if all cased characters in S are lowercase and there is at least one cased character in S, False otherwise. """ return False def isnumeric(self): # real signature unknown; restored from __doc__ """ S.isnumeric() -> bool Return True if there are only numeric characters in S, False otherwise. """ return False def isspace(self): # real signature unknown; restored from __doc__ """ S.isspace() -> bool Return True if all characters in S are whitespace and there is at least one character in S, False otherwise. """ return False def istitle(self): # real signature unknown; restored from __doc__ """ S.istitle() -> bool Return True if S is a titlecased string and there is at least one character in S, i.e. upper- and titlecase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise. """ return False def isupper(self): # real signature unknown; restored from __doc__ """ S.isupper() -> bool Return True if all cased characters in S are uppercase and there is at least one cased character in S, False otherwise. """ return False def join(self, iterable): # real signature unknown; restored from __doc__ """ S.join(iterable) -> unicode Return a string which is the concatenation of the strings in the iterable. The separator between elements is S. """ return u"" def ljust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.ljust(width[, fillchar]) -> int Return S left-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space). """ return 0 def lower(self): # real signature unknown; restored from __doc__ """ S.lower() -> unicode Return a copy of the string S converted to lowercase. """ return u"" def lstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.lstrip([chars]) -> unicode Return a copy of the string S with leading whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is a str, it will be converted to unicode before stripping """ return u"" def partition(self, sep): # real signature unknown; restored from __doc__ """ S.partition(sep) -> (head, sep, tail) Search for the separator sep in S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return S and two empty strings. """ pass def replace(self, old, new, count=None): # real signature unknown; restored from __doc__ """ S.replace(old, new[, count]) -> unicode Return a copy of S with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. """ return u"" def rfind(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rfind(sub [,start [,end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure. """ return 0 def rindex(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.rindex(sub [,start [,end]]) -> int Like S.rfind() but raise ValueError when the substring is not found. """ return 0 def rjust(self, width, fillchar=None): # real signature unknown; restored from __doc__ """ S.rjust(width[, fillchar]) -> unicode Return S right-justified in a Unicode string of length width. Padding is done using the specified fill character (default is a space). """ return u"" def rpartition(self, sep): # real signature unknown; restored from __doc__ """ S.rpartition(sep) -> (head, sep, tail) Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S. """ pass def rsplit(self, sep=None, maxsplit=None): # real signature unknown; restored from __doc__ """ S.rsplit([sep [,maxsplit]]) -> list of strings Return a list of the words in S, using sep as the delimiter string, starting at the end of the string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not specified, any whitespace string is a separator. """ return [] def rstrip(self, chars=None): # real signature unknown; restored from __doc__ """ S.rstrip([chars]) -> unicode Return a copy of the string S with trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is a str, it will be converted to unicode before stripping """ return u"" def split(self, sep=None, maxsplit=None): # real signature unknown; restored from __doc__ """ S.split([sep [,maxsplit]]) -> list of strings Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. """ return [] def splitlines(self, keepends=False): # real signature unknown; restored from __doc__ """ S.splitlines(keepends=False) -> list of strings Return a list of the lines in S, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true. """ return [] def startswith(self, prefix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. """ return False def strip(self, chars=None): # real signature unknown; restored from __doc__ """ S.strip([chars]) -> unicode Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. If chars is a str, it will be converted to unicode before stripping """ return u"" def swapcase(self): # real signature unknown; restored from __doc__ """ S.swapcase() -> unicode Return a copy of S with uppercase characters converted to lowercase and vice versa. """ return u"" def title(self): # real signature unknown; restored from __doc__ """ S.title() -> unicode Return a titlecased version of S, i.e. words start with title case characters, all remaining cased characters have lower case. """ return u"" def translate(self, table): # real signature unknown; restored from __doc__ """ S.translate(table) -> unicode Return a copy of the string S, where all characters have been mapped through the given translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted. """ return u"" def upper(self): # real signature unknown; restored from __doc__ """ S.upper() -> unicode Return a copy of S converted to uppercase. """ return u"" def zfill(self, width): # real signature unknown; restored from __doc__ """ S.zfill(width) -> unicode Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated. """ return u"" def _formatter_field_name_split(self, *args, **kwargs): # real signature unknown pass def _formatter_parser(self, *args, **kwargs): # real signature unknown pass def __add__(self, y): # real signature unknown; restored from __doc__ """ x.__add__(y) <==> x+y """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x """ pass def __eq__(self, y): # real signature unknown; restored from __doc__ """ x.__eq__(y) <==> x==y """ pass def __format__(self, format_spec): # real signature unknown; restored from __doc__ """ S.__format__(format_spec) -> unicode Return a formatted version of S as described by format_spec. """ return u"" def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __getnewargs__(self, *args, **kwargs): # real signature unknown pass def __getslice__(self, i, j): # real signature unknown; restored from __doc__ """ x.__getslice__(i, j) <==> x[i:j] Use of negative indices is not supported. """ pass def __ge__(self, y): # real signature unknown; restored from __doc__ """ x.__ge__(y) <==> x>=y """ pass def __gt__(self, y): # real signature unknown; restored from __doc__ """ x.__gt__(y) <==> x>y """ pass def __hash__(self): # real signature unknown; restored from __doc__ """ x.__hash__() <==> hash(x) """ pass def __init__(self, string=u'', encoding=None, errors='strict'): # known special case of unicode.__init__ """ unicode(object='') -> unicode object unicode(string[, encoding[, errors]]) -> unicode object Create a new Unicode object from the given encoded string. encoding defaults to the current default string encoding. errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'. # (copied from class doc) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass def __le__(self, y): # real signature unknown; restored from __doc__ """ x.__le__(y) <==> x<=y """ pass def __lt__(self, y): # real signature unknown; restored from __doc__ """ x.__lt__(y) <==> x<y """ pass def __mod__(self, y): # real signature unknown; restored from __doc__ """ x.__mod__(y) <==> x%y """ pass def __mul__(self, n): # real signature unknown; restored from __doc__ """ x.__mul__(n) <==> x*n """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __ne__(self, y): # real signature unknown; restored from __doc__ """ x.__ne__(y) <==> x!=y """ pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __rmod__(self, y): # real signature unknown; restored from __doc__ """ x.__rmod__(y) <==> y%x """ pass def __rmul__(self, n): # real signature unknown; restored from __doc__ """ x.__rmul__(n) <==> n*x """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __str__(self): # real signature unknown; restored from __doc__ """ x.__str__() <==> str(x) """ pass class xrange(object): """ xrange(stop) -> xrange object xrange(start, stop[, step]) -> xrange object Like range(), but instead of returning a list, returns an object that generates the numbers in the range on demand. For looping, this is slightly faster than range() and more memory efficient. """ def __getattribute__(self, name): # real signature unknown; restored from __doc__ """ x.__getattribute__('name') <==> x.name """ pass def __getitem__(self, y): # real signature unknown; restored from __doc__ """ x.__getitem__(y) <==> x[y] """ pass def __init__(self, stop): # real signature unknown; restored from __doc__ pass def __iter__(self): # real signature unknown; restored from __doc__ """ x.__iter__() <==> iter(x) """ pass def __len__(self): # real signature unknown; restored from __doc__ """ x.__len__() <==> len(x) """ pass @staticmethod # known case of __new__ def __new__(S, *more): # real signature unknown; restored from __doc__ """ T.__new__(S, ...) -> a new object with type S, a subtype of T """ pass def __reduce__(self, *args, **kwargs): # real signature unknown pass def __repr__(self): # real signature unknown; restored from __doc__ """ x.__repr__() <==> repr(x) """ pass def __reversed__(self, *args, **kwargs): # real signature unknown """ Returns a reverse iterator. """ pass # variables with complex values Ellipsis = None # (!) real value is '' NotImplemented = None # (!) real value is ''
apache-2.0
allenlavoie/tensorflow
tensorflow/contrib/autograph/converters/logical_expressions.py
5
4878
# 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. # ============================================================================== """Converter for logical expressions. e.g. `a and b -> tf.logical_and(a, b)`. This is not done automatically in TF. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import gast from tensorflow.contrib.autograph.pyct import anno from tensorflow.contrib.autograph.pyct import parser from tensorflow.contrib.autograph.pyct import templates from tensorflow.contrib.autograph.pyct import transformer # TODO(mdan): Properly extrack boolean ops according to lazy eval rules. # Note that this isn't completely safe either, because tensors may have control # dependencies. # Note that for loops that should be done after the loop was converted to # tf.while_loop so that the expanded conditionals are properly scoped. # Used to signal that an operand is safe for non-lazy evaluation. SAFE_BOOLEAN_OPERAND = 'SAFE_BOOLEAN_OPERAND' class LogicalExpressionTransformer(transformer.Base): """Converts logical expressions to corresponding TF calls.""" def __init__(self, context): super(LogicalExpressionTransformer, self).__init__(context) # TODO(mdan): Look into replacing with bitwise operators instead. # TODO(mdan): Skip replacing if the function is trivial. self.op_mapping = { gast.And: 'tf.logical_and', gast.Eq: 'tf.equal', gast.Gt: 'tf.greater', gast.GtE: 'tf.greater_equal', gast.Lt: 'tf.less', gast.LtE: 'tf.less_equal', gast.Not: 'tf.logical_not', gast.NotEq: 'tf.not_equal', gast.Or: 'tf.logical_or', gast.USub: 'tf.negative', gast.Is: 'autograph_utils.dynamic_is', gast.IsNot: 'autograph_utils.dynamic_is_not' } def _expect_simple_symbol(self, operand): if isinstance(operand, gast.Name): return if anno.hasanno(operand, SAFE_BOOLEAN_OPERAND): return raise NotImplementedError( 'only simple local variables are supported in logical and compound ' 'comparison expressions; for example, we support "a or b" but not ' '"a.x or b"; for a workaround, assign the expression to a local ' 'variable and use that instead, for example "tmp = a.x", "tmp or b"') def _matching_func(self, operator): op_type = type(operator) mapped_op = self.op_mapping.get(op_type) if not mapped_op: raise NotImplementedError('operator %s is not yet supported' % op_type) return mapped_op def _as_function(self, func_name, args): template = """ func_name(args) """ replacement = templates.replace_as_expression( template, func_name=parser.parse_expression(func_name), args=args) anno.setanno(replacement, SAFE_BOOLEAN_OPERAND, True) return replacement def visit_Compare(self, node): node = self.generic_visit(node) ops_and_comps = list(zip(node.ops, node.comparators)) left = node.left op_tree = None # Repeated comparisons are converted to conjunctions: # a < b < c -> a < b and b < c while ops_and_comps: op, right = ops_and_comps.pop(0) binary_comparison = self._as_function( self._matching_func(op), (left, right)) if isinstance(left, gast.Name) and isinstance(right, gast.Name): anno.setanno(binary_comparison, SAFE_BOOLEAN_OPERAND, True) if op_tree: self._expect_simple_symbol(right) op_tree = self._as_function('tf.logical_and', (binary_comparison, op_tree)) else: op_tree = binary_comparison left = right assert op_tree is not None return op_tree def visit_UnaryOp(self, node): node = self.generic_visit(node) return self._as_function(self._matching_func(node.op), node.operand) def visit_BoolOp(self, node): node = self.generic_visit(node) node_values = node.values right = node.values.pop() self._expect_simple_symbol(right) while node_values: left = node_values.pop() self._expect_simple_symbol(left) right = self._as_function(self._matching_func(node.op), (left, right)) return right def transform(node, context): return LogicalExpressionTransformer(context).visit(node)
apache-2.0
sangwonl/stage34
webapp/api/handlers/stage.py
1
6612
from django.views import View from django.conf import settings from datetime import datetime from api.helpers.mixins import AuthRequiredMixin from api.helpers.http.jsend import JSENDSuccess, JSENDError from api.models.resources import Membership, Stage from libs.utils.model_ext import model_to_dict from worker.tasks.deployment import ( task_provision_stage, task_change_stage_status, task_delete_stage, task_refresh_stage ) import pytz import os import json import jwt SERIALIZE_FIELDS = [ 'id', 'title', 'endpoint', 'status', 'repo', 'default_branch', 'branch', 'created_at' ] class StageRootHandler(AuthRequiredMixin, View): def get(self, request, *args, **kwargs): org = Membership.get_org_of_user(request.user) if not org: return JSENDError(status_code=400, msg='org not found') stages_qs = Stage.objects.filter(org=org) stages = [model_to_dict(s, fields=SERIALIZE_FIELDS) for s in stages_qs] return JSENDSuccess(status_code=200, data=stages) def post(self, request, *args, **kwargs): json_body = json.loads(request.body) title = json_body.get('title') repo = json_body.get('repo') branch= json_body.get('branch') default_branch= json_body.get('default_branch') run_on_create = json_body.get('run_on_create', False) if not (title and repo and default_branch and branch): return JSENDError(status_code=400, msg='invalid stage info') org = Membership.get_org_of_user(request.user) if not org: return JSENDError(status_code=400, msg='org not found') stage = Stage.objects.create( org=org, title=title, repo=repo, default_branch=default_branch, branch=branch ) github_access_key = request.user.jwt_payload.get('access_token') task_provision_stage.apply_async(args=[github_access_key, stage.id, repo, branch, run_on_create]) stage_dict = model_to_dict(stage, fields=SERIALIZE_FIELDS) return JSENDSuccess(status_code=200, data=stage_dict) class StageDetailHandler(AuthRequiredMixin, View): def get_stage(self, org, stage_id): try: stage = Stage.objects.get(org=org, id=stage_id) except Stage.DoesNotExist: return None return stage def get(self, request, stage_id, *args, **kwargs): org = Membership.get_org_of_user(request.user) if not org: return JSENDError(status_code=400, msg='org not found') stage = self.get_stage(org, stage_id) if not stage: return JSENDError(status_code=404, msg='stage not found') stage_dict = model_to_dict(stage, fields=SERIALIZE_FIELDS) return JSENDSuccess(status_code=200, data=stage_dict) def put(self, request, stage_id, *args, **kwargs): json_body = json.loads(request.body) new_status = json_body.get('status') if not new_status or new_status not in ('running', 'paused'): return JSENDError(status_code=400, msg='invalid stage status') org = Membership.get_org_of_user(request.user) if not org: return JSENDError(status_code=400, msg='org not found') stage = self.get_stage(org, stage_id) if not stage: return JSENDError(status_code=404, msg='stage not found') cur_status = stage.status if cur_status != new_status: github_access_key = request.user.jwt_payload.get('access_token') task_change_stage_status.apply_async(args=[github_access_key, stage_id, new_status]) new_status = 'changing' stage.title = json_body.get('title', stage.title) stage.repo = json_body.get('repo', stage.repo) stage.default_branch = json_body.get('default_branch', stage.default_branch) stage.branch = json_body.get('branch', stage.branch) stage.status = new_status stage.save() stage_dict = model_to_dict(stage, fields=SERIALIZE_FIELDS) return JSENDSuccess(status_code=204) def delete(self, request, stage_id, *args, **kwargs): org = Membership.get_org_of_user(request.user) if not org: return JSENDError(status_code=400, msg='org not found') stage = self.get_stage(org, stage_id) if not stage: return JSENDError(status_code=404, msg='stage not found') stage.status = 'deleting' stage.save() github_access_key = request.user.jwt_payload.get('access_token') task_delete_stage.apply_async(args=[github_access_key, stage_id]) return JSENDSuccess(status_code=204) class StageLogHandler(AuthRequiredMixin, View): def get_log_path(self, stage_id): return os.path.join(settings.STAGE_REPO_HOME, stage_id, 'output.log') def get(self, request, stage_id, *args, **kwargs): org = Membership.get_org_of_user(request.user) if not org: return JSENDError(status_code=400, msg='org not found') log_path = self.get_log_path(stage_id) if not os.path.exists(log_path): return JSENDError(status_code=404, msg='log file not found') log_msgs = [] with open(log_path, 'rt') as f: log_msg = f.read() log_msgs = [l for l in log_msg.split('\n') if l] ts = os.path.getmtime(log_path) tz = pytz.timezone(settings.TIME_ZONE) dt = datetime.fromtimestamp(ts, tz=tz) log_data = {'log_messages': log_msgs, 'log_time': dt.isoformat()} return JSENDSuccess(status_code=200, data=log_data) class StageRefreshHandler(AuthRequiredMixin, View): def get_stage(self, org, stage_id): try: stage = Stage.objects.get(org=org, id=stage_id) except Stage.DoesNotExist: return None return stage def post(self, request, stage_id, *args, **kwargs): org = Membership.get_org_of_user(request.user) if not org: return JSENDError(status_code=400, msg='org not found') stage = self.get_stage(org, stage_id) if not stage: return JSENDError(status_code=404, msg='stage not found') github_access_key = request.user.jwt_payload.get('access_token') task_refresh_stage.apply_async(args=[github_access_key, stage_id]) stage.status = 'changing' stage.save() stage_dict = model_to_dict(stage, fields=SERIALIZE_FIELDS) return JSENDSuccess(status_code=204)
mit
martinbuc/missionplanner
packages/IronPython.StdLib.2.7.4/content/Lib/distutils/command/sdist.py
42
18344
"""distutils.command.sdist Implements the Distutils 'sdist' command (create a source distribution).""" __revision__ = "$Id$" import os import string import sys from glob import glob from warnings import warn from distutils.core import Command from distutils import dir_util, dep_util, file_util, archive_util from distutils.text_file import TextFile from distutils.errors import (DistutilsPlatformError, DistutilsOptionError, DistutilsTemplateError) from distutils.filelist import FileList from distutils import log from distutils.util import convert_path def show_formats(): """Print all possible values for the 'formats' option (used by the "--help-formats" command-line option). """ from distutils.fancy_getopt import FancyGetopt from distutils.archive_util import ARCHIVE_FORMATS formats = [] for format in ARCHIVE_FORMATS.keys(): formats.append(("formats=" + format, None, ARCHIVE_FORMATS[format][2])) formats.sort() FancyGetopt(formats).print_help( "List of available source distribution formats:") class sdist(Command): description = "create a source distribution (tarball, zip file, etc.)" def checking_metadata(self): """Callable used for the check sub-command. Placed here so user_options can view it""" return self.metadata_check user_options = [ ('template=', 't', "name of manifest template file [default: MANIFEST.in]"), ('manifest=', 'm', "name of manifest file [default: MANIFEST]"), ('use-defaults', None, "include the default file set in the manifest " "[default; disable with --no-defaults]"), ('no-defaults', None, "don't include the default file set"), ('prune', None, "specifically exclude files/directories that should not be " "distributed (build tree, RCS/CVS dirs, etc.) " "[default; disable with --no-prune]"), ('no-prune', None, "don't automatically exclude anything"), ('manifest-only', 'o', "just regenerate the manifest and then stop " "(implies --force-manifest)"), ('force-manifest', 'f', "forcibly regenerate the manifest and carry on as usual. " "Deprecated: now the manifest is always regenerated."), ('formats=', None, "formats for source distribution (comma-separated list)"), ('keep-temp', 'k', "keep the distribution tree around after creating " + "archive file(s)"), ('dist-dir=', 'd', "directory to put the source distribution archive(s) in " "[default: dist]"), ('metadata-check', None, "Ensure that all required elements of meta-data " "are supplied. Warn if any missing. [default]"), ('owner=', 'u', "Owner name used when creating a tar file [default: current user]"), ('group=', 'g', "Group name used when creating a tar file [default: current group]"), ] boolean_options = ['use-defaults', 'prune', 'manifest-only', 'force-manifest', 'keep-temp', 'metadata-check'] help_options = [ ('help-formats', None, "list available distribution formats", show_formats), ] negative_opt = {'no-defaults': 'use-defaults', 'no-prune': 'prune' } default_format = {'posix': 'gztar', 'nt': 'zip' } sub_commands = [('check', checking_metadata)] def initialize_options(self): # 'template' and 'manifest' are, respectively, the names of # the manifest template and manifest file. self.template = None self.manifest = None # 'use_defaults': if true, we will include the default file set # in the manifest self.use_defaults = 1 self.prune = 1 self.manifest_only = 0 self.force_manifest = 0 self.formats = None self.keep_temp = 0 self.dist_dir = None self.archive_files = None self.metadata_check = 1 self.owner = None self.group = None def finalize_options(self): if self.manifest is None: self.manifest = "MANIFEST" if self.template is None: self.template = "MANIFEST.in" self.ensure_string_list('formats') if self.formats is None: try: self.formats = [self.default_format[os.name]] except KeyError: raise DistutilsPlatformError, \ "don't know how to create source distributions " + \ "on platform %s" % os.name bad_format = archive_util.check_archive_formats(self.formats) if bad_format: raise DistutilsOptionError, \ "unknown archive format '%s'" % bad_format if self.dist_dir is None: self.dist_dir = "dist" def run(self): # 'filelist' contains the list of files that will make up the # manifest self.filelist = FileList() # Run sub commands for cmd_name in self.get_sub_commands(): self.run_command(cmd_name) # Do whatever it takes to get the list of files to process # (process the manifest template, read an existing manifest, # whatever). File list is accumulated in 'self.filelist'. self.get_file_list() # If user just wanted us to regenerate the manifest, stop now. if self.manifest_only: return # Otherwise, go ahead and create the source distribution tarball, # or zipfile, or whatever. self.make_distribution() def check_metadata(self): """Deprecated API.""" warn("distutils.command.sdist.check_metadata is deprecated, \ use the check command instead", PendingDeprecationWarning) check = self.distribution.get_command_obj('check') check.ensure_finalized() check.run() def get_file_list(self): """Figure out the list of files to include in the source distribution, and put it in 'self.filelist'. This might involve reading the manifest template (and writing the manifest), or just reading the manifest, or just using the default file set -- it all depends on the user's options. """ # new behavior: # the file list is recalculated everytime because # even if MANIFEST.in or setup.py are not changed # the user might have added some files in the tree that # need to be included. # # This makes --force the default and only behavior. template_exists = os.path.isfile(self.template) if not template_exists: self.warn(("manifest template '%s' does not exist " + "(using default file list)") % self.template) self.filelist.findall() if self.use_defaults: self.add_defaults() if template_exists: self.read_template() if self.prune: self.prune_file_list() self.filelist.sort() self.filelist.remove_duplicates() self.write_manifest() def add_defaults(self): """Add all the default files to self.filelist: - README or README.txt - setup.py - test/test*.py - all pure Python modules mentioned in setup script - all files pointed by package_data (build_py) - all files defined in data_files. - all files defined as scripts. - all C sources listed as part of extensions or C libraries in the setup script (doesn't catch C headers!) Warns if (README or README.txt) or setup.py are missing; everything else is optional. """ standards = [('README', 'README.txt'), self.distribution.script_name] for fn in standards: if isinstance(fn, tuple): alts = fn got_it = 0 for fn in alts: if os.path.exists(fn): got_it = 1 self.filelist.append(fn) break if not got_it: self.warn("standard file not found: should have one of " + string.join(alts, ', ')) else: if os.path.exists(fn): self.filelist.append(fn) else: self.warn("standard file '%s' not found" % fn) optional = ['test/test*.py', 'setup.cfg'] for pattern in optional: files = filter(os.path.isfile, glob(pattern)) if files: self.filelist.extend(files) # build_py is used to get: # - python modules # - files defined in package_data build_py = self.get_finalized_command('build_py') # getting python files if self.distribution.has_pure_modules(): self.filelist.extend(build_py.get_source_files()) # getting package_data files # (computed in build_py.data_files by build_py.finalize_options) for pkg, src_dir, build_dir, filenames in build_py.data_files: for filename in filenames: self.filelist.append(os.path.join(src_dir, filename)) # getting distribution.data_files if self.distribution.has_data_files(): for item in self.distribution.data_files: if isinstance(item, str): # plain file item = convert_path(item) if os.path.isfile(item): self.filelist.append(item) else: # a (dirname, filenames) tuple dirname, filenames = item for f in filenames: f = convert_path(f) if os.path.isfile(f): self.filelist.append(f) if self.distribution.has_ext_modules(): build_ext = self.get_finalized_command('build_ext') self.filelist.extend(build_ext.get_source_files()) if self.distribution.has_c_libraries(): build_clib = self.get_finalized_command('build_clib') self.filelist.extend(build_clib.get_source_files()) if self.distribution.has_scripts(): build_scripts = self.get_finalized_command('build_scripts') self.filelist.extend(build_scripts.get_source_files()) def read_template(self): """Read and parse manifest template file named by self.template. (usually "MANIFEST.in") The parsing and processing is done by 'self.filelist', which updates itself accordingly. """ log.info("reading manifest template '%s'", self.template) template = TextFile(self.template, strip_comments=1, skip_blanks=1, join_lines=1, lstrip_ws=1, rstrip_ws=1, collapse_join=1) while 1: line = template.readline() if line is None: # end of file break try: self.filelist.process_template_line(line) except DistutilsTemplateError, msg: self.warn("%s, line %d: %s" % (template.filename, template.current_line, msg)) def prune_file_list(self): """Prune off branches that might slip into the file list as created by 'read_template()', but really don't belong there: * the build tree (typically "build") * the release tree itself (only an issue if we ran "sdist" previously with --keep-temp, or it aborted) * any RCS, CVS, .svn, .hg, .git, .bzr, _darcs directories """ build = self.get_finalized_command('build') base_dir = self.distribution.get_fullname() self.filelist.exclude_pattern(None, prefix=build.build_base) self.filelist.exclude_pattern(None, prefix=base_dir) # pruning out vcs directories # both separators are used under win32 if sys.platform == 'win32': seps = r'/|\\' else: seps = '/' vcs_dirs = ['RCS', 'CVS', r'\.svn', r'\.hg', r'\.git', r'\.bzr', '_darcs'] vcs_ptrn = r'(^|%s)(%s)(%s).*' % (seps, '|'.join(vcs_dirs), seps) self.filelist.exclude_pattern(vcs_ptrn, is_regex=1) def write_manifest(self): """Write the file list in 'self.filelist' (presumably as filled in by 'add_defaults()' and 'read_template()') to the manifest file named by 'self.manifest'. """ if os.path.isfile(self.manifest): fp = open(self.manifest) try: first_line = fp.readline() finally: fp.close() if first_line != '# file GENERATED by distutils, do NOT edit\n': log.info("not writing to manually maintained " "manifest file '%s'" % self.manifest) return content = self.filelist.files[:] content.insert(0, '# file GENERATED by distutils, do NOT edit') self.execute(file_util.write_file, (self.manifest, content), "writing manifest file '%s'" % self.manifest) def read_manifest(self): """Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution. """ log.info("reading manifest file '%s'", self.manifest) manifest = open(self.manifest) while 1: line = manifest.readline() if line == '': # end of file break if line[-1] == '\n': line = line[0:-1] self.filelist.append(line) manifest.close() def make_release_tree(self, base_dir, files): """Create the directory tree that will become the source distribution archive. All directories implied by the filenames in 'files' are created under 'base_dir', and then we hard link or copy (if hard linking is unavailable) those files into place. Essentially, this duplicates the developer's source tree, but in a directory named after the distribution, containing only the files to be distributed. """ # Create all the directories under 'base_dir' necessary to # put 'files' there; the 'mkpath()' is just so we don't die # if the manifest happens to be empty. self.mkpath(base_dir) dir_util.create_tree(base_dir, files, dry_run=self.dry_run) # And walk over the list of files, either making a hard link (if # os.link exists) to each one that doesn't already exist in its # corresponding location under 'base_dir', or copying each file # that's out-of-date in 'base_dir'. (Usually, all files will be # out-of-date, because by default we blow away 'base_dir' when # we're done making the distribution archives.) if hasattr(os, 'link'): # can make hard links on this system link = 'hard' msg = "making hard links in %s..." % base_dir else: # nope, have to copy link = None msg = "copying files to %s..." % base_dir if not files: log.warn("no files to distribute -- empty manifest?") else: log.info(msg) for file in files: if not os.path.isfile(file): log.warn("'%s' not a regular file -- skipping" % file) else: dest = os.path.join(base_dir, file) self.copy_file(file, dest, link=link) self.distribution.metadata.write_pkg_info(base_dir) def make_distribution(self): """Create the source distribution(s). First, we create the release tree with 'make_release_tree()'; then, we create all required archive files (according to 'self.formats') from the release tree. Finally, we clean up by blowing away the release tree (unless 'self.keep_temp' is true). The list of archive files created is stored so it can be retrieved later by 'get_archive_files()'. """ # Don't warn about missing meta-data here -- should be (and is!) # done elsewhere. base_dir = self.distribution.get_fullname() base_name = os.path.join(self.dist_dir, base_dir) self.make_release_tree(base_dir, self.filelist.files) archive_files = [] # remember names of files we create # tar archive must be created last to avoid overwrite and remove if 'tar' in self.formats: self.formats.append(self.formats.pop(self.formats.index('tar'))) for fmt in self.formats: file = self.make_archive(base_name, fmt, base_dir=base_dir, owner=self.owner, group=self.group) archive_files.append(file) self.distribution.dist_files.append(('sdist', '', file)) self.archive_files = archive_files if not self.keep_temp: dir_util.remove_tree(base_dir, dry_run=self.dry_run) def get_archive_files(self): """Return the list of archive files created when the command was run, or None if the command hasn't run yet. """ return self.archive_files
gpl-3.0
jimkmc/micropython
tests/bytecode/pylib-tests/abc.py
765
8057
# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Abstract Base Classes (ABCs) according to PEP 3119.""" from _weakrefset import WeakSet def abstractmethod(funcobj): """A decorator indicating abstract methods. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract methods are overridden. The abstract methods can be called using any of the normal 'super' call mechanisms. Usage: class C(metaclass=ABCMeta): @abstractmethod def my_abstract_method(self, ...): ... """ funcobj.__isabstractmethod__ = True return funcobj class abstractclassmethod(classmethod): """ A decorator indicating abstract classmethods. Similar to abstractmethod. Usage: class C(metaclass=ABCMeta): @abstractclassmethod def my_abstract_classmethod(cls, ...): ... 'abstractclassmethod' is deprecated. Use 'classmethod' with 'abstractmethod' instead. """ __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable) class abstractstaticmethod(staticmethod): """ A decorator indicating abstract staticmethods. Similar to abstractmethod. Usage: class C(metaclass=ABCMeta): @abstractstaticmethod def my_abstract_staticmethod(...): ... 'abstractstaticmethod' is deprecated. Use 'staticmethod' with 'abstractmethod' instead. """ __isabstractmethod__ = True def __init__(self, callable): callable.__isabstractmethod__ = True super().__init__(callable) class abstractproperty(property): """ A decorator indicating abstract properties. Requires that the metaclass is ABCMeta or derived from it. A class that has a metaclass derived from ABCMeta cannot be instantiated unless all of its abstract properties are overridden. The abstract properties can be called using any of the normal 'super' call mechanisms. Usage: class C(metaclass=ABCMeta): @abstractproperty def my_abstract_property(self): ... This defines a read-only property; you can also define a read-write abstract property using the 'long' form of property declaration: class C(metaclass=ABCMeta): def getx(self): ... def setx(self, value): ... x = abstractproperty(getx, setx) 'abstractproperty' is deprecated. Use 'property' with 'abstractmethod' instead. """ __isabstractmethod__ = True class ABCMeta(type): """Metaclass for defining Abstract Base Classes (ABCs). Use this metaclass to create an ABC. An ABC can be subclassed directly, and then acts as a mix-in class. You can also register unrelated concrete classes (even built-in classes) and unrelated ABCs as 'virtual subclasses' -- these and their descendants will be considered subclasses of the registering ABC by the built-in issubclass() function, but the registering ABC won't show up in their MRO (Method Resolution Order) nor will method implementations defined by the registering ABC be callable (not even via super()). """ # A global counter that is incremented each time a class is # registered as a virtual subclass of anything. It forces the # negative cache to be cleared before its next use. _abc_invalidation_counter = 0 def __new__(mcls, name, bases, namespace): cls = super().__new__(mcls, name, bases, namespace) # Compute set of abstract method names abstracts = {name for name, value in namespace.items() if getattr(value, "__isabstractmethod__", False)} for base in bases: for name in getattr(base, "__abstractmethods__", set()): value = getattr(cls, name, None) if getattr(value, "__isabstractmethod__", False): abstracts.add(name) cls.__abstractmethods__ = frozenset(abstracts) # Set up inheritance registry cls._abc_registry = WeakSet() cls._abc_cache = WeakSet() cls._abc_negative_cache = WeakSet() cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter return cls def register(cls, subclass): """Register a virtual subclass of an ABC. Returns the subclass, to allow usage as a class decorator. """ if not isinstance(subclass, type): raise TypeError("Can only register classes") if issubclass(subclass, cls): return subclass # Already a subclass # Subtle: test for cycles *after* testing for "already a subclass"; # this means we allow X.register(X) and interpret it as a no-op. if issubclass(cls, subclass): # This would create a cycle, which is bad for the algorithm below raise RuntimeError("Refusing to create an inheritance cycle") cls._abc_registry.add(subclass) ABCMeta._abc_invalidation_counter += 1 # Invalidate negative cache return subclass def _dump_registry(cls, file=None): """Debug helper to print the ABC registry.""" print("Class: %s.%s" % (cls.__module__, cls.__name__), file=file) print("Inv.counter: %s" % ABCMeta._abc_invalidation_counter, file=file) for name in sorted(cls.__dict__.keys()): if name.startswith("_abc_"): value = getattr(cls, name) print("%s: %r" % (name, value), file=file) def __instancecheck__(cls, instance): """Override for isinstance(instance, cls).""" # Inline the cache checking subclass = instance.__class__ if subclass in cls._abc_cache: return True subtype = type(instance) if subtype is subclass: if (cls._abc_negative_cache_version == ABCMeta._abc_invalidation_counter and subclass in cls._abc_negative_cache): return False # Fall back to the subclass check. return cls.__subclasscheck__(subclass) return any(cls.__subclasscheck__(c) for c in {subclass, subtype}) def __subclasscheck__(cls, subclass): """Override for issubclass(subclass, cls).""" # Check cache if subclass in cls._abc_cache: return True # Check negative cache; may have to invalidate if cls._abc_negative_cache_version < ABCMeta._abc_invalidation_counter: # Invalidate the negative cache cls._abc_negative_cache = WeakSet() cls._abc_negative_cache_version = ABCMeta._abc_invalidation_counter elif subclass in cls._abc_negative_cache: return False # Check the subclass hook ok = cls.__subclasshook__(subclass) if ok is not NotImplemented: assert isinstance(ok, bool) if ok: cls._abc_cache.add(subclass) else: cls._abc_negative_cache.add(subclass) return ok # Check if it's a direct subclass if cls in getattr(subclass, '__mro__', ()): cls._abc_cache.add(subclass) return True # Check if it's a subclass of a registered class (recursive) for rcls in cls._abc_registry: if issubclass(subclass, rcls): cls._abc_cache.add(subclass) return True # Check if it's a subclass of a subclass (recursive) for scls in cls.__subclasses__(): if issubclass(subclass, scls): cls._abc_cache.add(subclass) return True # No dice; update negative cache cls._abc_negative_cache.add(subclass) return False
mit
globaltoken/globaltoken
test/functional/test_framework/authproxy.py
1
7759
# Copyright (c) 2011 Jeff Garzik # # Previous copyright, from python-jsonrpc/jsonrpc/proxy.py: # # Copyright (c) 2007 Jan-Klaas Kollhof # # This file is part of jsonrpc. # # jsonrpc 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 software 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 software; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA """HTTP proxy for opening RPC connection to globaltokend. AuthServiceProxy has the following improvements over python-jsonrpc's ServiceProxy class: - HTTP connections persist for the life of the AuthServiceProxy object (if server supports HTTP/1.1) - sends protocol 'version', per JSON-RPC 1.1 - sends proper, incrementing 'id' - sends Basic HTTP authentication headers - parses all JSON numbers that look like floats as Decimal - uses standard Python json lib """ import base64 import decimal import http.client import json import logging import socket import time import urllib.parse HTTP_TIMEOUT = 30 USER_AGENT = "AuthServiceProxy/0.1" log = logging.getLogger("BitcoinRPC") class JSONRPCException(Exception): def __init__(self, rpc_error): try: errmsg = '%(message)s (%(code)i)' % rpc_error except (KeyError, TypeError): errmsg = '' super().__init__(errmsg) self.error = rpc_error def EncodeDecimal(o): if isinstance(o, decimal.Decimal): return str(o) raise TypeError(repr(o) + " is not JSON serializable") class AuthServiceProxy(): __id_count = 0 # ensure_ascii: escape unicode as \uXXXX, passed to json.dumps def __init__(self, service_url, service_name=None, timeout=HTTP_TIMEOUT, connection=None, ensure_ascii=True): self.__service_url = service_url self._service_name = service_name self.ensure_ascii = ensure_ascii # can be toggled on the fly by tests self.__url = urllib.parse.urlparse(service_url) port = 80 if self.__url.port is None else self.__url.port user = None if self.__url.username is None else self.__url.username.encode('utf8') passwd = None if self.__url.password is None else self.__url.password.encode('utf8') authpair = user + b':' + passwd self.__auth_header = b'Basic ' + base64.b64encode(authpair) if connection: # Callables re-use the connection of the original proxy self.__conn = connection elif self.__url.scheme == 'https': self.__conn = http.client.HTTPSConnection(self.__url.hostname, port, timeout=timeout) else: self.__conn = http.client.HTTPConnection(self.__url.hostname, port, timeout=timeout) def __getattr__(self, name): if name.startswith('__') and name.endswith('__'): # Python internal stuff raise AttributeError if self._service_name is not None: name = "%s.%s" % (self._service_name, name) return AuthServiceProxy(self.__service_url, name, connection=self.__conn) def _request(self, method, path, postdata): ''' Do a HTTP request, with retry if we get disconnected (e.g. due to a timeout). This is a workaround for https://bugs.python.org/issue3566 which is fixed in Python 3.5. ''' headers = {'Host': self.__url.hostname, 'User-Agent': USER_AGENT, 'Authorization': self.__auth_header, 'Content-type': 'application/json'} try: self.__conn.request(method, path, postdata, headers) return self._get_response() except http.client.BadStatusLine as e: if e.line == "''": # if connection was closed, try again self.__conn.close() self.__conn.request(method, path, postdata, headers) return self._get_response() else: raise except (BrokenPipeError, ConnectionResetError): # Python 3.5+ raises BrokenPipeError instead of BadStatusLine when the connection was reset # ConnectionResetError happens on FreeBSD with Python 3.4 self.__conn.close() self.__conn.request(method, path, postdata, headers) return self._get_response() def get_request(self, *args, **argsn): AuthServiceProxy.__id_count += 1 log.debug("-%s-> %s %s" % (AuthServiceProxy.__id_count, self._service_name, json.dumps(args, default=EncodeDecimal, ensure_ascii=self.ensure_ascii))) if args and argsn: raise ValueError('Cannot handle both named and positional arguments') return {'version': '1.1', 'method': self._service_name, 'params': args or argsn, 'id': AuthServiceProxy.__id_count} def __call__(self, *args, **argsn): postdata = json.dumps(self.get_request(*args, **argsn), default=EncodeDecimal, ensure_ascii=self.ensure_ascii) response = self._request('POST', self.__url.path, postdata.encode('utf-8')) if response['error'] is not None: raise JSONRPCException(response['error']) elif 'result' not in response: raise JSONRPCException({ 'code': -343, 'message': 'missing JSON-RPC result'}) else: return response['result'] def batch(self, rpc_call_list): postdata = json.dumps(list(rpc_call_list), default=EncodeDecimal, ensure_ascii=self.ensure_ascii) log.debug("--> " + postdata) return self._request('POST', self.__url.path, postdata.encode('utf-8')) def _get_response(self): req_start_time = time.time() try: http_response = self.__conn.getresponse() except socket.timeout as e: raise JSONRPCException({ 'code': -344, 'message': '%r RPC took longer than %f seconds. Consider ' 'using larger timeout for calls that take ' 'longer to return.' % (self._service_name, self.__conn.timeout)}) if http_response is None: raise JSONRPCException({ 'code': -342, 'message': 'missing HTTP response from server'}) content_type = http_response.getheader('Content-Type') if content_type != 'application/json': raise JSONRPCException({ 'code': -342, 'message': 'non-JSON HTTP response with \'%i %s\' from server' % (http_response.status, http_response.reason)}) responsedata = http_response.read().decode('utf8') response = json.loads(responsedata, parse_float=decimal.Decimal) elapsed = time.time() - req_start_time if "error" in response and response["error"] is None: log.debug("<-%s- [%.6f] %s" % (response["id"], elapsed, json.dumps(response["result"], default=EncodeDecimal, ensure_ascii=self.ensure_ascii))) else: log.debug("<-- [%.6f] %s" % (elapsed, responsedata)) return response def __truediv__(self, relative_uri): return AuthServiceProxy("{}/{}".format(self.__service_url, relative_uri), self._service_name, connection=self.__conn)
mit
jtomasek/tuskar-ui-1
tuskar_ui/infrastructure/resource_management/resource_classes/workflows.py
1
12384
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import workflows from tuskar_ui import api as tuskar import tuskar_ui.workflows import re from tuskar_ui.infrastructure. \ resource_management.resource_classes.tables import FlavorTemplatesTable from tuskar_ui.infrastructure. \ resource_management.resource_classes.tables import RacksTable class ResourceClassInfoAndFlavorsAction(workflows.Action): name = forms.CharField(max_length=255, label=_("Class Name"), help_text="", required=True) service_type = forms.ChoiceField(label=_('Class Type'), required=True, choices=[('', ''), ('compute', ('Compute')), ('not_compute', ('Non Compute')), ], widget=forms.Select( attrs={'class': 'switchable'}) ) image = forms.ChoiceField(label=_('Provisioning Image'), required=True, choices=[('compute-img', ('overcloud-compute'))], widget=forms.Select( attrs={'class': 'switchable'}) ) def clean(self): cleaned_data = super(ResourceClassInfoAndFlavorsAction, self).clean() name = cleaned_data.get('name') resource_class_id = self.initial.get('resource_class_id', None) try: resource_classes = tuskar.ResourceClass.list(self.request) except Exception: resource_classes = [] msg = _('Unable to get resource class list') exceptions.check_message(["Connection", "refused"], msg) raise for resource_class in resource_classes: if resource_class.name == name and \ resource_class_id != resource_class.id: raise forms.ValidationError( _('The name "%s" is already used by' ' another resource class.') % name ) return cleaned_data class Meta: name = _("Class Settings") help_text = _("From here you can fill the class " "settings and add flavors to class.") class CreateResourceClassInfoAndFlavors(tuskar_ui.workflows.TableStep): table_classes = (FlavorTemplatesTable,) action_class = ResourceClassInfoAndFlavorsAction template_name = 'infrastructure/resource_management/resource_classes/'\ '_resource_class_info_and_flavors_step.html' contributes = ("name", "service_type", "flavors_object_ids", 'max_vms') def contribute(self, data, context): request = self.workflow.request if data: context["flavors_object_ids"] =\ request.POST.getlist("flavors_object_ids") # todo: lsmola django can't parse dictionaruy from POST # this should be rewritten to django formset context["max_vms"] = {} for index, value in request.POST.items(): match = re.match( '^(flavors_object_ids__max_vms__(.*?))$', index) if match: context["max_vms"][match.groups()[1]] = value context.update(data) return context def get_flavors_data(self): try: resource_class_id = self.workflow.context.get("resource_class_id") if resource_class_id: resource_class = tuskar.ResourceClass.get( self.workflow.request, resource_class_id) # TODO(lsmola ugly interface, rewrite) self._tables['flavors'].active_multi_select_values = \ resource_class.flavortemplates_ids all_flavors = resource_class.all_flavors else: all_flavors = tuskar.FlavorTemplate.list( self.workflow.request) except Exception: all_flavors = [] exceptions.handle(self.workflow.request, _('Unable to retrieve resource flavors list.')) return all_flavors class RacksAction(workflows.Action): class Meta: name = _("Racks") class CreateRacks(tuskar_ui.workflows.TableStep): table_classes = (RacksTable,) action_class = RacksAction contributes = ("racks_object_ids") template_name = 'infrastructure/resource_management/'\ 'resource_classes/_racks_step.html' def contribute(self, data, context): request = self.workflow.request context["racks_object_ids"] =\ request.POST.getlist("racks_object_ids") context.update(data) return context def get_racks_data(self): try: resource_class_id = self.workflow.context.get("resource_class_id") if resource_class_id: resource_class = tuskar.ResourceClass.get( self.workflow.request, resource_class_id) # TODO(lsmola ugly interface, rewrite) self._tables['racks'].active_multi_select_values = \ resource_class.racks_ids racks = \ resource_class.all_racks else: racks = \ tuskar.Rack.list(self.workflow.request, True) except Exception: racks = [] exceptions.handle(self.workflow.request, _('Unable to retrieve racks list.')) return racks class ResourceClassWorkflowMixin: # FIXME active tabs coflict # When on page with tabs, the workflow with more steps is used, # there is a conflict of active tabs and it always shows the # first tab after an action. So I explicitly specify to what # tab it should redirect after action, until the coflict will # be fixed in Horizon. def get_index_url(self): """This url is used both as success and failure url""" return "%s?tab=resource_management_tabs__resource_classes_tab" %\ reverse("horizon:infrastructure:resource_management:index") def get_success_url(self): return self.get_index_url() def get_failure_url(self): return self.get_index_url() def format_status_message(self, message): name = self.context.get('name') return message % name def _get_flavors(self, request, data): flavors = [] flavor_ids = data.get('flavors_object_ids') or [] max_vms = data.get('max_vms') resource_class_name = data['name'] for template_id in flavor_ids: template = tuskar.FlavorTemplate.get(request, template_id) capacities = [] for c in template.capacities: capacities.append({'name': c.name, 'value': str(c.value), 'unit': c.unit}) # FIXME: tuskar uses resource-class-name prefix for flavors, # e.g. m1.large, we add rc name to the template name: flavor_name = "%s.%s" % (resource_class_name, template.name) flavors.append({'name': flavor_name, 'max_vms': max_vms.get(template.id, None), 'capacities': capacities}) return flavors def _add_racks(self, request, data, resource_class): ids_to_add = data.get('racks_object_ids') or [] resource_class.set_racks(request, ids_to_add) class CreateResourceClass(ResourceClassWorkflowMixin, workflows.Workflow): default_steps = (CreateResourceClassInfoAndFlavors, CreateRacks) slug = "create_resource_class" name = _("Create Class") finalize_button_name = _("Create Class") success_message = _('Created class "%s".') failure_message = _('Unable to create class "%s".') def _create_resource_class_info(self, request, data): try: flavors = self._get_flavors(request, data) return tuskar.ResourceClass.create( request, name=data['name'], service_type=data['service_type'], flavors=flavors) except Exception: redirect = self.get_failure_url() exceptions.handle(request, _('Unable to create resource class.'), redirect=redirect) return None def handle(self, request, data): resource_class = self._create_resource_class_info(request, data) self._add_racks(request, data, resource_class) return True class UpdateResourceClassInfoAndFlavors(CreateResourceClassInfoAndFlavors): depends_on = ("resource_class_id",) class UpdateRacks(CreateRacks): depends_on = ("resource_class_id",) class UpdateResourceClass(ResourceClassWorkflowMixin, workflows.Workflow): default_steps = (UpdateResourceClassInfoAndFlavors, UpdateRacks) slug = "update_resource_class" name = _("Update Class") finalize_button_name = _("Update Class") success_message = _('Updated class "%s".') failure_message = _('Unable to update class "%s".') def _update_resource_class_info(self, request, data): try: flavors = self._get_flavors(request, data) return tuskar.ResourceClass.update( request, data['resource_class_id'], name=data['name'], service_type=data['service_type'], flavors=flavors) except Exception: redirect = self.get_failure_url() exceptions.handle(request, _('Unable to create resource class.'), redirect=redirect) return None def handle(self, request, data): resource_class = self._update_resource_class_info(request, data) self._add_racks(request, data, resource_class) return True class DetailUpdateWorkflow(UpdateResourceClass): def get_index_url(self): """This url is used both as success and failure url""" url = "horizon:infrastructure:resource_management:resource_classes:"\ "detail" return "%s?tab=resource_class_details__overview" % ( reverse(url, args=(self.context["resource_class_id"]))) class UpdateRacksWorkflow(UpdateResourceClass): def get_index_url(self): """This url is used both as success and failure url""" url = "horizon:infrastructure:resource_management:resource_classes:"\ "detail" return "%s?tab=resource_class_details__racks" % ( reverse(url, args=(self.context["resource_class_id"]))) class UpdateFlavorsWorkflow(UpdateResourceClass): def get_index_url(self): """This url is used both as success and failure url""" url = "horizon:infrastructure:resource_management:resource_classes:"\ "detail" return "%s?tab=resource_class_details__flavors" % ( reverse(url, args=(self.context["resource_class_id"])))
apache-2.0
khushboo9293/postorius
src/postorius/models.py
2
11004
# -*- coding: utf-8 -*- # Copyright (C) 1998-2015 by the Free Software Foundation, Inc. # # This file is part of Postorius. # # Postorius 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. # # Postorius 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 # Postorius. If not, see <http://www.gnu.org/licenses/>. from __future__ import ( absolute_import, division, print_function, unicode_literals) import random import hashlib import logging from datetime import datetime, timedelta from django.conf import settings from django.contrib.auth.models import User from django.core.exceptions import ImproperlyConfigured from django.core.mail import send_mail from django.db.models.signals import post_save from django.core.urlresolvers import reverse from django.dispatch import receiver from django.db import models from django.http import Http404 from django.template import Context from django.template.loader import get_template from mailmanclient import MailmanConnectionError from postorius.utils import get_client from urllib2 import HTTPError logger = logging.getLogger(__name__) @receiver(post_save, sender=User) def create_mailman_user(sender, **kwargs): if kwargs.get('created'): autocreate = False try: autocreate = settings.AUTOCREATE_MAILMAN_USER except AttributeError: pass if autocreate: user = kwargs.get('instance') client = get_client() try: client.create_user(user.email, None, None) except HTTPError: pass class MailmanApiError(Exception): """Raised if the API is not available. """ pass class Mailman404Error(Exception): """Proxy exception. Raised if the API returns 404.""" pass class MailmanRestManager(object): """Manager class to give a model class CRUD access to the API. Returns objects (or lists of objects) retrived from the API. """ def __init__(self, resource_name, resource_name_plural, cls_name=None): self.resource_name = resource_name self.resource_name_plural = resource_name_plural def all(self): try: return getattr(get_client(), self.resource_name_plural) except AttributeError: raise MailmanApiError except MailmanConnectionError, e: raise MailmanApiError(e) def get(self, **kwargs): try: method = getattr(get_client(), 'get_' + self.resource_name) return method(**kwargs) except AttributeError, e: raise MailmanApiError(e) except HTTPError, e: if e.code == 404: raise Mailman404Error('Mailman resource could not be found.') else: raise except MailmanConnectionError, e: raise MailmanApiError(e) def get_or_404(self, **kwargs): """Similar to `self.get` but raises standard Django 404 error. """ try: return self.get(**kwargs) except Mailman404Error: raise Http404 except MailmanConnectionError, e: raise MailmanApiError(e) def create(self, **kwargs): try: method = getattr(get_client(), 'create_' + self.resource_name) return method(**kwargs) except AttributeError, e: raise MailmanApiError(e) except HTTPError, e: if e.code == 409: raise MailmanApiError else: raise except MailmanConnectionError: raise MailmanApiError def delete(self): """Not implemented since the objects returned from the API have a `delete` method of their own. """ pass class MailmanListManager(MailmanRestManager): def __init__(self): super(MailmanListManager, self).__init__('list', 'lists') def all(self, only_public=False): try: objects = getattr(get_client(), self.resource_name_plural) except AttributeError: raise MailmanApiError except MailmanConnectionError, e: raise MailmanApiError(e) if only_public: public = [] for obj in objects: if obj.settings.get('advertised', False): public.append(obj) return public else: return objects def by_mail_host(self, mail_host, only_public=False): objects = self.all(only_public) host_objects = [] for obj in objects: if obj.mail_host == mail_host: host_objects.append(obj) return host_objects class MailmanRestModel(object): """Simple REST Model class to make REST API calls Django style. """ MailmanApiError = MailmanApiError DoesNotExist = Mailman404Error def __init__(self, **kwargs): self.kwargs = kwargs def save(self): """Proxy function for `objects.create`. (REST API uses `create`, while Django uses `save`.) """ self.objects.create(**self.kwargs) class Domain(MailmanRestModel): """Domain model class. """ objects = MailmanRestManager('domain', 'domains') class List(MailmanRestModel): """List model class. """ objects = MailmanListManager() class MailmanUser(MailmanRestModel): """MailmanUser model class. """ objects = MailmanRestManager('user', 'users') class Member(MailmanRestModel): """Member model class. """ objects = MailmanRestManager('member', 'members') class AddressConfirmationProfileManager(models.Manager): """ Manager class for AddressConfirmationProfile. """ def create_profile(self, email, user): # Create or update a profile # Guarantee an email bytestr type that can be fed to hashlib. email_str = email if isinstance(email_str, unicode): email_str = email_str.encode('utf-8') activation_key = hashlib.sha1( str(random.random())+email_str).hexdigest() # Make now tz naive (we don't care about the timezone) now = datetime.now().replace(tzinfo=None) # Either update an existing profile record for the given email address try: profile = self.get(email=email) profile.activation_key = activation_key profile.created = now profile.save() # ... or create a new one. except AddressConfirmationProfile.DoesNotExist: profile = self.create(email=email, activation_key=activation_key, user=user, created=now) return profile class AddressConfirmationProfile(models.Model): """ Profile model for temporarily storing an activation key to register an email address. """ email = models.EmailField() activation_key = models.CharField(max_length=40) created = models.DateTimeField() user = models.ForeignKey(User) objects = AddressConfirmationProfileManager() def __unicode__(self): return u'Address Confirmation Profile for {0}'.format(self.email) @property def is_expired(self): """ a profile expires after 1 day by default. This can be configured in the settings. >>> EMAIL_CONFIRMATION_EXPIRATION_DELTA = timedelta(days=2) """ expiration_delta = getattr( settings, 'EMAIL_CONFIRMATION_EXPIRATION_DELTA', timedelta(days=1)) age = datetime.now().replace(tzinfo=None) - \ self.created.replace(tzinfo=None) return age > expiration_delta def _create_host_url(self, request): # Create the host url protocol = 'https' if not request.is_secure(): protocol = 'http' server_name = request.META['SERVER_NAME'] if server_name[-1] == '/': server_name = server_name[:len(server_name) - 1] return '{0}://{1}'.format(protocol, server_name) def send_confirmation_link(self, request, template_context=None, template_path=None): """ Send out a message containing a link to activate the given address. The following settings are recognized: >>> EMAIL_CONFIRMATION_TEMPLATE = 'postorius/address_confirmation_message.txt' >>> EMAIL_CONFIRMATION_FROM = 'postmaster@list.org' >>> EMAIL_CONFIRMATION_SUBJECT = 'Confirmation needed' :param request: The HTTP request object. :type request: HTTPRequest :param template_context: The context used when rendering the template. Falls back to host url and activation link. :type template_context: django.template.Context """ # create the host url and the activation link need for the template host_url = self._create_host_url(request) # Get the url string from url conf. url = reverse('address_activation_link', kwargs={'activation_key': self.activation_key}) activation_link = '{0}{1}'.format(host_url, url) # Detect the right template path, either from the param, # the setting or the default if not template_path: template_path = getattr(settings, 'EMAIL_CONFIRMATION_TEMPLATE', 'postorius/address_confirmation_message.txt') # Create a template context (if there is none) containing # the activation_link and the host_url. if not template_context: template_context = Context( {'activation_link': activation_link, 'host_url': host_url}) email_subject = getattr( settings, 'EMAIL_CONFIRMATION_SUBJECT', u'Confirmation needed') try: sender_address = getattr(settings, 'EMAIL_CONFIRMATION_FROM') except AttributeError: # settings.EMAIL_CONFIRMATION_FROM is not defined, fallback # settings.DEFAULT_EMAIL_FROM as mentioned in the django # docs. If that also fails, raise a `ImproperlyConfigured` Error. try: sender_address = getattr(settings, 'DEFAULT_FROM_EMAIL') except AttributeError: raise ImproperlyConfigured send_mail(email_subject, get_template(template_path).render(template_context), sender_address, [self.email])
gpl-3.0
chaso137/wot-xvm
src/xpm/xpm/mods/lib/tlslite/utils/pem.py
116
3587
# Author: Trevor Perrin # See the LICENSE file for legal information regarding use of this file. from .compat import * import binascii #This code is shared with tackpy (somewhat), so I'd rather make minimal #changes, and preserve the use of a2b_base64 throughout. def dePem(s, name): """Decode a PEM string into a bytearray of its payload. The input must contain an appropriate PEM prefix and postfix based on the input name string, e.g. for name="CERTIFICATE": -----BEGIN CERTIFICATE----- MIIBXDCCAUSgAwIBAgIBADANBgkqhkiG9w0BAQUFADAPMQ0wCwYDVQQDEwRUQUNL ... KoZIhvcNAQEFBQADAwA5kw== -----END CERTIFICATE----- The first such PEM block in the input will be found, and its payload will be base64 decoded and returned. """ prefix = "-----BEGIN %s-----" % name postfix = "-----END %s-----" % name start = s.find(prefix) if start == -1: raise SyntaxError("Missing PEM prefix") end = s.find(postfix, start+len(prefix)) if end == -1: raise SyntaxError("Missing PEM postfix") s = s[start+len("-----BEGIN %s-----" % name) : end] retBytes = a2b_base64(s) # May raise SyntaxError return retBytes def dePemList(s, name): """Decode a sequence of PEM blocks into a list of bytearrays. The input must contain any number of PEM blocks, each with the appropriate PEM prefix and postfix based on the input name string, e.g. for name="TACK BREAK SIG". Arbitrary text can appear between and before and after the PEM blocks. For example: " Created by TACK.py 0.9.3 Created at 2012-02-01T00:30:10Z -----BEGIN TACK BREAK SIG----- ATKhrz5C6JHJW8BF5fLVrnQss6JnWVyEaC0p89LNhKPswvcC9/s6+vWLd9snYTUv YMEBdw69PUP8JB4AdqA3K6Ap0Fgd9SSTOECeAKOUAym8zcYaXUwpk0+WuPYa7Zmm SkbOlK4ywqt+amhWbg9txSGUwFO5tWUHT3QrnRlE/e3PeNFXLx5Bckg= -----END TACK BREAK SIG----- Created by TACK.py 0.9.3 Created at 2012-02-01T00:30:11Z -----BEGIN TACK BREAK SIG----- ATKhrz5C6JHJW8BF5fLVrnQss6JnWVyEaC0p89LNhKPswvcC9/s6+vWLd9snYTUv YMEBdw69PUP8JB4AdqA3K6BVCWfcjN36lx6JwxmZQncS6sww7DecFO/qjSePCxwM +kdDqX/9/183nmjx6bf0ewhPXkA0nVXsDYZaydN8rJU1GaMlnjcIYxY= -----END TACK BREAK SIG----- " All such PEM blocks will be found, decoded, and return in an ordered list of bytearrays, which may have zero elements if not PEM blocks are found. """ bList = [] prefix = "-----BEGIN %s-----" % name postfix = "-----END %s-----" % name while 1: start = s.find(prefix) if start == -1: return bList end = s.find(postfix, start+len(prefix)) if end == -1: raise SyntaxError("Missing PEM postfix") s2 = s[start+len(prefix) : end] retBytes = a2b_base64(s2) # May raise SyntaxError bList.append(retBytes) s = s[end+len(postfix) : ] def pem(b, name): """Encode a payload bytearray into a PEM string. The input will be base64 encoded, then wrapped in a PEM prefix/postfix based on the name string, e.g. for name="CERTIFICATE": -----BEGIN CERTIFICATE----- MIIBXDCCAUSgAwIBAgIBADANBgkqhkiG9w0BAQUFADAPMQ0wCwYDVQQDEwRUQUNL ... KoZIhvcNAQEFBQADAwA5kw== -----END CERTIFICATE----- """ s1 = b2a_base64(b)[:-1] # remove terminating \n s2 = "" while s1: s2 += s1[:64] + "\n" s1 = s1[64:] s = ("-----BEGIN %s-----\n" % name) + s2 + \ ("-----END %s-----\n" % name) return s def pemSniff(inStr, name): searchStr = "-----BEGIN %s-----" % name return searchStr in inStr
gpl-3.0
waytai/odoo
openerp/addons/base/res/res_config.py
243
30944
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 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 from operator import attrgetter import re import openerp from openerp import SUPERUSER_ID from openerp.osv import osv, fields from openerp.tools import ustr from openerp.tools.translate import _ from openerp import exceptions from lxml import etree _logger = logging.getLogger(__name__) class res_config_module_installation_mixin(object): def _install_modules(self, cr, uid, modules, context): """Install the requested modules. return the next action to execute modules is a list of tuples (mod_name, browse_record | None) """ ir_module = self.pool.get('ir.module.module') to_install_ids = [] to_install_missing_names = [] for name, module in modules: if not module: to_install_missing_names.append(name) elif module.state == 'uninstalled': to_install_ids.append(module.id) result = None if to_install_ids: result = ir_module.button_immediate_install(cr, uid, to_install_ids, context=context) #FIXME: if result is not none, the corresponding todo will be skipped because it was just marked done if to_install_missing_names: return { 'type': 'ir.actions.client', 'tag': 'apps', 'params': {'modules': to_install_missing_names}, } return result class res_config_configurable(osv.osv_memory): ''' Base classes for new-style configuration items Configuration items should inherit from this class, implement the execute method (and optionally the cancel one) and have their view inherit from the related res_config_view_base view. ''' _name = 'res.config' def _next_action(self, cr, uid, context=None): Todos = self.pool['ir.actions.todo'] _logger.info('getting next %s', Todos) active_todos = Todos.browse(cr, uid, Todos.search(cr, uid, ['&', ('type', '=', 'automatic'), ('state','=','open')]), context=context) user_groups = set(map( lambda g: g.id, self.pool['res.users'].browse(cr, uid, [uid], context=context)[0].groups_id)) valid_todos_for_user = [ todo for todo in active_todos if not todo.groups_id or bool(user_groups.intersection(( group.id for group in todo.groups_id))) ] if valid_todos_for_user: return valid_todos_for_user[0] return None def _next(self, cr, uid, context=None): _logger.info('getting next operation') next = self._next_action(cr, uid, context=context) _logger.info('next action is %s', next) if next: res = next.action_launch(context=context) res['nodestroy'] = False return res return { 'type': 'ir.actions.client', 'tag': 'reload', } def start(self, cr, uid, ids, context=None): return self.next(cr, uid, ids, context) def next(self, cr, uid, ids, context=None): """ Returns the next todo action to execute (using the default sort order) """ return self._next(cr, uid, context=context) def execute(self, cr, uid, ids, context=None): """ Method called when the user clicks on the ``Next`` button. Execute *must* be overloaded unless ``action_next`` is overloaded (which is something you generally don't need to do). If ``execute`` returns an action dictionary, that action is executed rather than just going to the next configuration item. """ raise NotImplementedError( 'Configuration items need to implement execute') def cancel(self, cr, uid, ids, context=None): """ Method called when the user click on the ``Skip`` button. ``cancel`` should be overloaded instead of ``action_skip``. As with ``execute``, if it returns an action dictionary that action is executed in stead of the default (going to the next configuration item) The default implementation is a NOOP. ``cancel`` is also called by the default implementation of ``action_cancel``. """ pass def action_next(self, cr, uid, ids, context=None): """ Action handler for the ``next`` event. Sets the status of the todo the event was sent from to ``done``, calls ``execute`` and -- unless ``execute`` returned an action dictionary -- executes the action provided by calling ``next``. """ next = self.execute(cr, uid, ids, context=context) if next: return next return self.next(cr, uid, ids, context=context) def action_skip(self, cr, uid, ids, context=None): """ Action handler for the ``skip`` event. Sets the status of the todo the event was sent from to ``skip``, calls ``cancel`` and -- unless ``cancel`` returned an action dictionary -- executes the action provided by calling ``next``. """ next = self.cancel(cr, uid, ids, context=context) if next: return next return self.next(cr, uid, ids, context=context) def action_cancel(self, cr, uid, ids, context=None): """ Action handler for the ``cancel`` event. That event isn't generated by the res.config.view.base inheritable view, the inherited view has to overload one of the buttons (or add one more). Sets the status of the todo the event was sent from to ``cancel``, calls ``cancel`` and -- unless ``cancel`` returned an action dictionary -- executes the action provided by calling ``next``. """ next = self.cancel(cr, uid, ids, context=context) if next: return next return self.next(cr, uid, ids, context=context) class res_config_installer(osv.osv_memory, res_config_module_installation_mixin): """ New-style configuration base specialized for addons selection and installation. Basic usage ----------- Subclasses can simply define a number of _columns as fields.boolean objects. The keys (column names) should be the names of the addons to install (when selected). Upon action execution, selected boolean fields (and those only) will be interpreted as addons to install, and batch-installed. Additional addons ----------------- It is also possible to require the installation of an additional addon set when a specific preset of addons has been marked for installation (in the basic usage only, additionals can't depend on one another). These additionals are defined through the ``_install_if`` property. This property is a mapping of a collection of addons (by name) to a collection of addons (by name) [#]_, and if all the *key* addons are selected for installation, then the *value* ones will be selected as well. For example:: _install_if = { ('sale','crm'): ['sale_crm'], } This will install the ``sale_crm`` addon if and only if both the ``sale`` and ``crm`` addons are selected for installation. You can define as many additionals as you wish, and additionals can overlap in key and value. For instance:: _install_if = { ('sale','crm'): ['sale_crm'], ('sale','project'): ['sale_service'], } will install both ``sale_crm`` and ``sale_service`` if all of ``sale``, ``crm`` and ``project`` are selected for installation. Hook methods ------------ Subclasses might also need to express dependencies more complex than that provided by additionals. In this case, it's possible to define methods of the form ``_if_%(name)s`` where ``name`` is the name of a boolean field. If the field is selected, then the corresponding module will be marked for installation *and* the hook method will be executed. Hook methods take the usual set of parameters (cr, uid, ids, context) and can return a collection of additional addons to install (if they return anything, otherwise they should not return anything, though returning any "falsy" value such as None or an empty collection will have the same effect). Complete control ---------------- The last hook is to simply overload the ``modules_to_install`` method, which implements all the mechanisms above. This method takes the usual set of parameters (cr, uid, ids, context) and returns a ``set`` of addons to install (addons selected by the above methods minus addons from the *basic* set which are already installed) [#]_ so an overloader can simply manipulate the ``set`` returned by ``res_config_installer.modules_to_install`` to add or remove addons. Skipping the installer ---------------------- Unless it is removed from the view, installers have a *skip* button which invokes ``action_skip`` (and the ``cancel`` hook from ``res.config``). Hooks and additionals *are not run* when skipping installation, even for already installed addons. Again, setup your hooks accordingly. .. [#] note that since a mapping key needs to be hashable, it's possible to use a tuple or a frozenset, but not a list or a regular set .. [#] because the already-installed modules are only pruned at the very end of ``modules_to_install``, additionals and hooks depending on them *are guaranteed to execute*. Setup your hooks accordingly. """ _name = 'res.config.installer' _inherit = 'res.config' _install_if = {} def already_installed(self, cr, uid, context=None): """ For each module, check if it's already installed and if it is return its name :returns: a list of the already installed modules in this installer :rtype: [str] """ return map(attrgetter('name'), self._already_installed(cr, uid, context=context)) def _already_installed(self, cr, uid, context=None): """ For each module (boolean fields in a res.config.installer), check if it's already installed (either 'to install', 'to upgrade' or 'installed') and if it is return the module's record :returns: a list of all installed modules in this installer :rtype: recordset (collection of Record) """ modules = self.pool['ir.module.module'] selectable = [field for field in self._columns if type(self._columns[field]) is fields.boolean] return modules.browse( cr, uid, modules.search(cr, uid, [('name','in',selectable), ('state','in',['to install', 'installed', 'to upgrade'])], context=context), context=context) def modules_to_install(self, cr, uid, ids, context=None): """ selects all modules to install: * checked boolean fields * return values of hook methods. Hook methods are of the form ``_if_%(addon_name)s``, and are called if the corresponding addon is marked for installation. They take the arguments cr, uid, ids and context, and return an iterable of addon names * additionals, additionals are setup through the ``_install_if`` class variable. ``_install_if`` is a dict of {iterable:iterable} where key and value are iterables of addon names. If all the addons in the key are selected for installation (warning: addons added through hooks don't count), then the addons in the value are added to the set of modules to install * not already installed """ base = set(module_name for installer in self.read(cr, uid, ids, context=context) for module_name, to_install in installer.iteritems() if module_name != 'id' if type(self._columns.get(module_name)) is fields.boolean if to_install) hooks_results = set() for module in base: hook = getattr(self, '_if_%s'% module, None) if hook: hooks_results.update(hook(cr, uid, ids, context=None) or set()) additionals = set( module for requirements, consequences \ in self._install_if.iteritems() if base.issuperset(requirements) for module in consequences) return (base | hooks_results | additionals).difference( self.already_installed(cr, uid, context)) def default_get(self, cr, uid, fields_list, context=None): ''' If an addon is already installed, check it by default ''' defaults = super(res_config_installer, self).default_get( cr, uid, fields_list, context=context) return dict(defaults, **dict.fromkeys( self.already_installed(cr, uid, context=context), True)) def fields_get(self, cr, uid, fields=None, context=None, write_access=True, attributes=None): """ If an addon is already installed, set it to readonly as res.config.installer doesn't handle uninstallations of already installed addons """ fields = super(res_config_installer, self).fields_get( cr, uid, fields, context, write_access, attributes) for name in self.already_installed(cr, uid, context=context): if name not in fields: continue fields[name].update( readonly=True, help= ustr(fields[name].get('help', '')) + _('\n\nThis addon is already installed on your system')) return fields def execute(self, cr, uid, ids, context=None): to_install = list(self.modules_to_install( cr, uid, ids, context=context)) _logger.info('Selecting addons %s to install', to_install) ir_module = self.pool.get('ir.module.module') modules = [] for name in to_install: mod_ids = ir_module.search(cr, uid, [('name', '=', name)]) record = ir_module.browse(cr, uid, mod_ids[0], context) if mod_ids else None modules.append((name, record)) return self._install_modules(cr, uid, modules, context=context) class res_config_settings(osv.osv_memory, res_config_module_installation_mixin): """ Base configuration wizard for application settings. It provides support for setting default values, assigning groups to employee users, and installing modules. To make such a 'settings' wizard, define a model like:: class my_config_wizard(osv.osv_memory): _name = 'my.settings' _inherit = 'res.config.settings' _columns = { 'default_foo': fields.type(..., default_model='my.model'), 'group_bar': fields.boolean(..., group='base.group_user', implied_group='my.group'), 'module_baz': fields.boolean(...), 'other_field': fields.type(...), } The method ``execute`` provides some support based on a naming convention: * For a field like 'default_XXX', ``execute`` sets the (global) default value of the field 'XXX' in the model named by ``default_model`` to the field's value. * For a boolean field like 'group_XXX', ``execute`` adds/removes 'implied_group' to/from the implied groups of 'group', depending on the field's value. By default 'group' is the group Employee. Groups are given by their xml id. The attribute 'group' may contain several xml ids, separated by commas. * For a boolean field like 'module_XXX', ``execute`` triggers the immediate installation of the module named 'XXX' if the field has value ``True``. * For the other fields, the method ``execute`` invokes all methods with a name that starts with 'set_'; such methods can be defined to implement the effect of those fields. The method ``default_get`` retrieves values that reflect the current status of the fields like 'default_XXX', 'group_XXX' and 'module_XXX'. It also invokes all methods with a name that starts with 'get_default_'; such methods can be defined to provide current values for other fields. """ _name = 'res.config.settings' def copy(self, cr, uid, id, values, context=None): raise osv.except_osv(_("Cannot duplicate configuration!"), "") def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): ret_val = super(res_config_settings, self).fields_view_get( cr, user, view_id=view_id, view_type=view_type, context=context, toolbar=toolbar, submenu=submenu) doc = etree.XML(ret_val['arch']) for field in ret_val['fields']: if not field.startswith("module_"): continue for node in doc.xpath("//field[@name='%s']" % field): if 'on_change' not in node.attrib: node.set("on_change", "onchange_module(%s, '%s')" % (field, field)) ret_val['arch'] = etree.tostring(doc) return ret_val def onchange_module(self, cr, uid, ids, field_value, module_name, context={}): module_pool = self.pool.get('ir.module.module') module_ids = module_pool.search( cr, uid, [('name', '=', module_name.replace("module_", '')), ('state','in', ['to install', 'installed', 'to upgrade'])], context=context) if module_ids and not field_value: dep_ids = module_pool.downstream_dependencies(cr, uid, module_ids, context=context) dep_name = [x.shortdesc for x in module_pool.browse( cr, uid, dep_ids + module_ids, context=context)] message = '\n'.join(dep_name) return { 'warning': { 'title': _('Warning!'), 'message': _('Disabling this option will also uninstall the following modules \n%s') % message, } } return {} def _get_classified_fields(self, cr, uid, context=None): """ return a dictionary with the fields classified by category:: { 'default': [('default_foo', 'model', 'foo'), ...], 'group': [('group_bar', [browse_group], browse_implied_group), ...], 'module': [('module_baz', browse_module), ...], 'other': ['other_field', ...], } """ ir_model_data = self.pool['ir.model.data'] ir_module = self.pool['ir.module.module'] def ref(xml_id): mod, xml = xml_id.split('.', 1) return ir_model_data.get_object(cr, uid, mod, xml, context=context) defaults, groups, modules, others = [], [], [], [] for name, field in self._columns.items(): if name.startswith('default_') and hasattr(field, 'default_model'): defaults.append((name, field.default_model, name[8:])) elif name.startswith('group_') and isinstance(field, fields.boolean) and hasattr(field, 'implied_group'): field_groups = getattr(field, 'group', 'base.group_user').split(',') groups.append((name, map(ref, field_groups), ref(field.implied_group))) elif name.startswith('module_') and isinstance(field, fields.boolean): mod_ids = ir_module.search(cr, uid, [('name', '=', name[7:])]) record = ir_module.browse(cr, uid, mod_ids[0], context) if mod_ids else None modules.append((name, record)) else: others.append(name) return {'default': defaults, 'group': groups, 'module': modules, 'other': others} def default_get(self, cr, uid, fields, context=None): ir_values = self.pool['ir.values'] classified = self._get_classified_fields(cr, uid, context) res = super(res_config_settings, self).default_get(cr, uid, fields, context) # defaults: take the corresponding default value they set for name, model, field in classified['default']: value = ir_values.get_default(cr, uid, model, field) if value is not None: res[name] = value # groups: which groups are implied by the group Employee for name, groups, implied_group in classified['group']: res[name] = all(implied_group in group.implied_ids for group in groups) # modules: which modules are installed/to install for name, module in classified['module']: res[name] = module and module.state in ('installed', 'to install', 'to upgrade') # other fields: call all methods that start with 'get_default_' for method in dir(self): if method.startswith('get_default_'): res.update(getattr(self, method)(cr, uid, fields, context)) return res def execute(self, cr, uid, ids, context=None): if context is None: context = {} context = dict(context, active_test=False) if uid != SUPERUSER_ID and not self.pool['res.users'].has_group(cr, uid, 'base.group_erp_manager'): raise openerp.exceptions.AccessError(_("Only administrators can change the settings")) ir_values = self.pool['ir.values'] ir_module = self.pool['ir.module.module'] res_groups = self.pool['res.groups'] classified = self._get_classified_fields(cr, uid, context=context) config = self.browse(cr, uid, ids[0], context) # default values fields for name, model, field in classified['default']: ir_values.set_default(cr, SUPERUSER_ID, model, field, config[name]) # group fields: modify group / implied groups for name, groups, implied_group in classified['group']: gids = map(int, groups) if config[name]: res_groups.write(cr, uid, gids, {'implied_ids': [(4, implied_group.id)]}, context=context) else: res_groups.write(cr, uid, gids, {'implied_ids': [(3, implied_group.id)]}, context=context) uids = set() for group in groups: uids.update(map(int, group.users)) implied_group.write({'users': [(3, u) for u in uids]}) # other fields: execute all methods that start with 'set_' for method in dir(self): if method.startswith('set_'): getattr(self, method)(cr, uid, ids, context) # module fields: install/uninstall the selected modules to_install = [] to_uninstall_ids = [] lm = len('module_') for name, module in classified['module']: if config[name]: to_install.append((name[lm:], module)) else: if module and module.state in ('installed', 'to upgrade'): to_uninstall_ids.append(module.id) if to_uninstall_ids: ir_module.button_immediate_uninstall(cr, uid, to_uninstall_ids, context=context) action = self._install_modules(cr, uid, to_install, context=context) if action: return action # After the uninstall/install calls, the self.pool is no longer valid. # So we reach into the RegistryManager directly. res_config = openerp.modules.registry.RegistryManager.get(cr.dbname)['res.config'] config = res_config.next(cr, uid, [], context=context) or {} if config.get('type') not in ('ir.actions.act_window_close',): return config # force client-side reload (update user menu and current view) return { 'type': 'ir.actions.client', 'tag': 'reload', } def cancel(self, cr, uid, ids, context=None): # ignore the current record, and send the action to reopen the view act_window = self.pool['ir.actions.act_window'] action_ids = act_window.search(cr, uid, [('res_model', '=', self._name)]) if action_ids: return act_window.read(cr, uid, action_ids[0], [], context=context) return {} def name_get(self, cr, uid, ids, context=None): """ Override name_get method to return an appropriate configuration wizard name, and not the generated name.""" if not ids: return [] # name_get may receive int id instead of an id list if isinstance(ids, (int, long)): ids = [ids] act_window = self.pool['ir.actions.act_window'] action_ids = act_window.search(cr, uid, [('res_model', '=', self._name)], context=context) name = self._name if action_ids: name = act_window.read(cr, uid, action_ids[0], ['name'], context=context)['name'] return [(record.id, name) for record in self.browse(cr, uid , ids, context=context)] def get_option_path(self, cr, uid, menu_xml_id, context=None): """ Fetch the path to a specified configuration view and the action id to access it. :param string menu_xml_id: the xml id of the menuitem where the view is located, structured as follows: module_name.menuitem_xml_id (e.g.: "base.menu_sale_config") :return tuple: - t[0]: string: full path to the menuitem (e.g.: "Settings/Configuration/Sales") - t[1]: int or long: id of the menuitem's action """ module_name, menu_xml_id = menu_xml_id.split('.') dummy, menu_id = self.pool['ir.model.data'].get_object_reference(cr, uid, module_name, menu_xml_id) ir_ui_menu = self.pool['ir.ui.menu'].browse(cr, uid, menu_id, context=context) return (ir_ui_menu.complete_name, ir_ui_menu.action.id) def get_option_name(self, cr, uid, full_field_name, context=None): """ Fetch the human readable name of a specified configuration option. :param string full_field_name: the full name of the field, structured as follows: model_name.field_name (e.g.: "sale.config.settings.fetchmail_lead") :return string: human readable name of the field (e.g.: "Create leads from incoming mails") """ model_name, field_name = full_field_name.rsplit('.', 1) return self.pool[model_name].fields_get(cr, uid, allfields=[field_name], context=context)[field_name]['string'] def get_config_warning(self, cr, msg, context=None): """ Helper: return a Warning exception with the given message where the %(field:xxx)s and/or %(menu:yyy)s are replaced by the human readable field's name and/or menuitem's full path. Usage: ------ Just include in your error message %(field:model_name.field_name)s to obtain the human readable field's name, and/or %(menu:module_name.menuitem_xml_id)s to obtain the menuitem's full path. Example of use: --------------- from openerp.addons.base.res.res_config import get_warning_config raise get_warning_config(cr, _("Error: this action is prohibited. You should check the field %(field:sale.config.settings.fetchmail_lead)s in %(menu:base.menu_sale_config)s."), context=context) This will return an exception containing the following message: Error: this action is prohibited. You should check the field Create leads from incoming mails in Settings/Configuration/Sales. What if there is another substitution in the message already? ------------------------------------------------------------- You could have a situation where the error message you want to upgrade already contains a substitution. Example: Cannot find any account journal of %s type for this company.\n\nYou can create one in the menu: \nConfiguration\Journals\Journals. What you want to do here is simply to replace the path by %menu:account.menu_account_config)s, and leave the rest alone. In order to do that, you can use the double percent (%%) to escape your new substitution, like so: Cannot find any account journal of %s type for this company.\n\nYou can create one in the %%(menu:account.menu_account_config)s. """ res_config_obj = openerp.registry(cr.dbname)['res.config.settings'] regex_path = r'%\(((?:menu|field):[a-z_\.]*)\)s' # Process the message # 1/ find the menu and/or field references, put them in a list references = re.findall(regex_path, msg, flags=re.I) # 2/ fetch the menu and/or field replacement values (full path and # human readable field's name) and the action_id if any values = {} action_id = None for item in references: ref_type, ref = item.split(':') if ref_type == 'menu': values[item], action_id = res_config_obj.get_option_path(cr, SUPERUSER_ID, ref, context=context) elif ref_type == 'field': values[item] = res_config_obj.get_option_name(cr, SUPERUSER_ID, ref, context=context) # 3/ substitute and return the result if (action_id): return exceptions.RedirectWarning(msg % values, action_id, _('Go to the configuration panel')) return exceptions.Warning(msg % values) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
ppmt/Crust
flask/lib/python2.7/site-packages/pip/_vendor/distlib/scripts.py
203
12894
# -*- coding: utf-8 -*- # # Copyright (C) 2013-2014 Vinay Sajip. # Licensed to the Python Software Foundation under a contributor agreement. # See LICENSE.txt and CONTRIBUTORS.txt. # from io import BytesIO import logging import os import re import struct import sys from .compat import sysconfig, detect_encoding, ZipFile from .resources import finder from .util import (FileOperator, get_export_entry, convert_path, get_executable, in_venv) logger = logging.getLogger(__name__) _DEFAULT_MANIFEST = ''' <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <assemblyIdentity version="1.0.0.0" processorArchitecture="X86" name="%s" type="win32"/> <!-- Identify the application security requirements. --> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly>'''.strip() # check if Python is called on the first line with this expression FIRST_LINE_RE = re.compile(b'^#!.*pythonw?[0-9.]*([ \t].*)?$') SCRIPT_TEMPLATE = '''# -*- coding: utf-8 -*- if __name__ == '__main__': import sys, re def _resolve(module, func): __import__(module) mod = sys.modules[module] parts = func.split('.') result = getattr(mod, parts.pop(0)) for p in parts: result = getattr(result, p) return result try: sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) func = _resolve('%(module)s', '%(func)s') rc = func() # None interpreted as 0 except Exception as e: # only supporting Python >= 2.6 sys.stderr.write('%%s\\n' %% e) rc = 1 sys.exit(rc) ''' class ScriptMaker(object): """ A class to copy or create scripts from source scripts or callable specifications. """ script_template = SCRIPT_TEMPLATE executable = None # for shebangs def __init__(self, source_dir, target_dir, add_launchers=True, dry_run=False, fileop=None): self.source_dir = source_dir self.target_dir = target_dir self.add_launchers = add_launchers self.force = False self.clobber = False # It only makes sense to set mode bits on POSIX. self.set_mode = (os.name == 'posix') self.variants = set(('', 'X.Y')) self._fileop = fileop or FileOperator(dry_run) def _get_alternate_executable(self, executable, options): if options.get('gui', False) and os.name == 'nt': dn, fn = os.path.split(executable) fn = fn.replace('python', 'pythonw') executable = os.path.join(dn, fn) return executable def _get_shebang(self, encoding, post_interp=b'', options=None): enquote = True if self.executable: executable = self.executable enquote = False # assume this will be taken care of elif not sysconfig.is_python_build(): executable = get_executable() elif in_venv(): executable = os.path.join(sysconfig.get_path('scripts'), 'python%s' % sysconfig.get_config_var('EXE')) else: executable = os.path.join( sysconfig.get_config_var('BINDIR'), 'python%s%s' % (sysconfig.get_config_var('VERSION'), sysconfig.get_config_var('EXE'))) if options: executable = self._get_alternate_executable(executable, options) # If the user didn't specify an executable, it may be necessary to # cater for executable paths with spaces (not uncommon on Windows) if enquote and ' ' in executable: executable = '"%s"' % executable # Issue #51: don't use fsencode, since we later try to # check that the shebang is decodable using utf-8. executable = executable.encode('utf-8') # in case of IronPython, play safe and enable frames support if (sys.platform == 'cli' and '-X:Frames' not in post_interp and '-X:FullFrames' not in post_interp): post_interp += b' -X:Frames' shebang = b'#!' + executable + post_interp + b'\n' # Python parser starts to read a script using UTF-8 until # it gets a #coding:xxx cookie. The shebang has to be the # first line of a file, the #coding:xxx cookie cannot be # written before. So the shebang has to be decodable from # UTF-8. try: shebang.decode('utf-8') except UnicodeDecodeError: raise ValueError( 'The shebang (%r) is not decodable from utf-8' % shebang) # If the script is encoded to a custom encoding (use a # #coding:xxx cookie), the shebang has to be decodable from # the script encoding too. if encoding != 'utf-8': try: shebang.decode(encoding) except UnicodeDecodeError: raise ValueError( 'The shebang (%r) is not decodable ' 'from the script encoding (%r)' % (shebang, encoding)) return shebang def _get_script_text(self, entry): return self.script_template % dict(module=entry.prefix, func=entry.suffix) manifest = _DEFAULT_MANIFEST def get_manifest(self, exename): base = os.path.basename(exename) return self.manifest % base def _write_script(self, names, shebang, script_bytes, filenames, ext): use_launcher = self.add_launchers and os.name == 'nt' linesep = os.linesep.encode('utf-8') if not use_launcher: script_bytes = shebang + linesep + script_bytes else: if ext == 'py': launcher = self._get_launcher('t') else: launcher = self._get_launcher('w') stream = BytesIO() with ZipFile(stream, 'w') as zf: zf.writestr('__main__.py', script_bytes) zip_data = stream.getvalue() script_bytes = launcher + shebang + linesep + zip_data for name in names: outname = os.path.join(self.target_dir, name) if use_launcher: n, e = os.path.splitext(outname) if e.startswith('.py'): outname = n outname = '%s.exe' % outname try: self._fileop.write_binary_file(outname, script_bytes) except Exception: # Failed writing an executable - it might be in use. logger.warning('Failed to write executable - trying to ' 'use .deleteme logic') dfname = '%s.deleteme' % outname if os.path.exists(dfname): os.remove(dfname) # Not allowed to fail here os.rename(outname, dfname) # nor here self._fileop.write_binary_file(outname, script_bytes) logger.debug('Able to replace executable using ' '.deleteme logic') try: os.remove(dfname) except Exception: pass # still in use - ignore error else: if os.name == 'nt' and not outname.endswith('.' + ext): outname = '%s.%s' % (outname, ext) if os.path.exists(outname) and not self.clobber: logger.warning('Skipping existing file %s', outname) continue self._fileop.write_binary_file(outname, script_bytes) if self.set_mode: self._fileop.set_executable_mode([outname]) filenames.append(outname) def _make_script(self, entry, filenames, options=None): post_interp = b'' if options: args = options.get('interpreter_args', []) if args: args = ' %s' % ' '.join(args) post_interp = args.encode('utf-8') shebang = self._get_shebang('utf-8', post_interp, options=options) script = self._get_script_text(entry).encode('utf-8') name = entry.name scriptnames = set() if '' in self.variants: scriptnames.add(name) if 'X' in self.variants: scriptnames.add('%s%s' % (name, sys.version[0])) if 'X.Y' in self.variants: scriptnames.add('%s-%s' % (name, sys.version[:3])) if options and options.get('gui', False): ext = 'pyw' else: ext = 'py' self._write_script(scriptnames, shebang, script, filenames, ext) def _copy_script(self, script, filenames): adjust = False script = os.path.join(self.source_dir, convert_path(script)) outname = os.path.join(self.target_dir, os.path.basename(script)) if not self.force and not self._fileop.newer(script, outname): logger.debug('not copying %s (up-to-date)', script) return # Always open the file, but ignore failures in dry-run mode -- # that way, we'll get accurate feedback if we can read the # script. try: f = open(script, 'rb') except IOError: if not self.dry_run: raise f = None else: encoding, lines = detect_encoding(f.readline) f.seek(0) first_line = f.readline() if not first_line: logger.warning('%s: %s is an empty file (skipping)', self.get_command_name(), script) return match = FIRST_LINE_RE.match(first_line.replace(b'\r\n', b'\n')) if match: adjust = True post_interp = match.group(1) or b'' if not adjust: if f: f.close() self._fileop.copy_file(script, outname) if self.set_mode: self._fileop.set_executable_mode([outname]) filenames.append(outname) else: logger.info('copying and adjusting %s -> %s', script, self.target_dir) if not self._fileop.dry_run: shebang = self._get_shebang(encoding, post_interp) if b'pythonw' in first_line: ext = 'pyw' else: ext = 'py' n = os.path.basename(outname) self._write_script([n], shebang, f.read(), filenames, ext) if f: f.close() @property def dry_run(self): return self._fileop.dry_run @dry_run.setter def dry_run(self, value): self._fileop.dry_run = value if os.name == 'nt': # Executable launcher support. # Launchers are from https://bitbucket.org/vinay.sajip/simple_launcher/ def _get_launcher(self, kind): if struct.calcsize('P') == 8: # 64-bit bits = '64' else: bits = '32' name = '%s%s.exe' % (kind, bits) # Issue 31: don't hardcode an absolute package name, but # determine it relative to the current package distlib_package = __name__.rsplit('.', 1)[0] result = finder(distlib_package).find(name).bytes return result # Public API follows def make(self, specification, options=None): """ Make a script. :param specification: The specification, which is either a valid export entry specification (to make a script from a callable) or a filename (to make a script by copying from a source location). :param options: A dictionary of options controlling script generation. :return: A list of all absolute pathnames written to. """ filenames = [] entry = get_export_entry(specification) if entry is None: self._copy_script(specification, filenames) else: self._make_script(entry, filenames, options=options) return filenames def make_multiple(self, specifications, options=None): """ Take a list of specifications and make scripts from them, :param specifications: A list of specifications. :return: A list of all absolute pathnames written to, """ filenames = [] for specification in specifications: filenames.extend(self.make(specification, options)) return filenames
gpl-2.0
kuszmaul/PerconaFT
src/tests/ipm.py
92
1263
#!/usr/local/bin/python2.6 import sys import os import pexpect import getpass # # remote_cmd # nameaddr='admn@192.168.1.254' passwd='admn' def IPM_cmd(cmds): # password handling ssh_newkey = 'Are you sure you want to continue connecting' p=pexpect.spawn('ssh %s' % nameaddr, timeout=60) i=p.expect([ssh_newkey,'Password:',pexpect.EOF]) if i==0: p.sendline('yes') i=p.expect([ssh_newkey,'Password:',pexpect.EOF]) if i==1: p.sendline(passwd) elif i==2: print "I either got key or connection timeout" pass # run command(s) i = p.expect('Sentry:') for cmd in cmds: if i==0: p.sendline(cmd) else: print 'p.expect saw', p.before i = p.expect('Sentry:') print p.before # close session p.sendline('quit') p.expect(pexpect.EOF) return 0 def IPM_power_on(): IPM_cmd(['on all']) def IPM_power_off(): IPM_cmd(['off all']) def main(argv): # passwd = getpass.getpass('password for %s:' % (nameaddr)) if argv[1] == 'on': IPM_power_on() elif argv[1] == 'off': IPM_power_off() else: IPM_cmd(argv[1:]) return 0 if __name__ == '__main__': sys.exit(main(sys.argv))
agpl-3.0
rockyzhang/zhangyanhit-python-for-android-mips
python-build/python-libs/gdata/src/gdata/Crypto/Protocol/Chaffing.py
226
9467
"""This file implements the chaffing algorithm. Winnowing and chaffing is a technique for enhancing privacy without requiring strong encryption. In short, the technique takes a set of authenticated message blocks (the wheat) and adds a number of chaff blocks which have randomly chosen data and MAC fields. This means that to an adversary, the chaff blocks look as valid as the wheat blocks, and so the authentication would have to be performed on every block. By tailoring the number of chaff blocks added to the message, the sender can make breaking the message computationally infeasible. There are many other interesting properties of the winnow/chaff technique. For example, say Alice is sending a message to Bob. She packetizes the message and performs an all-or-nothing transformation on the packets. Then she authenticates each packet with a message authentication code (MAC). The MAC is a hash of the data packet, and there is a secret key which she must share with Bob (key distribution is an exercise left to the reader). She then adds a serial number to each packet, and sends the packets to Bob. Bob receives the packets, and using the shared secret authentication key, authenticates the MACs for each packet. Those packets that have bad MACs are simply discarded. The remainder are sorted by serial number, and passed through the reverse all-or-nothing transform. The transform means that an eavesdropper (say Eve) must acquire all the packets before any of the data can be read. If even one packet is missing, the data is useless. There's one twist: by adding chaff packets, Alice and Bob can make Eve's job much harder, since Eve now has to break the shared secret key, or try every combination of wheat and chaff packet to read any of the message. The cool thing is that Bob doesn't need to add any additional code; the chaff packets are already filtered out because their MACs don't match (in all likelihood -- since the data and MACs for the chaff packets are randomly chosen it is possible, but very unlikely that a chaff MAC will match the chaff data). And Alice need not even be the party adding the chaff! She could be completely unaware that a third party, say Charles, is adding chaff packets to her messages as they are transmitted. For more information on winnowing and chaffing see this paper: Ronald L. Rivest, "Chaffing and Winnowing: Confidentiality without Encryption" http://theory.lcs.mit.edu/~rivest/chaffing.txt """ __revision__ = "$Id: Chaffing.py,v 1.7 2003/02/28 15:23:21 akuchling Exp $" from Crypto.Util.number import bytes_to_long class Chaff: """Class implementing the chaff adding algorithm. Methods for subclasses: _randnum(size): Returns a randomly generated number with a byte-length equal to size. Subclasses can use this to implement better random data and MAC generating algorithms. The default algorithm is probably not very cryptographically secure. It is most important that the chaff data does not contain any patterns that can be used to discern it from wheat data without running the MAC. """ def __init__(self, factor=1.0, blocksper=1): """Chaff(factor:float, blocksper:int) factor is the number of message blocks to add chaff to, expressed as a percentage between 0.0 and 1.0. blocksper is the number of chaff blocks to include for each block being chaffed. Thus the defaults add one chaff block to every message block. By changing the defaults, you can adjust how computationally difficult it could be for an adversary to brute-force crack the message. The difficulty is expressed as: pow(blocksper, int(factor * number-of-blocks)) For ease of implementation, when factor < 1.0, only the first int(factor*number-of-blocks) message blocks are chaffed. """ if not (0.0<=factor<=1.0): raise ValueError, "'factor' must be between 0.0 and 1.0" if blocksper < 0: raise ValueError, "'blocksper' must be zero or more" self.__factor = factor self.__blocksper = blocksper def chaff(self, blocks): """chaff( [(serial-number:int, data:string, MAC:string)] ) : [(int, string, string)] Add chaff to message blocks. blocks is a list of 3-tuples of the form (serial-number, data, MAC). Chaff is created by choosing a random number of the same byte-length as data, and another random number of the same byte-length as MAC. The message block's serial number is placed on the chaff block and all the packet's chaff blocks are randomly interspersed with the single wheat block. This method then returns a list of 3-tuples of the same form. Chaffed blocks will contain multiple instances of 3-tuples with the same serial number, but the only way to figure out which blocks are wheat and which are chaff is to perform the MAC hash and compare values. """ chaffedblocks = [] # count is the number of blocks to add chaff to. blocksper is the # number of chaff blocks to add per message block that is being # chaffed. count = len(blocks) * self.__factor blocksper = range(self.__blocksper) for i, wheat in map(None, range(len(blocks)), blocks): # it shouldn't matter which of the n blocks we add chaff to, so for # ease of implementation, we'll just add them to the first count # blocks if i < count: serial, data, mac = wheat datasize = len(data) macsize = len(mac) addwheat = 1 # add chaff to this block for j in blocksper: import sys chaffdata = self._randnum(datasize) chaffmac = self._randnum(macsize) chaff = (serial, chaffdata, chaffmac) # mix up the order, if the 5th bit is on then put the # wheat on the list if addwheat and bytes_to_long(self._randnum(16)) & 0x40: chaffedblocks.append(wheat) addwheat = 0 chaffedblocks.append(chaff) if addwheat: chaffedblocks.append(wheat) else: # just add the wheat chaffedblocks.append(wheat) return chaffedblocks def _randnum(self, size): # TBD: Not a very secure algorithm. # TBD: size * 2 to work around possible bug in RandomPool from Crypto.Util import randpool import time pool = randpool.RandomPool(size * 2) while size > pool.entropy: pass # we now have enough entropy in the pool to get size bytes of random # data... well, probably return pool.get_bytes(size) if __name__ == '__main__': text = """\ We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty, and the pursuit of Happiness. That to secure these rights, Governments are instituted among Men, deriving their just powers from the consent of the governed. That whenever any Form of Government becomes destructive of these ends, it is the Right of the People to alter or to abolish it, and to institute new Government, laying its foundation on such principles and organizing its powers in such form, as to them shall seem most likely to effect their Safety and Happiness. """ print 'Original text:\n==========' print text print '==========' # first transform the text into packets blocks = [] ; size = 40 for i in range(0, len(text), size): blocks.append( text[i:i+size] ) # now get MACs for all the text blocks. The key is obvious... print 'Calculating MACs...' from Crypto.Hash import HMAC, SHA key = 'Jefferson' macs = [HMAC.new(key, block, digestmod=SHA).digest() for block in blocks] assert len(blocks) == len(macs) # put these into a form acceptable as input to the chaffing procedure source = [] m = map(None, range(len(blocks)), blocks, macs) print m for i, data, mac in m: source.append((i, data, mac)) # now chaff these print 'Adding chaff...' c = Chaff(factor=0.5, blocksper=2) chaffed = c.chaff(source) from base64 import encodestring # print the chaffed message blocks. meanwhile, separate the wheat from # the chaff wheat = [] print 'chaffed message blocks:' for i, data, mac in chaffed: # do the authentication h = HMAC.new(key, data, digestmod=SHA) pmac = h.digest() if pmac == mac: tag = '-->' wheat.append(data) else: tag = ' ' # base64 adds a trailing newline print tag, '%3d' % i, \ repr(data), encodestring(mac)[:-1] # now decode the message packets and check it against the original text print 'Undigesting wheat...' newtext = "".join(wheat) if newtext == text: print 'They match!' else: print 'They differ!'
apache-2.0
TathagataChakraborti/resource-conflicts
PLANROB-2015/py2.5/lib/python2.5/distutils/command/bdist_msi.py
88
30900
# -*- coding: iso-8859-1 -*- # Copyright (C) 2005, 2006 Martin v. Löwis # Licensed to PSF under a Contributor Agreement. # The bdist_wininst command proper # based on bdist_wininst """ Implements the bdist_msi command. """ import sys, os, string from distutils.core import Command from distutils.util import get_platform from distutils.dir_util import remove_tree from distutils.sysconfig import get_python_version from distutils.version import StrictVersion from distutils.errors import DistutilsOptionError from distutils import log import msilib from msilib import schema, sequence, text from msilib import Directory, Feature, Dialog, add_data class PyDialog(Dialog): """Dialog class with a fixed layout: controls at the top, then a ruler, then a list of buttons: back, next, cancel. Optionally a bitmap at the left.""" def __init__(self, *args, **kw): """Dialog(database, name, x, y, w, h, attributes, title, first, default, cancel, bitmap=true)""" Dialog.__init__(self, *args) ruler = self.h - 36 bmwidth = 152*ruler/328 #if kw.get("bitmap", True): # self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin") self.line("BottomLine", 0, ruler, self.w, 0) def title(self, title): "Set the title text of the dialog at the top." # name, x, y, w, h, flags=Visible|Enabled|Transparent|NoPrefix, # text, in VerdanaBold10 self.text("Title", 15, 10, 320, 60, 0x30003, r"{\VerdanaBold10}%s" % title) def back(self, title, next, name = "Back", active = 1): """Add a back button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 180, self.h-27 , 56, 17, flags, title, next) def cancel(self, title, next, name = "Cancel", active = 1): """Add a cancel button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 304, self.h-27, 56, 17, flags, title, next) def next(self, title, next, name = "Next", active = 1): """Add a Next button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 236, self.h-27, 56, 17, flags, title, next) def xbutton(self, name, title, next, xpos): """Add a button with a given title, the tab-next button, its name in the Control table, giving its x position; the y-position is aligned with the other buttons. Return the button, so that events can be associated""" return self.pushbutton(name, int(self.w*xpos - 28), self.h-27, 56, 17, 3, title, next) class bdist_msi (Command): description = "create a Microsoft Installer (.msi) binary distribution" user_options = [('bdist-dir=', None, "temporary directory for creating the distribution"), ('keep-temp', 'k', "keep the pseudo-installation tree around after " + "creating the distribution archive"), ('target-version=', None, "require a specific python version" + " on the target system"), ('no-target-compile', 'c', "do not compile .py to .pyc on the target system"), ('no-target-optimize', 'o', "do not compile .py to .pyo (optimized)" "on the target system"), ('dist-dir=', 'd', "directory to put final built distributions in"), ('skip-build', None, "skip rebuilding everything (for testing/debugging)"), ('install-script=', None, "basename of installation script to be run after" "installation or before deinstallation"), ('pre-install-script=', None, "Fully qualified filename of a script to be run before " "any files are installed. This script need not be in the " "distribution"), ] boolean_options = ['keep-temp', 'no-target-compile', 'no-target-optimize', 'skip-build'] def initialize_options (self): self.bdist_dir = None self.keep_temp = 0 self.no_target_compile = 0 self.no_target_optimize = 0 self.target_version = None self.dist_dir = None self.skip_build = 0 self.install_script = None self.pre_install_script = None def finalize_options (self): if self.bdist_dir is None: bdist_base = self.get_finalized_command('bdist').bdist_base self.bdist_dir = os.path.join(bdist_base, 'msi') short_version = get_python_version() if self.target_version: if not self.skip_build and self.distribution.has_ext_modules()\ and self.target_version != short_version: raise DistutilsOptionError, \ "target version can only be %s, or the '--skip_build'" \ " option must be specified" % (short_version,) else: self.target_version = short_version self.set_undefined_options('bdist', ('dist_dir', 'dist_dir')) if self.pre_install_script: raise DistutilsOptionError, "the pre-install-script feature is not yet implemented" if self.install_script: for script in self.distribution.scripts: if self.install_script == os.path.basename(script): break else: raise DistutilsOptionError, \ "install_script '%s' not found in scripts" % \ self.install_script self.install_script_key = None # finalize_options() def run (self): if not self.skip_build: self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.prefix = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 install_lib = self.reinitialize_command('install_lib') # we do not want to include pyc or pyo files install_lib.compile = 0 install_lib.optimize = 0 if self.distribution.has_ext_modules(): # If we are building an installer for a Python version other # than the one we are currently running, then we need to ensure # our build_lib reflects the other Python version rather than ours. # Note that for target_version!=sys.version, we must have skipped the # build step, so there is no issue with enforcing the build of this # version. target_version = self.target_version if not target_version: assert self.skip_build, "Should have already checked this" target_version = sys.version[0:3] plat_specifier = ".%s-%s" % (get_platform(), target_version) build = self.get_finalized_command('build') build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier) log.info("installing to %s", self.bdist_dir) install.ensure_finalized() # avoid warning of 'install_lib' about installing # into a directory not in sys.path sys.path.insert(0, os.path.join(self.bdist_dir, 'PURELIB')) install.run() del sys.path[0] self.mkpath(self.dist_dir) fullname = self.distribution.get_fullname() installer_name = self.get_installer_filename(fullname) installer_name = os.path.abspath(installer_name) if os.path.exists(installer_name): os.unlink(installer_name) metadata = self.distribution.metadata author = metadata.author if not author: author = metadata.maintainer if not author: author = "UNKNOWN" version = metadata.get_version() # ProductVersion must be strictly numeric # XXX need to deal with prerelease versions sversion = "%d.%d.%d" % StrictVersion(version).version # Prefix ProductName with Python x.y, so that # it sorts together with the other Python packages # in Add-Remove-Programs (APR) product_name = "Python %s %s" % (self.target_version, self.distribution.get_fullname()) self.db = msilib.init_database(installer_name, schema, product_name, msilib.gen_uuid(), sversion, author) msilib.add_tables(self.db, sequence) props = [('DistVersion', version)] email = metadata.author_email or metadata.maintainer_email if email: props.append(("ARPCONTACT", email)) if metadata.url: props.append(("ARPURLINFOABOUT", metadata.url)) if props: add_data(self.db, 'Property', props) self.add_find_python() self.add_files() self.add_scripts() self.add_ui() self.db.Commit() if hasattr(self.distribution, 'dist_files'): self.distribution.dist_files.append(('bdist_msi', self.target_version, fullname)) if not self.keep_temp: remove_tree(self.bdist_dir, dry_run=self.dry_run) def add_files(self): db = self.db cab = msilib.CAB("distfiles") f = Feature(db, "default", "Default Feature", "Everything", 1, directory="TARGETDIR") f.set_current() rootdir = os.path.abspath(self.bdist_dir) root = Directory(db, cab, None, rootdir, "TARGETDIR", "SourceDir") db.Commit() todo = [root] while todo: dir = todo.pop() for file in os.listdir(dir.absolute): afile = os.path.join(dir.absolute, file) if os.path.isdir(afile): newdir = Directory(db, cab, dir, file, file, "%s|%s" % (dir.make_short(file), file)) todo.append(newdir) else: key = dir.add_file(file) if file==self.install_script: if self.install_script_key: raise DistutilsOptionError, "Multiple files with name %s" % file self.install_script_key = '[#%s]' % key cab.commit(db) def add_find_python(self): """Adds code to the installer to compute the location of Python. Properties PYTHON.MACHINE, PYTHON.USER, PYTHONDIR and PYTHON will be set in both the execute and UI sequences; PYTHONDIR will be set from PYTHON.USER if defined, else from PYTHON.MACHINE. PYTHON is PYTHONDIR\python.exe""" install_path = r"SOFTWARE\Python\PythonCore\%s\InstallPath" % self.target_version add_data(self.db, "RegLocator", [("python.machine", 2, install_path, None, 2), ("python.user", 1, install_path, None, 2)]) add_data(self.db, "AppSearch", [("PYTHON.MACHINE", "python.machine"), ("PYTHON.USER", "python.user")]) add_data(self.db, "CustomAction", [("PythonFromMachine", 51+256, "PYTHONDIR", "[PYTHON.MACHINE]"), ("PythonFromUser", 51+256, "PYTHONDIR", "[PYTHON.USER]"), ("PythonExe", 51+256, "PYTHON", "[PYTHONDIR]\\python.exe"), ("InitialTargetDir", 51+256, "TARGETDIR", "[PYTHONDIR]")]) add_data(self.db, "InstallExecuteSequence", [("PythonFromMachine", "PYTHON.MACHINE", 401), ("PythonFromUser", "PYTHON.USER", 402), ("PythonExe", None, 403), ("InitialTargetDir", 'TARGETDIR=""', 404), ]) add_data(self.db, "InstallUISequence", [("PythonFromMachine", "PYTHON.MACHINE", 401), ("PythonFromUser", "PYTHON.USER", 402), ("PythonExe", None, 403), ("InitialTargetDir", 'TARGETDIR=""', 404), ]) def add_scripts(self): if self.install_script: add_data(self.db, "CustomAction", [("install_script", 50, "PYTHON", self.install_script_key)]) add_data(self.db, "InstallExecuteSequence", [("install_script", "NOT Installed", 6800)]) if self.pre_install_script: scriptfn = os.path.join(self.bdist_dir, "preinstall.bat") f = open(scriptfn, "w") # The batch file will be executed with [PYTHON], so that %1 # is the path to the Python interpreter; %0 will be the path # of the batch file. # rem =""" # %1 %0 # exit # """ # <actual script> f.write('rem ="""\n%1 %0\nexit\n"""\n') f.write(open(self.pre_install_script).read()) f.close() add_data(self.db, "Binary", [("PreInstall", msilib.Binary(scriptfn)) ]) add_data(self.db, "CustomAction", [("PreInstall", 2, "PreInstall", None) ]) add_data(self.db, "InstallExecuteSequence", [("PreInstall", "NOT Installed", 450)]) def add_ui(self): db = self.db x = y = 50 w = 370 h = 300 title = "[ProductName] Setup" # see "Dialog Style Bits" modal = 3 # visible | modal modeless = 1 # visible track_disk_space = 32 # UI customization properties add_data(db, "Property", # See "DefaultUIFont Property" [("DefaultUIFont", "DlgFont8"), # See "ErrorDialog Style Bit" ("ErrorDialog", "ErrorDlg"), ("Progress1", "Install"), # modified in maintenance type dlg ("Progress2", "installs"), ("MaintenanceForm_Action", "Repair"), # possible values: ALL, JUSTME ("WhichUsers", "ALL") ]) # Fonts, see "TextStyle Table" add_data(db, "TextStyle", [("DlgFont8", "Tahoma", 9, None, 0), ("DlgFontBold8", "Tahoma", 8, None, 1), #bold ("VerdanaBold10", "Verdana", 10, None, 1), ("VerdanaRed9", "Verdana", 9, 255, 0), ]) # UI Sequences, see "InstallUISequence Table", "Using a Sequence Table" # Numbers indicate sequence; see sequence.py for how these action integrate add_data(db, "InstallUISequence", [("PrepareDlg", "Not Privileged or Windows9x or Installed", 140), ("WhichUsersDlg", "Privileged and not Windows9x and not Installed", 141), # In the user interface, assume all-users installation if privileged. ("SelectDirectoryDlg", "Not Installed", 1230), # XXX no support for resume installations yet #("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240), ("MaintenanceTypeDlg", "Installed AND NOT RESUME AND NOT Preselected", 1250), ("ProgressDlg", None, 1280)]) add_data(db, 'ActionText', text.ActionText) add_data(db, 'UIText', text.UIText) ##################################################################### # Standard dialogs: FatalError, UserExit, ExitDialog fatal=PyDialog(db, "FatalError", x, y, w, h, modal, title, "Finish", "Finish", "Finish") fatal.title("[ProductName] Installer ended prematurely") fatal.back("< Back", "Finish", active = 0) fatal.cancel("Cancel", "Back", active = 0) fatal.text("Description1", 15, 70, 320, 80, 0x30003, "[ProductName] setup ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again.") fatal.text("Description2", 15, 155, 320, 20, 0x30003, "Click the Finish button to exit the Installer.") c=fatal.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Exit") user_exit=PyDialog(db, "UserExit", x, y, w, h, modal, title, "Finish", "Finish", "Finish") user_exit.title("[ProductName] Installer was interrupted") user_exit.back("< Back", "Finish", active = 0) user_exit.cancel("Cancel", "Back", active = 0) user_exit.text("Description1", 15, 70, 320, 80, 0x30003, "[ProductName] setup was interrupted. Your system has not been modified. " "To install this program at a later time, please run the installation again.") user_exit.text("Description2", 15, 155, 320, 20, 0x30003, "Click the Finish button to exit the Installer.") c = user_exit.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Exit") exit_dialog = PyDialog(db, "ExitDialog", x, y, w, h, modal, title, "Finish", "Finish", "Finish") exit_dialog.title("Completing the [ProductName] Installer") exit_dialog.back("< Back", "Finish", active = 0) exit_dialog.cancel("Cancel", "Back", active = 0) exit_dialog.text("Description", 15, 235, 320, 20, 0x30003, "Click the Finish button to exit the Installer.") c = exit_dialog.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Return") ##################################################################### # Required dialog: FilesInUse, ErrorDlg inuse = PyDialog(db, "FilesInUse", x, y, w, h, 19, # KeepModeless|Modal|Visible title, "Retry", "Retry", "Retry", bitmap=False) inuse.text("Title", 15, 6, 200, 15, 0x30003, r"{\DlgFontBold8}Files in Use") inuse.text("Description", 20, 23, 280, 20, 0x30003, "Some files that need to be updated are currently in use.") inuse.text("Text", 20, 55, 330, 50, 3, "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.") inuse.control("List", "ListBox", 20, 107, 330, 130, 7, "FileInUseProcess", None, None, None) c=inuse.back("Exit", "Ignore", name="Exit") c.event("EndDialog", "Exit") c=inuse.next("Ignore", "Retry", name="Ignore") c.event("EndDialog", "Ignore") c=inuse.cancel("Retry", "Exit", name="Retry") c.event("EndDialog","Retry") # See "Error Dialog". See "ICE20" for the required names of the controls. error = Dialog(db, "ErrorDlg", 50, 10, 330, 101, 65543, # Error|Minimize|Modal|Visible title, "ErrorText", None, None) error.text("ErrorText", 50,9,280,48,3, "") #error.control("ErrorIcon", "Icon", 15, 9, 24, 24, 5242881, None, "py.ico", None, None) error.pushbutton("N",120,72,81,21,3,"No",None).event("EndDialog","ErrorNo") error.pushbutton("Y",240,72,81,21,3,"Yes",None).event("EndDialog","ErrorYes") error.pushbutton("A",0,72,81,21,3,"Abort",None).event("EndDialog","ErrorAbort") error.pushbutton("C",42,72,81,21,3,"Cancel",None).event("EndDialog","ErrorCancel") error.pushbutton("I",81,72,81,21,3,"Ignore",None).event("EndDialog","ErrorIgnore") error.pushbutton("O",159,72,81,21,3,"Ok",None).event("EndDialog","ErrorOk") error.pushbutton("R",198,72,81,21,3,"Retry",None).event("EndDialog","ErrorRetry") ##################################################################### # Global "Query Cancel" dialog cancel = Dialog(db, "CancelDlg", 50, 10, 260, 85, 3, title, "No", "No", "No") cancel.text("Text", 48, 15, 194, 30, 3, "Are you sure you want to cancel [ProductName] installation?") #cancel.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None, # "py.ico", None, None) c=cancel.pushbutton("Yes", 72, 57, 56, 17, 3, "Yes", "No") c.event("EndDialog", "Exit") c=cancel.pushbutton("No", 132, 57, 56, 17, 3, "No", "Yes") c.event("EndDialog", "Return") ##################################################################### # Global "Wait for costing" dialog costing = Dialog(db, "WaitForCostingDlg", 50, 10, 260, 85, modal, title, "Return", "Return", "Return") costing.text("Text", 48, 15, 194, 30, 3, "Please wait while the installer finishes determining your disk space requirements.") c = costing.pushbutton("Return", 102, 57, 56, 17, 3, "Return", None) c.event("EndDialog", "Exit") ##################################################################### # Preparation dialog: no user input except cancellation prep = PyDialog(db, "PrepareDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel") prep.text("Description", 15, 70, 320, 40, 0x30003, "Please wait while the Installer prepares to guide you through the installation.") prep.title("Welcome to the [ProductName] Installer") c=prep.text("ActionText", 15, 110, 320, 20, 0x30003, "Pondering...") c.mapping("ActionText", "Text") c=prep.text("ActionData", 15, 135, 320, 30, 0x30003, None) c.mapping("ActionData", "Text") prep.back("Back", None, active=0) prep.next("Next", None, active=0) c=prep.cancel("Cancel", None) c.event("SpawnDialog", "CancelDlg") ##################################################################### # Target directory selection seldlg = PyDialog(db, "SelectDirectoryDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") seldlg.title("Select Destination Directory") version = sys.version[:3]+" " seldlg.text("Hint", 15, 30, 300, 40, 3, "The destination directory should contain a Python %sinstallation" % version) seldlg.back("< Back", None, active=0) c = seldlg.next("Next >", "Cancel") c.event("SetTargetPath", "TARGETDIR", ordering=1) c.event("SpawnWaitDialog", "WaitForCostingDlg", ordering=2) c.event("EndDialog", "Return", ordering=3) c = seldlg.cancel("Cancel", "DirectoryCombo") c.event("SpawnDialog", "CancelDlg") seldlg.control("DirectoryCombo", "DirectoryCombo", 15, 70, 272, 80, 393219, "TARGETDIR", None, "DirectoryList", None) seldlg.control("DirectoryList", "DirectoryList", 15, 90, 308, 136, 3, "TARGETDIR", None, "PathEdit", None) seldlg.control("PathEdit", "PathEdit", 15, 230, 306, 16, 3, "TARGETDIR", None, "Next", None) c = seldlg.pushbutton("Up", 306, 70, 18, 18, 3, "Up", None) c.event("DirectoryListUp", "0") c = seldlg.pushbutton("NewDir", 324, 70, 30, 18, 3, "New", None) c.event("DirectoryListNew", "0") ##################################################################### # Disk cost cost = PyDialog(db, "DiskCostDlg", x, y, w, h, modal, title, "OK", "OK", "OK", bitmap=False) cost.text("Title", 15, 6, 200, 15, 0x30003, "{\DlgFontBold8}Disk Space Requirements") cost.text("Description", 20, 20, 280, 20, 0x30003, "The disk space required for the installation of the selected features.") cost.text("Text", 20, 53, 330, 60, 3, "The highlighted volumes (if any) do not have enough disk space " "available for the currently selected features. You can either " "remove some files from the highlighted volumes, or choose to " "install less features onto local drive(s), or select different " "destination drive(s).") cost.control("VolumeList", "VolumeCostList", 20, 100, 330, 150, 393223, None, "{120}{70}{70}{70}{70}", None, None) cost.xbutton("OK", "Ok", None, 0.5).event("EndDialog", "Return") ##################################################################### # WhichUsers Dialog. Only available on NT, and for privileged users. # This must be run before FindRelatedProducts, because that will # take into account whether the previous installation was per-user # or per-machine. We currently don't support going back to this # dialog after "Next" was selected; to support this, we would need to # find how to reset the ALLUSERS property, and how to re-run # FindRelatedProducts. # On Windows9x, the ALLUSERS property is ignored on the command line # and in the Property table, but installer fails according to the documentation # if a dialog attempts to set ALLUSERS. whichusers = PyDialog(db, "WhichUsersDlg", x, y, w, h, modal, title, "AdminInstall", "Next", "Cancel") whichusers.title("Select whether to install [ProductName] for all users of this computer.") # A radio group with two options: allusers, justme g = whichusers.radiogroup("AdminInstall", 15, 60, 260, 50, 3, "WhichUsers", "", "Next") g.add("ALL", 0, 5, 150, 20, "Install for all users") g.add("JUSTME", 0, 25, 150, 20, "Install just for me") whichusers.back("Back", None, active=0) c = whichusers.next("Next >", "Cancel") c.event("[ALLUSERS]", "1", 'WhichUsers="ALL"', 1) c.event("EndDialog", "Return", ordering = 2) c = whichusers.cancel("Cancel", "AdminInstall") c.event("SpawnDialog", "CancelDlg") ##################################################################### # Installation Progress dialog (modeless) progress = PyDialog(db, "ProgressDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel", bitmap=False) progress.text("Title", 20, 15, 200, 15, 0x30003, "{\DlgFontBold8}[Progress1] [ProductName]") progress.text("Text", 35, 65, 300, 30, 3, "Please wait while the Installer [Progress2] [ProductName]. " "This may take several minutes.") progress.text("StatusLabel", 35, 100, 35, 20, 3, "Status:") c=progress.text("ActionText", 70, 100, w-70, 20, 3, "Pondering...") c.mapping("ActionText", "Text") #c=progress.text("ActionData", 35, 140, 300, 20, 3, None) #c.mapping("ActionData", "Text") c=progress.control("ProgressBar", "ProgressBar", 35, 120, 300, 10, 65537, None, "Progress done", None, None) c.mapping("SetProgress", "Progress") progress.back("< Back", "Next", active=False) progress.next("Next >", "Cancel", active=False) progress.cancel("Cancel", "Back").event("SpawnDialog", "CancelDlg") ################################################################### # Maintenance type: repair/uninstall maint = PyDialog(db, "MaintenanceTypeDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") maint.title("Welcome to the [ProductName] Setup Wizard") maint.text("BodyText", 15, 63, 330, 42, 3, "Select whether you want to repair or remove [ProductName].") g=maint.radiogroup("RepairRadioGroup", 15, 108, 330, 60, 3, "MaintenanceForm_Action", "", "Next") #g.add("Change", 0, 0, 200, 17, "&Change [ProductName]") g.add("Repair", 0, 18, 200, 17, "&Repair [ProductName]") g.add("Remove", 0, 36, 200, 17, "Re&move [ProductName]") maint.back("< Back", None, active=False) c=maint.next("Finish", "Cancel") # Change installation: Change progress dialog to "Change", then ask # for feature selection #c.event("[Progress1]", "Change", 'MaintenanceForm_Action="Change"', 1) #c.event("[Progress2]", "changes", 'MaintenanceForm_Action="Change"', 2) # Reinstall: Change progress dialog to "Repair", then invoke reinstall # Also set list of reinstalled features to "ALL" c.event("[REINSTALL]", "ALL", 'MaintenanceForm_Action="Repair"', 5) c.event("[Progress1]", "Repairing", 'MaintenanceForm_Action="Repair"', 6) c.event("[Progress2]", "repairs", 'MaintenanceForm_Action="Repair"', 7) c.event("Reinstall", "ALL", 'MaintenanceForm_Action="Repair"', 8) # Uninstall: Change progress to "Remove", then invoke uninstall # Also set list of removed features to "ALL" c.event("[REMOVE]", "ALL", 'MaintenanceForm_Action="Remove"', 11) c.event("[Progress1]", "Removing", 'MaintenanceForm_Action="Remove"', 12) c.event("[Progress2]", "removes", 'MaintenanceForm_Action="Remove"', 13) c.event("Remove", "ALL", 'MaintenanceForm_Action="Remove"', 14) # Close dialog when maintenance action scheduled c.event("EndDialog", "Return", 'MaintenanceForm_Action<>"Change"', 20) #c.event("NewDialog", "SelectFeaturesDlg", 'MaintenanceForm_Action="Change"', 21) maint.cancel("Cancel", "RepairRadioGroup").event("SpawnDialog", "CancelDlg") def get_installer_filename(self, fullname): # Factored out to allow overriding in subclasses installer_name = os.path.join(self.dist_dir, "%s.win32-py%s.msi" % (fullname, self.target_version)) return installer_name
mit
vladimir-ipatov/ganeti
test/py/ganeti.impexpd_unittest.py
9
8733
#!/usr/bin/python # # Copyright (C) 2010 Google Inc. # # 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. """Script for testing ganeti.impexpd""" import os import sys import re import unittest import socket from ganeti import constants from ganeti import objects from ganeti import compat from ganeti import utils from ganeti import errors from ganeti import impexpd import testutils class CmdBuilderConfig(objects.ConfigObject): __slots__ = [ "bind", "key", "cert", "ca", "host", "port", "ipv4", "ipv6", "compress", "magic", "connect_timeout", "connect_retries", "cmd_prefix", "cmd_suffix", ] def CheckCmdWord(cmd, word): wre = re.compile(r"\b%s\b" % re.escape(word)) return compat.any(wre.search(i) for i in cmd) class TestCommandBuilder(unittest.TestCase): def test(self): for mode in [constants.IEM_IMPORT, constants.IEM_EXPORT]: if mode == constants.IEM_IMPORT: comprcmd = "gunzip" elif mode == constants.IEM_EXPORT: comprcmd = "gzip" for compress in [constants.IEC_NONE, constants.IEC_GZIP]: for magic in [None, 10 * "-", "HelloWorld", "J9plh4nFo2", "24A02A81-2264-4B51-A882-A2AB9D85B420"]: opts = CmdBuilderConfig(magic=magic, compress=compress) builder = impexpd.CommandBuilder(mode, opts, 1, 2, 3) magic_cmd = builder._GetMagicCommand() dd_cmd = builder._GetDdCommand() if magic: self.assert_(("M=%s" % magic) in magic_cmd) self.assert_(("M=%s" % magic) in dd_cmd) else: self.assertFalse(magic_cmd) for host in ["localhost", "198.51.100.4", "192.0.2.99"]: for port in [0, 1, 1234, 7856, 45452]: for cmd_prefix in [None, "PrefixCommandGoesHere|", "dd if=/dev/hda bs=1048576 |"]: for cmd_suffix in [None, "< /some/file/name", "| dd of=/dev/null"]: opts = CmdBuilderConfig(host=host, port=port, compress=compress, cmd_prefix=cmd_prefix, cmd_suffix=cmd_suffix) builder = impexpd.CommandBuilder(mode, opts, 1, 2, 3) # Check complete command cmd = builder.GetCommand() self.assert_(isinstance(cmd, list)) if compress == constants.IEC_GZIP: self.assert_(CheckCmdWord(cmd, comprcmd)) if cmd_prefix is not None: self.assert_(compat.any(cmd_prefix in i for i in cmd)) if cmd_suffix is not None: self.assert_(compat.any(cmd_suffix in i for i in cmd)) # Check socat command socat_cmd = builder._GetSocatCommand() if mode == constants.IEM_IMPORT: ssl_addr = socat_cmd[-2].split(",") self.assert_(("OPENSSL-LISTEN:%s" % port) in ssl_addr) elif mode == constants.IEM_EXPORT: ssl_addr = socat_cmd[-1].split(",") self.assert_(("OPENSSL:%s:%s" % (host, port)) in ssl_addr) self.assert_("verify=1" in ssl_addr) def testIPv6(self): for mode in [constants.IEM_IMPORT, constants.IEM_EXPORT]: opts = CmdBuilderConfig(host="localhost", port=6789, ipv4=False, ipv6=False) builder = impexpd.CommandBuilder(mode, opts, 1, 2, 3) cmd = builder._GetSocatCommand() self.assert_(compat.all("pf=" not in i for i in cmd)) # IPv4 opts = CmdBuilderConfig(host="localhost", port=6789, ipv4=True, ipv6=False) builder = impexpd.CommandBuilder(mode, opts, 1, 2, 3) cmd = builder._GetSocatCommand() self.assert_(compat.any(",pf=ipv4" in i for i in cmd)) # IPv6 opts = CmdBuilderConfig(host="localhost", port=6789, ipv4=False, ipv6=True) builder = impexpd.CommandBuilder(mode, opts, 1, 2, 3) cmd = builder._GetSocatCommand() self.assert_(compat.any(",pf=ipv6" in i for i in cmd)) # IPv4 and IPv6 opts = CmdBuilderConfig(host="localhost", port=6789, ipv4=True, ipv6=True) builder = impexpd.CommandBuilder(mode, opts, 1, 2, 3) self.assertRaises(AssertionError, builder._GetSocatCommand) def testCommaError(self): opts = CmdBuilderConfig(host="localhost", port=1234, ca="/some/path/with,a/,comma") for mode in [constants.IEM_IMPORT, constants.IEM_EXPORT]: builder = impexpd.CommandBuilder(mode, opts, 1, 2, 3) self.assertRaises(errors.GenericError, builder.GetCommand) def testOptionLengthError(self): testopts = [ CmdBuilderConfig(bind="0.0.0.0" + ("A" * impexpd.SOCAT_OPTION_MAXLEN), port=1234, ca="/tmp/ca"), CmdBuilderConfig(host="localhost", port=1234, ca="/tmp/ca" + ("B" * impexpd.SOCAT_OPTION_MAXLEN)), CmdBuilderConfig(host="localhost", port=1234, key="/tmp/key" + ("B" * impexpd.SOCAT_OPTION_MAXLEN)), ] for opts in testopts: for mode in [constants.IEM_IMPORT, constants.IEM_EXPORT]: builder = impexpd.CommandBuilder(mode, opts, 1, 2, 3) self.assertRaises(errors.GenericError, builder.GetCommand) opts.host = "localhost" + ("A" * impexpd.SOCAT_OPTION_MAXLEN) builder = impexpd.CommandBuilder(constants.IEM_EXPORT, opts, 1, 2, 3) self.assertRaises(errors.GenericError, builder.GetCommand) def testModeError(self): mode = "foobarbaz" assert mode not in [constants.IEM_IMPORT, constants.IEM_EXPORT] opts = CmdBuilderConfig(host="localhost", port=1234) builder = impexpd.CommandBuilder(mode, opts, 1, 2, 3) self.assertRaises(errors.GenericError, builder.GetCommand) class TestVerifyListening(unittest.TestCase): def test(self): self.assertEqual(impexpd._VerifyListening(socket.AF_INET, "192.0.2.7", 1234), ("192.0.2.7", 1234)) self.assertEqual(impexpd._VerifyListening(socket.AF_INET6, "::1", 9876), ("::1", 9876)) self.assertEqual(impexpd._VerifyListening(socket.AF_INET6, "[::1]", 4563), ("::1", 4563)) self.assertEqual(impexpd._VerifyListening(socket.AF_INET6, "[2001:db8::1:4563]", 4563), ("2001:db8::1:4563", 4563)) def testError(self): for family in [socket.AF_UNIX, socket.AF_INET, socket.AF_INET6]: self.assertRaises(errors.GenericError, impexpd._VerifyListening, family, "", 1234) self.assertRaises(errors.GenericError, impexpd._VerifyListening, family, "192", 999) for family in [socket.AF_UNIX, socket.AF_INET6]: self.assertRaises(errors.GenericError, impexpd._VerifyListening, family, "192.0.2.7", 1234) self.assertRaises(errors.GenericError, impexpd._VerifyListening, family, "[2001:db8::1", 1234) self.assertRaises(errors.GenericError, impexpd._VerifyListening, family, "2001:db8::1]", 1234) for family in [socket.AF_UNIX, socket.AF_INET]: self.assertRaises(errors.GenericError, impexpd._VerifyListening, family, "::1", 1234) class TestCalcThroughput(unittest.TestCase): def test(self): self.assertEqual(impexpd._CalcThroughput([]), None) self.assertEqual(impexpd._CalcThroughput([(0, 0)]), None) samples = [ (0.0, 0.0), (10.0, 100.0), ] self.assertAlmostEqual(impexpd._CalcThroughput(samples), 10.0, 3) samples = [ (5.0, 7.0), (10.0, 100.0), (16.0, 181.0), ] self.assertAlmostEqual(impexpd._CalcThroughput(samples), 15.818, 3) if __name__ == "__main__": testutils.GanetiTestProgram()
gpl-2.0
mayankcu/Django-social
venv/Lib/site-packages/django/contrib/gis/geos/prototypes/predicates.py
623
1777
""" This module houses the GEOS ctypes prototype functions for the unary and binary predicate operations on geometries. """ from ctypes import c_char, c_char_p, c_double from django.contrib.gis.geos.libgeos import GEOM_PTR from django.contrib.gis.geos.prototypes.errcheck import check_predicate from django.contrib.gis.geos.prototypes.threadsafe import GEOSFunc ## Binary & unary predicate functions ## def binary_predicate(func, *args): "For GEOS binary predicate functions." argtypes = [GEOM_PTR, GEOM_PTR] if args: argtypes += args func.argtypes = argtypes func.restype = c_char func.errcheck = check_predicate return func def unary_predicate(func): "For GEOS unary predicate functions." func.argtypes = [GEOM_PTR] func.restype = c_char func.errcheck = check_predicate return func ## Unary Predicates ## geos_hasz = unary_predicate(GEOSFunc('GEOSHasZ')) geos_isempty = unary_predicate(GEOSFunc('GEOSisEmpty')) geos_isring = unary_predicate(GEOSFunc('GEOSisRing')) geos_issimple = unary_predicate(GEOSFunc('GEOSisSimple')) geos_isvalid = unary_predicate(GEOSFunc('GEOSisValid')) ## Binary Predicates ## geos_contains = binary_predicate(GEOSFunc('GEOSContains')) geos_crosses = binary_predicate(GEOSFunc('GEOSCrosses')) geos_disjoint = binary_predicate(GEOSFunc('GEOSDisjoint')) geos_equals = binary_predicate(GEOSFunc('GEOSEquals')) geos_equalsexact = binary_predicate(GEOSFunc('GEOSEqualsExact'), c_double) geos_intersects = binary_predicate(GEOSFunc('GEOSIntersects')) geos_overlaps = binary_predicate(GEOSFunc('GEOSOverlaps')) geos_relatepattern = binary_predicate(GEOSFunc('GEOSRelatePattern'), c_char_p) geos_touches = binary_predicate(GEOSFunc('GEOSTouches')) geos_within = binary_predicate(GEOSFunc('GEOSWithin'))
bsd-3-clause
iansf/sky_engine
sky/tools/webkitpy/layout_tests/port/linux.py
7
6967
# Copyright (C) 2010 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 re from webkitpy.common.webkit_finder import WebKitFinder from webkitpy.layout_tests.breakpad.dump_reader_multipart import DumpReaderLinux from webkitpy.layout_tests.models import test_run_results from webkitpy.layout_tests.port import base from webkitpy.layout_tests.port import config _log = logging.getLogger(__name__) class LinuxPort(base.Port): port_name = 'linux' SUPPORTED_VERSIONS = ('x86', 'x86_64') FALLBACK_PATHS = { 'x86_64': [ 'linux' ] } FALLBACK_PATHS['x86'] = ['linux-x86'] + FALLBACK_PATHS['x86_64'] DEFAULT_BUILD_DIRECTORIES = ('out',) BUILD_REQUIREMENTS_URL = 'https://code.google.com/p/chromium/wiki/LinuxBuildInstructions' @classmethod def _determine_driver_path_statically(cls, host, options): config_object = config.Config(host.executive, host.filesystem) build_directory = getattr(options, 'build_directory', None) finder = WebKitFinder(host.filesystem) webkit_base = finder.webkit_base() chromium_base = finder.chromium_base() driver_name = cls.SKY_SHELL_NAME if hasattr(options, 'configuration') and options.configuration: configuration = options.configuration else: configuration = config_object.default_configuration() return cls._static_build_path(host.filesystem, build_directory, chromium_base, configuration, [driver_name]) @staticmethod def _determine_architecture(filesystem, executive, driver_path): file_output = '' if filesystem.isfile(driver_path): # The --dereference flag tells file to follow symlinks file_output = executive.run_command(['file', '--brief', '--dereference', driver_path], return_stderr=True) if re.match(r'ELF 32-bit LSB\s+executable', file_output): return 'x86' if re.match(r'ELF 64-bit LSB\s+executable', file_output): return 'x86_64' if file_output: _log.warning('Could not determine architecture from "file" output: %s' % file_output) # We don't know what the architecture is; default to 'x86' because # maybe we're rebaselining and the binary doesn't actually exist, # or something else weird is going on. It's okay to do this because # if we actually try to use the binary, check_build() should fail. return 'x86_64' @classmethod def determine_full_port_name(cls, host, options, port_name): if port_name.endswith('linux'): return port_name + '-' + cls._determine_architecture(host.filesystem, host.executive, cls._determine_driver_path_statically(host, options)) return port_name def __init__(self, host, port_name, **kwargs): super(LinuxPort, self).__init__(host, port_name, **kwargs) (base, arch) = port_name.rsplit('-', 1) assert base == 'linux' assert arch in self.SUPPORTED_VERSIONS assert port_name in ('linux', 'linux-x86', 'linux-x86_64') self._version = 'lucid' # We only support lucid right now. self._architecture = arch if not self.get_option('disable_breakpad'): self._dump_reader = DumpReaderLinux(host, self._build_path()) def default_baseline_search_path(self): port_names = self.FALLBACK_PATHS[self._architecture] return map(self._webkit_baseline_path, port_names) def _modules_to_search_for_symbols(self): return [self._build_path('libffmpegsumo.so')] def check_build(self, needs_http, printer): result = super(LinuxPort, self).check_build(needs_http, printer) if result: _log.error('For complete Linux build requirements, please see:') _log.error('') _log.error(' http://code.google.com/p/chromium/wiki/LinuxBuildInstructions') return result def look_for_new_crash_logs(self, crashed_processes, start_time): if self.get_option('disable_breakpad'): return None return self._dump_reader.look_for_new_crash_logs(crashed_processes, start_time) def clobber_old_port_specific_results(self): if not self.get_option('disable_breakpad'): self._dump_reader.clobber_old_results() def operating_system(self): return 'linux' # # PROTECTED METHODS # def _check_apache_install(self): result = self._check_file_exists(self.path_to_apache(), "apache2") result = self._check_file_exists(self.path_to_apache_config_file(), "apache2 config file") and result if not result: _log.error(' Please install using: "sudo apt-get install apache2 libapache2-mod-php5"') _log.error('') return result def _wdiff_missing_message(self): return 'wdiff is not installed; please install using "sudo apt-get install wdiff"' def path_to_apache(self): # The Apache binary path can vary depending on OS and distribution # See http://wiki.apache.org/httpd/DistrosDefaultLayout for path in ["/usr/sbin/httpd", "/usr/sbin/apache2"]: if self._filesystem.exists(path): return path _log.error("Could not find apache. Not installed or unknown path.") return None def _path_to_driver(self, configuration=None): binary_name = self.driver_name() return self._build_path_with_configuration(configuration, binary_name)
bsd-3-clause
rgommers/statsmodels
statsmodels/duration/tests/survival_r_results.py
34
11980
import numpy as np coef_20_1_bre = np.array([-0.9185611]) se_20_1_bre = np.array([0.4706831]) time_20_1_bre = np.array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,1.1,1.2,1.3,1.4,1.5]) hazard_20_1_bre = np.array([0,0,0.04139181,0.1755379,0.3121216,0.3121216,0.4263121,0.6196358,0.6196358,0.6196358,0.909556,1.31083,1.31083]) coef_20_1_et_bre = np.array([-0.8907007]) se_20_1_et_bre = np.array([0.4683384]) time_20_1_et_bre = np.array([0]) hazard_20_1_et_bre = np.array([0]) coef_20_1_st_bre = np.array([-0.5766809]) se_20_1_st_bre = np.array([0.4418918]) time_20_1_st_bre = np.array([0]) hazard_20_1_st_bre = np.array([0]) coef_20_1_et_st_bre = np.array([-0.5785683]) se_20_1_et_st_bre = np.array([0.4388437]) time_20_1_et_st_bre = np.array([0]) hazard_20_1_et_st_bre = np.array([0]) coef_20_1_efr = np.array([-0.9975319]) se_20_1_efr = np.array([0.4792421]) time_20_1_efr = np.array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,1.1,1.2,1.3,1.4,1.5]) hazard_20_1_efr = np.array([0,0,0.03934634,0.1663316,0.2986427,0.2986427,0.4119189,0.6077373,0.6077373,0.6077373,0.8933041,1.285732,1.285732]) coef_20_1_et_efr = np.array([-0.9679541]) se_20_1_et_efr = np.array([0.4766406]) time_20_1_et_efr = np.array([0]) hazard_20_1_et_efr = np.array([0]) coef_20_1_st_efr = np.array([-0.6345294]) se_20_1_st_efr = np.array([0.4455952]) time_20_1_st_efr = np.array([0]) hazard_20_1_st_efr = np.array([0]) coef_20_1_et_st_efr = np.array([-0.6355622]) se_20_1_et_st_efr = np.array([0.4423104]) time_20_1_et_st_efr = np.array([0]) hazard_20_1_et_st_efr = np.array([0]) coef_50_1_bre = np.array([-0.6761247]) se_50_1_bre = np.array([0.25133]) time_50_1_bre = np.array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.1,1.2,1.5,1.6,1.7,1.8,1.9,2.4,2.8]) hazard_50_1_bre = np.array([0,0.04895521,0.08457461,0.2073863,0.2382473,0.2793018,0.3271622,0.3842953,0.3842953,0.5310807,0.6360276,0.7648251,0.7648251,0.9294298,0.9294298,0.9294298,1.206438,1.555569,1.555569]) coef_50_1_et_bre = np.array([-0.6492871]) se_50_1_et_bre = np.array([0.2542493]) time_50_1_et_bre = np.array([0]) hazard_50_1_et_bre = np.array([0]) coef_50_1_st_bre = np.array([-0.7051135]) se_50_1_st_bre = np.array([0.2852093]) time_50_1_st_bre = np.array([0]) hazard_50_1_st_bre = np.array([0]) coef_50_1_et_st_bre = np.array([-0.8672546]) se_50_1_et_st_bre = np.array([0.3443235]) time_50_1_et_st_bre = np.array([0]) hazard_50_1_et_st_bre = np.array([0]) coef_50_1_efr = np.array([-0.7119322]) se_50_1_efr = np.array([0.2533563]) time_50_1_efr = np.array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.1,1.2,1.5,1.6,1.7,1.8,1.9,2.4,2.8]) hazard_50_1_efr = np.array([0,0.04773902,0.08238731,0.2022993,0.2327053,0.2736316,0.3215519,0.3787123,0.3787123,0.526184,0.6323073,0.7627338,0.7627338,0.9288858,0.9288858,0.9288858,1.206835,1.556054,1.556054]) coef_50_1_et_efr = np.array([-0.7103063]) se_50_1_et_efr = np.array([0.2598129]) time_50_1_et_efr = np.array([0]) hazard_50_1_et_efr = np.array([0]) coef_50_1_st_efr = np.array([-0.7417904]) se_50_1_st_efr = np.array([0.2846437]) time_50_1_st_efr = np.array([0]) hazard_50_1_st_efr = np.array([0]) coef_50_1_et_st_efr = np.array([-0.9276112]) se_50_1_et_st_efr = np.array([0.3462638]) time_50_1_et_st_efr = np.array([0]) hazard_50_1_et_st_efr = np.array([0]) coef_50_2_bre = np.array([-0.5935189,0.5035724]) se_50_2_bre = np.array([0.2172841,0.2399933]) time_50_2_bre = np.array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.1,1.2,1.3,1.4,1.5,1.9,2.7,2.9]) hazard_50_2_bre = np.array([0.02695812,0.09162381,0.1309537,0.1768423,0.2033353,0.2033353,0.3083449,0.3547287,0.4076453,0.4761318,0.5579718,0.7610905,0.918962,0.918962,1.136173,1.605757,2.457676,2.457676]) coef_50_2_et_bre = np.array([-0.4001465,0.4415933]) se_50_2_et_bre = np.array([0.1992302,0.2525949]) time_50_2_et_bre = np.array([0]) hazard_50_2_et_bre = np.array([0]) coef_50_2_st_bre = np.array([-0.6574891,0.4416079]) se_50_2_st_bre = np.array([0.2753398,0.269458]) time_50_2_st_bre = np.array([0]) hazard_50_2_st_bre = np.array([0]) coef_50_2_et_st_bre = np.array([-0.3607069,0.2731982]) se_50_2_et_st_bre = np.array([0.255415,0.306942]) time_50_2_et_st_bre = np.array([0]) hazard_50_2_et_st_bre = np.array([0]) coef_50_2_efr = np.array([-0.6107485,0.5309737]) se_50_2_efr = np.array([0.2177713,0.2440535]) time_50_2_efr = np.array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.1,1.2,1.3,1.4,1.5,1.9,2.7,2.9]) hazard_50_2_efr = np.array([0.02610571,0.08933637,0.1279094,0.1731699,0.19933,0.19933,0.303598,0.3497025,0.4023939,0.4706978,0.5519237,0.7545023,0.9129989,0.9129989,1.13186,1.60574,2.472615,2.472615]) coef_50_2_et_efr = np.array([-0.4092002,0.4871344]) se_50_2_et_efr = np.array([0.1968905,0.2608527]) time_50_2_et_efr = np.array([0]) hazard_50_2_et_efr = np.array([0]) coef_50_2_st_efr = np.array([-0.6631286,0.4663285]) se_50_2_st_efr = np.array([0.2748224,0.273603]) time_50_2_st_efr = np.array([0]) hazard_50_2_st_efr = np.array([0]) coef_50_2_et_st_efr = np.array([-0.3656059,0.2943912]) se_50_2_et_st_efr = np.array([0.2540752,0.3124632]) time_50_2_et_st_efr = np.array([0]) hazard_50_2_et_st_efr = np.array([0]) coef_100_5_bre = np.array([-0.529776,-0.2916374,-0.1205425,0.3493476,0.6034305]) se_100_5_bre = np.array([0.1789305,0.1482505,0.1347422,0.1528205,0.1647927]) time_100_5_bre = np.array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2,2.1,2.5,2.8,3.2,3.3]) hazard_100_5_bre = np.array([0.02558588,0.05608812,0.1087773,0.1451098,0.1896703,0.2235791,0.3127521,0.3355107,0.439452,0.504983,0.5431706,0.5841462,0.5841462,0.5841462,0.6916466,0.7540191,0.8298704,1.027876,1.170335,1.379306,1.648758,1.943177,1.943177,1.943177,4.727101]) coef_100_5_et_bre = np.array([-0.4000784,-0.1790941,-0.1378969,0.3288529,0.533246]) se_100_5_et_bre = np.array([0.1745655,0.1513545,0.1393968,0.1487803,0.1686992]) time_100_5_et_bre = np.array([0]) hazard_100_5_et_bre = np.array([0]) coef_100_5_st_bre = np.array([-0.53019,-0.3225739,-0.1241568,0.3246598,0.6196859]) se_100_5_st_bre = np.array([0.1954581,0.1602811,0.1470644,0.17121,0.1784115]) time_100_5_st_bre = np.array([0]) hazard_100_5_st_bre = np.array([0]) coef_100_5_et_st_bre = np.array([-0.3977171,-0.2166136,-0.1387623,0.3251726,0.5664705]) se_100_5_et_st_bre = np.array([0.1951054,0.1707925,0.1501968,0.1699932,0.1843428]) time_100_5_et_st_bre = np.array([0]) hazard_100_5_et_st_bre = np.array([0]) coef_100_5_efr = np.array([-0.5641909,-0.3233021,-0.1234858,0.3712328,0.6421963]) se_100_5_efr = np.array([0.1804027,0.1496253,0.1338531,0.1529832,0.1670848]) time_100_5_efr = np.array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2,2.1,2.5,2.8,3.2,3.3]) hazard_100_5_efr = np.array([0.02393412,0.05276399,0.1028432,0.1383859,0.1823461,0.2158107,0.3037825,0.3264864,0.4306648,0.4964367,0.5348595,0.5760305,0.5760305,0.5760305,0.6842238,0.7468135,0.8228841,1.023195,1.166635,1.379361,1.652898,1.950119,1.950119,1.950119,4.910635]) coef_100_5_et_efr = np.array([-0.4338666,-0.2140139,-0.1397387,0.3535993,0.5768645]) se_100_5_et_efr = np.array([0.1756485,0.1527244,0.138298,0.1488427,0.1716654]) time_100_5_et_efr = np.array([0]) hazard_100_5_et_efr = np.array([0]) coef_100_5_st_efr = np.array([-0.5530876,-0.3331652,-0.128381,0.3503472,0.6397813]) se_100_5_st_efr = np.array([0.1969338,0.1614976,0.1464088,0.171299,0.1800787]) time_100_5_st_efr = np.array([0]) hazard_100_5_st_efr = np.array([0]) coef_100_5_et_st_efr = np.array([-0.421153,-0.2350069,-0.1433638,0.3538863,0.5934568]) se_100_5_et_st_efr = np.array([0.1961729,0.1724719,0.1492979,0.170464,0.1861849]) time_100_5_et_st_efr = np.array([0]) hazard_100_5_et_st_efr = np.array([0]) coef_1000_10_bre = np.array([-0.4699279,-0.464557,-0.308411,-0.2158298,-0.09048563,0.09359662,0.112588,0.3343705,0.3480601,0.5634985]) se_1000_10_bre = np.array([0.04722914,0.04785291,0.04503528,0.04586872,0.04429793,0.0446141,0.04139944,0.04464292,0.04559903,0.04864393]) time_1000_10_bre = np.array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9,3,3.1,3.2,3.3,3.4,3.5,3.6,3.7,3.8,3.9,4,4.1,4.2,4.3,4.4,4.6,4.8,4.9,5,5.1,5.2,5.7,5.8,5.9,6.9]) hazard_1000_10_bre = np.array([0.01610374,0.04853538,0.08984849,0.1311329,0.168397,0.2230488,0.2755388,0.3312606,0.3668702,0.4146558,0.477935,0.5290705,0.5831775,0.6503129,0.7113068,0.7830385,0.8361717,0.8910061,0.9615944,1.024011,1.113399,1.165349,1.239827,1.352902,1.409548,1.53197,1.601843,1.682158,1.714907,1.751564,1.790898,1.790898,1.83393,1.83393,1.936055,1.992303,2.050778,2.118776,2.263056,2.504999,2.739343,2.895514,3.090349,3.090349,3.391772,3.728142,4.152769,4.152769,4.152769,4.725957,4.725957,5.69653,5.69653,5.69653]) coef_1000_10_et_bre = np.array([-0.410889,-0.3929442,-0.2975845,-0.1851533,-0.0918359,0.1011997,0.106735,0.2899179,0.3220672,0.5069589]) se_1000_10_et_bre = np.array([0.04696754,0.04732169,0.04537707,0.04605371,0.04365232,0.04450021,0.04252475,0.04482007,0.04562374,0.04859727]) time_1000_10_et_bre = np.array([0]) hazard_1000_10_et_bre = np.array([0]) coef_1000_10_st_bre = np.array([-0.471015,-0.4766859,-0.3070839,-0.2091938,-0.09190845,0.0964942,0.1138269,0.3307131,0.3543551,0.562492]) se_1000_10_st_bre = np.array([0.04814778,0.04841938,0.04572291,0.04641227,0.04502525,0.04517603,0.04203737,0.04524356,0.04635037,0.04920866]) time_1000_10_st_bre = np.array([0]) hazard_1000_10_st_bre = np.array([0]) coef_1000_10_et_st_bre = np.array([-0.4165849,-0.4073504,-0.2980959,-0.1765194,-0.09152798,0.1013213,0.1009838,0.2859668,0.3247608,0.5044448]) se_1000_10_et_st_bre = np.array([0.04809818,0.04809499,0.0460829,0.04679922,0.0445294,0.04514045,0.04339298,0.04580591,0.04652447,0.04920744]) time_1000_10_et_st_bre = np.array([0]) hazard_1000_10_et_st_bre = np.array([0]) coef_1000_10_efr = np.array([-0.4894399,-0.4839746,-0.3227769,-0.2261293,-0.09318482,0.09767154,0.1173205,0.3493732,0.3640146,0.5879749]) se_1000_10_efr = np.array([0.0474181,0.04811855,0.04507655,0.04603044,0.04440409,0.04478202,0.04136728,0.04473343,0.045768,0.04891375]) time_1000_10_efr = np.array([0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1,1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2,2.1,2.2,2.3,2.4,2.5,2.6,2.7,2.8,2.9,3,3.1,3.2,3.3,3.4,3.5,3.6,3.7,3.8,3.9,4,4.1,4.2,4.3,4.4,4.6,4.8,4.9,5,5.1,5.2,5.7,5.8,5.9,6.9]) hazard_1000_10_efr = np.array([0.01549698,0.04680035,0.08682564,0.1269429,0.1632388,0.2167291,0.2682311,0.3231316,0.3582936,0.4054892,0.4681098,0.5188697,0.5727059,0.639571,0.7003012,0.7718979,0.825053,0.880063,0.950935,1.013828,1.103903,1.156314,1.231707,1.346235,1.40359,1.527475,1.598231,1.6795,1.712779,1.750227,1.790455,1.790455,1.834455,1.834455,1.938997,1.996804,2.056859,2.126816,2.275217,2.524027,2.76669,2.929268,3.13247,3.13247,3.448515,3.80143,4.249649,4.249649,4.249649,4.851365,4.851365,5.877307,5.877307,5.877307]) coef_1000_10_et_efr = np.array([-0.4373066,-0.4131901,-0.3177637,-0.1978493,-0.09679451,0.1092037,0.1136069,0.3088907,0.3442007,0.5394121]) se_1000_10_et_efr = np.array([0.04716041,0.04755342,0.04546713,0.04627802,0.04376583,0.04474868,0.04259991,0.04491564,0.04589027,0.04890847]) time_1000_10_et_efr = np.array([0]) hazard_1000_10_et_efr = np.array([0]) coef_1000_10_st_efr = np.array([-0.4911117,-0.4960756,-0.3226152,-0.220949,-0.09478141,0.1015735,0.1195524,0.3446977,0.3695904,0.5878576]) se_1000_10_st_efr = np.array([0.04833676,0.04868554,0.04578407,0.04661755,0.04518267,0.04537135,0.04202183,0.04531266,0.0464931,0.04949831]) time_1000_10_st_efr = np.array([0]) hazard_1000_10_st_efr = np.array([0]) coef_1000_10_et_st_efr = np.array([-0.444355,-0.4283278,-0.3198815,-0.1901781,-0.09727039,0.1106191,0.1092104,0.3034778,0.3451699,0.5382381]) se_1000_10_et_st_efr = np.array([0.04830664,0.04833619,0.04617371,0.04706401,0.04472699,0.0454208,0.04350539,0.04588588,0.04675675,0.04950987]) time_1000_10_et_st_efr = np.array([0]) hazard_1000_10_et_st_efr = np.array([0])
bsd-3-clause
forman/dectree
examples/intertidal_flat_classif/intertidal_flat_classif.py
1
12362
from numba import jit, jitclass, float64 import numpy as np @jit(nopython=True) def _B1_LT_085(x): # B1.LT_085: lt(0.85) if 0.0 == 0.0: return 1.0 if x < 0.85 else 0.0 x1 = 0.85 - 0.0 x2 = 0.85 + 0.0 if x <= x1: return 1.0 if x <= x2: return 1.0 - (x - x1) / (x2 - x1) return 0.0 @jit(nopython=True) def _B1_GT_1(x): # B1.GT_1: gt(1.0) if 0.0 == 0.0: return 1.0 if x > 1.0 else 0.0 x1 = 1.0 - 0.0 x2 = 1.0 + 0.0 if x <= x1: return 0.0 if x <= x2: return (x - x1) / (x2 - x1) return 1.0 @jit(nopython=True) def _B2_GT_0(x): # B2.GT_0: gt(0.0) if 0.0 == 0.0: return 1.0 if x > 0.0 else 0.0 x1 = 0.0 - 0.0 x2 = 0.0 + 0.0 if x <= x1: return 0.0 if x <= x2: return (x - x1) / (x2 - x1) return 1.0 @jit(nopython=True) def _B3_LT_005(x): # B3.LT_005: lt(0.05) if 0.0 == 0.0: return 1.0 if x < 0.05 else 0.0 x1 = 0.05 - 0.0 x2 = 0.05 + 0.0 if x <= x1: return 1.0 if x <= x2: return 1.0 - (x - x1) / (x2 - x1) return 0.0 @jit(nopython=True) def _B3_LT_01(x): # B3.LT_01: lt(0.1) if 0.0 == 0.0: return 1.0 if x < 0.1 else 0.0 x1 = 0.1 - 0.0 x2 = 0.1 + 0.0 if x <= x1: return 1.0 if x <= x2: return 1.0 - (x - x1) / (x2 - x1) return 0.0 @jit(nopython=True) def _B3_LT_015(x): # B3.LT_015: lt(0.15) if 0.0 == 0.0: return 1.0 if x < 0.15 else 0.0 x1 = 0.15 - 0.0 x2 = 0.15 + 0.0 if x <= x1: return 1.0 if x <= x2: return 1.0 - (x - x1) / (x2 - x1) return 0.0 @jit(nopython=True) def _B3_LT_02(x): # B3.LT_02: lt(0.2) if 0.0 == 0.0: return 1.0 if x < 0.2 else 0.0 x1 = 0.2 - 0.0 x2 = 0.2 + 0.0 if x <= x1: return 1.0 if x <= x2: return 1.0 - (x - x1) / (x2 - x1) return 0.0 @jit(nopython=True) def _B4_NODATA(x): # B4.NODATA: eq(0.0) if 0.0 == 0.0: return 1.0 if x == 0.0 else 0.0 x1 = 0.0 - 0.0 x2 = 0.0 x3 = 0.0 + 0.0 if x <= x1: return 0.0 if x <= x2: return (x - x1) / (x2 - x1) if x <= x3: return 1.0 - (x - x2) / (x3 - x2) return 0.0 @jit(nopython=True) def _B5_LT_01(x): # B5.LT_01: lt(0.1) if 0.0 == 0.0: return 1.0 if x < 0.1 else 0.0 x1 = 0.1 - 0.0 x2 = 0.1 + 0.0 if x <= x1: return 1.0 if x <= x2: return 1.0 - (x - x1) / (x2 - x1) return 0.0 @jit(nopython=True) def _B7_LT_05(x): # B7.LT_05: lt(0.5) if 0.0 == 0.0: return 1.0 if x < 0.5 else 0.0 x1 = 0.5 - 0.0 x2 = 0.5 + 0.0 if x <= x1: return 1.0 if x <= x2: return 1.0 - (x - x1) / (x2 - x1) return 0.0 @jit(nopython=True) def _B8_GT_0(x): # B8.GT_0: gt(0.0) if 0.0 == 0.0: return 1.0 if x > 0.0 else 0.0 x1 = 0.0 - 0.0 x2 = 0.0 + 0.0 if x <= x1: return 0.0 if x <= x2: return (x - x1) / (x2 - x1) return 1.0 @jit(nopython=True) def _B8_LT_009(x): # B8.LT_009: lt(0.09) if 0.0 == 0.0: return 1.0 if x < 0.09 else 0.0 x1 = 0.09 - 0.0 x2 = 0.09 + 0.0 if x <= x1: return 1.0 if x <= x2: return 1.0 - (x - x1) / (x2 - x1) return 0.0 @jit(nopython=True) def _B8_GT_033(x): # B8.GT_033: gt(0.33) if 0.0 == 0.0: return 1.0 if x > 0.33 else 0.0 x1 = 0.33 - 0.0 x2 = 0.33 + 0.0 if x <= x1: return 0.0 if x <= x2: return (x - x1) / (x2 - x1) return 1.0 @jit(nopython=True) def _B8_GT_035(x): # B8.GT_035: gt(0.35) if 0.0 == 0.0: return 1.0 if x > 0.35 else 0.0 x1 = 0.35 - 0.0 x2 = 0.35 + 0.0 if x <= x1: return 0.0 if x <= x2: return (x - x1) / (x2 - x1) return 1.0 @jit(nopython=True) def _B8_GT_04(x): # B8.GT_04: gt(0.4) if 0.0 == 0.0: return 1.0 if x > 0.4 else 0.0 x1 = 0.4 - 0.0 x2 = 0.4 + 0.0 if x <= x1: return 0.0 if x <= x2: return (x - x1) / (x2 - x1) return 1.0 @jit(nopython=True) def _B8_GT_045(x): # B8.GT_045: gt(0.45) if 0.0 == 0.0: return 1.0 if x > 0.45 else 0.0 x1 = 0.45 - 0.0 x2 = 0.45 + 0.0 if x <= x1: return 0.0 if x <= x2: return (x - x1) / (x2 - x1) return 1.0 @jit(nopython=True) def _B8_LT_085(x): # B8.LT_085: lt(0.85) if 0.0 == 0.0: return 1.0 if x < 0.85 else 0.0 x1 = 0.85 - 0.0 x2 = 0.85 + 0.0 if x <= x1: return 1.0 if x <= x2: return 1.0 - (x - x1) / (x2 - x1) return 0.0 @jit(nopython=True) def _B16_GT_0(x): # B16.GT_0: gt(0.0) if 0.0 == 0.0: return 1.0 if x > 0.0 else 0.0 x1 = 0.0 - 0.0 x2 = 0.0 + 0.0 if x <= x1: return 0.0 if x <= x2: return (x - x1) / (x2 - x1) return 1.0 @jit(nopython=True) def _B19_GT_015(x): # B19.GT_015: gt(0.15) if 0.0 == 0.0: return 1.0 if x > 0.15 else 0.0 x1 = 0.15 - 0.0 x2 = 0.15 + 0.0 if x <= x1: return 0.0 if x <= x2: return (x - x1) / (x2 - x1) return 1.0 @jit(nopython=True) def _BSum_GT_011(x): # BSum.GT_011: gt(0.11) if 0.0 == 0.0: return 1.0 if x > 0.11 else 0.0 x1 = 0.11 - 0.0 x2 = 0.11 + 0.0 if x <= x1: return 0.0 if x <= x2: return (x - x1) / (x2 - x1) return 1.0 @jit(nopython=True) def _BSum_GT_013(x): # BSum.GT_013: gt(0.13) if 0.0 == 0.0: return 1.0 if x > 0.13 else 0.0 x1 = 0.13 - 0.0 x2 = 0.13 + 0.0 if x <= x1: return 0.0 if x <= x2: return (x - x1) / (x2 - x1) return 1.0 @jit(nopython=True) def _BSum_GT_016(x): # BSum.GT_016: gt(0.16) if 0.0 == 0.0: return 1.0 if x > 0.16 else 0.0 x1 = 0.16 - 0.0 x2 = 0.16 + 0.0 if x <= x1: return 0.0 if x <= x2: return (x - x1) / (x2 - x1) return 1.0 @jit(nopython=True) def _Class_FALSE(x): # Class.FALSE: false() return 0.0 @jit(nopython=True) def _Class_TRUE(x): # Class.TRUE: true() return 1.0 _InputsSpec = [ ("b1", float64[:]), ("b2", float64[:]), ("b3", float64[:]), ("b4", float64[:]), ("b5", float64[:]), ("b6", float64[:]), ("b7", float64[:]), ("b8", float64[:]), ("b12", float64[:]), ("b13", float64[:]), ("b14", float64[:]), ("b15", float64[:]), ("b16", float64[:]), ("b19", float64[:]), ("b100", float64[:]), ("bsum", float64[:]), ] @jitclass(_InputsSpec) class Inputs: def __init__(self, size: int): self.b1 = np.zeros(size, dtype=np.float64) self.b2 = np.zeros(size, dtype=np.float64) self.b3 = np.zeros(size, dtype=np.float64) self.b4 = np.zeros(size, dtype=np.float64) self.b5 = np.zeros(size, dtype=np.float64) self.b6 = np.zeros(size, dtype=np.float64) self.b7 = np.zeros(size, dtype=np.float64) self.b8 = np.zeros(size, dtype=np.float64) self.b12 = np.zeros(size, dtype=np.float64) self.b13 = np.zeros(size, dtype=np.float64) self.b14 = np.zeros(size, dtype=np.float64) self.b15 = np.zeros(size, dtype=np.float64) self.b16 = np.zeros(size, dtype=np.float64) self.b19 = np.zeros(size, dtype=np.float64) self.b100 = np.zeros(size, dtype=np.float64) self.bsum = np.zeros(size, dtype=np.float64) _OutputsSpec = [ ("nodata", float64[:]), ("Wasser", float64[:]), ("Schill", float64[:]), ("Muschel", float64[:]), ("dense2", float64[:]), ("dense1", float64[:]), ("Strand", float64[:]), ("Sand", float64[:]), ("Misch", float64[:]), ("Misch2", float64[:]), ("Schlick", float64[:]), ("schlick_t", float64[:]), ("Wasser2", float64[:]), ] @jitclass(_OutputsSpec) class Outputs: def __init__(self, size: int): self.nodata = np.zeros(size, dtype=np.float64) self.Wasser = np.zeros(size, dtype=np.float64) self.Schill = np.zeros(size, dtype=np.float64) self.Muschel = np.zeros(size, dtype=np.float64) self.dense2 = np.zeros(size, dtype=np.float64) self.dense1 = np.zeros(size, dtype=np.float64) self.Strand = np.zeros(size, dtype=np.float64) self.Sand = np.zeros(size, dtype=np.float64) self.Misch = np.zeros(size, dtype=np.float64) self.Misch2 = np.zeros(size, dtype=np.float64) self.Schlick = np.zeros(size, dtype=np.float64) self.schlick_t = np.zeros(size, dtype=np.float64) self.Wasser2 = np.zeros(size, dtype=np.float64) @jit(nopython=True) def apply_rules(inputs: Inputs, outputs: Outputs): for i in range(len(outputs.nodata)): t0 = 1.0 # if b4 is NODATA: t1 = min(t0, _B4_NODATA(inputs.b4[i])) # nodata = TRUE outputs.nodata[i] = t1 # else: t1 = min(t0, 1.0 - t1) # if (b8 is GT_033 and b1 is LT_085) or b8 is LT_009: t2 = min(t1, max(min(_B8_GT_033(inputs.b8[i]), _B1_LT_085(inputs.b1[i])), _B8_LT_009(inputs.b8[i]))) # if b5 is LT_01: t3 = min(t2, _B5_LT_01(inputs.b5[i])) # Wasser = TRUE outputs.Wasser[i] = t3 # else: t3 = min(t2, 1.0 - t3) # if (b19 is GT_015 and (b8 is GT_04 and b8 is LT_085) and b7 is LT_05) or (b8 is GT_04 and bsum is GT_011) or (b8 is GT_035 and bsum is GT_016): t4 = min(t3, max(max(min(min(_B19_GT_015(inputs.b19[i]), min(_B8_GT_04(inputs.b8[i]), _B8_LT_085(inputs.b8[i]))), _B7_LT_05(inputs.b7[i])), min(_B8_GT_04(inputs.b8[i]), _BSum_GT_011(inputs.bsum[i]))), min(_B8_GT_035(inputs.b8[i]), _BSum_GT_016(inputs.bsum[i])))) # if bsum is GT_013: t5 = min(t4, _BSum_GT_013(inputs.bsum[i])) # Schill = TRUE outputs.Schill[i] = t5 # else: t5 = min(t4, 1.0 - t5) # Muschel = TRUE outputs.Muschel[i] = t5 # else: t4 = min(t3, 1.0 - t4) # if b8 is GT_045: t5 = min(t4, _B8_GT_045(inputs.b8[i])) # dense2 = TRUE outputs.dense2[i] = t5 # else: t5 = min(t4, 1.0 - t5) # dense1 = TRUE outputs.dense1[i] = t5 # else: t2 = min(t1, 1.0 - t2) # if b1 is GT_1: t3 = min(t2, _B1_GT_1(inputs.b1[i])) # Strand = TRUE outputs.Strand[i] = t3 # else: t3 = min(t2, 1.0 - t3) # if b3 is LT_005: t4 = min(t3, _B3_LT_005(inputs.b3[i])) # Sand = TRUE outputs.Sand[i] = t4 # else: t4 = min(t3, 1.0 - t4) # if b3 is LT_01 and b8 is GT_0: t5 = min(t4, min(_B3_LT_01(inputs.b3[i]), _B8_GT_0(inputs.b8[i]))) # Misch = TRUE outputs.Misch[i] = t5 # else: t5 = min(t4, 1.0 - t5) # if b3 is LT_015 and b8 is GT_0: t6 = min(t5, min(_B3_LT_015(inputs.b3[i]), _B8_GT_0(inputs.b8[i]))) # Misch2 = TRUE outputs.Misch2[i] = t6 # else: t6 = min(t5, 1.0 - t6) # if b3 is LT_02 and b2 is GT_0 and b8 is GT_0: t7 = min(t6, min(min(_B3_LT_02(inputs.b3[i]), _B2_GT_0(inputs.b2[i])), _B8_GT_0(inputs.b8[i]))) # Schlick = TRUE outputs.Schlick[i] = t7 # else: t7 = min(t6, 1.0 - t7) # if b16 is GT_0 and b8 is GT_0: t8 = min(t7, min(_B16_GT_0(inputs.b16[i]), _B8_GT_0(inputs.b8[i]))) # schlick_t = TRUE outputs.schlick_t[i] = t8 # else: t8 = min(t7, 1.0 - t8) # Wasser2 = TRUE outputs.Wasser2[i] = t8
mit
blacklin/kbengine
kbe/src/lib/python/Lib/pickle.py
67
55641
"""Create portable serialized representations of Python objects. See module copyreg for a mechanism for registering custom picklers. See module pickletools source for extensive comments. Classes: Pickler Unpickler Functions: dump(object, file) dumps(object) -> string load(file) -> object loads(string) -> object Misc variables: __version__ format_version compatible_formats """ from types import FunctionType from copyreg import dispatch_table from copyreg import _extension_registry, _inverted_registry, _extension_cache from itertools import islice import sys from sys import maxsize from struct import pack, unpack import re import io import codecs import _compat_pickle __all__ = ["PickleError", "PicklingError", "UnpicklingError", "Pickler", "Unpickler", "dump", "dumps", "load", "loads"] # Shortcut for use in isinstance testing bytes_types = (bytes, bytearray) # These are purely informational; no code uses these. format_version = "4.0" # File format version we write compatible_formats = ["1.0", # Original protocol 0 "1.1", # Protocol 0 with INST added "1.2", # Original protocol 1 "1.3", # Protocol 1 with BINFLOAT added "2.0", # Protocol 2 "3.0", # Protocol 3 "4.0", # Protocol 4 ] # Old format versions we can read # This is the highest protocol number we know how to read. HIGHEST_PROTOCOL = 4 # The protocol we write by default. May be less than HIGHEST_PROTOCOL. # We intentionally write a protocol that Python 2.x cannot read; # there are too many issues with that. DEFAULT_PROTOCOL = 3 class PickleError(Exception): """A common base class for the other pickling exceptions.""" pass class PicklingError(PickleError): """This exception is raised when an unpicklable object is passed to the dump() method. """ pass class UnpicklingError(PickleError): """This exception is raised when there is a problem unpickling an object, such as a security violation. Note that other exceptions may also be raised during unpickling, including (but not necessarily limited to) AttributeError, EOFError, ImportError, and IndexError. """ pass # An instance of _Stop is raised by Unpickler.load_stop() in response to # the STOP opcode, passing the object that is the result of unpickling. class _Stop(Exception): def __init__(self, value): self.value = value # Jython has PyStringMap; it's a dict subclass with string keys try: from org.python.core import PyStringMap except ImportError: PyStringMap = None # Pickle opcodes. See pickletools.py for extensive docs. The listing # here is in kind-of alphabetical order of 1-character pickle code. # pickletools groups them by purpose. MARK = b'(' # push special markobject on stack STOP = b'.' # every pickle ends with STOP POP = b'0' # discard topmost stack item POP_MARK = b'1' # discard stack top through topmost markobject DUP = b'2' # duplicate top stack item FLOAT = b'F' # push float object; decimal string argument INT = b'I' # push integer or bool; decimal string argument BININT = b'J' # push four-byte signed int BININT1 = b'K' # push 1-byte unsigned int LONG = b'L' # push long; decimal string argument BININT2 = b'M' # push 2-byte unsigned int NONE = b'N' # push None PERSID = b'P' # push persistent object; id is taken from string arg BINPERSID = b'Q' # " " " ; " " " " stack REDUCE = b'R' # apply callable to argtuple, both on stack STRING = b'S' # push string; NL-terminated string argument BINSTRING = b'T' # push string; counted binary string argument SHORT_BINSTRING= b'U' # " " ; " " " " < 256 bytes UNICODE = b'V' # push Unicode string; raw-unicode-escaped'd argument BINUNICODE = b'X' # " " " ; counted UTF-8 string argument APPEND = b'a' # append stack top to list below it BUILD = b'b' # call __setstate__ or __dict__.update() GLOBAL = b'c' # push self.find_class(modname, name); 2 string args DICT = b'd' # build a dict from stack items EMPTY_DICT = b'}' # push empty dict APPENDS = b'e' # extend list on stack by topmost stack slice GET = b'g' # push item from memo on stack; index is string arg BINGET = b'h' # " " " " " " ; " " 1-byte arg INST = b'i' # build & push class instance LONG_BINGET = b'j' # push item from memo on stack; index is 4-byte arg LIST = b'l' # build list from topmost stack items EMPTY_LIST = b']' # push empty list OBJ = b'o' # build & push class instance PUT = b'p' # store stack top in memo; index is string arg BINPUT = b'q' # " " " " " ; " " 1-byte arg LONG_BINPUT = b'r' # " " " " " ; " " 4-byte arg SETITEM = b's' # add key+value pair to dict TUPLE = b't' # build tuple from topmost stack items EMPTY_TUPLE = b')' # push empty tuple SETITEMS = b'u' # modify dict by adding topmost key+value pairs BINFLOAT = b'G' # push float; arg is 8-byte float encoding TRUE = b'I01\n' # not an opcode; see INT docs in pickletools.py FALSE = b'I00\n' # not an opcode; see INT docs in pickletools.py # Protocol 2 PROTO = b'\x80' # identify pickle protocol NEWOBJ = b'\x81' # build object by applying cls.__new__ to argtuple EXT1 = b'\x82' # push object from extension registry; 1-byte index EXT2 = b'\x83' # ditto, but 2-byte index EXT4 = b'\x84' # ditto, but 4-byte index TUPLE1 = b'\x85' # build 1-tuple from stack top TUPLE2 = b'\x86' # build 2-tuple from two topmost stack items TUPLE3 = b'\x87' # build 3-tuple from three topmost stack items NEWTRUE = b'\x88' # push True NEWFALSE = b'\x89' # push False LONG1 = b'\x8a' # push long from < 256 bytes LONG4 = b'\x8b' # push really big long _tuplesize2code = [EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3] # Protocol 3 (Python 3.x) BINBYTES = b'B' # push bytes; counted binary string argument SHORT_BINBYTES = b'C' # " " ; " " " " < 256 bytes # Protocol 4 SHORT_BINUNICODE = b'\x8c' # push short string; UTF-8 length < 256 bytes BINUNICODE8 = b'\x8d' # push very long string BINBYTES8 = b'\x8e' # push very long bytes string EMPTY_SET = b'\x8f' # push empty set on the stack ADDITEMS = b'\x90' # modify set by adding topmost stack items FROZENSET = b'\x91' # build frozenset from topmost stack items NEWOBJ_EX = b'\x92' # like NEWOBJ but work with keyword only arguments STACK_GLOBAL = b'\x93' # same as GLOBAL but using names on the stacks MEMOIZE = b'\x94' # store top of the stack in memo FRAME = b'\x95' # indicate the beginning of a new frame __all__.extend([x for x in dir() if re.match("[A-Z][A-Z0-9_]+$", x)]) class _Framer: _FRAME_SIZE_TARGET = 64 * 1024 def __init__(self, file_write): self.file_write = file_write self.current_frame = None def start_framing(self): self.current_frame = io.BytesIO() def end_framing(self): if self.current_frame and self.current_frame.tell() > 0: self.commit_frame(force=True) self.current_frame = None def commit_frame(self, force=False): if self.current_frame: f = self.current_frame if f.tell() >= self._FRAME_SIZE_TARGET or force: with f.getbuffer() as data: n = len(data) write = self.file_write write(FRAME) write(pack("<Q", n)) write(data) f.seek(0) f.truncate() def write(self, data): if self.current_frame: return self.current_frame.write(data) else: return self.file_write(data) class _Unframer: def __init__(self, file_read, file_readline, file_tell=None): self.file_read = file_read self.file_readline = file_readline self.current_frame = None def read(self, n): if self.current_frame: data = self.current_frame.read(n) if not data and n != 0: self.current_frame = None return self.file_read(n) if len(data) < n: raise UnpicklingError( "pickle exhausted before end of frame") return data else: return self.file_read(n) def readline(self): if self.current_frame: data = self.current_frame.readline() if not data: self.current_frame = None return self.file_readline() if data[-1] != b'\n': raise UnpicklingError( "pickle exhausted before end of frame") return data else: return self.file_readline() def load_frame(self, frame_size): if self.current_frame and self.current_frame.read() != b'': raise UnpicklingError( "beginning of a new frame before end of current frame") self.current_frame = io.BytesIO(self.file_read(frame_size)) # Tools used for pickling. def _getattribute(obj, name, allow_qualname=False): dotted_path = name.split(".") if not allow_qualname and len(dotted_path) > 1: raise AttributeError("Can't get qualified attribute {!r} on {!r}; " + "use protocols >= 4 to enable support" .format(name, obj)) for subpath in dotted_path: if subpath == '<locals>': raise AttributeError("Can't get local attribute {!r} on {!r}" .format(name, obj)) try: obj = getattr(obj, subpath) except AttributeError: raise AttributeError("Can't get attribute {!r} on {!r}" .format(name, obj)) return obj def whichmodule(obj, name, allow_qualname=False): """Find the module an object belong to.""" module_name = getattr(obj, '__module__', None) if module_name is not None: return module_name for module_name, module in sys.modules.items(): if module_name == '__main__' or module is None: continue try: if _getattribute(module, name, allow_qualname) is obj: return module_name except AttributeError: pass return '__main__' def encode_long(x): r"""Encode a long to a two's complement little-endian binary string. Note that 0 is a special case, returning an empty string, to save a byte in the LONG1 pickling context. >>> encode_long(0) b'' >>> encode_long(255) b'\xff\x00' >>> encode_long(32767) b'\xff\x7f' >>> encode_long(-256) b'\x00\xff' >>> encode_long(-32768) b'\x00\x80' >>> encode_long(-128) b'\x80' >>> encode_long(127) b'\x7f' >>> """ if x == 0: return b'' nbytes = (x.bit_length() >> 3) + 1 result = x.to_bytes(nbytes, byteorder='little', signed=True) if x < 0 and nbytes > 1: if result[-1] == 0xff and (result[-2] & 0x80) != 0: result = result[:-1] return result def decode_long(data): r"""Decode a long from a two's complement little-endian binary string. >>> decode_long(b'') 0 >>> decode_long(b"\xff\x00") 255 >>> decode_long(b"\xff\x7f") 32767 >>> decode_long(b"\x00\xff") -256 >>> decode_long(b"\x00\x80") -32768 >>> decode_long(b"\x80") -128 >>> decode_long(b"\x7f") 127 """ return int.from_bytes(data, byteorder='little', signed=True) # Pickling machinery class _Pickler: def __init__(self, file, protocol=None, *, fix_imports=True): """This takes a binary file for writing a pickle data stream. The optional *protocol* argument tells the pickler to use the given protocol; supported protocols are 0, 1, 2, 3 and 4. The default protocol is 3; a backward-incompatible protocol designed for Python 3. Specifying a negative protocol version selects the highest protocol version supported. The higher the protocol used, the more recent the version of Python needed to read the pickle produced. The *file* argument must have a write() method that accepts a single bytes argument. It can thus be a file object opened for binary writing, a io.BytesIO instance, or any other custom object that meets this interface. If *fix_imports* is True and *protocol* is less than 3, pickle will try to map the new Python 3 names to the old module names used in Python 2, so that the pickle data stream is readable with Python 2. """ if protocol is None: protocol = DEFAULT_PROTOCOL if protocol < 0: protocol = HIGHEST_PROTOCOL elif not 0 <= protocol <= HIGHEST_PROTOCOL: raise ValueError("pickle protocol must be <= %d" % HIGHEST_PROTOCOL) try: self._file_write = file.write except AttributeError: raise TypeError("file must have a 'write' attribute") self.framer = _Framer(self._file_write) self.write = self.framer.write self.memo = {} self.proto = int(protocol) self.bin = protocol >= 1 self.fast = 0 self.fix_imports = fix_imports and protocol < 3 def clear_memo(self): """Clears the pickler's "memo". The memo is the data structure that remembers which objects the pickler has already seen, so that shared or recursive objects are pickled by reference and not by value. This method is useful when re-using picklers. """ self.memo.clear() def dump(self, obj): """Write a pickled representation of obj to the open file.""" # Check whether Pickler was initialized correctly. This is # only needed to mimic the behavior of _pickle.Pickler.dump(). if not hasattr(self, "_file_write"): raise PicklingError("Pickler.__init__() was not called by " "%s.__init__()" % (self.__class__.__name__,)) if self.proto >= 2: self.write(PROTO + pack("<B", self.proto)) if self.proto >= 4: self.framer.start_framing() self.save(obj) self.write(STOP) self.framer.end_framing() def memoize(self, obj): """Store an object in the memo.""" # The Pickler memo is a dictionary mapping object ids to 2-tuples # that contain the Unpickler memo key and the object being memoized. # The memo key is written to the pickle and will become # the key in the Unpickler's memo. The object is stored in the # Pickler memo so that transient objects are kept alive during # pickling. # The use of the Unpickler memo length as the memo key is just a # convention. The only requirement is that the memo values be unique. # But there appears no advantage to any other scheme, and this # scheme allows the Unpickler memo to be implemented as a plain (but # growable) array, indexed by memo key. if self.fast: return assert id(obj) not in self.memo idx = len(self.memo) self.write(self.put(idx)) self.memo[id(obj)] = idx, obj # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i. def put(self, idx): if self.proto >= 4: return MEMOIZE elif self.bin: if idx < 256: return BINPUT + pack("<B", idx) else: return LONG_BINPUT + pack("<I", idx) else: return PUT + repr(idx).encode("ascii") + b'\n' # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i. def get(self, i): if self.bin: if i < 256: return BINGET + pack("<B", i) else: return LONG_BINGET + pack("<I", i) return GET + repr(i).encode("ascii") + b'\n' def save(self, obj, save_persistent_id=True): self.framer.commit_frame() # Check for persistent id (defined by a subclass) pid = self.persistent_id(obj) if pid is not None and save_persistent_id: self.save_pers(pid) return # Check the memo x = self.memo.get(id(obj)) if x is not None: self.write(self.get(x[0])) return # Check the type dispatch table t = type(obj) f = self.dispatch.get(t) if f is not None: f(self, obj) # Call unbound method with explicit self return # Check private dispatch table if any, or else copyreg.dispatch_table reduce = getattr(self, 'dispatch_table', dispatch_table).get(t) if reduce is not None: rv = reduce(obj) else: # Check for a class with a custom metaclass; treat as regular class try: issc = issubclass(t, type) except TypeError: # t is not a class (old Boost; see SF #502085) issc = False if issc: self.save_global(obj) return # Check for a __reduce_ex__ method, fall back to __reduce__ reduce = getattr(obj, "__reduce_ex__", None) if reduce is not None: rv = reduce(self.proto) else: reduce = getattr(obj, "__reduce__", None) if reduce is not None: rv = reduce() else: raise PicklingError("Can't pickle %r object: %r" % (t.__name__, obj)) # Check for string returned by reduce(), meaning "save as global" if isinstance(rv, str): self.save_global(obj, rv) return # Assert that reduce() returned a tuple if not isinstance(rv, tuple): raise PicklingError("%s must return string or tuple" % reduce) # Assert that it returned an appropriately sized tuple l = len(rv) if not (2 <= l <= 5): raise PicklingError("Tuple returned by %s must have " "two to five elements" % reduce) # Save the reduce() output and finally memoize the object self.save_reduce(obj=obj, *rv) def persistent_id(self, obj): # This exists so a subclass can override it return None def save_pers(self, pid): # Save a persistent id reference if self.bin: self.save(pid, save_persistent_id=False) self.write(BINPERSID) else: self.write(PERSID + str(pid).encode("ascii") + b'\n') def save_reduce(self, func, args, state=None, listitems=None, dictitems=None, obj=None): # This API is called by some subclasses if not isinstance(args, tuple): raise PicklingError("args from save_reduce() must be a tuple") if not callable(func): raise PicklingError("func from save_reduce() must be callable") save = self.save write = self.write func_name = getattr(func, "__name__", "") if self.proto >= 4 and func_name == "__newobj_ex__": cls, args, kwargs = args if not hasattr(cls, "__new__"): raise PicklingError("args[0] from {} args has no __new__" .format(func_name)) if obj is not None and cls is not obj.__class__: raise PicklingError("args[0] from {} args has the wrong class" .format(func_name)) save(cls) save(args) save(kwargs) write(NEWOBJ_EX) elif self.proto >= 2 and func_name == "__newobj__": # A __reduce__ implementation can direct protocol 2 or newer to # use the more efficient NEWOBJ opcode, while still # allowing protocol 0 and 1 to work normally. For this to # work, the function returned by __reduce__ should be # called __newobj__, and its first argument should be a # class. The implementation for __newobj__ # should be as follows, although pickle has no way to # verify this: # # def __newobj__(cls, *args): # return cls.__new__(cls, *args) # # Protocols 0 and 1 will pickle a reference to __newobj__, # while protocol 2 (and above) will pickle a reference to # cls, the remaining args tuple, and the NEWOBJ code, # which calls cls.__new__(cls, *args) at unpickling time # (see load_newobj below). If __reduce__ returns a # three-tuple, the state from the third tuple item will be # pickled regardless of the protocol, calling __setstate__ # at unpickling time (see load_build below). # # Note that no standard __newobj__ implementation exists; # you have to provide your own. This is to enforce # compatibility with Python 2.2 (pickles written using # protocol 0 or 1 in Python 2.3 should be unpicklable by # Python 2.2). cls = args[0] if not hasattr(cls, "__new__"): raise PicklingError( "args[0] from __newobj__ args has no __new__") if obj is not None and cls is not obj.__class__: raise PicklingError( "args[0] from __newobj__ args has the wrong class") args = args[1:] save(cls) save(args) write(NEWOBJ) else: save(func) save(args) write(REDUCE) if obj is not None: # If the object is already in the memo, this means it is # recursive. In this case, throw away everything we put on the # stack, and fetch the object back from the memo. if id(obj) in self.memo: write(POP + self.get(self.memo[id(obj)][0])) else: self.memoize(obj) # More new special cases (that work with older protocols as # well): when __reduce__ returns a tuple with 4 or 5 items, # the 4th and 5th item should be iterators that provide list # items and dict items (as (key, value) tuples), or None. if listitems is not None: self._batch_appends(listitems) if dictitems is not None: self._batch_setitems(dictitems) if state is not None: save(state) write(BUILD) # Methods below this point are dispatched through the dispatch table dispatch = {} def save_none(self, obj): self.write(NONE) dispatch[type(None)] = save_none def save_bool(self, obj): if self.proto >= 2: self.write(NEWTRUE if obj else NEWFALSE) else: self.write(TRUE if obj else FALSE) dispatch[bool] = save_bool def save_long(self, obj): if self.bin: # If the int is small enough to fit in a signed 4-byte 2's-comp # format, we can store it more efficiently than the general # case. # First one- and two-byte unsigned ints: if obj >= 0: if obj <= 0xff: self.write(BININT1 + pack("<B", obj)) return if obj <= 0xffff: self.write(BININT2 + pack("<H", obj)) return # Next check for 4-byte signed ints: if -0x80000000 <= obj <= 0x7fffffff: self.write(BININT + pack("<i", obj)) return if self.proto >= 2: encoded = encode_long(obj) n = len(encoded) if n < 256: self.write(LONG1 + pack("<B", n) + encoded) else: self.write(LONG4 + pack("<i", n) + encoded) return self.write(LONG + repr(obj).encode("ascii") + b'L\n') dispatch[int] = save_long def save_float(self, obj): if self.bin: self.write(BINFLOAT + pack('>d', obj)) else: self.write(FLOAT + repr(obj).encode("ascii") + b'\n') dispatch[float] = save_float def save_bytes(self, obj): if self.proto < 3: if not obj: # bytes object is empty self.save_reduce(bytes, (), obj=obj) else: self.save_reduce(codecs.encode, (str(obj, 'latin1'), 'latin1'), obj=obj) return n = len(obj) if n <= 0xff: self.write(SHORT_BINBYTES + pack("<B", n) + obj) elif n > 0xffffffff and self.proto >= 4: self.write(BINBYTES8 + pack("<Q", n) + obj) else: self.write(BINBYTES + pack("<I", n) + obj) self.memoize(obj) dispatch[bytes] = save_bytes def save_str(self, obj): if self.bin: encoded = obj.encode('utf-8', 'surrogatepass') n = len(encoded) if n <= 0xff and self.proto >= 4: self.write(SHORT_BINUNICODE + pack("<B", n) + encoded) elif n > 0xffffffff and self.proto >= 4: self.write(BINUNICODE8 + pack("<Q", n) + encoded) else: self.write(BINUNICODE + pack("<I", n) + encoded) else: obj = obj.replace("\\", "\\u005c") obj = obj.replace("\n", "\\u000a") self.write(UNICODE + obj.encode('raw-unicode-escape') + b'\n') self.memoize(obj) dispatch[str] = save_str def save_tuple(self, obj): if not obj: # tuple is empty if self.bin: self.write(EMPTY_TUPLE) else: self.write(MARK + TUPLE) return n = len(obj) save = self.save memo = self.memo if n <= 3 and self.proto >= 2: for element in obj: save(element) # Subtle. Same as in the big comment below. if id(obj) in memo: get = self.get(memo[id(obj)][0]) self.write(POP * n + get) else: self.write(_tuplesize2code[n]) self.memoize(obj) return # proto 0 or proto 1 and tuple isn't empty, or proto > 1 and tuple # has more than 3 elements. write = self.write write(MARK) for element in obj: save(element) if id(obj) in memo: # Subtle. d was not in memo when we entered save_tuple(), so # the process of saving the tuple's elements must have saved # the tuple itself: the tuple is recursive. The proper action # now is to throw away everything we put on the stack, and # simply GET the tuple (it's already constructed). This check # could have been done in the "for element" loop instead, but # recursive tuples are a rare thing. get = self.get(memo[id(obj)][0]) if self.bin: write(POP_MARK + get) else: # proto 0 -- POP_MARK not available write(POP * (n+1) + get) return # No recursion. write(TUPLE) self.memoize(obj) dispatch[tuple] = save_tuple def save_list(self, obj): if self.bin: self.write(EMPTY_LIST) else: # proto 0 -- can't use EMPTY_LIST self.write(MARK + LIST) self.memoize(obj) self._batch_appends(obj) dispatch[list] = save_list _BATCHSIZE = 1000 def _batch_appends(self, items): # Helper to batch up APPENDS sequences save = self.save write = self.write if not self.bin: for x in items: save(x) write(APPEND) return it = iter(items) while True: tmp = list(islice(it, self._BATCHSIZE)) n = len(tmp) if n > 1: write(MARK) for x in tmp: save(x) write(APPENDS) elif n: save(tmp[0]) write(APPEND) # else tmp is empty, and we're done if n < self._BATCHSIZE: return def save_dict(self, obj): if self.bin: self.write(EMPTY_DICT) else: # proto 0 -- can't use EMPTY_DICT self.write(MARK + DICT) self.memoize(obj) self._batch_setitems(obj.items()) dispatch[dict] = save_dict if PyStringMap is not None: dispatch[PyStringMap] = save_dict def _batch_setitems(self, items): # Helper to batch up SETITEMS sequences; proto >= 1 only save = self.save write = self.write if not self.bin: for k, v in items: save(k) save(v) write(SETITEM) return it = iter(items) while True: tmp = list(islice(it, self._BATCHSIZE)) n = len(tmp) if n > 1: write(MARK) for k, v in tmp: save(k) save(v) write(SETITEMS) elif n: k, v = tmp[0] save(k) save(v) write(SETITEM) # else tmp is empty, and we're done if n < self._BATCHSIZE: return def save_set(self, obj): save = self.save write = self.write if self.proto < 4: self.save_reduce(set, (list(obj),), obj=obj) return write(EMPTY_SET) self.memoize(obj) it = iter(obj) while True: batch = list(islice(it, self._BATCHSIZE)) n = len(batch) if n > 0: write(MARK) for item in batch: save(item) write(ADDITEMS) if n < self._BATCHSIZE: return dispatch[set] = save_set def save_frozenset(self, obj): save = self.save write = self.write if self.proto < 4: self.save_reduce(frozenset, (list(obj),), obj=obj) return write(MARK) for item in obj: save(item) if id(obj) in self.memo: # If the object is already in the memo, this means it is # recursive. In this case, throw away everything we put on the # stack, and fetch the object back from the memo. write(POP_MARK + self.get(self.memo[id(obj)][0])) return write(FROZENSET) self.memoize(obj) dispatch[frozenset] = save_frozenset def save_global(self, obj, name=None): write = self.write memo = self.memo if name is None and self.proto >= 4: name = getattr(obj, '__qualname__', None) if name is None: name = obj.__name__ module_name = whichmodule(obj, name, allow_qualname=self.proto >= 4) try: __import__(module_name, level=0) module = sys.modules[module_name] obj2 = _getattribute(module, name, allow_qualname=self.proto >= 4) except (ImportError, KeyError, AttributeError): raise PicklingError( "Can't pickle %r: it's not found as %s.%s" % (obj, module_name, name)) else: if obj2 is not obj: raise PicklingError( "Can't pickle %r: it's not the same object as %s.%s" % (obj, module_name, name)) if self.proto >= 2: code = _extension_registry.get((module_name, name)) if code: assert code > 0 if code <= 0xff: write(EXT1 + pack("<B", code)) elif code <= 0xffff: write(EXT2 + pack("<H", code)) else: write(EXT4 + pack("<i", code)) return # Non-ASCII identifiers are supported only with protocols >= 3. if self.proto >= 4: self.save(module_name) self.save(name) write(STACK_GLOBAL) elif self.proto >= 3: write(GLOBAL + bytes(module_name, "utf-8") + b'\n' + bytes(name, "utf-8") + b'\n') else: if self.fix_imports: r_name_mapping = _compat_pickle.REVERSE_NAME_MAPPING r_import_mapping = _compat_pickle.REVERSE_IMPORT_MAPPING if (module_name, name) in r_name_mapping: module_name, name = r_name_mapping[(module_name, name)] if module_name in r_import_mapping: module_name = r_import_mapping[module_name] try: write(GLOBAL + bytes(module_name, "ascii") + b'\n' + bytes(name, "ascii") + b'\n') except UnicodeEncodeError: raise PicklingError( "can't pickle global identifier '%s.%s' using " "pickle protocol %i" % (module, name, self.proto)) self.memoize(obj) def save_type(self, obj): if obj is type(None): return self.save_reduce(type, (None,), obj=obj) elif obj is type(NotImplemented): return self.save_reduce(type, (NotImplemented,), obj=obj) elif obj is type(...): return self.save_reduce(type, (...,), obj=obj) return self.save_global(obj) dispatch[FunctionType] = save_global dispatch[type] = save_type # Unpickling machinery class _Unpickler: def __init__(self, file, *, fix_imports=True, encoding="ASCII", errors="strict"): """This takes a binary file for reading a pickle data stream. The protocol version of the pickle is detected automatically, so no proto argument is needed. The argument *file* must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return bytes. Thus *file* can be a binary file object opened for reading, a io.BytesIO object, or any other custom object that meets this interface. The file-like object must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return bytes. Thus file-like object can be a binary file object opened for reading, a BytesIO object, or any other custom object that meets this interface. Optional keyword arguments are *fix_imports*, *encoding* and *errors*, which are used to control compatiblity support for pickle stream generated by Python 2. If *fix_imports* is True, pickle will try to map the old Python 2 names to the new names used in Python 3. The *encoding* and *errors* tell pickle how to decode 8-bit string instances pickled by Python 2; these default to 'ASCII' and 'strict', respectively. *encoding* can be 'bytes' to read theses 8-bit string instances as bytes objects. """ self._file_readline = file.readline self._file_read = file.read self.memo = {} self.encoding = encoding self.errors = errors self.proto = 0 self.fix_imports = fix_imports def load(self): """Read a pickled object representation from the open file. Return the reconstituted object hierarchy specified in the file. """ # Check whether Unpickler was initialized correctly. This is # only needed to mimic the behavior of _pickle.Unpickler.dump(). if not hasattr(self, "_file_read"): raise UnpicklingError("Unpickler.__init__() was not called by " "%s.__init__()" % (self.__class__.__name__,)) self._unframer = _Unframer(self._file_read, self._file_readline) self.read = self._unframer.read self.readline = self._unframer.readline self.mark = object() # any new unique object self.stack = [] self.append = self.stack.append self.proto = 0 read = self.read dispatch = self.dispatch try: while True: key = read(1) if not key: raise EOFError assert isinstance(key, bytes_types) dispatch[key[0]](self) except _Stop as stopinst: return stopinst.value # Return largest index k such that self.stack[k] is self.mark. # If the stack doesn't contain a mark, eventually raises IndexError. # This could be sped by maintaining another stack, of indices at which # the mark appears. For that matter, the latter stack would suffice, # and we wouldn't need to push mark objects on self.stack at all. # Doing so is probably a good thing, though, since if the pickle is # corrupt (or hostile) we may get a clue from finding self.mark embedded # in unpickled objects. def marker(self): stack = self.stack mark = self.mark k = len(stack)-1 while stack[k] is not mark: k = k-1 return k def persistent_load(self, pid): raise UnpicklingError("unsupported persistent id encountered") dispatch = {} def load_proto(self): proto = self.read(1)[0] if not 0 <= proto <= HIGHEST_PROTOCOL: raise ValueError("unsupported pickle protocol: %d" % proto) self.proto = proto dispatch[PROTO[0]] = load_proto def load_frame(self): frame_size, = unpack('<Q', self.read(8)) if frame_size > sys.maxsize: raise ValueError("frame size > sys.maxsize: %d" % frame_size) self._unframer.load_frame(frame_size) dispatch[FRAME[0]] = load_frame def load_persid(self): pid = self.readline()[:-1].decode("ascii") self.append(self.persistent_load(pid)) dispatch[PERSID[0]] = load_persid def load_binpersid(self): pid = self.stack.pop() self.append(self.persistent_load(pid)) dispatch[BINPERSID[0]] = load_binpersid def load_none(self): self.append(None) dispatch[NONE[0]] = load_none def load_false(self): self.append(False) dispatch[NEWFALSE[0]] = load_false def load_true(self): self.append(True) dispatch[NEWTRUE[0]] = load_true def load_int(self): data = self.readline() if data == FALSE[1:]: val = False elif data == TRUE[1:]: val = True else: val = int(data, 0) self.append(val) dispatch[INT[0]] = load_int def load_binint(self): self.append(unpack('<i', self.read(4))[0]) dispatch[BININT[0]] = load_binint def load_binint1(self): self.append(self.read(1)[0]) dispatch[BININT1[0]] = load_binint1 def load_binint2(self): self.append(unpack('<H', self.read(2))[0]) dispatch[BININT2[0]] = load_binint2 def load_long(self): val = self.readline()[:-1] if val and val[-1] == b'L'[0]: val = val[:-1] self.append(int(val, 0)) dispatch[LONG[0]] = load_long def load_long1(self): n = self.read(1)[0] data = self.read(n) self.append(decode_long(data)) dispatch[LONG1[0]] = load_long1 def load_long4(self): n, = unpack('<i', self.read(4)) if n < 0: # Corrupt or hostile pickle -- we never write one like this raise UnpicklingError("LONG pickle has negative byte count") data = self.read(n) self.append(decode_long(data)) dispatch[LONG4[0]] = load_long4 def load_float(self): self.append(float(self.readline()[:-1])) dispatch[FLOAT[0]] = load_float def load_binfloat(self): self.append(unpack('>d', self.read(8))[0]) dispatch[BINFLOAT[0]] = load_binfloat def _decode_string(self, value): # Used to allow strings from Python 2 to be decoded either as # bytes or Unicode strings. This should be used only with the # STRING, BINSTRING and SHORT_BINSTRING opcodes. if self.encoding == "bytes": return value else: return value.decode(self.encoding, self.errors) def load_string(self): data = self.readline()[:-1] # Strip outermost quotes if len(data) >= 2 and data[0] == data[-1] and data[0] in b'"\'': data = data[1:-1] else: raise UnpicklingError("the STRING opcode argument must be quoted") self.append(self._decode_string(codecs.escape_decode(data)[0])) dispatch[STRING[0]] = load_string def load_binstring(self): # Deprecated BINSTRING uses signed 32-bit length len, = unpack('<i', self.read(4)) if len < 0: raise UnpicklingError("BINSTRING pickle has negative byte count") data = self.read(len) self.append(self._decode_string(data)) dispatch[BINSTRING[0]] = load_binstring def load_binbytes(self): len, = unpack('<I', self.read(4)) if len > maxsize: raise UnpicklingError("BINBYTES exceeds system's maximum size " "of %d bytes" % maxsize) self.append(self.read(len)) dispatch[BINBYTES[0]] = load_binbytes def load_unicode(self): self.append(str(self.readline()[:-1], 'raw-unicode-escape')) dispatch[UNICODE[0]] = load_unicode def load_binunicode(self): len, = unpack('<I', self.read(4)) if len > maxsize: raise UnpicklingError("BINUNICODE exceeds system's maximum size " "of %d bytes" % maxsize) self.append(str(self.read(len), 'utf-8', 'surrogatepass')) dispatch[BINUNICODE[0]] = load_binunicode def load_binunicode8(self): len, = unpack('<Q', self.read(8)) if len > maxsize: raise UnpicklingError("BINUNICODE8 exceeds system's maximum size " "of %d bytes" % maxsize) self.append(str(self.read(len), 'utf-8', 'surrogatepass')) dispatch[BINUNICODE8[0]] = load_binunicode8 def load_short_binstring(self): len = self.read(1)[0] data = self.read(len) self.append(self._decode_string(data)) dispatch[SHORT_BINSTRING[0]] = load_short_binstring def load_short_binbytes(self): len = self.read(1)[0] self.append(self.read(len)) dispatch[SHORT_BINBYTES[0]] = load_short_binbytes def load_short_binunicode(self): len = self.read(1)[0] self.append(str(self.read(len), 'utf-8', 'surrogatepass')) dispatch[SHORT_BINUNICODE[0]] = load_short_binunicode def load_tuple(self): k = self.marker() self.stack[k:] = [tuple(self.stack[k+1:])] dispatch[TUPLE[0]] = load_tuple def load_empty_tuple(self): self.append(()) dispatch[EMPTY_TUPLE[0]] = load_empty_tuple def load_tuple1(self): self.stack[-1] = (self.stack[-1],) dispatch[TUPLE1[0]] = load_tuple1 def load_tuple2(self): self.stack[-2:] = [(self.stack[-2], self.stack[-1])] dispatch[TUPLE2[0]] = load_tuple2 def load_tuple3(self): self.stack[-3:] = [(self.stack[-3], self.stack[-2], self.stack[-1])] dispatch[TUPLE3[0]] = load_tuple3 def load_empty_list(self): self.append([]) dispatch[EMPTY_LIST[0]] = load_empty_list def load_empty_dictionary(self): self.append({}) dispatch[EMPTY_DICT[0]] = load_empty_dictionary def load_empty_set(self): self.append(set()) dispatch[EMPTY_SET[0]] = load_empty_set def load_frozenset(self): k = self.marker() self.stack[k:] = [frozenset(self.stack[k+1:])] dispatch[FROZENSET[0]] = load_frozenset def load_list(self): k = self.marker() self.stack[k:] = [self.stack[k+1:]] dispatch[LIST[0]] = load_list def load_dict(self): k = self.marker() items = self.stack[k+1:] d = {items[i]: items[i+1] for i in range(0, len(items), 2)} self.stack[k:] = [d] dispatch[DICT[0]] = load_dict # INST and OBJ differ only in how they get a class object. It's not # only sensible to do the rest in a common routine, the two routines # previously diverged and grew different bugs. # klass is the class to instantiate, and k points to the topmost mark # object, following which are the arguments for klass.__init__. def _instantiate(self, klass, k): args = tuple(self.stack[k+1:]) del self.stack[k:] if (args or not isinstance(klass, type) or hasattr(klass, "__getinitargs__")): try: value = klass(*args) except TypeError as err: raise TypeError("in constructor for %s: %s" % (klass.__name__, str(err)), sys.exc_info()[2]) else: value = klass.__new__(klass) self.append(value) def load_inst(self): module = self.readline()[:-1].decode("ascii") name = self.readline()[:-1].decode("ascii") klass = self.find_class(module, name) self._instantiate(klass, self.marker()) dispatch[INST[0]] = load_inst def load_obj(self): # Stack is ... markobject classobject arg1 arg2 ... k = self.marker() klass = self.stack.pop(k+1) self._instantiate(klass, k) dispatch[OBJ[0]] = load_obj def load_newobj(self): args = self.stack.pop() cls = self.stack.pop() obj = cls.__new__(cls, *args) self.append(obj) dispatch[NEWOBJ[0]] = load_newobj def load_newobj_ex(self): kwargs = self.stack.pop() args = self.stack.pop() cls = self.stack.pop() obj = cls.__new__(cls, *args, **kwargs) self.append(obj) dispatch[NEWOBJ_EX[0]] = load_newobj_ex def load_global(self): module = self.readline()[:-1].decode("utf-8") name = self.readline()[:-1].decode("utf-8") klass = self.find_class(module, name) self.append(klass) dispatch[GLOBAL[0]] = load_global def load_stack_global(self): name = self.stack.pop() module = self.stack.pop() if type(name) is not str or type(module) is not str: raise UnpicklingError("STACK_GLOBAL requires str") self.append(self.find_class(module, name)) dispatch[STACK_GLOBAL[0]] = load_stack_global def load_ext1(self): code = self.read(1)[0] self.get_extension(code) dispatch[EXT1[0]] = load_ext1 def load_ext2(self): code, = unpack('<H', self.read(2)) self.get_extension(code) dispatch[EXT2[0]] = load_ext2 def load_ext4(self): code, = unpack('<i', self.read(4)) self.get_extension(code) dispatch[EXT4[0]] = load_ext4 def get_extension(self, code): nil = [] obj = _extension_cache.get(code, nil) if obj is not nil: self.append(obj) return key = _inverted_registry.get(code) if not key: if code <= 0: # note that 0 is forbidden # Corrupt or hostile pickle. raise UnpicklingError("EXT specifies code <= 0") raise ValueError("unregistered extension code %d" % code) obj = self.find_class(*key) _extension_cache[code] = obj self.append(obj) def find_class(self, module, name): # Subclasses may override this. if self.proto < 3 and self.fix_imports: if (module, name) in _compat_pickle.NAME_MAPPING: module, name = _compat_pickle.NAME_MAPPING[(module, name)] if module in _compat_pickle.IMPORT_MAPPING: module = _compat_pickle.IMPORT_MAPPING[module] __import__(module, level=0) return _getattribute(sys.modules[module], name, allow_qualname=self.proto >= 4) def load_reduce(self): stack = self.stack args = stack.pop() func = stack[-1] try: value = func(*args) except: print(sys.exc_info()) print(func, args) raise stack[-1] = value dispatch[REDUCE[0]] = load_reduce def load_pop(self): del self.stack[-1] dispatch[POP[0]] = load_pop def load_pop_mark(self): k = self.marker() del self.stack[k:] dispatch[POP_MARK[0]] = load_pop_mark def load_dup(self): self.append(self.stack[-1]) dispatch[DUP[0]] = load_dup def load_get(self): i = int(self.readline()[:-1]) self.append(self.memo[i]) dispatch[GET[0]] = load_get def load_binget(self): i = self.read(1)[0] self.append(self.memo[i]) dispatch[BINGET[0]] = load_binget def load_long_binget(self): i, = unpack('<I', self.read(4)) self.append(self.memo[i]) dispatch[LONG_BINGET[0]] = load_long_binget def load_put(self): i = int(self.readline()[:-1]) if i < 0: raise ValueError("negative PUT argument") self.memo[i] = self.stack[-1] dispatch[PUT[0]] = load_put def load_binput(self): i = self.read(1)[0] if i < 0: raise ValueError("negative BINPUT argument") self.memo[i] = self.stack[-1] dispatch[BINPUT[0]] = load_binput def load_long_binput(self): i, = unpack('<I', self.read(4)) if i > maxsize: raise ValueError("negative LONG_BINPUT argument") self.memo[i] = self.stack[-1] dispatch[LONG_BINPUT[0]] = load_long_binput def load_memoize(self): memo = self.memo memo[len(memo)] = self.stack[-1] dispatch[MEMOIZE[0]] = load_memoize def load_append(self): stack = self.stack value = stack.pop() list = stack[-1] list.append(value) dispatch[APPEND[0]] = load_append def load_appends(self): stack = self.stack mark = self.marker() list_obj = stack[mark - 1] items = stack[mark + 1:] if isinstance(list_obj, list): list_obj.extend(items) else: append = list_obj.append for item in items: append(item) del stack[mark:] dispatch[APPENDS[0]] = load_appends def load_setitem(self): stack = self.stack value = stack.pop() key = stack.pop() dict = stack[-1] dict[key] = value dispatch[SETITEM[0]] = load_setitem def load_setitems(self): stack = self.stack mark = self.marker() dict = stack[mark - 1] for i in range(mark + 1, len(stack), 2): dict[stack[i]] = stack[i + 1] del stack[mark:] dispatch[SETITEMS[0]] = load_setitems def load_additems(self): stack = self.stack mark = self.marker() set_obj = stack[mark - 1] items = stack[mark + 1:] if isinstance(set_obj, set): set_obj.update(items) else: add = set_obj.add for item in items: add(item) del stack[mark:] dispatch[ADDITEMS[0]] = load_additems def load_build(self): stack = self.stack state = stack.pop() inst = stack[-1] setstate = getattr(inst, "__setstate__", None) if setstate is not None: setstate(state) return slotstate = None if isinstance(state, tuple) and len(state) == 2: state, slotstate = state if state: inst_dict = inst.__dict__ intern = sys.intern for k, v in state.items(): if type(k) is str: inst_dict[intern(k)] = v else: inst_dict[k] = v if slotstate: for k, v in slotstate.items(): setattr(inst, k, v) dispatch[BUILD[0]] = load_build def load_mark(self): self.append(self.mark) dispatch[MARK[0]] = load_mark def load_stop(self): value = self.stack.pop() raise _Stop(value) dispatch[STOP[0]] = load_stop # Shorthands def _dump(obj, file, protocol=None, *, fix_imports=True): _Pickler(file, protocol, fix_imports=fix_imports).dump(obj) def _dumps(obj, protocol=None, *, fix_imports=True): f = io.BytesIO() _Pickler(f, protocol, fix_imports=fix_imports).dump(obj) res = f.getvalue() assert isinstance(res, bytes_types) return res def _load(file, *, fix_imports=True, encoding="ASCII", errors="strict"): return _Unpickler(file, fix_imports=fix_imports, encoding=encoding, errors=errors).load() def _loads(s, *, fix_imports=True, encoding="ASCII", errors="strict"): if isinstance(s, str): raise TypeError("Can't load pickle from unicode string") file = io.BytesIO(s) return _Unpickler(file, fix_imports=fix_imports, encoding=encoding, errors=errors).load() # Use the faster _pickle if possible try: from _pickle import ( PickleError, PicklingError, UnpicklingError, Pickler, Unpickler, dump, dumps, load, loads ) except ImportError: Pickler, Unpickler = _Pickler, _Unpickler dump, dumps, load, loads = _dump, _dumps, _load, _loads # Doctest def _test(): import doctest return doctest.testmod() if __name__ == "__main__": import argparse parser = argparse.ArgumentParser( description='display contents of the pickle files') parser.add_argument( 'pickle_file', type=argparse.FileType('br'), nargs='*', help='the pickle file') parser.add_argument( '-t', '--test', action='store_true', help='run self-test suite') parser.add_argument( '-v', action='store_true', help='run verbosely; only affects self-test run') args = parser.parse_args() if args.test: _test() else: if not args.pickle_file: parser.print_help() else: import pprint for f in args.pickle_file: obj = load(f) pprint.pprint(obj)
lgpl-3.0
Shabbypenguin/Jellybean_kernel
tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/SchedGui.py
12980
5411
# SchedGui.py - Python extension for perf script, basic GUI code for # traces drawing and overview. # # Copyright (C) 2010 by Frederic Weisbecker <fweisbec@gmail.com> # # This software is distributed under the terms of the GNU General # Public License ("GPL") version 2 as published by the Free Software # Foundation. try: import wx except ImportError: raise ImportError, "You need to install the wxpython lib for this script" class RootFrame(wx.Frame): Y_OFFSET = 100 RECT_HEIGHT = 100 RECT_SPACE = 50 EVENT_MARKING_WIDTH = 5 def __init__(self, sched_tracer, title, parent = None, id = -1): wx.Frame.__init__(self, parent, id, title) (self.screen_width, self.screen_height) = wx.GetDisplaySize() self.screen_width -= 10 self.screen_height -= 10 self.zoom = 0.5 self.scroll_scale = 20 self.sched_tracer = sched_tracer self.sched_tracer.set_root_win(self) (self.ts_start, self.ts_end) = sched_tracer.interval() self.update_width_virtual() self.nr_rects = sched_tracer.nr_rectangles() + 1 self.height_virtual = RootFrame.Y_OFFSET + (self.nr_rects * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)) # whole window panel self.panel = wx.Panel(self, size=(self.screen_width, self.screen_height)) # scrollable container self.scroll = wx.ScrolledWindow(self.panel) self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale) self.scroll.EnableScrolling(True, True) self.scroll.SetFocus() # scrollable drawing area self.scroll_panel = wx.Panel(self.scroll, size=(self.screen_width - 15, self.screen_height / 2)) self.scroll_panel.Bind(wx.EVT_PAINT, self.on_paint) self.scroll_panel.Bind(wx.EVT_KEY_DOWN, self.on_key_press) self.scroll_panel.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down) self.scroll.Bind(wx.EVT_PAINT, self.on_paint) self.scroll.Bind(wx.EVT_KEY_DOWN, self.on_key_press) self.scroll.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down) self.scroll.Fit() self.Fit() self.scroll_panel.SetDimensions(-1, -1, self.width_virtual, self.height_virtual, wx.SIZE_USE_EXISTING) self.txt = None self.Show(True) def us_to_px(self, val): return val / (10 ** 3) * self.zoom def px_to_us(self, val): return (val / self.zoom) * (10 ** 3) def scroll_start(self): (x, y) = self.scroll.GetViewStart() return (x * self.scroll_scale, y * self.scroll_scale) def scroll_start_us(self): (x, y) = self.scroll_start() return self.px_to_us(x) def paint_rectangle_zone(self, nr, color, top_color, start, end): offset_px = self.us_to_px(start - self.ts_start) width_px = self.us_to_px(end - self.ts_start) offset_py = RootFrame.Y_OFFSET + (nr * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)) width_py = RootFrame.RECT_HEIGHT dc = self.dc if top_color is not None: (r, g, b) = top_color top_color = wx.Colour(r, g, b) brush = wx.Brush(top_color, wx.SOLID) dc.SetBrush(brush) dc.DrawRectangle(offset_px, offset_py, width_px, RootFrame.EVENT_MARKING_WIDTH) width_py -= RootFrame.EVENT_MARKING_WIDTH offset_py += RootFrame.EVENT_MARKING_WIDTH (r ,g, b) = color color = wx.Colour(r, g, b) brush = wx.Brush(color, wx.SOLID) dc.SetBrush(brush) dc.DrawRectangle(offset_px, offset_py, width_px, width_py) def update_rectangles(self, dc, start, end): start += self.ts_start end += self.ts_start self.sched_tracer.fill_zone(start, end) def on_paint(self, event): dc = wx.PaintDC(self.scroll_panel) self.dc = dc width = min(self.width_virtual, self.screen_width) (x, y) = self.scroll_start() start = self.px_to_us(x) end = self.px_to_us(x + width) self.update_rectangles(dc, start, end) def rect_from_ypixel(self, y): y -= RootFrame.Y_OFFSET rect = y / (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE) height = y % (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE) if rect < 0 or rect > self.nr_rects - 1 or height > RootFrame.RECT_HEIGHT: return -1 return rect def update_summary(self, txt): if self.txt: self.txt.Destroy() self.txt = wx.StaticText(self.panel, -1, txt, (0, (self.screen_height / 2) + 50)) def on_mouse_down(self, event): (x, y) = event.GetPositionTuple() rect = self.rect_from_ypixel(y) if rect == -1: return t = self.px_to_us(x) + self.ts_start self.sched_tracer.mouse_down(rect, t) def update_width_virtual(self): self.width_virtual = self.us_to_px(self.ts_end - self.ts_start) def __zoom(self, x): self.update_width_virtual() (xpos, ypos) = self.scroll.GetViewStart() xpos = self.us_to_px(x) / self.scroll_scale self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale, xpos, ypos) self.Refresh() def zoom_in(self): x = self.scroll_start_us() self.zoom *= 2 self.__zoom(x) def zoom_out(self): x = self.scroll_start_us() self.zoom /= 2 self.__zoom(x) def on_key_press(self, event): key = event.GetRawKeyCode() if key == ord("+"): self.zoom_in() return if key == ord("-"): self.zoom_out() return key = event.GetKeyCode() (x, y) = self.scroll.GetViewStart() if key == wx.WXK_RIGHT: self.scroll.Scroll(x + 1, y) elif key == wx.WXK_LEFT: self.scroll.Scroll(x - 1, y) elif key == wx.WXK_DOWN: self.scroll.Scroll(x, y + 1) elif key == wx.WXK_UP: self.scroll.Scroll(x, y - 1)
gpl-2.0
rajashreer7/autotest-client-tests
linux-tools/libpwquality/libpwquality.py
4
1206
#!/bin/python import os, subprocess import logging from autotest.client import test from autotest.client.shared import error class libpwquality(test.test): """ Autotest module for testing basic functionality of libpwquality @author Tejaswini Sambamurthy <tejaswin.linux.vnet.ibm.com> """ version = 1 nfail = 0 path = '' def initialize(self): """ Sets the overall failure counter for the test. """ self.nfail = 0 logging.info('\n Test initialize successfully') def run_once(self, test_path=''): """ Trigger test run """ try: os.environ["LTPBIN"] = "%s/shared" %(test_path) ret_val = subprocess.call(test_path + '/libpwquality' + '/libpwquality.sh', shell=True) if ret_val != 0: self.nfail += 1 except error.CmdError, e: self.nfail += 1 logging.error("Test Failed: %s", e) def postprocess(self): if self.nfail != 0: logging.info('\n nfails is non-zero') raise error.TestError('\nTest failed') else: logging.info('\n Test completed successfully ')
gpl-2.0
pfouque/deezer-python
deezer/tests/test_resources.py
1
9053
# -*- coding: utf-8 -*- import json import unittest from types import GeneratorType import deezer from mock import patch from .mocked_methods import fake_urlopen class TestResources(unittest.TestCase): def setUp(self): self.patcher = patch('deezer.client.urlopen', fake_urlopen) self.patcher.start() def tearDown(self): self.patcher.stop() def test_resource_dict(self): """ Test that resource can be converted to dict """ client = deezer.Client() response = fake_urlopen(client.object_url('track', 3135556)) resp_str = response.read().decode('utf-8') response.close() data = json.loads(resp_str) resource = deezer.resources.Resource(client, data) self.assertEqual(resource.asdict(), data) def test_resource_relation(self): """ Test passing parent object when using get_relation """ client = deezer.Client() album = client.get_album(302127) tracks = album.get_tracks() self.assertTrue(tracks[0].album is album) def test_album_attributes(self): """ Test album resource """ client = deezer.Client() album = client.get_album(302127) self.assertTrue(hasattr(album, 'title')) self.assertEqual(repr(album), '<Album: Discovery>') artist = album.get_artist() self.assertIsInstance(artist, deezer.resources.Artist) self.assertEqual(repr(artist), '<Artist: Daft Punk>') def test_album_tracks(self): """ Test tracks method of album resource """ client = deezer.Client() album = client.get_album(302127) tracks = album.get_tracks() self.assertIsInstance(tracks, list) track = tracks[0] self.assertIsInstance(track, deezer.resources.Track) self.assertEqual(repr(track), '<Track: One More Time>') self.assertEqual(type(album.iter_tracks()), GeneratorType) track = list(album.iter_tracks())[0] self.assertIsInstance(track, deezer.resources.Track) def test_artist_attributes(self): """ Test artist resource """ client = deezer.Client() artist = client.get_artist(27) self.assertTrue(hasattr(artist, 'name')) self.assertIsInstance(artist, deezer.resources.Artist) self.assertEqual(repr(artist), '<Artist: Daft Punk>') def test_artist_albums(self): """ Test albums method of artist resource """ client = deezer.Client() artist = client.get_artist(27) albums = artist.get_albums() self.assertIsInstance(albums, list) album = albums[0] self.assertIsInstance(album, deezer.resources.Album) self.assertEqual(repr(album), '<Album: Human After All (Remixes) (Remixes)>') self.assertEqual(type(artist.iter_albums()), GeneratorType) def test_artist_top(self): """ Test top method of artist resource """ client = deezer.Client() artist = client.get_artist(27) tracks = artist.get_top() self.assertIsInstance(tracks, list) track = tracks[0] self.assertIsInstance(track, deezer.resources.Track) self.assertEqual(repr(track), '<Track: Get Lucky (Radio Edit)>') def test_artist_radio(self): """ Test radio method of artist resource """ client = deezer.Client() artist = client.get_artist(27) tracks = artist.get_radio() self.assertIsInstance(tracks, list) track = tracks[0] self.assertIsInstance(track, deezer.resources.Track) self.assertEqual(repr(track), '<Track: Lose Yourself to Dance>') def test_artist_related(self): """ Test related method of artist resource """ client = deezer.Client() artist = client.get_artist(27) artists = artist.get_related() self.assertIsInstance(artists, list) artist = artists[0] self.assertIsInstance(artist, deezer.resources.Artist) self.assertEqual(repr(artist), '<Artist: Justice>') self.assertEqual(type(artist.iter_related()), GeneratorType) def test_track_attributes(self): """ Test track resource """ client = deezer.Client() track = client.get_track(3135556) artist = track.get_artist() album = track.get_album() self.assertTrue(hasattr(track, 'title')) self.assertIsInstance(track, deezer.resources.Track) self.assertIsInstance(artist, deezer.resources.Artist) self.assertIsInstance(album, deezer.resources.Album) self.assertEqual(repr(track), '<Track: Harder Better Faster Stronger>') self.assertEqual(repr(artist), '<Artist: Daft Punk>') self.assertEqual(repr(album), '<Album: Discovery>') def test_radio_attributes(self): """ Test radio resource """ client = deezer.Client() radio = client.get_radio(23261) self.assertTrue(hasattr(radio, 'title')) self.assertIsInstance(radio, deezer.resources.Radio) self.assertEqual(repr(radio), '<Radio: Telegraph Classical>') def test_radio_tracks(self): """ Test tracks method of radio resource """ client = deezer.Client() radio = client.get_radio(23261) tracks = radio.get_tracks() self.assertIsInstance(tracks, list) track = tracks[2] self.assertIsInstance(track, deezer.resources.Track) self.assertEqual(repr(track), '<Track: Schumann: Kinderszenen, Op.15 - 11. Fürchtenmachen>') self.assertEqual(type(radio.iter_tracks()), GeneratorType) def test_genre_attributes(self): """ Test genre resource """ client = deezer.Client() genre = client.get_genre(106) self.assertTrue(hasattr(genre, 'name')) self.assertIsInstance(genre, deezer.resources.Genre) self.assertEqual(repr(genre), '<Genre: Electro>') def test_genre_artists(self): """ Test artists method of genre resource """ client = deezer.Client() genre = client.get_genre(106) artists = genre.get_artists() self.assertIsInstance(artists, list) artist = artists[0] self.assertIsInstance(artist, deezer.resources.Artist) self.assertEqual(repr(artist), '<Artist: Calvin Harris>') self.assertEqual(type(genre.iter_artists()), GeneratorType) def test_genre_radios(self): """ Test radios method of genre resource """ client = deezer.Client() genre = client.get_genre(106) radios = genre.get_radios() self.assertIsInstance(radios, list) radio = radios[0] self.assertIsInstance(radio, deezer.resources.Radio) self.assertEqual(repr(radio), '<Radio: Techno/House>') self.assertEqual(type(genre.iter_radios()), GeneratorType) def test_chart_tracks(self): """ Test tracks method of chart resource """ client = deezer.Client() chart = client.get_chart() tracks = chart.get_tracks() self.assertIsInstance(tracks, list) track = tracks[0] self.assertIsInstance(track, deezer.resources.Track) self.assertEqual(repr(track), '<Track: Starboy>') self.assertEqual(type(chart.iter_tracks()), GeneratorType) def test_chart_artists(self): """ Test artists method of chart resource """ client = deezer.Client() chart = client.get_chart() artists = chart.get_artists() self.assertIsInstance(artists, list) artist = artists[0] self.assertIsInstance(artist, deezer.resources.Artist) self.assertEqual(repr(artist), '<Artist: Pnl>') self.assertEqual(type(chart.iter_artists()), GeneratorType) def test_chart_albums(self): """ Test albums method of chart resource """ client = deezer.Client() chart = client.get_chart() albums = chart.get_albums() self.assertIsInstance(albums, list) album = albums[0] self.assertIsInstance(album, deezer.resources.Album) self.assertEqual(repr(album), "<Album: Where Is l'album de Gradur>") self.assertEqual(type(chart.iter_albums()), GeneratorType) def test_chart_playlists(self): """ Test playlists method of chart resource """ client = deezer.Client() chart = client.get_chart() playlists = chart.get_playlists() self.assertIsInstance(playlists, list) playlist = playlists[0] self.assertIsInstance(playlist, deezer.resources.Playlist) self.assertEqual(repr(playlist), "<Playlist: Top France>") self.assertEqual(type(chart.iter_playlists()), GeneratorType)
mit
gsnedders/presto-testo
wpt/websockets/autobahn/oberstet-Autobahn-643d2ee/demo/broadcast/broadcast_server.py
4
2351
############################################################################### ## ## Copyright 2011 Tavendo GmbH ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## ############################################################################### import sys from twisted.internet import reactor from twisted.python import log from autobahn.websocket import WebSocketServerFactory, WebSocketServerProtocol, listenWS class BroadcastServerProtocol(WebSocketServerProtocol): def onOpen(self): self.factory.register(self) def onMessage(self, msg, binary): if not binary: self.factory.broadcast("received message '%s' from %s" % (msg, self.peerstr)) def connectionLost(self, reason): WebSocketServerProtocol.connectionLost(self, reason) self.factory.unregister(self) class BroadcastServerFactory(WebSocketServerFactory): protocol = BroadcastServerProtocol def __init__(self, url): WebSocketServerFactory.__init__(self, url) self.clients = [] self.tickcount = 0 self.tick() def tick(self): self.tickcount += 1 self.broadcast("tick %d" % self.tickcount) reactor.callLater(1, self.tick) def register(self, client): if not client in self.clients: print "registered client " + client.peerstr self.clients.append(client) def unregister(self, client): if client in self.clients: print "unregistered client " + client.peerstr self.clients.remove(client) def broadcast(self, msg): print "broadcasting message '%s' .." % msg for c in self.clients: print "send to " + c.peerstr c.sendMessage(msg) if __name__ == '__main__': log.startLogging(sys.stdout) factory = BroadcastServerFactory("ws://localhost:9000") listenWS(factory) reactor.run()
bsd-3-clause
isabellemao/Hello-World
python/Junior2015CCCJ4.py
1
1278
#Problem J4: Arrival Time departure_time = input() split_departure = list(departure_time) #The time of departure, split into a list. #Split the list departure_hour = split_departure[0:2] departure_minute = split_departure[3:5] #Change the split list to integers. departure_hour = int("".join(departure_hour)) departure_minute = int("".join(departure_minute)) #The start and end of the rush hours rh_start_1 = 7 rh_end_1 = 10 rh_start_2 = 15 rh_end_2 = 19 #Set the current time hour = departure_hour minute = departure_minute #For the 120 minutes it usually takes Fiona to commute for counter in range(1, 121): #If it's currently rush hour if hour >= rh_start_1 and hour < rh_end_1 or hour >= rh_start_2 and hour < rh_end_2: #Twice as slow if rush hour minute += 2 else: #Normal speed if normal time minute += 1 if minute >= 60: minute = 0 #Reset hour hour += 1 if hour == 24: hour = 0 #Add fake zeroes if required. if hour < 10: hour = str(hour) hour = "0" + hour else: hour = str(hour) if minute < 10: minute = str(minute) minute = "0" + minute else: minute = str(minute) #Make a valid output. output = hour , ":" , minute output = "".join(output) print(output)
apache-2.0
JosephCastro/selenium
py/selenium/webdriver/support/wait.py
81
4070
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import time from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import TimeoutException POLL_FREQUENCY = 0.5 # How long to sleep inbetween calls to the method IGNORED_EXCEPTIONS = (NoSuchElementException,) # exceptions ignored during calls to the method class WebDriverWait(object): def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None): """Constructor, takes a WebDriver instance and timeout in seconds. :Args: - driver - Instance of WebDriver (Ie, Firefox, Chrome or Remote) - timeout - Number of seconds before timing out - poll_frequency - sleep interval between calls By default, it is 0.5 second. - ignored_exceptions - iterable structure of exception classes ignored during calls. By default, it contains NoSuchElementException only. Example: from selenium.webdriver.support.ui import WebDriverWait \n element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("someId")) \n is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\ \n until_not(lambda x: x.find_element_by_id("someId").is_displayed()) """ self._driver = driver self._timeout = timeout self._poll = poll_frequency # avoid the divide by zero if self._poll == 0: self._poll = POLL_FREQUENCY exceptions = list(IGNORED_EXCEPTIONS) if ignored_exceptions is not None: try: exceptions.extend(iter(ignored_exceptions)) except TypeError: # ignored_exceptions is not iterable exceptions.append(ignored_exceptions) self._ignored_exceptions = tuple(exceptions) def __repr__(self): return '<{0.__module__}.{0.__name__} (session="{1}")>'.format( type(self), self._driver.session_id) def until(self, method, message=''): """Calls the method provided with the driver as an argument until the \ return value is not False.""" screen = None stacktrace = None end_time = time.time() + self._timeout while True: try: value = method(self._driver) if value: return value except self._ignored_exceptions as exc: screen = getattr(exc, 'screen', None) stacktrace = getattr(exc, 'stacktrace', None) time.sleep(self._poll) if time.time() > end_time: break raise TimeoutException(message, screen, stacktrace) def until_not(self, method, message=''): """Calls the method provided with the driver as an argument until the \ return value is False.""" end_time = time.time() + self._timeout while True: try: value = method(self._driver) if not value: return value except self._ignored_exceptions: return True time.sleep(self._poll) if time.time() > end_time: break raise TimeoutException(message)
apache-2.0
FUSED-Wind/fusedwind
src/fusedwind/lib/cubicspline.py
2
2234
import numpy as np from scipy.linalg import solve_banded from fusedwind.lib.utilities import _checkIfFloat class NaturalCubicSpline(object): """ class implementation of utilities.cubic_with_deriv """ def __init__(self, xp, yp): if np.any(np.diff(xp) < 0): raise TypeError('xp must be in ascending order') # n = len(x) self.m = len(xp) xk = xp[1:-1] yk = yp[1:-1] xkp = xp[2:] ykp = yp[2:] xkm = xp[:-2] ykm = yp[:-2] b = (ykp - yk)/(xkp - xk) - (yk - ykm)/(xk - xkm) l = (xk - xkm)/6.0 d = (xkp - xkm)/3.0 u = (xkp - xk)/6.0 # u[0] = 0.0 # non-existent entries # l[-1] = 0.0 # solve for second derivatives fpp = solve_banded((1, 1), np.matrix([u, d, l]), b) self.fpp = np.concatenate([[0.0], fpp, [0.0]]) # natural spline self.xp = xp self.yp = yp def __call__(self, x, deriv=False): x, n = _checkIfFloat(x) y = np.zeros(n) dydx = np.zeros(n) dydxp = np.zeros((n, self.m)) dydyp = np.zeros((n, self.m)) # find location in vector for i in range(n): if x[i] < self.xp[0]: j = 0 elif x[i] > self.xp[-1]: j = self.m-2 else: for j in range(self.m-1): if self.xp[j+1] > x[i]: break x1 = self.xp[j] y1 = self.yp[j] x2 = self.xp[j+1] y2 = self.yp[j+1] A = (x2 - x[i])/(x2 - x1) B = 1 - A C = 1.0/6*(A**3 - A)*(x2 - x1)**2 D = 1.0/6*(B**3 - B)*(x2 - x1)**2 y[i] = A * y1 + B * y2 + C * self.fpp[j] + D * self.fpp[j+1] dAdx = -1.0/(x2 - x1) dBdx = -dAdx dCdx = 1.0/6 * (3 * A**2 - 1) * dAdx * (x2 - x1)**2 dDdx = 1.0/6 * (3 * B**2 - 1) * dBdx * (x2 - x1)**2 dydx[i] = dAdx * y1 + dBdx * y2 + dCdx * self.fpp[j] + dDdx * self.fpp[j+1] if n == 1: y = y[0] dydx = dydx[0] if deriv: return y, dydx else: return y
apache-2.0
googleapis/python-pubsublite
google/cloud/pubsublite_v1/types/__init__.py
1
4702
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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 .admin import ( CreateReservationRequest, CreateSubscriptionRequest, CreateTopicRequest, DeleteReservationRequest, DeleteSubscriptionRequest, DeleteTopicRequest, GetReservationRequest, GetSubscriptionRequest, GetTopicPartitionsRequest, GetTopicRequest, ListReservationsRequest, ListReservationsResponse, ListReservationTopicsRequest, ListReservationTopicsResponse, ListSubscriptionsRequest, ListSubscriptionsResponse, ListTopicsRequest, ListTopicsResponse, ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, OperationMetadata, SeekSubscriptionRequest, SeekSubscriptionResponse, TopicPartitions, UpdateReservationRequest, UpdateSubscriptionRequest, UpdateTopicRequest, ) from .common import ( AttributeValues, Cursor, PubSubMessage, Reservation, SequencedMessage, Subscription, TimeTarget, Topic, ) from .cursor import ( CommitCursorRequest, CommitCursorResponse, InitialCommitCursorRequest, InitialCommitCursorResponse, ListPartitionCursorsRequest, ListPartitionCursorsResponse, PartitionCursor, SequencedCommitCursorRequest, SequencedCommitCursorResponse, StreamingCommitCursorRequest, StreamingCommitCursorResponse, ) from .publisher import ( InitialPublishRequest, InitialPublishResponse, MessagePublishRequest, MessagePublishResponse, PublishRequest, PublishResponse, ) from .subscriber import ( FlowControlRequest, InitialPartitionAssignmentRequest, InitialSubscribeRequest, InitialSubscribeResponse, MessageResponse, PartitionAssignment, PartitionAssignmentAck, PartitionAssignmentRequest, SeekRequest, SeekResponse, SubscribeRequest, SubscribeResponse, ) from .topic_stats import ( ComputeHeadCursorRequest, ComputeHeadCursorResponse, ComputeMessageStatsRequest, ComputeMessageStatsResponse, ComputeTimeCursorRequest, ComputeTimeCursorResponse, ) __all__ = ( "CreateReservationRequest", "CreateSubscriptionRequest", "CreateTopicRequest", "DeleteReservationRequest", "DeleteSubscriptionRequest", "DeleteTopicRequest", "GetReservationRequest", "GetSubscriptionRequest", "GetTopicPartitionsRequest", "GetTopicRequest", "ListReservationsRequest", "ListReservationsResponse", "ListReservationTopicsRequest", "ListReservationTopicsResponse", "ListSubscriptionsRequest", "ListSubscriptionsResponse", "ListTopicsRequest", "ListTopicsResponse", "ListTopicSubscriptionsRequest", "ListTopicSubscriptionsResponse", "OperationMetadata", "SeekSubscriptionRequest", "SeekSubscriptionResponse", "TopicPartitions", "UpdateReservationRequest", "UpdateSubscriptionRequest", "UpdateTopicRequest", "AttributeValues", "Cursor", "PubSubMessage", "Reservation", "SequencedMessage", "Subscription", "TimeTarget", "Topic", "CommitCursorRequest", "CommitCursorResponse", "InitialCommitCursorRequest", "InitialCommitCursorResponse", "ListPartitionCursorsRequest", "ListPartitionCursorsResponse", "PartitionCursor", "SequencedCommitCursorRequest", "SequencedCommitCursorResponse", "StreamingCommitCursorRequest", "StreamingCommitCursorResponse", "InitialPublishRequest", "InitialPublishResponse", "MessagePublishRequest", "MessagePublishResponse", "PublishRequest", "PublishResponse", "FlowControlRequest", "InitialPartitionAssignmentRequest", "InitialSubscribeRequest", "InitialSubscribeResponse", "MessageResponse", "PartitionAssignment", "PartitionAssignmentAck", "PartitionAssignmentRequest", "SeekRequest", "SeekResponse", "SubscribeRequest", "SubscribeResponse", "ComputeHeadCursorRequest", "ComputeHeadCursorResponse", "ComputeMessageStatsRequest", "ComputeMessageStatsResponse", "ComputeTimeCursorRequest", "ComputeTimeCursorResponse", )
apache-2.0
jounex/hue
desktop/core/ext-py/Mako-0.8.1/test/test_tgplugin.py
36
1260
import unittest from mako.ext.turbogears import TGPlugin from test.util import flatten_result, result_lines from test import TemplateTest, template_base tl = TGPlugin(options=dict(directories=[template_base]), extension='html') class TestTGPlugin(TemplateTest): def test_basic(self): t = tl.load_template('/index.html') assert result_lines(t.render()) == [ "this is index" ] def test_subdir(self): t = tl.load_template('/subdir/index.html') assert result_lines(t.render()) == [ "this is sub index", "this is include 2" ] assert tl.load_template('/subdir/index.html').module_id == '_subdir_index_html' def test_basic_dot(self): t = tl.load_template('index') assert result_lines(t.render()) == [ "this is index" ] def test_subdir_dot(self): t = tl.load_template('subdir.index') assert result_lines(t.render()) == [ "this is sub index", "this is include 2" ] assert tl.load_template('subdir.index').module_id == '_subdir_index_html' def test_string(self): t = tl.load_template('foo', "hello world") assert t.render() == "hello world"
apache-2.0
gisce/OCB
openerp/report/render/rml2pdf/__init__.py
75
1135
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from trml2pdf import parseString, parseNode #.apidoc title: RML to PDF engine # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
robosafe/testbench_vRAL_hydro
bert2_simulator/sim_step_monitors/assertion_monitor_manager.py
1
2830
#!/usr/bin/env python """ Assertion Monitor Manager Created by David Western, June 2015. """ from coverage import coverage import imp import rospkg import rospy from std_msgs.msg import UInt64 from std_srvs.srv import Empty import sys class AMM: def __init__(self,AM_list_file,trace_label): # Read list of assertion monitors to run (from file?): rospack = rospkg.RosPack() path = rospack.get_path('bert2_simulator') path = path+'/sim_step_monitors/' print("--- Assertion monitors to run:") self.AM_names = [line.rstrip('\n') for line in open(path+AM_list_file)] print(self.AM_names) # Instantiate assertion monitors: self.AMs = [] # Initialise empty list of AMs. for idx, class_name in enumerate(self.AM_names): print(class_name) print path+class_name+'.py' module = imp.load_source(class_name, path+class_name+'.py') #module = __import__(path+class_name) # N.B. These two lines imply that we class_ = getattr(module, class_name) # require the AM to be defined in a # file with the same name as the class. self.AMs.append(class_(trace_label)) # Check AM has the mandatory attributes: mand_attrs = ['step'] for attr in mand_attrs: if not hasattr(self.AMs[idx],attr): rospy.logerr("Assertion monitor specification '%s' does not define the attribute \ '%s', which is required by AMM (assertion_monitor_manager.py). \ Does %s inherite from an assertion monitor base class?", self.AMs[idx].__name__, attr, self.AMs[idx].__name__) # Get service self.unpause_gazebo = rospy.ServiceProxy('gazebo/unpause_physics',Empty) # Subscriber to triggers, which come on each sim step: rospy.Subscriber("AM_trigger", UInt64, self.trigger_AMs) def trigger_AMs(self,data): iteration = data.data sim_time = rospy.get_time() # Step all assertion monitors: for idx, AM in enumerate(self.AMs): AM.step(iteration,sim_time) # Release gazebo now we've finished the checks for this step: #print "unpausing" #self.unpause_gazebo() # Problem: This line prevents Gazebo's pause button from working (unless you # get a lucky click). if __name__ == '__main__': try: if len(sys.argv) < 3: print("usage: rosrun [package_name] assertion_monitor_manager.py AM_list_file.txt report_file_name") else: rospy.init_node('AMM') AMMInst = AMM(sys.argv[1],sys.argv[2]) rospy.spin() except rospy.ROSInterruptException: #to stop the code when pressing Ctr+c pass
gpl-3.0
ContinuumIO/chaco
examples/demo/xray_plot.py
3
5751
""" Implementation of a plot using a custom overlay and tool """ from __future__ import with_statement import numpy from traits.api import HasTraits, Instance, Enum from traitsui.api import View, Item from enable.api import ComponentEditor from chaco.api import Plot, ArrayPlotData, AbstractOverlay from enable.api import BaseTool from enable.markers import DOT_MARKER, DotMarker class BoxSelectTool(BaseTool): """ Tool for selecting all points within a box There are 2 states for this tool, normal and selecting. While the left mouse button is down the metadata on the datasources will be updated with the current selected bounds. Note that the tool does not actually store the selected point, but the bounds of the box. """ event_state = Enum("normal", "selecting") def normal_left_down(self, event): self.event_state = "selecting" self.selecting_mouse_move(event) def selecting_left_up(self, event): self.event_state = "normal" def selecting_mouse_move(self, event): x1, y1 = self.map_to_data(event.x - 25, event.y - 25) x2, y2 = self.map_to_data(event.x + 25, event.y + 25) index_datasource = self.component.index index_datasource.metadata['selections'] = (x1, x2) value_datasource = self.component.value value_datasource.metadata['selections'] = (y1, y2) self.component.request_redraw() def map_to_data(self, x, y): """ Returns the data space coordinates of the given x and y. Takes into account orientation of the plot and the axis setting. """ plot = self.component if plot.orientation == "h": index = plot.x_mapper.map_data(x) value = plot.y_mapper.map_data(y) else: index = plot.y_mapper.map_data(y) value = plot.x_mapper.map_data(x) return index, value class XRayOverlay(AbstractOverlay): """ Overlay which draws scatter markers on top of plot data points. This overlay should be combined with a tool which updates the datasources metadata with selection bounds. """ marker = DotMarker() def overlay(self, component, gc, view_bounds=None, mode='normal'): x_range = self._get_selection_index_screen_range() y_range = self._get_selection_value_screen_range() if len(x_range) == 0: return x1, x2 = x_range y1, y2 = y_range with gc: gc.set_alpha(0.8) gc.set_fill_color((1.0, 1.0, 1.0)) gc.rect(x1, y1, x2 - x1, y2 - y1) gc.draw_path() pts = self._get_selected_points() if len(pts) == 0: return screen_pts = self.component.map_screen(pts) if hasattr(gc, 'draw_marker_at_points'): gc.draw_marker_at_points(screen_pts, 3, DOT_MARKER) else: gc.save_state() for sx, sy in screen_pts: gc.translate_ctm(sx, sy) gc.begin_path() self.marker.add_to_path(gc, 3) gc.draw_path(self.marker.draw_mode) gc.translate_ctm(-sx, -sy) gc.restore_state() def _get_selected_points(self): """ gets all the points within the bounds defined in the datasources metadata """ index_datasource = self.component.index index_selection = index_datasource.metadata['selections'] index = index_datasource.get_data() value_datasource = self.component.value value_selection = value_datasource.metadata['selections'] value = value_datasource.get_data() x_indices = numpy.where((index > index_selection[0]) & (index < index_selection[-1])) y_indices = numpy.where((value > value_selection[0]) & (value < value_selection[-1])) indices = list(set(x_indices[0]) & set(y_indices[0])) sel_index = index[indices] sel_value = value[indices] return zip(sel_index, sel_value) def _get_selection_index_screen_range(self): """ maps the selected bounds which were set by the tool into screen space. The screen space points can be used for drawing the overlay """ index_datasource = self.component.index index_mapper = self.component.index_mapper index_selection = index_datasource.metadata['selections'] return tuple(index_mapper.map_screen(numpy.array(index_selection))) def _get_selection_value_screen_range(self): """ maps the selected bounds which were set by the tool into screen space. The screen space points can be used for drawing the overlay """ value_datasource = self.component.value value_mapper = self.component.value_mapper value_selection = value_datasource.metadata['selections'] return tuple(value_mapper.map_screen(numpy.array(value_selection))) class PlotExample(HasTraits): plot = Instance(Plot) traits_view = View(Item('plot', editor=ComponentEditor()), width=600, height=600) def __init__(self, index, value, *args, **kw): super(PlotExample, self).__init__(*args, **kw) plot_data = ArrayPlotData(index=index) plot_data.set_data('value', value) self.plot = Plot(plot_data) line = self.plot.plot(('index', 'value'))[0] line.overlays.append(XRayOverlay(line)) line.tools.append(BoxSelectTool(line)) index = numpy.arange(0, 25, 0.25) value = numpy.sin(index) + numpy.arange(0, 10, 0.1) example = PlotExample(index, value) example.configure_traits()
bsd-3-clause
xuweiliang/Codelibrary
nova/db/sqlalchemy/migrate_repo/versions/302_pgsql_add_instance_system_metadata_index.py
43
1322
# Copyright 2015 Huawei. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_db.sqlalchemy import utils INDEX_COLUMNS = ['instance_uuid'] # using the index name same with mysql INDEX_NAME = 'instance_uuid' SYS_META_TABLE_NAME = 'instance_system_metadata' def upgrade(migrate_engine): """Add instance_system_metadata indexes missing on PostgreSQL and other DB. """ # This index was already added by migration 216 for MySQL if migrate_engine.name != 'mysql': # Adds index for PostgreSQL and other DB if not utils.index_exists(migrate_engine, SYS_META_TABLE_NAME, INDEX_NAME): utils.add_index(migrate_engine, SYS_META_TABLE_NAME, INDEX_NAME, INDEX_COLUMNS)
apache-2.0
0x7E/ubuntu-tweak
ubuntutweak/settings/ccm/Utils.py
5
12852
# -*- coding: UTF-8 -*- # 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. # # Authors: Quinn Storm (quinn@beryl-project.org) # Patrick Niklaus (marex@opencompositing.org) # Guillaume Seguin (guillaume@segu.in) # Christopher Williams (christopherw@verizon.net) # Copyright (C) 2007 Quinn Storm import os import weakref from gi.repository import GObject, Gtk, Gdk, Pango from Constants import * from cgi import escape as protect_pango_markup import operator import itertools import locale import gettext locale.setlocale(locale.LC_ALL, "") gettext.bindtextdomain("ccsm", DataDir + "/locale") gettext.textdomain("ccsm") _ = gettext.gettext IconTheme = Gtk.IconTheme.get_default() #TODO #if not IconDir in IconTheme.get_search_path(): # IconTheme.prepend_search_path(IconDir) def gtk_process_events (): while Gtk.events_pending (): Gtk.main_iteration () def getScreens(): screens = [] display = Gdk.Display.get_default() nScreens = display.get_n_screens() for i in range(nScreens): screens.append(i) return screens def getDefaultScreen(): display = Gdk.Display.get_default() return display.get_default_screen().get_number() def protect_markup_dict (dict_): return dict((k, protect_pango_markup (v)) for (k, v) in dict_.items()) class Image (Gtk.Image): def __init__ (self, name = None, type = ImageNone, size = 32, useMissingImage = False): GObject.GObject.__init__ (self) if not name: return if useMissingImage: self.set_from_stock (Gtk.STOCK_MISSING_IMAGE, Gtk.IconSize.LARGE_TOOLBAR) return try: if type in (ImagePlugin, ImageCategory, ImageThemed): pixbuf = None if type == ImagePlugin: name = "plugin-" + name try: pixbuf = IconTheme.load_icon (name, size, 0) except GObject.GError: pixbuf = IconTheme.load_icon ("plugin-unknown", size, 0) elif type == ImageCategory: name = "plugins-" + name try: pixbuf = IconTheme.load_icon (name, size, 0) except GObject.GError: pixbuf = IconTheme.load_icon ("plugins-unknown", size, 0) else: pixbuf = IconTheme.load_icon (name, size, 0) self.set_from_pixbuf (pixbuf) elif type == ImageStock: self.set_from_stock (name, size) except GObject.GError as e: self.set_from_stock (Gtk.STOCK_MISSING_IMAGE, Gtk.IconSize.BUTTON) class ActionImage (Gtk.Alignment): map = { "keyboard" : "input-keyboard", "button" : "input-mouse", "edges" : "video-display", "bell" : "audio-x-generic" } def __init__ (self, action): GObject.GObject.__init__ (self, 0, 0.5) self.set_padding (0, 0, 0, 10) if action in self.map: action = self.map[action] self.add (Image (name = action, type = ImageThemed, size = 22)) class SizedButton (Gtk.Button): minWidth = -1 minHeight = -1 def __init__ (self, minWidth = -1, minHeight = -1): super (SizedButton, self).__init__ () self.minWidth = minWidth self.minHeight = minHeight self.connect ("size-request", self.adjust_size) def adjust_size (self, widget, requisition): width, height = requisition.width, requisition.height newWidth = max (width, self.minWidth) newHeight = max (height, self.minHeight) self.set_size_request (newWidth, newHeight) class PrettyButton (Gtk.Button): __gsignals__ = { 'draw': 'override', } _old_toplevel = None def __init__ (self): super (PrettyButton, self).__init__ () self.states = { "focus" : False, "pointer" : False } self.set_size_request (200, -1) self.set_relief (Gtk.ReliefStyle.NONE) self.connect ("focus-in-event", self.update_state_in, "focus") self.connect ("focus-out-event", self.update_state_out, "focus") self.connect ("hierarchy-changed", self.hierarchy_changed) def hierarchy_changed (self, widget, old_toplevel): if old_toplevel == self._old_toplevel: return if not old_toplevel and self.state != Gtk.StateType.NORMAL: self.set_state(Gtk.StateType.PRELIGHT) self.set_state(Gtk.StateType.NORMAL) self._old_toplevel = old_toplevel def update_state_in (self, *args): state = args[-1] self.set_state (Gtk.StateType.PRELIGHT) self.states[state] = True def update_state_out (self, *args): state = args[-1] self.states[state] = False if True in self.states.values (): self.set_state (Gtk.StateType.PRELIGHT) else: self.set_state (Gtk.StateType.NORMAL) def do_expose_event (self, event): has_focus = self.flags () & Gtk.HAS_FOCUS if has_focus: self.unset_flags (Gtk.HAS_FOCUS) ret = super (PrettyButton, self).do_expose_event (self, event) if has_focus: self.set_flags (Gtk.HAS_FOCUS) return ret class Label(Gtk.Label): def __init__(self, value = "", wrap = 160): GObject.GObject.__init__(self, value) self.props.xalign = 0 self.props.wrap_mode = Pango.WrapMode.WORD self.set_line_wrap(True) self.set_size_request(wrap, -1) class NotFoundBox(Gtk.Alignment): def __init__(self, value=""): GObject.GObject.__init__(self, 0.5, 0.5, 0.0, 0.0) box = Gtk.HBox() self.Warning = Gtk.Label() self.Markup = _("<span size=\"large\"><b>No matches found.</b> </span><span>\n\n Your filter \"<b>%s</b>\" does not match any items.</span>") value = protect_pango_markup(value) self.Warning.set_markup(self.Markup % value) image = Image("face-surprise", ImageThemed, 48) box.pack_start(image, False, False, 0) box.pack_start(self.Warning, True, True, 15) self.add(box) def update(self, value): value = protect_pango_markup(value) self.Warning.set_markup(self.Markup % value) class IdleSettingsParser: def __init__(self, context, main): def FilterPlugin (p): return not p.Initialized and p.Enabled self.Context = context self.Main = main self.PluginList = [p for p in self.Context.Plugins.items() if FilterPlugin(p[1])] nCategories = len (main.MainPage.RightWidget._boxes) self.CategoryLoadIconsList = list(range(3, nCategories)) # Skip the first 3 print('Loading icons...') GObject.timeout_add (150, self.Wait) def Wait(self): if not self.PluginList: return False if len (self.CategoryLoadIconsList) == 0: # If we're done loading icons GObject.idle_add (self.ParseSettings) else: GObject.idle_add (self.LoadCategoryIcons) return False def ParseSettings(self): name, plugin = self.PluginList[0] if not plugin.Initialized: plugin.Update () self.Main.RefreshPage(plugin) self.PluginList.remove (self.PluginList[0]) GObject.timeout_add (200, self.Wait) return False def LoadCategoryIcons(self): from ccm.Widgets import PluginButton catIndex = self.CategoryLoadIconsList[0] pluginWindow = self.Main.MainPage.RightWidget categoryBox = pluginWindow._boxes[catIndex] for (pluginIndex, plugin) in \ enumerate (categoryBox.get_unfiltered_plugins()): categoryBox._buttons[pluginIndex] = PluginButton (plugin) categoryBox.rebuild_table (categoryBox._current_cols, True) pluginWindow.connect_buttons (categoryBox) self.CategoryLoadIconsList.remove (self.CategoryLoadIconsList[0]) GObject.timeout_add (150, self.Wait) return False # Updates all registered setting when they where changed through CompizConfig class Updater: def __init__ (self): self.VisibleSettings = {} self.Plugins = [] self.Block = 0 def SetContext (self, context): self.Context = context GObject.timeout_add (2000, self.Update) def Append (self, widget): reference = weakref.ref(widget) setting = widget.Setting self.VisibleSettings.setdefault((setting.Plugin.Name, setting.Name), []).append(reference) def AppendPlugin (self, plugin): self.Plugins.append (plugin) def Remove (self, widget): setting = widget.Setting l = self.VisibleSettings.get((setting.Plugin.Name, setting.Name)) if not l: return for i, ref in enumerate(list(l)): if ref() is widget: l.remove(ref) break def UpdatePlugins(self): for plugin in self.Plugins: plugin.Read() def UpdateSetting (self, setting): widgets = self.VisibleSettings.get((setting.Plugin.Name, setting.Name)) if not widgets: return for reference in widgets: widget = reference() if widget is not None: widget.Read() def Update (self): if self.Block > 0: return True if self.Context.ProcessEvents(): changed = self.Context.ChangedSettings if [s for s in changed if s.Plugin.Name == "core" and s.Name == "active_plugins"]: self.UpdatePlugins() for setting in list(changed): widgets = self.VisibleSettings.get((setting.Plugin.Name, setting.Name)) if widgets: for reference in widgets: widget = reference() if widget is not None: widget.Read() if widget.List: widget.ListWidget.Read() changed.remove(setting) self.Context.ChangedSettings = changed return True GlobalUpdater = Updater () class PluginSetting: def __init__ (self, plugin, widget, handler): self.Widget = widget self.Plugin = plugin self.Handler = handler GlobalUpdater.AppendPlugin (self) def Read (self): widget = self.Widget widget.handler_block(self.Handler) widget.set_active (self.Plugin.Enabled) widget.set_sensitive (self.Plugin.Context.AutoSort) widget.handler_unblock(self.Handler) class PureVirtualError(Exception): pass def SettingKeyFunc(value): return value.Plugin.Ranking[value.Name] def CategoryKeyFunc(category): if 'General' == category: return '' else: return category or 'zzzzzzzz' def GroupIndexKeyFunc(item): return item[1][0] FirstItemKeyFunc = operator.itemgetter(0) EnumSettingKeyFunc = operator.itemgetter(1) PluginKeyFunc = operator.attrgetter('ShortDesc') def HasOnlyType (settings, stype): return settings and not [s for s in settings if s.Type != stype] def GetSettings(group, types=None): def TypeFilter (settings, types): for setting in settings: if setting.Type in types: yield setting if types: screen = TypeFilter(iter(group.Screen.values()), types) else: screen = iter(group.Screen.values()) return screen # Support python 2.4 try: any all except NameError: def any(iterable): for element in iterable: if element: return True return False def all(iterable): for element in iterable: if not element: return False return True
gpl-2.0
YongseopKim/crosswalk-test-suite
webapi/tct-csp-w3c-tests/csp-py/csp_media-src_none_audio_blocked_int.py
30
3064
def main(request, response): import simplejson as json f = file('config.json') source = f.read() s = json.JSONDecoder().decode(source) url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1]) url2 = "http://" + s['host'] + ":" + str(s['ports']['http'][0]) _CSP = "media-src 'none'; script-src 'self' 'unsafe-inline'" response.headers.set("Content-Security-Policy", _CSP) response.headers.set("X-Content-Security-Policy", _CSP) response.headers.set("X-WebKit-CSP", _CSP) return """<!DOCTYPE html> <!-- Copyright (c) 2013 Intel Corporation. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of works must retain the original copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the original 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 Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this work without specific prior written permission. THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "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 INTEL CORPORATION 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. Authors: Zhang, Zhiqiang <zhiqiang.zhang@intel.com> --> <html> <head> <title>CSP Test: csp_media-src_none_audio_blocked_int</title> <link rel="author" title="Intel" href="http://www.intel.com"/> <link rel="help" href="http://www.w3.org/TR/2012/CR-CSP-20121115/#media-src"/> <meta name="flags" content=""/> <meta name="assert" content="media-src *; script-src 'self' 'unsafe-inline'"/> <meta charset="utf-8"/> <script src="../resources/testharness.js"></script> <script src="../resources/testharnessreport.js"></script> </head> <body> <div id="log"></div> <audio id="m"></audio> <script> var t = async_test(document.title); var m = document.getElementById("m"); m.src = "support/khronos/red-green.theora.ogv"; window.setTimeout(function() { t.step(function() { assert_true(m.currentSrc == "", "audio.currentSrc should be empty after setting src attribute"); }); t.done(); }, 0); </script> </body> </html> """
bsd-3-clause
gccpacman/shadowsocks
shadowsocks/shell.py
652
12736
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright 2015 clowwindy # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import, division, print_function, \ with_statement import os import json import sys import getopt import logging from shadowsocks.common import to_bytes, to_str, IPNetwork from shadowsocks import encrypt VERBOSE_LEVEL = 5 verbose = 0 def check_python(): info = sys.version_info if info[0] == 2 and not info[1] >= 6: print('Python 2.6+ required') sys.exit(1) elif info[0] == 3 and not info[1] >= 3: print('Python 3.3+ required') sys.exit(1) elif info[0] not in [2, 3]: print('Python version not supported') sys.exit(1) def print_exception(e): global verbose logging.error(e) if verbose > 0: import traceback traceback.print_exc() def print_shadowsocks(): version = '' try: import pkg_resources version = pkg_resources.get_distribution('shadowsocks').version except Exception: pass print('Shadowsocks %s' % version) def find_config(): config_path = 'config.json' if os.path.exists(config_path): return config_path config_path = os.path.join(os.path.dirname(__file__), '../', 'config.json') if os.path.exists(config_path): return config_path return None def check_config(config, is_local): if config.get('daemon', None) == 'stop': # no need to specify configuration for daemon stop return if is_local and not config.get('password', None): logging.error('password not specified') print_help(is_local) sys.exit(2) if not is_local and not config.get('password', None) \ and not config.get('port_password', None) \ and not config.get('manager_address'): logging.error('password or port_password not specified') print_help(is_local) sys.exit(2) if 'local_port' in config: config['local_port'] = int(config['local_port']) if config.get('server_port', None) and type(config['server_port']) != list: config['server_port'] = int(config['server_port']) if config.get('local_address', '') in [b'0.0.0.0']: logging.warn('warning: local set to listen on 0.0.0.0, it\'s not safe') if config.get('server', '') in ['127.0.0.1', 'localhost']: logging.warn('warning: server set to listen on %s:%s, are you sure?' % (to_str(config['server']), config['server_port'])) if (config.get('method', '') or '').lower() == 'table': logging.warn('warning: table is not safe; please use a safer cipher, ' 'like AES-256-CFB') if (config.get('method', '') or '').lower() == 'rc4': logging.warn('warning: RC4 is not safe; please use a safer cipher, ' 'like AES-256-CFB') if config.get('timeout', 300) < 100: logging.warn('warning: your timeout %d seems too short' % int(config.get('timeout'))) if config.get('timeout', 300) > 600: logging.warn('warning: your timeout %d seems too long' % int(config.get('timeout'))) if config.get('password') in [b'mypassword']: logging.error('DON\'T USE DEFAULT PASSWORD! Please change it in your ' 'config.json!') sys.exit(1) if config.get('user', None) is not None: if os.name != 'posix': logging.error('user can be used only on Unix') sys.exit(1) encrypt.try_cipher(config['password'], config['method']) def get_config(is_local): global verbose logging.basicConfig(level=logging.INFO, format='%(levelname)-s: %(message)s') if is_local: shortopts = 'hd:s:b:p:k:l:m:c:t:vq' longopts = ['help', 'fast-open', 'pid-file=', 'log-file=', 'user=', 'version'] else: shortopts = 'hd:s:p:k:m:c:t:vq' longopts = ['help', 'fast-open', 'pid-file=', 'log-file=', 'workers=', 'forbidden-ip=', 'user=', 'manager-address=', 'version'] try: config_path = find_config() optlist, args = getopt.getopt(sys.argv[1:], shortopts, longopts) for key, value in optlist: if key == '-c': config_path = value if config_path: logging.info('loading config from %s' % config_path) with open(config_path, 'rb') as f: try: config = parse_json_in_str(f.read().decode('utf8')) except ValueError as e: logging.error('found an error in config.json: %s', e.message) sys.exit(1) else: config = {} v_count = 0 for key, value in optlist: if key == '-p': config['server_port'] = int(value) elif key == '-k': config['password'] = to_bytes(value) elif key == '-l': config['local_port'] = int(value) elif key == '-s': config['server'] = to_str(value) elif key == '-m': config['method'] = to_str(value) elif key == '-b': config['local_address'] = to_str(value) elif key == '-v': v_count += 1 # '-vv' turns on more verbose mode config['verbose'] = v_count elif key == '-t': config['timeout'] = int(value) elif key == '--fast-open': config['fast_open'] = True elif key == '--workers': config['workers'] = int(value) elif key == '--manager-address': config['manager_address'] = value elif key == '--user': config['user'] = to_str(value) elif key == '--forbidden-ip': config['forbidden_ip'] = to_str(value).split(',') elif key in ('-h', '--help'): if is_local: print_local_help() else: print_server_help() sys.exit(0) elif key == '--version': print_shadowsocks() sys.exit(0) elif key == '-d': config['daemon'] = to_str(value) elif key == '--pid-file': config['pid-file'] = to_str(value) elif key == '--log-file': config['log-file'] = to_str(value) elif key == '-q': v_count -= 1 config['verbose'] = v_count except getopt.GetoptError as e: print(e, file=sys.stderr) print_help(is_local) sys.exit(2) if not config: logging.error('config not specified') print_help(is_local) sys.exit(2) config['password'] = to_bytes(config.get('password', b'')) config['method'] = to_str(config.get('method', 'aes-256-cfb')) config['port_password'] = config.get('port_password', None) config['timeout'] = int(config.get('timeout', 300)) config['fast_open'] = config.get('fast_open', False) config['workers'] = config.get('workers', 1) config['pid-file'] = config.get('pid-file', '/var/run/shadowsocks.pid') config['log-file'] = config.get('log-file', '/var/log/shadowsocks.log') config['verbose'] = config.get('verbose', False) config['local_address'] = to_str(config.get('local_address', '127.0.0.1')) config['local_port'] = config.get('local_port', 1080) if is_local: if config.get('server', None) is None: logging.error('server addr not specified') print_local_help() sys.exit(2) else: config['server'] = to_str(config['server']) else: config['server'] = to_str(config.get('server', '0.0.0.0')) try: config['forbidden_ip'] = \ IPNetwork(config.get('forbidden_ip', '127.0.0.0/8,::1/128')) except Exception as e: logging.error(e) sys.exit(2) config['server_port'] = config.get('server_port', None) logging.getLogger('').handlers = [] logging.addLevelName(VERBOSE_LEVEL, 'VERBOSE') if config['verbose'] >= 2: level = VERBOSE_LEVEL elif config['verbose'] == 1: level = logging.DEBUG elif config['verbose'] == -1: level = logging.WARN elif config['verbose'] <= -2: level = logging.ERROR else: level = logging.INFO verbose = config['verbose'] logging.basicConfig(level=level, format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S') check_config(config, is_local) return config def print_help(is_local): if is_local: print_local_help() else: print_server_help() def print_local_help(): print('''usage: sslocal [OPTION]... A fast tunnel proxy that helps you bypass firewalls. You can supply configurations via either config file or command line arguments. Proxy options: -c CONFIG path to config file -s SERVER_ADDR server address -p SERVER_PORT server port, default: 8388 -b LOCAL_ADDR local binding address, default: 127.0.0.1 -l LOCAL_PORT local port, default: 1080 -k PASSWORD password -m METHOD encryption method, default: aes-256-cfb -t TIMEOUT timeout in seconds, default: 300 --fast-open use TCP_FASTOPEN, requires Linux 3.7+ General options: -h, --help show this help message and exit -d start/stop/restart daemon mode --pid-file PID_FILE pid file for daemon mode --log-file LOG_FILE log file for daemon mode --user USER username to run as -v, -vv verbose mode -q, -qq quiet mode, only show warnings/errors --version show version information Online help: <https://github.com/shadowsocks/shadowsocks> ''') def print_server_help(): print('''usage: ssserver [OPTION]... A fast tunnel proxy that helps you bypass firewalls. You can supply configurations via either config file or command line arguments. Proxy options: -c CONFIG path to config file -s SERVER_ADDR server address, default: 0.0.0.0 -p SERVER_PORT server port, default: 8388 -k PASSWORD password -m METHOD encryption method, default: aes-256-cfb -t TIMEOUT timeout in seconds, default: 300 --fast-open use TCP_FASTOPEN, requires Linux 3.7+ --workers WORKERS number of workers, available on Unix/Linux --forbidden-ip IPLIST comma seperated IP list forbidden to connect --manager-address ADDR optional server manager UDP address, see wiki General options: -h, --help show this help message and exit -d start/stop/restart daemon mode --pid-file PID_FILE pid file for daemon mode --log-file LOG_FILE log file for daemon mode --user USER username to run as -v, -vv verbose mode -q, -qq quiet mode, only show warnings/errors --version show version information Online help: <https://github.com/shadowsocks/shadowsocks> ''') def _decode_list(data): rv = [] for item in data: if hasattr(item, 'encode'): item = item.encode('utf-8') elif isinstance(item, list): item = _decode_list(item) elif isinstance(item, dict): item = _decode_dict(item) rv.append(item) return rv def _decode_dict(data): rv = {} for key, value in data.items(): if hasattr(value, 'encode'): value = value.encode('utf-8') elif isinstance(value, list): value = _decode_list(value) elif isinstance(value, dict): value = _decode_dict(value) rv[key] = value return rv def parse_json_in_str(data): # parse json and convert everything from unicode to str return json.loads(data, object_hook=_decode_dict)
apache-2.0
reingart/rad2py
assignments/program10A.py
16
3944
#!/usr/bin/env python # coding:utf-8 "PSP Program 6A - Linear Regression Prediction Interval" __author__ = "Mariano Reingart (reingart@gmail.com)" __copyright__ = "Copyright (C) 2011 Mariano Reingart" __license__ = "GPL 3.0" from math import sqrt, pi # reuse previous programs from program1A import mean from program5A import simpson_rule_integrate, gamma def double_sided_student_t_probability(t, n): "Calculate the p-value using a double sided student t distribution" # create the function for n degrees of freedom: k = gamma(n + 1, 2) / (sqrt(n * pi) * gamma(n, 2)) f_t_dist = lambda u: k * (1 + (u ** 2) / float(n)) ** (- (n + 1) / 2.0) # integrate a finite area from the origin to t p_aux = simpson_rule_integrate(f_t_dist, 0, t) # return the area of the two tails of the distribution (symmetrical) return (0.5 - p_aux) * 2 def double_sided_student_t_value(p, n): "Calculate the t-value using a double sided student t distribution" # replaces table lookup, thanks to http://statpages.org/pdfs.html v = dv = 0.5 t = 0 while dv > 0.000001: t = 1 / v - 1 dv = dv / 2 if double_sided_student_t_probability(t, n) > p: v = v - dv else: v = v + dv return t def variance(x_values, y_values, b0, b1): "Calculate the mean square deviation of the linear regeression line" # take the variance from the regression line instead of the data average sum_aux = sum([(y - b0 - b1 * x) ** 2 for x, y in zip(x_values, y_values)]) n = float(len(x_values)) return (1 / (n - 2.0)) * sum_aux def prediction_interval(x_values, y_values, x_k, alpha): """Calculate the linear regression parameters for a set of n values then calculate the upper and lower prediction interval """ # calculate aux variables x_avg = mean(x_values) y_avg = mean(y_values) n = len(x_values) sum_xy = sum([(x_values[i] * y_values[i]) for i in range(n)]) sum_x2 = sum([(x_values[i] ** 2) for i in range(n)]) # calculate regression coefficients b1 = (sum_xy - (n * x_avg * y_avg)) / (sum_x2 - n * (x_avg ** 2)) b0 = y_avg - b1 * x_avg # calculate the t-value for the given alpha p-value t = double_sided_student_t_value(1 - alpha, n - 2) # calculate the standard deviation sigma = sqrt(variance(x_values, y_values, b0, b1)) # calculate the range sum_xi_xavg = sum([(x - x_avg) ** 2 for x in x_values], 0.0) aux = 1 + (1 / float(n)) + ((x_k - x_avg) ** 2) / sum_xi_xavg p_range = t * sigma * sqrt(aux) # combine the range with the x_k projection: return b0, b1, p_range, x_k + p_range, x_k - p_range, t def test_student_t_integration(): # test student t values assert round(double_sided_student_t_probability(t=1.8595, n=8), 4) == 0.1 assert round(double_sided_student_t_value(p=0.1, n=8), 4) == 1.8595 if __name__ == "__main__": test_student_t_integration() # Table D8 "Size Estimating regression data" est_loc = [130, 650, 99, 150, 128, 302, 95, 945, 368, 961] act_new_chg_loc = [186, 699, 132, 272, 291, 331, 199, 1890, 788, 1601] projection = 644.429 # 70 percent b0, b1, p_range, upi, lpi, t = prediction_interval( est_loc, act_new_chg_loc, projection, alpha=0.7) print "70% Prediction interval: ", b0, b1, p_range, upi, lpi, t assert round(t, 3) == 1.108 assert round(b0, 2) == -22.55 assert round(b1, 4) == 1.7279 assert round(p_range, 3) == 236.563 assert round(upi, 2) == 880.99 assert round(lpi, 2) == 407.87 # 90 percent b0, b1, p_range, upi, lpi, t = prediction_interval( est_loc, act_new_chg_loc, projection, alpha=0.9) print "90% Prediction interval: ", b0, b1, p_range, upi, lpi, t assert round(t, 2) == 1.86 assert round(p_range, 2) == 396.97 assert round(upi, 2) == 1041.4 assert round(lpi, 2) == 247.46
gpl-3.0
40223245/2015cdb_g6-team1
static/Brython3.1.1-20150328-091302/Lib/site-packages/highlight.py
617
2518
import keyword import _jsre as re from browser import html letters = 'abcdefghijklmnopqrstuvwxyz' letters += letters.upper()+'_' digits = '0123456789' builtin_funcs = ("abs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|" + "eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|" + "binfile|iter|property|tuple|bool|filter|len|range|type|bytearray|" + "float|list|raw_input|unichr|callable|format|locals|reduce|unicode|" + "chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|" + "cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|" + "__import__|complex|hash|min|set|apply|delattr|help|next|setattr|" + "buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern") kw_pattern = '^('+'|'.join(keyword.kwlist)+')$' bf_pattern = '^('+builtin_funcs+')$' def highlight(txt, string_color="blue", comment_color="green", keyword_color="purple"): res = html.PRE() i = 0 name = '' while i<len(txt): car = txt[i] if car in ["'",'"']: k = i+1 while k<len(txt): if txt[k]==car: nb_as = 0 j = k-1 while True: if txt[j]=='\\': nb_as+=1 j -= 1 else: break if nb_as % 2 == 0: res <= html.SPAN(txt[i:k+1], style=dict(color=string_color)) i = k break k += 1 elif car == '#': # comment end = txt.find('\n', i) if end== -1: res <= html.SPAN(txt[i:],style=dict(color=comment_color)) break else: res <= html.SPAN(txt[i:end],style=dict(color=comment_color)) i = end-1 elif car in letters: name += car elif car in digits and name: name += car else: if name: if re.search(kw_pattern,name): res <= html.SPAN(name,style=dict(color=keyword_color)) elif re.search(bf_pattern,name): res <= html.SPAN(name,style=dict(color=keyword_color)) else: res <= name name = '' res <= car i += 1 res <= name return res
gpl-3.0
JeremyRubin/bitcoin
test/functional/test_framework/siphash.py
91
2014
#!/usr/bin/env python3 # Copyright (c) 2016-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. """Specialized SipHash-2-4 implementations. This implements SipHash-2-4 for 256-bit integers. """ def rotl64(n, b): return n >> (64 - b) | (n & ((1 << (64 - b)) - 1)) << b def siphash_round(v0, v1, v2, v3): v0 = (v0 + v1) & ((1 << 64) - 1) v1 = rotl64(v1, 13) v1 ^= v0 v0 = rotl64(v0, 32) v2 = (v2 + v3) & ((1 << 64) - 1) v3 = rotl64(v3, 16) v3 ^= v2 v0 = (v0 + v3) & ((1 << 64) - 1) v3 = rotl64(v3, 21) v3 ^= v0 v2 = (v2 + v1) & ((1 << 64) - 1) v1 = rotl64(v1, 17) v1 ^= v2 v2 = rotl64(v2, 32) return (v0, v1, v2, v3) def siphash256(k0, k1, h): n0 = h & ((1 << 64) - 1) n1 = (h >> 64) & ((1 << 64) - 1) n2 = (h >> 128) & ((1 << 64) - 1) n3 = (h >> 192) & ((1 << 64) - 1) v0 = 0x736f6d6570736575 ^ k0 v1 = 0x646f72616e646f6d ^ k1 v2 = 0x6c7967656e657261 ^ k0 v3 = 0x7465646279746573 ^ k1 ^ n0 v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0 ^= n0 v3 ^= n1 v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0 ^= n1 v3 ^= n2 v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0 ^= n2 v3 ^= n3 v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0 ^= n3 v3 ^= 0x2000000000000000 v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0 ^= 0x2000000000000000 v2 ^= 0xFF v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) v0, v1, v2, v3 = siphash_round(v0, v1, v2, v3) return v0 ^ v1 ^ v2 ^ v3
mit
tempesta-tech/linux-4.1-tfw
tools/perf/scripts/python/failed-syscalls-by-pid.py
1996
2233
# failed system call counts, by pid # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # Displays system-wide failed system call totals, broken down by pid. # If a [comm] arg is specified, only syscalls called by [comm] are displayed. import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * usage = "perf script -s syscall-counts-by-pid.py [comm|pid]\n"; for_comm = None for_pid = None if len(sys.argv) > 2: sys.exit(usage) if len(sys.argv) > 1: try: for_pid = int(sys.argv[1]) except: for_comm = sys.argv[1] syscalls = autodict() def trace_begin(): print "Press control+C to stop and show the summary" def trace_end(): print_error_totals() def raw_syscalls__sys_exit(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, common_callchain, id, ret): if (for_comm and common_comm != for_comm) or \ (for_pid and common_pid != for_pid ): return if ret < 0: try: syscalls[common_comm][common_pid][id][ret] += 1 except TypeError: syscalls[common_comm][common_pid][id][ret] = 1 def syscalls__sys_exit(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, id, ret): raw_syscalls__sys_exit(**locals()) def print_error_totals(): if for_comm is not None: print "\nsyscall errors for %s:\n\n" % (for_comm), else: print "\nsyscall errors:\n\n", print "%-30s %10s\n" % ("comm [pid]", "count"), print "%-30s %10s\n" % ("------------------------------", \ "----------"), comm_keys = syscalls.keys() for comm in comm_keys: pid_keys = syscalls[comm].keys() for pid in pid_keys: print "\n%s [%d]\n" % (comm, pid), id_keys = syscalls[comm][pid].keys() for id in id_keys: print " syscall: %-16s\n" % syscall_name(id), ret_keys = syscalls[comm][pid][id].keys() for ret, val in sorted(syscalls[comm][pid][id].iteritems(), key = lambda(k, v): (v, k), reverse = True): print " err = %-20s %10d\n" % (strerror(ret), val),
gpl-2.0
yuanke/hadoop-hbase
contrib/hod/hodlib/Common/setup.py
182
45814
#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. # $Id:setup.py 5158 2007-04-09 00:14:35Z zim $ # $Id:setup.py 5158 2007-04-09 00:14:35Z zim $ # #------------------------------------------------------------------------------ """'setup' provides for reading and verifing configuration files based on Python's SafeConfigParser class.""" import sys, os, re, pprint from ConfigParser import SafeConfigParser from optparse import OptionParser, IndentedHelpFormatter, OptionGroup from util import get_perms, replace_escapes from types import typeValidator, typeValidatorInstance, is_valid_type, \ typeToString from hodlib.Hod.hod import hodHelp reEmailAddress = re.compile("^.*@.*$") reEmailDelimit = re.compile("@") reComma = re.compile("\s*,\s*") reDot = re.compile("\.") reCommentHack = re.compile("^.*?\s+#|;.*", flags=re.S) reCommentNewline = re.compile("\n|\r$") reKeyVal = r"(?<!\\)=" reKeyVal = re.compile(reKeyVal) reKeyValList = r"(?<!\\)," reKeyValList = re.compile(reKeyValList) errorPrefix = 'error' requiredPerms = '0660' class definition: def __init__(self): """Generates a configuration definition object.""" self.__def = {} self.__defOrder = [] def __repr__(self): return pprint.pformat(self.__def) def __getitem__(self, section): return self.__def[section] def __iter__(self): return iter(self.__def) def sections(self): """Returns a list of sections/groups.""" if len(self.__defOrder): return self.__defOrder else: return self.__def.keys() def add_section(self, section): """Add a configuration section / option group.""" if self.__def.has_key(section): raise Exception("Section already exists: '%s'" % section) else: self.__def[section] = {} def add_def(self, section, var, type, desc, help = True, default = None, req = True, validate = True, short = None): """ Add a variable definition. section - section name var - variable name type - valid hodlib.types desc - description of variable help - display help for this variable default - default value req - bool, requried? validate - bool, validate type value? short - short symbol (1 character), help - bool, display help?""" if self.__def.has_key(section): if not is_valid_type(type): raise Exception("Type (type) is invalid: %s.%s - '%s'" % (section, var, type)) if not isinstance(desc, str): raise Exception("Description (desc) must be a string: %s.%s - '%s'" % ( section, var, desc)) if not isinstance(req, bool): raise Exception("Required (req) must be a bool: %s.%s - '%s'" % (section, var, req)) if not isinstance(validate, bool): raise Exception("Validate (validate) must be a bool: %s.%s - '%s'" % ( section, var, validate)) if self.__def[section].has_key(var): raise Exception("Variable name already defined: '%s'" % var) else: self.__def[section][var] = { 'type' : type, 'desc' : desc, 'help' : help, 'default' : default, 'req' : req, 'validate' : validate, 'short' : short } else: raise Exception("Section does not exist: '%s'" % section) def add_defs(self, defList, defOrder=None): """ Add a series of definitions. defList = { section0 : ((name0, type0, desc0, help0, default0, req0, validate0, short0), .... (nameN, typeN, descN, helpN, defaultN, reqN, validateN, shortN)), .... sectionN : ... } Where the short synmbol is optional and can only be one char.""" for section in defList.keys(): self.add_section(section) for defTuple in defList[section]: if isinstance(defTuple, tuple): if len(defTuple) < 7: raise Exception( "section %s is missing an element: %s" % ( section, pprint.pformat(defTuple))) else: raise Exception("section %s of defList is not a tuple" % section) if len(defTuple) == 7: self.add_def(section, defTuple[0], defTuple[1], defTuple[2], defTuple[3], defTuple[4], defTuple[5], defTuple[6]) else: self.add_def(section, defTuple[0], defTuple[1], defTuple[2], defTuple[3], defTuple[4], defTuple[5], defTuple[6], defTuple[7]) if defOrder: for section in defOrder: if section in self.__def: self.__defOrder.append(section) for section in self.__def: if not section in defOrder: raise Exception( "section %s is missing from specified defOrder." % section) class baseConfig: def __init__(self, configDef, originalDir=None): self.__toString = typeToString() self.__validated = False self._configDef = configDef self._options = None self._mySections = [] self._dict = {} self.configFile = None self.__originalDir = originalDir if self._configDef: self._mySections = configDef.sections() def __repr__(self): """Returns a string representation of a config object including all normalizations.""" print_string = ''; for section in self._mySections: print_string = "%s[%s]\n" % (print_string, section) options = self._dict[section].keys() for option in options: print_string = "%s%s = %s\n" % (print_string, option, self._dict[section][option]) print_string = "%s\n" % (print_string) print_string = re.sub("\n\n$", "", print_string) return print_string def __getitem__(self, section): """ Returns a dictionary of configuration name and values by section. """ return self._dict[section] def __setitem__(self, section, value): self._dict[section] = value def __iter__(self): return iter(self._dict) def has_key(self, section): status = False if section in self._dict: status = True return status # Prints configuration error messages def var_error(self, section, option, *addData): errorStrings = [] if not self._dict[section].has_key(option): self._dict[section][option] = None errorStrings.append("%s: invalid '%s' specified in section %s (--%s.%s): %s" % ( errorPrefix, option, section, section, option, self._dict[section][option])) if addData: errorStrings.append("%s: additional info: %s\n" % (errorPrefix, addData[0])) return errorStrings def var_error_suggest(self, errorStrings): if self.configFile: errorStrings.append("Check your command line options and/or " + \ "your configuration file %s" % self.configFile) def __get_args(self, section): def __dummyToString(type, value): return value toString = __dummyToString if self.__validated: toString = self.__toString args = [] if isinstance(self._dict[section], dict): for option in self._dict[section]: if section in self._configDef and \ option in self._configDef[section]: if self._configDef[section][option]['type'] == 'bool': if self._dict[section][option] == 'True' or \ self._dict[section][option] == True: args.append("--%s.%s" % (section, option)) else: args.append("--%s.%s" % (section, option)) args.append(toString( self._configDef[section][option]['type'], self._dict[section][option])) else: if section in self._configDef: if self._configDef[section][option]['type'] == 'bool': if self._dict[section] == 'True' or \ self._dict[section] == True: args.append("--%s" % section) else: if self._dict[section] != 'config': args.append("--%s" % section) args.append(toString(self._configDef[section]['type'], self._dict[section])) return args def values(self): return self._dict.values() def keys(self): return self._dict.keys() def get_args(self, exclude=None, section=None): """Retrieve a tuple of config arguments.""" args = [] if section: args = self.__get_args(section) else: for section in self._dict: if exclude: if not section in exclude: args.extend(self.__get_args(section)) else: args.extend(self.__get_args(section)) return tuple(args) def verify(self): """Verifies each configuration variable, using the configValidator class, based on its type as defined by the dictionary configDef. Upon encountering a problem an error is printed to STDERR and false is returned.""" oldDir = os.getcwd() if self.__originalDir: os.chdir(self.__originalDir) status = True statusMsgs = [] if self._configDef: errorCount = 0 configValidator = typeValidator(self.__originalDir) # foreach section and option by type string as defined in configDef # add value to be validated to validator for section in self._mySections: for option in self._configDef[section].keys(): configVarName = "%s.%s" % (section, option) if self._dict[section].has_key(option): if self._configDef[section][option].has_key('validate'): if self._configDef[section][option]['validate']: # is the section.option needed to be validated? configValidator.add(configVarName, self._configDef[section][option]['type'], self._dict[section][option]) else: # If asked not to validate, just normalize self[section][option] = \ configValidator.normalize( self._configDef[section][option]['type'], self._dict[section][option]) if self._configDef[section][option]['default'] != \ None: self._configDef[section][option]['default'] = \ configValidator.normalize( self._configDef[section][option]['type'], self._configDef[section][option]['default'] ) self._configDef[section][option]['default'] = \ self.__toString( self._configDef[section][option]['type'], self._configDef[section][option]['default'] ) else: # This should not happen. Just in case, take this as 'to be validated' case. configValidator.add(configVarName, self._configDef[section][option]['type'], self._dict[section][option]) elif self._configDef[section][option]['req']: statusMsgs.append("%s: %s.%s is not defined." % (errorPrefix, section, option)) errorCount = errorCount + 1 configValidator.validate() for valueInfo in configValidator.validatedInfo: sectionsOptions = reDot.split(valueInfo['name']) if valueInfo['isValid'] == 1: self._dict[sectionsOptions[0]][sectionsOptions[1]] = \ valueInfo['normalized'] else: if valueInfo['errorData']: statusMsgs.extend(self.var_error(sectionsOptions[0], sectionsOptions[1], valueInfo['errorData'])) else: statusMsgs.extend(self.var_error(sectionsOptions[0], sectionsOptions[1])) errorCount = errorCount + 1 if errorCount > 1: statusMsgs.append( "%s: %s problems found." % ( errorPrefix, errorCount)) self.var_error_suggest(statusMsgs) status = False elif errorCount > 0: statusMsgs.append( "%s: %s problem found." % ( errorPrefix, errorCount)) self.var_error_suggest(statusMsgs) status = False self.__validated = True if self.__originalDir: os.chdir(oldDir) return status,statusMsgs def normalizeValue(self, section, option) : return typeValidatorInstance.normalize( self._configDef[section][option]['type'], self[section][option]) def validateValue(self, section, option): # Validates a section.option and exits on error valueInfo = typeValidatorInstance.verify( self._configDef[section][option]['type'], self[section][option]) if valueInfo['isValid'] == 1: return [] else: if valueInfo['errorData']: return self.var_error(section, option, valueInfo['errorData']) else: return self.var_error(section, option) class config(SafeConfigParser, baseConfig): def __init__(self, configFile, configDef=None, originalDir=None, options=None, checkPerms=False): """Constructs config object. configFile - configuration file to read configDef - definition object options - options object checkPerms - check file permission on config file, 0660 sample configuration file: [snis] modules_dir = modules/ ; location of infoModules md5_defs_dir = etc/md5_defs ; location of infoTree md5 defs info_store = var/info ; location of nodeInfo store cam_daemon = localhost:8200 ; cam daemon address""" SafeConfigParser.__init__(self) baseConfig.__init__(self, configDef, originalDir) if(os.path.exists(configFile)): self.configFile = configFile else: raise IOError self._options = options ## UNUSED CODE : checkPerms is never True ## zim: this code is used if one instantiates config() with checkPerms set to ## True. if checkPerms: self.__check_perms() self.read(configFile) self._configDef = configDef if not self._configDef: self._mySections = self.sections() self.__initialize_config_dict() def __initialize_config_dict(self): """ build a dictionary of config vars keyed by section name defined in configDef, if options defined override config""" for section in self._mySections: items = self.items(section) self._dict[section] = {} # First fill self._dict with whatever is given in hodrc. # Going by this, options given at the command line either override # options in hodrc, or get appended to the list, like for # hod.client-params. Note that after this dict has _only_ hodrc # params for keyValuePair in items: # stupid commenting bug in ConfigParser class, lines without an # option value pair or section required that ; or # are at the # beginning of the line, :( newValue = reCommentHack.sub("", keyValuePair[1]) newValue = reCommentNewline.sub("", newValue) self._dict[section][keyValuePair[0]] = newValue # end of filling with options given in hodrc # now start filling in command line options if self._options: for option in self._configDef[section].keys(): if self._options[section].has_key(option): # the user has given an option compoundOpt = "%s.%s" %(section,option) if ( compoundOpt == \ 'gridservice-mapred.final-server-params' \ or compoundOpt == \ 'gridservice-hdfs.final-server-params' \ or compoundOpt == \ 'gridservice-mapred.server-params' \ or compoundOpt == \ 'gridservice-hdfs.server-params' \ or compoundOpt == \ 'hod.client-params' ): if ( compoundOpt == \ 'gridservice-mapred.final-server-params' \ or compoundOpt == \ 'gridservice-hdfs.final-server-params' ): overwrite = False else: overwrite = True # Append to the current list of values in self._dict if not self._dict[section].has_key(option): self._dict[section][option] = "" dictOpts = reKeyValList.split(self._dict[section][option]) dictOptsKeyVals = {} for opt in dictOpts: if opt != '': # when dict _has_ params from hodrc if reKeyVal.search(opt): (key, val) = reKeyVal.split(opt,1) # we only consider the first '=' for splitting # we do this to support passing params like # mapred.child.java.opts=-Djava.library.path=some_dir # Even in case of an invalid error like unescaped '=', # we don't want to fail here itself. We leave such errors # to be caught during validation which happens after this dictOptsKeyVals[key] = val else: # this means an invalid option. Leaving it #for config.verify to catch dictOptsKeyVals[opt] = None cmdLineOpts = reKeyValList.split(self._options[section][option]) for opt in cmdLineOpts: if reKeyVal.search(opt): # Same as for hodrc options. only consider # the first = ( key, val ) = reKeyVal.split(opt,1) else: key = opt val = None # whatever is given at cmdline overrides # what is given in hodrc only for non-final params if dictOptsKeyVals.has_key(key): if overwrite: dictOptsKeyVals[key] = val else: dictOptsKeyVals[key] = val self._dict[section][option] = "" for key in dictOptsKeyVals: if self._dict[section][option] == "": if dictOptsKeyVals[key]: self._dict[section][option] = key + "=" + \ dictOptsKeyVals[key] else: #invalid option. let config.verify catch self._dict[section][option] = key else: if dictOptsKeyVals[key]: self._dict[section][option] = \ self._dict[section][option] + "," + key + \ "=" + dictOptsKeyVals[key] else: #invalid option. let config.verify catch self._dict[section][option] = \ self._dict[section][option] + "," + key else: # for rest of the options, that don't need # appending business. # options = cmdline opts + defaults # dict = hodrc opts only # only non default opts can overwrite any opt # currently in dict if not self._dict[section].has_key(option): # options not mentioned in hodrc self._dict[section][option] = \ self._options[section][option] elif self._configDef[section][option]['default'] != \ self._options[section][option]: # option mentioned in hodrc but user has given a # non-default option self._dict[section][option] = \ self._options[section][option] ## UNUSED METHOD ## zim: is too :) def __check_perms(self): perms = None if self._options: try: perms = get_perms(self.configFile) except OSError, data: self._options.print_help() raise Exception("*** could not find config file: %s" % data) sys.exit(1) else: perms = get_perms(self.configFile) if perms != requiredPerms: error = "*** '%s' has invalid permission: %s should be %s\n" % \ (self.configFile, perms, requiredPerms) raise Exception( error) sys.exit(1) def replace_escape_seqs(self): """ replace any escaped characters """ replace_escapes(self) class formatter(IndentedHelpFormatter): def format_option_strings(self, option): """Return a comma-separated list of option strings & metavariables.""" if option.takes_value(): metavar = option.metavar or option.dest.upper() short_opts = [sopt for sopt in option._short_opts] long_opts = [self._long_opt_fmt % (lopt, metavar) for lopt in option._long_opts] else: short_opts = option._short_opts long_opts = option._long_opts if self.short_first: opts = short_opts + long_opts else: opts = long_opts + short_opts return ", ".join(opts) class options(OptionParser, baseConfig): def __init__(self, optionDef, usage, version, originalDir=None, withConfig=False, defaultConfig=None, defaultLocation=None, name=None): """Constructs and options object. optionDef - definition object usage - usage statement version - version string withConfig - used in conjunction with a configuration file defaultConfig - default configuration file """ OptionParser.__init__(self, usage=usage) baseConfig.__init__(self, optionDef, originalDir) self.formatter = formatter(4, max_help_position=100, width=180, short_first=1) self.__name = name self.__version = version self.__withConfig = withConfig self.__defaultConfig = defaultConfig self.__defaultLoc = defaultLocation self.args = [] self.__optionList = [] self.__compoundOpts = [] self.__shortMap = {} self.__alphaString = 'abcdefghijklmnopqrstuvxyzABCDEFGHIJKLMNOPQRSTUVXYZ1234567890' self.__alpha = [] self.__parsedOptions = {} self.__reserved = [ 'h' ] self.__orig_grps = [] self.__orig_grp_lists = {} self.__orig_option_list = [] self.__display_grps = [] self.__display_grp_lists = {} self.__display_option_list = [] self.config = None if self.__withConfig: self.__reserved.append('c') self.__reserved.append('v') self.__gen_alpha() # build self.__optionList, so it contains all the options that are # possible. the list elements are of the form section.option for section in self._mySections: if self.__withConfig and section == 'config': raise Exception( "withConfig set 'config' cannot be used as a section name") for option in self._configDef[section].keys(): if '.' in option: raise Exception("Options cannot contain: '.'") elif self.__withConfig and option == 'config': raise Exception( "With config set, option config is not allowed.") elif self.__withConfig and option == 'verbose-help': raise Exception( "With config set, option verbose-help is not allowed.") self.__optionList.append(self.__splice_compound(section, option)) self.__build_short_map() self.__add_options() self.__init_display_options() (self.__parsedOptions, self.args) = self.parse_args() # Now process the positional arguments only for the client side if self.__name == 'hod': hodhelp = hodHelp() _operation = getattr(self.__parsedOptions,'hod.operation') _script = getattr(self.__parsedOptions, 'hod.script') nArgs = self.args.__len__() if _operation: # -o option is given if nArgs != 0: self.error('invalid syntax : command and operation(-o) cannot coexist') elif nArgs == 0 and _script: # for a script option, without subcommand: hod -s script ... pass elif nArgs == 0: print "Usage: ",hodhelp.help() sys.exit(0) else: # subcommand is given cmdstr = self.args[0] # the subcommand itself cmdlist = hodhelp.ops if cmdstr not in cmdlist: print "Usage: ", hodhelp.help() sys.exit(2) numNodes = None clusterDir = None # Check which subcommand. cmdstr = subcommand itself now. if cmdstr == "allocate": clusterDir = getattr(self.__parsedOptions, 'hod.clusterdir') numNodes = getattr(self.__parsedOptions, 'hod.nodecount') if not clusterDir or not numNodes: print hodhelp.usage(cmdstr) sys.exit(3) cmdstr = cmdstr + ' ' + clusterDir + ' ' + numNodes setattr(self.__parsedOptions,'hod.operation', cmdstr) elif cmdstr == "deallocate" or cmdstr == "info": clusterDir = getattr(self.__parsedOptions, 'hod.clusterdir') if not clusterDir: print hodhelp.usage(cmdstr) sys.exit(3) cmdstr = cmdstr + ' ' + clusterDir setattr(self.__parsedOptions,'hod.operation', cmdstr) elif cmdstr == "list": setattr(self.__parsedOptions,'hod.operation', cmdstr) pass elif cmdstr == "script": clusterDir = getattr(self.__parsedOptions, 'hod.clusterdir') numNodes = getattr(self.__parsedOptions, 'hod.nodecount') originalDir = getattr(self.__parsedOptions, 'hod.original-dir') if originalDir and clusterDir: self.remove_exit_code_file(originalDir, clusterDir) if not _script or not clusterDir or not numNodes: print hodhelp.usage(cmdstr) sys.exit(3) pass elif cmdstr == "help": if nArgs == 1: self.print_help() sys.exit(0) elif nArgs != 2: self.print_help() sys.exit(3) elif self.args[1] == 'options': self.print_options() sys.exit(0) cmdstr = cmdstr + ' ' + self.args[1] setattr(self.__parsedOptions,'hod.operation', cmdstr) # end of processing for arguments on the client side if self.__withConfig: self.config = self.__parsedOptions.config if not self.config: self.error("configuration file must be specified") if not os.path.isabs(self.config): # A relative path. Append the original directory which would be the # current directory at the time of launch try: origDir = getattr(self.__parsedOptions, 'hod.original-dir') if origDir is not None: self.config = os.path.join(origDir, self.config) self.__parsedOptions.config = self.config except AttributeError, e: self.error("hod.original-dir is not defined.\ Cannot get current directory") if not os.path.exists(self.config): if self.__defaultLoc and not re.search("/", self.config): self.__parsedOptions.config = os.path.join( self.__defaultLoc, self.config) self.__build_dict() def norm_cluster_dir(self, orig_dir, directory): directory = os.path.expanduser(directory) if not os.path.isabs(directory): directory = os.path.join(orig_dir, directory) directory = os.path.abspath(directory) return directory def remove_exit_code_file(self, orig_dir, dir): try: dir = self.norm_cluster_dir(orig_dir, dir) if os.path.exists(dir): exit_code_file = os.path.join(dir, "script.exitcode") if os.path.exists(exit_code_file): os.remove(exit_code_file) except: print >>sys.stderr, "Could not remove the script.exitcode file." def __init_display_options(self): self.__orig_option_list = self.option_list[:] optionListTitleMap = {} for option in self.option_list: optionListTitleMap[option._long_opts[0]] = option self.__orig_grps = self.option_groups[:] for group in self.option_groups: self.__orig_grp_lists[group.title] = group.option_list[:] groupTitleMap = {} optionTitleMap = {} for group in self.option_groups: groupTitleMap[group.title] = group optionTitleMap[group.title] = {} for option in group.option_list: (sectionName, optionName) = \ self.__split_compound(option._long_opts[0]) optionTitleMap[group.title][optionName] = option for section in self._mySections: for option in self._configDef[section]: if self._configDef[section][option]['help']: if groupTitleMap.has_key(section): if not self.__display_grp_lists.has_key(section): self.__display_grp_lists[section] = [] self.__display_grp_lists[section].append( optionTitleMap[section][option]) try: self.__display_option_list.append( optionListTitleMap["--" + self.__splice_compound( section, option)]) except KeyError: pass try: self.__display_option_list.append(optionListTitleMap['--config']) except KeyError: pass self.__display_option_list.append(optionListTitleMap['--help']) self.__display_option_list.append(optionListTitleMap['--verbose-help']) self.__display_option_list.append(optionListTitleMap['--version']) self.__display_grps = self.option_groups[:] for section in self._mySections: if self.__display_grp_lists.has_key(section): self.__orig_grp_lists[section] = \ groupTitleMap[section].option_list else: try: self.__display_grps.remove(groupTitleMap[section]) except KeyError: pass def __gen_alpha(self): assignedOptions = [] for section in self._configDef: for option in self._configDef[section]: if self._configDef[section][option]['short']: assignedOptions.append( self._configDef[section][option]['short']) for symbol in self.__alphaString: if not symbol in assignedOptions: self.__alpha.append(symbol) def __splice_compound(self, section, option): return "%s.%s" % (section, option) def __split_compound(self, compound): return compound.split('.') def __build_short_map(self): """ build a short_map of parametername : short_option. This is done only for those parameters that don't have short options already defined in configDef. If possible, the first letter in the option that is not already used/reserved as a short option is allotted. Otherwise the first letter in __alpha that isn't still used is allotted. e.g. { 'hodring.java-home': 'T', 'resource_manager.batch-home': 'B' } """ optionsKey = {} for compound in self.__optionList: (section, option) = self.__split_compound(compound) if not optionsKey.has_key(section): optionsKey[section] = [] optionsKey[section].append(option) for section in self._configDef.sections(): options = optionsKey[section] options.sort() for option in options: if not self._configDef[section][option]['short']: compound = self.__splice_compound(section, option) shortOptions = self.__shortMap.values() for i in range(0, len(option)): letter = option[i] letter = letter.lower() if letter in self.__alpha: if not letter in shortOptions and \ not letter in self.__reserved: self.__shortMap[compound] = letter break if not self.__shortMap.has_key(compound): for i in range(0, len(self.__alpha)): letter = self.__alpha[i] if not letter in shortOptions and \ not letter in self.__reserved: self.__shortMap[compound] = letter def __add_option(self, config, compoundOpt, section, option, group=None): addMethod = self.add_option if group: addMethod=group.add_option self.__compoundOpts.append(compoundOpt) if compoundOpt == 'gridservice-mapred.final-server-params' or \ compoundOpt == 'gridservice-hdfs.final-server-params' or \ compoundOpt == 'gridservice-mapred.server-params' or \ compoundOpt == 'gridservice-hdfs.server-params' or \ compoundOpt == 'hod.client-params': _action = 'append' elif config[section][option]['type'] == 'bool': _action = 'store_true' else: _action = 'store' if self.__shortMap.has_key(compoundOpt): addMethod("-" + self.__shortMap[compoundOpt], "--" + compoundOpt, dest=compoundOpt, action= _action, metavar=config[section][option]['type'], default=config[section][option]['default'], help=config[section][option]['desc']) else: if config[section][option]['short']: addMethod("-" + config[section][option]['short'], "--" + compoundOpt, dest=compoundOpt, action= _action, metavar=config[section][option]['type'], default=config[section][option]['default'], help=config[section][option]['desc']) else: addMethod('', "--" + compoundOpt, dest=compoundOpt, action= _action, metavar=config[section][option]['type'], default=config[section][option]['default'], help=config[section][option]['desc']) def __add_options(self): if self.__withConfig: self.add_option("-c", "--config", dest='config', action='store', default=self.__defaultConfig, metavar='config_file', help="Full path to configuration file.") self.add_option("", "--verbose-help", action='help', default=None, metavar='flag', help="Display verbose help information.") self.add_option("-v", "--version", action='version', default=None, metavar='flag', help="Display version information.") self.version = self.__version if len(self._mySections) > 1: for section in self._mySections: group = OptionGroup(self, section) for option in self._configDef[section]: compoundOpt = self.__splice_compound(section, option) self.__add_option(self._configDef, compoundOpt, section, option, group) self.add_option_group(group) else: for section in self._mySections: for option in self._configDef[section]: compoundOpt = self.__splice_compound(section, option) self.__add_option(self._configDef, compoundOpt, section, option) def __build_dict(self): if self.__withConfig: self._dict['config'] = str(getattr(self.__parsedOptions, 'config')) for compoundOption in dir(self.__parsedOptions): if compoundOption in self.__compoundOpts: (section, option) = self.__split_compound(compoundOption) if not self._dict.has_key(section): self._dict[section] = {} if getattr(self.__parsedOptions, compoundOption): _attr = getattr(self.__parsedOptions, compoundOption) # when we have multi-valued parameters passed separately # from command line, python optparser pushes them into a # list. So converting all such lists to strings if type(_attr) == type([]): import string _attr = string.join(_attr,',') self._dict[section][option] = _attr for section in self._configDef: for option in self._configDef[section]: if self._configDef[section][option]['type'] == 'bool': compoundOption = self.__splice_compound(section, option) if not self._dict.has_key(section): self._dict[section] = {} if option not in self._dict[section]: self._dict[section][option] = False def __set_display_groups(self): if not '--verbose-help' in sys.argv: self.option_groups = self.__display_grps self.option_list = self.__display_option_list for group in self.option_groups: group.option_list = self.__display_grp_lists[group.title] def __unset_display_groups(self): if not '--verbose-help' in sys.argv: self.option_groups = self.__orig_grps self.option_list = self.__orig_option_list for group in self.option_groups: group.option_list = self.__orig_grp_lists[group.title] def print_help(self, file=None): self.__set_display_groups() OptionParser.print_help(self, file) self.__unset_display_groups() def print_options(self): _usage = self.usage self.set_usage('') self.print_help() self.set_usage(_usage) def verify(self): return baseConfig.verify(self) def replace_escape_seqs(self): replace_escapes(self)
apache-2.0
an7oine/WinVHS
Cygwin/lib/python2.7/distutils/command/bdist_msi.py
164
35191
# -*- coding: iso-8859-1 -*- # Copyright (C) 2005, 2006 Martin von Löwis # Licensed to PSF under a Contributor Agreement. # The bdist_wininst command proper # based on bdist_wininst """ Implements the bdist_msi command. """ import sys, os from sysconfig import get_python_version from distutils.core import Command from distutils.dir_util import remove_tree from distutils.version import StrictVersion from distutils.errors import DistutilsOptionError from distutils import log from distutils.util import get_platform import msilib from msilib import schema, sequence, text from msilib import Directory, Feature, Dialog, add_data class PyDialog(Dialog): """Dialog class with a fixed layout: controls at the top, then a ruler, then a list of buttons: back, next, cancel. Optionally a bitmap at the left.""" def __init__(self, *args, **kw): """Dialog(database, name, x, y, w, h, attributes, title, first, default, cancel, bitmap=true)""" Dialog.__init__(self, *args) ruler = self.h - 36 #if kw.get("bitmap", True): # self.bitmap("Bitmap", 0, 0, bmwidth, ruler, "PythonWin") self.line("BottomLine", 0, ruler, self.w, 0) def title(self, title): "Set the title text of the dialog at the top." # name, x, y, w, h, flags=Visible|Enabled|Transparent|NoPrefix, # text, in VerdanaBold10 self.text("Title", 15, 10, 320, 60, 0x30003, r"{\VerdanaBold10}%s" % title) def back(self, title, next, name = "Back", active = 1): """Add a back button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 180, self.h-27 , 56, 17, flags, title, next) def cancel(self, title, next, name = "Cancel", active = 1): """Add a cancel button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 304, self.h-27, 56, 17, flags, title, next) def next(self, title, next, name = "Next", active = 1): """Add a Next button with a given title, the tab-next button, its name in the Control table, possibly initially disabled. Return the button, so that events can be associated""" if active: flags = 3 # Visible|Enabled else: flags = 1 # Visible return self.pushbutton(name, 236, self.h-27, 56, 17, flags, title, next) def xbutton(self, name, title, next, xpos): """Add a button with a given title, the tab-next button, its name in the Control table, giving its x position; the y-position is aligned with the other buttons. Return the button, so that events can be associated""" return self.pushbutton(name, int(self.w*xpos - 28), self.h-27, 56, 17, 3, title, next) class bdist_msi (Command): description = "create a Microsoft Installer (.msi) binary distribution" user_options = [('bdist-dir=', None, "temporary directory for creating the distribution"), ('plat-name=', 'p', "platform name to embed in generated filenames " "(default: %s)" % get_platform()), ('keep-temp', 'k', "keep the pseudo-installation tree around after " + "creating the distribution archive"), ('target-version=', None, "require a specific python version" + " on the target system"), ('no-target-compile', 'c', "do not compile .py to .pyc on the target system"), ('no-target-optimize', 'o', "do not compile .py to .pyo (optimized)" "on the target system"), ('dist-dir=', 'd', "directory to put final built distributions in"), ('skip-build', None, "skip rebuilding everything (for testing/debugging)"), ('install-script=', None, "basename of installation script to be run after" "installation or before deinstallation"), ('pre-install-script=', None, "Fully qualified filename of a script to be run before " "any files are installed. This script need not be in the " "distribution"), ] boolean_options = ['keep-temp', 'no-target-compile', 'no-target-optimize', 'skip-build'] all_versions = ['2.0', '2.1', '2.2', '2.3', '2.4', '2.5', '2.6', '2.7', '2.8', '2.9', '3.0', '3.1', '3.2', '3.3', '3.4', '3.5', '3.6', '3.7', '3.8', '3.9'] other_version = 'X' def initialize_options (self): self.bdist_dir = None self.plat_name = None self.keep_temp = 0 self.no_target_compile = 0 self.no_target_optimize = 0 self.target_version = None self.dist_dir = None self.skip_build = None self.install_script = None self.pre_install_script = None self.versions = None def finalize_options (self): self.set_undefined_options('bdist', ('skip_build', 'skip_build')) if self.bdist_dir is None: bdist_base = self.get_finalized_command('bdist').bdist_base self.bdist_dir = os.path.join(bdist_base, 'msi') short_version = get_python_version() if (not self.target_version) and self.distribution.has_ext_modules(): self.target_version = short_version if self.target_version: self.versions = [self.target_version] if not self.skip_build and self.distribution.has_ext_modules()\ and self.target_version != short_version: raise DistutilsOptionError, \ "target version can only be %s, or the '--skip-build'" \ " option must be specified" % (short_version,) else: self.versions = list(self.all_versions) self.set_undefined_options('bdist', ('dist_dir', 'dist_dir'), ('plat_name', 'plat_name'), ) if self.pre_install_script: raise DistutilsOptionError, "the pre-install-script feature is not yet implemented" if self.install_script: for script in self.distribution.scripts: if self.install_script == os.path.basename(script): break else: raise DistutilsOptionError, \ "install_script '%s' not found in scripts" % \ self.install_script self.install_script_key = None # finalize_options() def run (self): if not self.skip_build: self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.prefix = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 install_lib = self.reinitialize_command('install_lib') # we do not want to include pyc or pyo files install_lib.compile = 0 install_lib.optimize = 0 if self.distribution.has_ext_modules(): # If we are building an installer for a Python version other # than the one we are currently running, then we need to ensure # our build_lib reflects the other Python version rather than ours. # Note that for target_version!=sys.version, we must have skipped the # build step, so there is no issue with enforcing the build of this # version. target_version = self.target_version if not target_version: assert self.skip_build, "Should have already checked this" target_version = sys.version[0:3] plat_specifier = ".%s-%s" % (self.plat_name, target_version) build = self.get_finalized_command('build') build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier) log.info("installing to %s", self.bdist_dir) install.ensure_finalized() # avoid warning of 'install_lib' about installing # into a directory not in sys.path sys.path.insert(0, os.path.join(self.bdist_dir, 'PURELIB')) install.run() del sys.path[0] self.mkpath(self.dist_dir) fullname = self.distribution.get_fullname() installer_name = self.get_installer_filename(fullname) installer_name = os.path.abspath(installer_name) if os.path.exists(installer_name): os.unlink(installer_name) metadata = self.distribution.metadata author = metadata.author if not author: author = metadata.maintainer if not author: author = "UNKNOWN" version = metadata.get_version() # ProductVersion must be strictly numeric # XXX need to deal with prerelease versions sversion = "%d.%d.%d" % StrictVersion(version).version # Prefix ProductName with Python x.y, so that # it sorts together with the other Python packages # in Add-Remove-Programs (APR) fullname = self.distribution.get_fullname() if self.target_version: product_name = "Python %s %s" % (self.target_version, fullname) else: product_name = "Python %s" % (fullname) self.db = msilib.init_database(installer_name, schema, product_name, msilib.gen_uuid(), sversion, author) msilib.add_tables(self.db, sequence) props = [('DistVersion', version)] email = metadata.author_email or metadata.maintainer_email if email: props.append(("ARPCONTACT", email)) if metadata.url: props.append(("ARPURLINFOABOUT", metadata.url)) if props: add_data(self.db, 'Property', props) self.add_find_python() self.add_files() self.add_scripts() self.add_ui() self.db.Commit() if hasattr(self.distribution, 'dist_files'): tup = 'bdist_msi', self.target_version or 'any', fullname self.distribution.dist_files.append(tup) if not self.keep_temp: remove_tree(self.bdist_dir, dry_run=self.dry_run) def add_files(self): db = self.db cab = msilib.CAB("distfiles") rootdir = os.path.abspath(self.bdist_dir) root = Directory(db, cab, None, rootdir, "TARGETDIR", "SourceDir") f = Feature(db, "Python", "Python", "Everything", 0, 1, directory="TARGETDIR") items = [(f, root, '')] for version in self.versions + [self.other_version]: target = "TARGETDIR" + version name = default = "Python" + version desc = "Everything" if version is self.other_version: title = "Python from another location" level = 2 else: title = "Python %s from registry" % version level = 1 f = Feature(db, name, title, desc, 1, level, directory=target) dir = Directory(db, cab, root, rootdir, target, default) items.append((f, dir, version)) db.Commit() seen = {} for feature, dir, version in items: todo = [dir] while todo: dir = todo.pop() for file in os.listdir(dir.absolute): afile = os.path.join(dir.absolute, file) if os.path.isdir(afile): short = "%s|%s" % (dir.make_short(file), file) default = file + version newdir = Directory(db, cab, dir, file, default, short) todo.append(newdir) else: if not dir.component: dir.start_component(dir.logical, feature, 0) if afile not in seen: key = seen[afile] = dir.add_file(file) if file==self.install_script: if self.install_script_key: raise DistutilsOptionError( "Multiple files with name %s" % file) self.install_script_key = '[#%s]' % key else: key = seen[afile] add_data(self.db, "DuplicateFile", [(key + version, dir.component, key, None, dir.logical)]) db.Commit() cab.commit(db) def add_find_python(self): """Adds code to the installer to compute the location of Python. Properties PYTHON.MACHINE.X.Y and PYTHON.USER.X.Y will be set from the registry for each version of Python. Properties TARGETDIRX.Y will be set from PYTHON.USER.X.Y if defined, else from PYTHON.MACHINE.X.Y. Properties PYTHONX.Y will be set to TARGETDIRX.Y\\python.exe""" start = 402 for ver in self.versions: install_path = r"SOFTWARE\Python\PythonCore\%s\InstallPath" % ver machine_reg = "python.machine." + ver user_reg = "python.user." + ver machine_prop = "PYTHON.MACHINE." + ver user_prop = "PYTHON.USER." + ver machine_action = "PythonFromMachine" + ver user_action = "PythonFromUser" + ver exe_action = "PythonExe" + ver target_dir_prop = "TARGETDIR" + ver exe_prop = "PYTHON" + ver if msilib.Win64: # type: msidbLocatorTypeRawValue + msidbLocatorType64bit Type = 2+16 else: Type = 2 add_data(self.db, "RegLocator", [(machine_reg, 2, install_path, None, Type), (user_reg, 1, install_path, None, Type)]) add_data(self.db, "AppSearch", [(machine_prop, machine_reg), (user_prop, user_reg)]) add_data(self.db, "CustomAction", [(machine_action, 51+256, target_dir_prop, "[" + machine_prop + "]"), (user_action, 51+256, target_dir_prop, "[" + user_prop + "]"), (exe_action, 51+256, exe_prop, "[" + target_dir_prop + "]\\python.exe"), ]) add_data(self.db, "InstallExecuteSequence", [(machine_action, machine_prop, start), (user_action, user_prop, start + 1), (exe_action, None, start + 2), ]) add_data(self.db, "InstallUISequence", [(machine_action, machine_prop, start), (user_action, user_prop, start + 1), (exe_action, None, start + 2), ]) add_data(self.db, "Condition", [("Python" + ver, 0, "NOT TARGETDIR" + ver)]) start += 4 assert start < 500 def add_scripts(self): if self.install_script: start = 6800 for ver in self.versions + [self.other_version]: install_action = "install_script." + ver exe_prop = "PYTHON" + ver add_data(self.db, "CustomAction", [(install_action, 50, exe_prop, self.install_script_key)]) add_data(self.db, "InstallExecuteSequence", [(install_action, "&Python%s=3" % ver, start)]) start += 1 # XXX pre-install scripts are currently refused in finalize_options() # but if this feature is completed, it will also need to add # entries for each version as the above code does if self.pre_install_script: scriptfn = os.path.join(self.bdist_dir, "preinstall.bat") f = open(scriptfn, "w") # The batch file will be executed with [PYTHON], so that %1 # is the path to the Python interpreter; %0 will be the path # of the batch file. # rem =""" # %1 %0 # exit # """ # <actual script> f.write('rem ="""\n%1 %0\nexit\n"""\n') f.write(open(self.pre_install_script).read()) f.close() add_data(self.db, "Binary", [("PreInstall", msilib.Binary(scriptfn)) ]) add_data(self.db, "CustomAction", [("PreInstall", 2, "PreInstall", None) ]) add_data(self.db, "InstallExecuteSequence", [("PreInstall", "NOT Installed", 450)]) def add_ui(self): db = self.db x = y = 50 w = 370 h = 300 title = "[ProductName] Setup" # see "Dialog Style Bits" modal = 3 # visible | modal modeless = 1 # visible # UI customization properties add_data(db, "Property", # See "DefaultUIFont Property" [("DefaultUIFont", "DlgFont8"), # See "ErrorDialog Style Bit" ("ErrorDialog", "ErrorDlg"), ("Progress1", "Install"), # modified in maintenance type dlg ("Progress2", "installs"), ("MaintenanceForm_Action", "Repair"), # possible values: ALL, JUSTME ("WhichUsers", "ALL") ]) # Fonts, see "TextStyle Table" add_data(db, "TextStyle", [("DlgFont8", "Tahoma", 9, None, 0), ("DlgFontBold8", "Tahoma", 8, None, 1), #bold ("VerdanaBold10", "Verdana", 10, None, 1), ("VerdanaRed9", "Verdana", 9, 255, 0), ]) # UI Sequences, see "InstallUISequence Table", "Using a Sequence Table" # Numbers indicate sequence; see sequence.py for how these action integrate add_data(db, "InstallUISequence", [("PrepareDlg", "Not Privileged or Windows9x or Installed", 140), ("WhichUsersDlg", "Privileged and not Windows9x and not Installed", 141), # In the user interface, assume all-users installation if privileged. ("SelectFeaturesDlg", "Not Installed", 1230), # XXX no support for resume installations yet #("ResumeDlg", "Installed AND (RESUME OR Preselected)", 1240), ("MaintenanceTypeDlg", "Installed AND NOT RESUME AND NOT Preselected", 1250), ("ProgressDlg", None, 1280)]) add_data(db, 'ActionText', text.ActionText) add_data(db, 'UIText', text.UIText) ##################################################################### # Standard dialogs: FatalError, UserExit, ExitDialog fatal=PyDialog(db, "FatalError", x, y, w, h, modal, title, "Finish", "Finish", "Finish") fatal.title("[ProductName] Installer ended prematurely") fatal.back("< Back", "Finish", active = 0) fatal.cancel("Cancel", "Back", active = 0) fatal.text("Description1", 15, 70, 320, 80, 0x30003, "[ProductName] setup ended prematurely because of an error. Your system has not been modified. To install this program at a later time, please run the installation again.") fatal.text("Description2", 15, 155, 320, 20, 0x30003, "Click the Finish button to exit the Installer.") c=fatal.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Exit") user_exit=PyDialog(db, "UserExit", x, y, w, h, modal, title, "Finish", "Finish", "Finish") user_exit.title("[ProductName] Installer was interrupted") user_exit.back("< Back", "Finish", active = 0) user_exit.cancel("Cancel", "Back", active = 0) user_exit.text("Description1", 15, 70, 320, 80, 0x30003, "[ProductName] setup was interrupted. Your system has not been modified. " "To install this program at a later time, please run the installation again.") user_exit.text("Description2", 15, 155, 320, 20, 0x30003, "Click the Finish button to exit the Installer.") c = user_exit.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Exit") exit_dialog = PyDialog(db, "ExitDialog", x, y, w, h, modal, title, "Finish", "Finish", "Finish") exit_dialog.title("Completing the [ProductName] Installer") exit_dialog.back("< Back", "Finish", active = 0) exit_dialog.cancel("Cancel", "Back", active = 0) exit_dialog.text("Description", 15, 235, 320, 20, 0x30003, "Click the Finish button to exit the Installer.") c = exit_dialog.next("Finish", "Cancel", name="Finish") c.event("EndDialog", "Return") ##################################################################### # Required dialog: FilesInUse, ErrorDlg inuse = PyDialog(db, "FilesInUse", x, y, w, h, 19, # KeepModeless|Modal|Visible title, "Retry", "Retry", "Retry", bitmap=False) inuse.text("Title", 15, 6, 200, 15, 0x30003, r"{\DlgFontBold8}Files in Use") inuse.text("Description", 20, 23, 280, 20, 0x30003, "Some files that need to be updated are currently in use.") inuse.text("Text", 20, 55, 330, 50, 3, "The following applications are using files that need to be updated by this setup. Close these applications and then click Retry to continue the installation or Cancel to exit it.") inuse.control("List", "ListBox", 20, 107, 330, 130, 7, "FileInUseProcess", None, None, None) c=inuse.back("Exit", "Ignore", name="Exit") c.event("EndDialog", "Exit") c=inuse.next("Ignore", "Retry", name="Ignore") c.event("EndDialog", "Ignore") c=inuse.cancel("Retry", "Exit", name="Retry") c.event("EndDialog","Retry") # See "Error Dialog". See "ICE20" for the required names of the controls. error = Dialog(db, "ErrorDlg", 50, 10, 330, 101, 65543, # Error|Minimize|Modal|Visible title, "ErrorText", None, None) error.text("ErrorText", 50,9,280,48,3, "") #error.control("ErrorIcon", "Icon", 15, 9, 24, 24, 5242881, None, "py.ico", None, None) error.pushbutton("N",120,72,81,21,3,"No",None).event("EndDialog","ErrorNo") error.pushbutton("Y",240,72,81,21,3,"Yes",None).event("EndDialog","ErrorYes") error.pushbutton("A",0,72,81,21,3,"Abort",None).event("EndDialog","ErrorAbort") error.pushbutton("C",42,72,81,21,3,"Cancel",None).event("EndDialog","ErrorCancel") error.pushbutton("I",81,72,81,21,3,"Ignore",None).event("EndDialog","ErrorIgnore") error.pushbutton("O",159,72,81,21,3,"Ok",None).event("EndDialog","ErrorOk") error.pushbutton("R",198,72,81,21,3,"Retry",None).event("EndDialog","ErrorRetry") ##################################################################### # Global "Query Cancel" dialog cancel = Dialog(db, "CancelDlg", 50, 10, 260, 85, 3, title, "No", "No", "No") cancel.text("Text", 48, 15, 194, 30, 3, "Are you sure you want to cancel [ProductName] installation?") #cancel.control("Icon", "Icon", 15, 15, 24, 24, 5242881, None, # "py.ico", None, None) c=cancel.pushbutton("Yes", 72, 57, 56, 17, 3, "Yes", "No") c.event("EndDialog", "Exit") c=cancel.pushbutton("No", 132, 57, 56, 17, 3, "No", "Yes") c.event("EndDialog", "Return") ##################################################################### # Global "Wait for costing" dialog costing = Dialog(db, "WaitForCostingDlg", 50, 10, 260, 85, modal, title, "Return", "Return", "Return") costing.text("Text", 48, 15, 194, 30, 3, "Please wait while the installer finishes determining your disk space requirements.") c = costing.pushbutton("Return", 102, 57, 56, 17, 3, "Return", None) c.event("EndDialog", "Exit") ##################################################################### # Preparation dialog: no user input except cancellation prep = PyDialog(db, "PrepareDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel") prep.text("Description", 15, 70, 320, 40, 0x30003, "Please wait while the Installer prepares to guide you through the installation.") prep.title("Welcome to the [ProductName] Installer") c=prep.text("ActionText", 15, 110, 320, 20, 0x30003, "Pondering...") c.mapping("ActionText", "Text") c=prep.text("ActionData", 15, 135, 320, 30, 0x30003, None) c.mapping("ActionData", "Text") prep.back("Back", None, active=0) prep.next("Next", None, active=0) c=prep.cancel("Cancel", None) c.event("SpawnDialog", "CancelDlg") ##################################################################### # Feature (Python directory) selection seldlg = PyDialog(db, "SelectFeaturesDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") seldlg.title("Select Python Installations") seldlg.text("Hint", 15, 30, 300, 20, 3, "Select the Python locations where %s should be installed." % self.distribution.get_fullname()) seldlg.back("< Back", None, active=0) c = seldlg.next("Next >", "Cancel") order = 1 c.event("[TARGETDIR]", "[SourceDir]", ordering=order) for version in self.versions + [self.other_version]: order += 1 c.event("[TARGETDIR]", "[TARGETDIR%s]" % version, "FEATURE_SELECTED AND &Python%s=3" % version, ordering=order) c.event("SpawnWaitDialog", "WaitForCostingDlg", ordering=order + 1) c.event("EndDialog", "Return", ordering=order + 2) c = seldlg.cancel("Cancel", "Features") c.event("SpawnDialog", "CancelDlg") c = seldlg.control("Features", "SelectionTree", 15, 60, 300, 120, 3, "FEATURE", None, "PathEdit", None) c.event("[FEATURE_SELECTED]", "1") ver = self.other_version install_other_cond = "FEATURE_SELECTED AND &Python%s=3" % ver dont_install_other_cond = "FEATURE_SELECTED AND &Python%s<>3" % ver c = seldlg.text("Other", 15, 200, 300, 15, 3, "Provide an alternate Python location") c.condition("Enable", install_other_cond) c.condition("Show", install_other_cond) c.condition("Disable", dont_install_other_cond) c.condition("Hide", dont_install_other_cond) c = seldlg.control("PathEdit", "PathEdit", 15, 215, 300, 16, 1, "TARGETDIR" + ver, None, "Next", None) c.condition("Enable", install_other_cond) c.condition("Show", install_other_cond) c.condition("Disable", dont_install_other_cond) c.condition("Hide", dont_install_other_cond) ##################################################################### # Disk cost cost = PyDialog(db, "DiskCostDlg", x, y, w, h, modal, title, "OK", "OK", "OK", bitmap=False) cost.text("Title", 15, 6, 200, 15, 0x30003, "{\DlgFontBold8}Disk Space Requirements") cost.text("Description", 20, 20, 280, 20, 0x30003, "The disk space required for the installation of the selected features.") cost.text("Text", 20, 53, 330, 60, 3, "The highlighted volumes (if any) do not have enough disk space " "available for the currently selected features. You can either " "remove some files from the highlighted volumes, or choose to " "install less features onto local drive(s), or select different " "destination drive(s).") cost.control("VolumeList", "VolumeCostList", 20, 100, 330, 150, 393223, None, "{120}{70}{70}{70}{70}", None, None) cost.xbutton("OK", "Ok", None, 0.5).event("EndDialog", "Return") ##################################################################### # WhichUsers Dialog. Only available on NT, and for privileged users. # This must be run before FindRelatedProducts, because that will # take into account whether the previous installation was per-user # or per-machine. We currently don't support going back to this # dialog after "Next" was selected; to support this, we would need to # find how to reset the ALLUSERS property, and how to re-run # FindRelatedProducts. # On Windows9x, the ALLUSERS property is ignored on the command line # and in the Property table, but installer fails according to the documentation # if a dialog attempts to set ALLUSERS. whichusers = PyDialog(db, "WhichUsersDlg", x, y, w, h, modal, title, "AdminInstall", "Next", "Cancel") whichusers.title("Select whether to install [ProductName] for all users of this computer.") # A radio group with two options: allusers, justme g = whichusers.radiogroup("AdminInstall", 15, 60, 260, 50, 3, "WhichUsers", "", "Next") g.add("ALL", 0, 5, 150, 20, "Install for all users") g.add("JUSTME", 0, 25, 150, 20, "Install just for me") whichusers.back("Back", None, active=0) c = whichusers.next("Next >", "Cancel") c.event("[ALLUSERS]", "1", 'WhichUsers="ALL"', 1) c.event("EndDialog", "Return", ordering = 2) c = whichusers.cancel("Cancel", "AdminInstall") c.event("SpawnDialog", "CancelDlg") ##################################################################### # Installation Progress dialog (modeless) progress = PyDialog(db, "ProgressDlg", x, y, w, h, modeless, title, "Cancel", "Cancel", "Cancel", bitmap=False) progress.text("Title", 20, 15, 200, 15, 0x30003, "{\DlgFontBold8}[Progress1] [ProductName]") progress.text("Text", 35, 65, 300, 30, 3, "Please wait while the Installer [Progress2] [ProductName]. " "This may take several minutes.") progress.text("StatusLabel", 35, 100, 35, 20, 3, "Status:") c=progress.text("ActionText", 70, 100, w-70, 20, 3, "Pondering...") c.mapping("ActionText", "Text") #c=progress.text("ActionData", 35, 140, 300, 20, 3, None) #c.mapping("ActionData", "Text") c=progress.control("ProgressBar", "ProgressBar", 35, 120, 300, 10, 65537, None, "Progress done", None, None) c.mapping("SetProgress", "Progress") progress.back("< Back", "Next", active=False) progress.next("Next >", "Cancel", active=False) progress.cancel("Cancel", "Back").event("SpawnDialog", "CancelDlg") ################################################################### # Maintenance type: repair/uninstall maint = PyDialog(db, "MaintenanceTypeDlg", x, y, w, h, modal, title, "Next", "Next", "Cancel") maint.title("Welcome to the [ProductName] Setup Wizard") maint.text("BodyText", 15, 63, 330, 42, 3, "Select whether you want to repair or remove [ProductName].") g=maint.radiogroup("RepairRadioGroup", 15, 108, 330, 60, 3, "MaintenanceForm_Action", "", "Next") #g.add("Change", 0, 0, 200, 17, "&Change [ProductName]") g.add("Repair", 0, 18, 200, 17, "&Repair [ProductName]") g.add("Remove", 0, 36, 200, 17, "Re&move [ProductName]") maint.back("< Back", None, active=False) c=maint.next("Finish", "Cancel") # Change installation: Change progress dialog to "Change", then ask # for feature selection #c.event("[Progress1]", "Change", 'MaintenanceForm_Action="Change"', 1) #c.event("[Progress2]", "changes", 'MaintenanceForm_Action="Change"', 2) # Reinstall: Change progress dialog to "Repair", then invoke reinstall # Also set list of reinstalled features to "ALL" c.event("[REINSTALL]", "ALL", 'MaintenanceForm_Action="Repair"', 5) c.event("[Progress1]", "Repairing", 'MaintenanceForm_Action="Repair"', 6) c.event("[Progress2]", "repairs", 'MaintenanceForm_Action="Repair"', 7) c.event("Reinstall", "ALL", 'MaintenanceForm_Action="Repair"', 8) # Uninstall: Change progress to "Remove", then invoke uninstall # Also set list of removed features to "ALL" c.event("[REMOVE]", "ALL", 'MaintenanceForm_Action="Remove"', 11) c.event("[Progress1]", "Removing", 'MaintenanceForm_Action="Remove"', 12) c.event("[Progress2]", "removes", 'MaintenanceForm_Action="Remove"', 13) c.event("Remove", "ALL", 'MaintenanceForm_Action="Remove"', 14) # Close dialog when maintenance action scheduled c.event("EndDialog", "Return", 'MaintenanceForm_Action<>"Change"', 20) #c.event("NewDialog", "SelectFeaturesDlg", 'MaintenanceForm_Action="Change"', 21) maint.cancel("Cancel", "RepairRadioGroup").event("SpawnDialog", "CancelDlg") def get_installer_filename(self, fullname): # Factored out to allow overriding in subclasses if self.target_version: base_name = "%s.%s-py%s.msi" % (fullname, self.plat_name, self.target_version) else: base_name = "%s.%s.msi" % (fullname, self.plat_name) installer_name = os.path.join(self.dist_dir, base_name) return installer_name
gpl-3.0
m-sanders/wagtail
wagtail/wagtailimages/migrations/0001_initial.py
31
3250
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import wagtail.wagtailimages.models import taggit.managers from django.conf import settings import wagtail.wagtailadmin.taggable class Migration(migrations.Migration): dependencies = [ ('taggit', '__latest__'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Filter', fields=[ ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')), ('spec', models.CharField(db_index=True, max_length=255)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Image', fields=[ ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')), ('title', models.CharField(verbose_name='Title', max_length=255)), ('file', models.ImageField(width_field='width', upload_to=wagtail.wagtailimages.models.get_upload_to, verbose_name='File', height_field='height')), ('width', models.IntegerField(editable=False)), ('height', models.IntegerField(editable=False)), ('created_at', models.DateTimeField(auto_now_add=True)), ('focal_point_x', models.PositiveIntegerField(editable=False, null=True)), ('focal_point_y', models.PositiveIntegerField(editable=False, null=True)), ('focal_point_width', models.PositiveIntegerField(editable=False, null=True)), ('focal_point_height', models.PositiveIntegerField(editable=False, null=True)), ('tags', taggit.managers.TaggableManager(verbose_name='Tags', blank=True, help_text=None, to='taggit.Tag', through='taggit.TaggedItem')), ('uploaded_by_user', models.ForeignKey(editable=False, blank=True, null=True, to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False, }, bases=(models.Model, wagtail.wagtailadmin.taggable.TagSearchable), ), migrations.CreateModel( name='Rendition', fields=[ ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')), ('file', models.ImageField(width_field='width', upload_to='images', height_field='height')), ('width', models.IntegerField(editable=False)), ('height', models.IntegerField(editable=False)), ('focal_point_key', models.CharField(editable=False, max_length=255, null=True)), ('filter', models.ForeignKey(related_name='+', to='wagtailimages.Filter')), ('image', models.ForeignKey(related_name='renditions', to='wagtailimages.Image')), ], options={ }, bases=(models.Model,), ), migrations.AlterUniqueTogether( name='rendition', unique_together=set([('image', 'filter', 'focal_point_key')]), ), ]
bsd-3-clause
Huskerboy/startbootstrap-freelancer
freelancer_env/Lib/re.py
36
15501
# # Secret Labs' Regular Expression Engine # # re-compatible interface for the sre matching engine # # Copyright (c) 1998-2001 by Secret Labs AB. All rights reserved. # # This version of the SRE library can be redistributed under CNRI's # Python 1.6 license. For any other use, please contact Secret Labs # AB (info@pythonware.com). # # Portions of this engine have been developed in cooperation with # CNRI. Hewlett-Packard provided funding for 1.6 integration and # other compatibility work. # r"""Support for regular expressions (RE). This module provides regular expression matching operations similar to those found in Perl. It supports both 8-bit and Unicode strings; both the pattern and the strings being processed can contain null bytes and characters outside the US ASCII range. Regular expressions can contain both special and ordinary characters. Most ordinary characters, like "A", "a", or "0", are the simplest regular expressions; they simply match themselves. You can concatenate ordinary characters, so last matches the string 'last'. The special characters are: "." Matches any character except a newline. "^" Matches the start of the string. "$" Matches the end of the string or just before the newline at the end of the string. "*" Matches 0 or more (greedy) repetitions of the preceding RE. Greedy means that it will match as many repetitions as possible. "+" Matches 1 or more (greedy) repetitions of the preceding RE. "?" Matches 0 or 1 (greedy) of the preceding RE. *?,+?,?? Non-greedy versions of the previous three special characters. {m,n} Matches from m to n repetitions of the preceding RE. {m,n}? Non-greedy version of the above. "\\" Either escapes special characters or signals a special sequence. [] Indicates a set of characters. A "^" as the first character indicates a complementing set. "|" A|B, creates an RE that will match either A or B. (...) Matches the RE inside the parentheses. The contents can be retrieved or matched later in the string. (?aiLmsux) Set the A, I, L, M, S, U, or X flag for the RE (see below). (?:...) Non-grouping version of regular parentheses. (?P<name>...) The substring matched by the group is accessible by name. (?P=name) Matches the text matched earlier by the group named name. (?#...) A comment; ignored. (?=...) Matches if ... matches next, but doesn't consume the string. (?!...) Matches if ... doesn't match next. (?<=...) Matches if preceded by ... (must be fixed length). (?<!...) Matches if not preceded by ... (must be fixed length). (?(id/name)yes|no) Matches yes pattern if the group with id/name matched, the (optional) no pattern otherwise. The special sequences consist of "\\" and a character from the list below. If the ordinary character is not on the list, then the resulting RE will match the second character. \number Matches the contents of the group of the same number. \A Matches only at the start of the string. \Z Matches only at the end of the string. \b Matches the empty string, but only at the start or end of a word. \B Matches the empty string, but not at the start or end of a word. \d Matches any decimal digit; equivalent to the set [0-9] in bytes patterns or string patterns with the ASCII flag. In string patterns without the ASCII flag, it will match the whole range of Unicode digits. \D Matches any non-digit character; equivalent to [^\d]. \s Matches any whitespace character; equivalent to [ \t\n\r\f\v] in bytes patterns or string patterns with the ASCII flag. In string patterns without the ASCII flag, it will match the whole range of Unicode whitespace characters. \S Matches any non-whitespace character; equivalent to [^\s]. \w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_] in bytes patterns or string patterns with the ASCII flag. In string patterns without the ASCII flag, it will match the range of Unicode alphanumeric characters (letters plus digits plus underscore). With LOCALE, it will match the set [0-9_] plus characters defined as letters for the current locale. \W Matches the complement of \w. \\ Matches a literal backslash. This module exports the following functions: match Match a regular expression pattern to the beginning of a string. fullmatch Match a regular expression pattern to all of a string. search Search a string for the presence of a pattern. sub Substitute occurrences of a pattern found in a string. subn Same as sub, but also return the number of substitutions made. split Split a string by the occurrences of a pattern. findall Find all occurrences of a pattern in a string. finditer Return an iterator yielding a match object for each match. compile Compile a pattern into a RegexObject. purge Clear the regular expression cache. escape Backslash all non-alphanumerics in a string. Some of the functions in this module takes flags as optional parameters: A ASCII For string patterns, make \w, \W, \b, \B, \d, \D match the corresponding ASCII character categories (rather than the whole Unicode categories, which is the default). For bytes patterns, this flag is the only available behaviour and needn't be specified. I IGNORECASE Perform case-insensitive matching. L LOCALE Make \w, \W, \b, \B, dependent on the current locale. M MULTILINE "^" matches the beginning of lines (after a newline) as well as the string. "$" matches the end of lines (before a newline) as well as the end of the string. S DOTALL "." matches any character at all, including the newline. X VERBOSE Ignore whitespace and comments for nicer looking RE's. U UNICODE For compatibility only. Ignored for string patterns (it is the default), and forbidden for bytes patterns. This module also defines an exception 'error'. """ import sys import sre_compile import sre_parse try: import _locale except ImportError: _locale = None # public symbols __all__ = [ "match", "fullmatch", "search", "sub", "subn", "split", "findall", "finditer", "compile", "purge", "template", "escape", "error", "A", "I", "L", "M", "S", "X", "U", "ASCII", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE", "UNICODE", ] __version__ = "2.2.1" # flags A = ASCII = sre_compile.SRE_FLAG_ASCII # assume ascii "locale" I = IGNORECASE = sre_compile.SRE_FLAG_IGNORECASE # ignore case L = LOCALE = sre_compile.SRE_FLAG_LOCALE # assume current 8-bit locale U = UNICODE = sre_compile.SRE_FLAG_UNICODE # assume unicode "locale" M = MULTILINE = sre_compile.SRE_FLAG_MULTILINE # make anchors look for newline S = DOTALL = sre_compile.SRE_FLAG_DOTALL # make dot match newline X = VERBOSE = sre_compile.SRE_FLAG_VERBOSE # ignore whitespace and comments # sre extensions (experimental, don't rely on these) T = TEMPLATE = sre_compile.SRE_FLAG_TEMPLATE # disable backtracking DEBUG = sre_compile.SRE_FLAG_DEBUG # dump pattern after compilation # sre exception error = sre_compile.error # -------------------------------------------------------------------- # public interface def match(pattern, string, flags=0): """Try to apply the pattern at the start of the string, returning a match object, or None if no match was found.""" return _compile(pattern, flags).match(string) def fullmatch(pattern, string, flags=0): """Try to apply the pattern to all of the string, returning a match object, or None if no match was found.""" return _compile(pattern, flags).fullmatch(string) def search(pattern, string, flags=0): """Scan through string looking for a match to the pattern, returning a match object, or None if no match was found.""" return _compile(pattern, flags).search(string) def sub(pattern, repl, string, count=0, flags=0): """Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used.""" return _compile(pattern, flags).sub(repl, string, count) def subn(pattern, repl, string, count=0, flags=0): """Return a 2-tuple containing (new_string, number). new_string is the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in the source string by the replacement repl. number is the number of substitutions that were made. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used.""" return _compile(pattern, flags).subn(repl, string, count) def split(pattern, string, maxsplit=0, flags=0): """Split the source string by the occurrences of the pattern, returning a list containing the resulting substrings. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit splits occur, and the remainder of the string is returned as the final element of the list.""" return _compile(pattern, flags).split(string, maxsplit) def findall(pattern, string, flags=0): """Return a list of all non-overlapping matches in the string. If one or more capturing groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.""" return _compile(pattern, flags).findall(string) def finditer(pattern, string, flags=0): """Return an iterator over all non-overlapping matches in the string. For each match, the iterator returns a match object. Empty matches are included in the result.""" return _compile(pattern, flags).finditer(string) def compile(pattern, flags=0): "Compile a regular expression pattern, returning a pattern object." return _compile(pattern, flags) def purge(): "Clear the regular expression caches" _cache.clear() _cache_repl.clear() def template(pattern, flags=0): "Compile a template pattern, returning a pattern object" return _compile(pattern, flags|T) _alphanum_str = frozenset( "_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890") _alphanum_bytes = frozenset( b"_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890") def escape(pattern): """ Escape all the characters in pattern except ASCII letters, numbers and '_'. """ if isinstance(pattern, str): alphanum = _alphanum_str s = list(pattern) for i, c in enumerate(pattern): if c not in alphanum: if c == "\000": s[i] = "\\000" else: s[i] = "\\" + c return "".join(s) else: alphanum = _alphanum_bytes s = [] esc = ord(b"\\") for c in pattern: if c in alphanum: s.append(c) else: if c == 0: s.extend(b"\\000") else: s.append(esc) s.append(c) return bytes(s) # -------------------------------------------------------------------- # internals _cache = {} _cache_repl = {} _pattern_type = type(sre_compile.compile("", 0)) _MAXCACHE = 512 def _compile(pattern, flags): # internal: compile pattern try: p, loc = _cache[type(pattern), pattern, flags] if loc is None or loc == _locale.setlocale(_locale.LC_CTYPE): return p except KeyError: pass if isinstance(pattern, _pattern_type): if flags: raise ValueError( "cannot process flags argument with a compiled pattern") return pattern if not sre_compile.isstring(pattern): raise TypeError("first argument must be string or compiled pattern") p = sre_compile.compile(pattern, flags) if not (flags & DEBUG): if len(_cache) >= _MAXCACHE: _cache.clear() if p.flags & LOCALE: if not _locale: return p loc = _locale.setlocale(_locale.LC_CTYPE) else: loc = None _cache[type(pattern), pattern, flags] = p, loc return p def _compile_repl(repl, pattern): # internal: compile replacement pattern try: return _cache_repl[repl, pattern] except KeyError: pass p = sre_parse.parse_template(repl, pattern) if len(_cache_repl) >= _MAXCACHE: _cache_repl.clear() _cache_repl[repl, pattern] = p return p def _expand(pattern, match, template): # internal: match.expand implementation hook template = sre_parse.parse_template(template, pattern) return sre_parse.expand_template(template, match) def _subx(pattern, template): # internal: pattern.sub/subn implementation helper template = _compile_repl(template, pattern) if not template[0] and len(template[1]) == 1: # literal replacement return template[1][0] def filter(match, template=template): return sre_parse.expand_template(template, match) return filter # register myself for pickling import copyreg def _pickle(p): return _compile, (p.pattern, p.flags) copyreg.pickle(_pattern_type, _pickle, _compile) # -------------------------------------------------------------------- # experimental stuff (see python-dev discussions for details) class Scanner: def __init__(self, lexicon, flags=0): from sre_constants import BRANCH, SUBPATTERN self.lexicon = lexicon # combine phrases into a compound pattern p = [] s = sre_parse.Pattern() s.flags = flags for phrase, action in lexicon: gid = s.opengroup() p.append(sre_parse.SubPattern(s, [ (SUBPATTERN, (gid, sre_parse.parse(phrase, flags))), ])) s.closegroup(gid, p[-1]) p = sre_parse.SubPattern(s, [(BRANCH, (None, p))]) self.scanner = sre_compile.compile(p) def scan(self, string): result = [] append = result.append match = self.scanner.scanner(string).match i = 0 while True: m = match() if not m: break j = m.end() if i == j: break action = self.lexicon[m.lastindex-1][1] if callable(action): self.match = m action = action(self, m.group()) if action is not None: append(action) i = j return result, string[i:]
mit
zcbenz/cefode-chromium
tools/telemetry/telemetry/core/extension_dict.py
35
1135
# 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. from telemetry.core import extension_to_load class ExtensionDict(object): """Dictionary of ExtensionPage instances, with extension_id as key""" def __init__(self, extension_dict_backend): self._extension_dict_backend = extension_dict_backend def __getitem__(self, load_extension): """Given an ExtensionToLoad instance, returns the corresponding ExtensionPage instance.""" if not isinstance(load_extension, extension_to_load.ExtensionToLoad): raise Exception("Input param must be of type ExtensionToLoad") return self._extension_dict_backend.__getitem__( load_extension.extension_id) def __contains__(self, load_extension): """Checks if this ExtensionToLoad instance has been loaded""" if not isinstance(load_extension, extension_to_load.ExtensionToLoad): raise Exception("Input param must be of type ExtensionToLoad") return self._extension_dict_backend.__contains__( load_extension.extension_id)
bsd-3-clause
pyKun/rally
rally/plugins/openstack/scenarios/ceilometer/samples.py
3
1169
# All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from rally import consts from rally.plugins.openstack.scenarios.ceilometer import utils as ceiloutils from rally.task.scenarios import base from rally.task import validation class CeilometerSamples(ceiloutils.CeilometerScenario): """Benchmark scenarios for Ceilometer Samples API.""" @validation.required_services(consts.Service.CEILOMETER) @validation.required_openstack(users=True) @base.scenario() def list_samples(self): """Fetch all samples. This scenario fetches list of all samples. """ self._list_samples()
apache-2.0
jlspyaozhongkai/Uter
third_party_backup/Python-2.7.9/Lib/email/mime/image.py
573
1764
# Copyright (C) 2001-2006 Python Software Foundation # Author: Barry Warsaw # Contact: email-sig@python.org """Class representing image/* type MIME documents.""" __all__ = ['MIMEImage'] import imghdr from email import encoders from email.mime.nonmultipart import MIMENonMultipart class MIMEImage(MIMENonMultipart): """Class for generating image/* type MIME documents.""" def __init__(self, _imagedata, _subtype=None, _encoder=encoders.encode_base64, **_params): """Create an image/* type MIME document. _imagedata is a string containing the raw image data. If this data can be decoded by the standard Python `imghdr' module, then the subtype will be automatically included in the Content-Type header. Otherwise, you can specify the specific image subtype via the _subtype parameter. _encoder is a function which will perform the actual encoding for transport of the image data. It takes one argument, which is this Image instance. It should use get_payload() and set_payload() to change the payload to the encoded form. It should also add any Content-Transfer-Encoding or other headers to the message as necessary. The default encoding is Base64. Any additional keyword arguments are passed to the base class constructor, which turns them into parameters on the Content-Type header. """ if _subtype is None: _subtype = imghdr.what(None, _imagedata) if _subtype is None: raise TypeError('Could not guess image MIME subtype') MIMENonMultipart.__init__(self, 'image', _subtype, **_params) self.set_payload(_imagedata) _encoder(self)
gpl-3.0
eayunstack/eayunstack-upgrade
ansible/library/keystone_v2_endpoint.py
1
9178
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2014, Kevin Carter <kevin.carter@rackspace.com> # # Copyright 2014, Rackspace US, 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. # Based on Jimmy Tang's implementation DOCUMENTATION = """ --- module: keystone_v2_endpoint short_description: - Manage OpenStack Identity (keystone) v2 endpoint. description: - Manage OpenStack Identity (keystone) v2 endpoint. endpoints. options: token: description: - The token to be uses in case the password is not specified required: true default: None endpoint: description: - The keystone url for authentication required: true service_name: description: - Name of the service. required: true default: None region_name: description: - Name of the region. required: true default: None service_type: description: - Type of service. required: true default: None endpoint_dict: description: - Dict of endpoint urls to add to keystone for a service required: true default: None type: dict state: description: - Ensuring the endpoint is either present, absent. - It always ensures endpoint is updated to latest url. required: False default: 'present' requirements: [ python-keystoneclient ] """ EXAMPLES = """ # Create an endpoint - keystone_v2_endpoint: region_name: "RegionOne" service_name: "glance" service_type: "image" endpoint: "http://127.0.0.1:5000/v2.0/" token: "ChangeMe" endpoint_dict: publicurl: "http://127.0.0.1:9292" adminurl: "http://127.0.0.1:9292" internalurl: "http://127.0.0.1:9292" """ try: from keystoneclient.v2_0 import client except ImportError: keystoneclient_found = False else: keystoneclient_found = True class ManageKeystoneV2Endpoint(object): def __init__(self, module): """Manage Keystone via Ansible.""" self.state_change = False self.keystone = None # Load AnsibleModule self.module = module @staticmethod def _facts(facts): """Return a dict for our Ansible facts. :param facts: ``dict`` Dict with data to return """ return {'keystone_facts': facts} def failure(self, error, rc, msg): """Return a Failure when running an Ansible command. :param error: ``str`` Error that occurred. :param rc: ``int`` Return code while executing an Ansible command. :param msg: ``str`` Message to report. """ self.module.fail_json(msg=msg, rc=rc, err=error) def _authenticate(self): """Return a keystone client object.""" endpoint = self.module.params.get('endpoint') token = self.module.params.get('token') if token is None: self.failure( error='Missing Auth Token', rc=2, msg='Auto token is required!' ) if token: self.keystone = client.Client( endpoint=endpoint, token=token ) def _get_service(self, name, srv_type=None): for entry in self.keystone.services.list(): if srv_type is not None: if entry.type == srv_type and name == entry.name: return entry elif entry.name == name: return entry else: return None def _get_endpoint(self, region, service_id): """ Getting endpoints per complete definition Returns the endpoint details for an endpoint matching region, service id. :param service_id: service to which the endpoint belongs :param region: geographic location of the endpoint """ for entry in self.keystone.endpoints.list(): check = [ entry.region == region, entry.service_id == service_id, ] if all(check): return entry else: return None def _compare_endpoint_info(self, endpoint, endpoint_dict): """ Compare existed endpoint with module parameters Return True if public, admin, internal urls are all the same. :param endpoint: endpoint existed :param endpoint_dict: endpoint info passed in """ check = [ endpoint.adminurl == endpoint_dict.get('adminurl'), endpoint.publicurl == endpoint_dict.get('publicurl'), endpoint.internalurl == endpoint_dict.get('internalurl') ] if all(check): return True else: return False def ensure_endpoint(self): """Ensures the deletion/modification/addition of endpoints within Keystone. Returns the endpoint ID on a successful run. """ self._authenticate() service_name = self.module.params.get('service_name') service_type = self.module.params.get('service_type') region = self.module.params.get('region_name') endpoint_dict = self.module.params.get('endpoint_dict') state = self.module.params.get('state') endpoint_dict = { 'adminurl': endpoint_dict.get('adminurl', ''), 'publicurl': endpoint_dict.get('publicurl', ''), 'internalurl': endpoint_dict.get('internalurl', '') } service = self._get_service(name=service_name, srv_type=service_type) if service is None: self.failure( error='service [ %s ] was not found.' % service_name, rc=2, msg='Service was not found, does it exist?' ) existed_endpoint = self._get_endpoint( region=region, service_id=service.id, ) delete_existed = False if state == 'present': ''' Creating an endpoint (if it does not exist) or creating a new one, and then deleting the existing endpoint that matches the service type, name, and region. ''' if existed_endpoint: if not self._compare_endpoint_info(existed_endpoint, endpoint_dict): delete_existed = True else: endpoint = existed_endpoint if (not existed_endpoint or delete_existed): self.state_change = True endpoint = self.keystone.endpoints.create( region=region, service_id=service.id, **endpoint_dict ) elif state == 'absent': if existed_endpoint is not None: self.state_change = True delete_existed = True if delete_existed: result = self.keystone.endpoints.delete(existed_endpoint.id) if result[0].status_code != 204: self.module.fail() if state != 'absent': facts = self._facts(endpoint.to_dict()) else: facts = self._facts({}) self.module.exit_json( changed=self.state_change, ansible_facts=facts ) # TODO(evrardjp): Deprecate state=update in Q. def main(): module = AnsibleModule( argument_spec=dict( token=dict( required=True ), endpoint=dict( required=True, ), region_name=dict( required=True ), service_name=dict( required=True ), service_type=dict( required=True ), endpoint_dict=dict( required=True, type='dict' ), state=dict( choices=['present', 'absent'], required=False, default='present' ) ), supports_check_mode=False, ) km = ManageKeystoneV2Endpoint(module=module) if not keystoneclient_found: km.failure( error='python-keystoneclient is missing', rc=2, msg='keystone client was not importable, is it installed?' ) facts = km.ensure_endpoint() # import module snippets from ansible.module_utils.basic import * # NOQA if __name__ == '__main__': main()
apache-2.0
haroldl/homeworklog
django/core/management/commands/reset.py
229
2598
from optparse import make_option from django.conf import settings from django.core.management.base import AppCommand, CommandError from django.core.management.color import no_style from django.core.management.sql import sql_reset from django.db import connections, transaction, DEFAULT_DB_ALIAS class Command(AppCommand): option_list = AppCommand.option_list + ( make_option('--noinput', action='store_false', dest='interactive', default=True, help='Tells Django to NOT prompt the user for input of any kind.'), make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Nominates a database to reset. ' 'Defaults to the "default" database.'), ) help = "Executes ``sqlreset`` for the given app(s) in the current database." args = '[appname ...]' output_transaction = True def handle_app(self, app, **options): # This command breaks a lot and should be deprecated import warnings warnings.warn( 'This command has been deprecated. The command ``flush`` can be used to delete everything. You can also use ALTER TABLE or DROP TABLE statements manually.', PendingDeprecationWarning ) using = options.get('database', DEFAULT_DB_ALIAS) connection = connections[using] app_name = app.__name__.split('.')[-2] self.style = no_style() sql_list = sql_reset(app, self.style, connection) if options.get('interactive'): confirm = raw_input(""" You have requested a database reset. This will IRREVERSIBLY DESTROY any data for the "%s" application in the database "%s". Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: """ % (app_name, connection.settings_dict['NAME'])) else: confirm = 'yes' if confirm == 'yes': try: cursor = connection.cursor() for sql in sql_list: cursor.execute(sql) except Exception, e: transaction.rollback_unless_managed() raise CommandError("""Error: %s couldn't be reset. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin.py sqlreset %s'. That's the SQL this command wasn't able to run. The full error: %s""" % (app_name, app_name, e)) transaction.commit_unless_managed() else: print "Reset cancelled."
bsd-3-clause
fards/Ainol_fire_kernel
tools/perf/scripts/python/futex-contention.py
11261
1486
# futex contention # (c) 2010, Arnaldo Carvalho de Melo <acme@redhat.com> # Licensed under the terms of the GNU GPL License version 2 # # Translation of: # # http://sourceware.org/systemtap/wiki/WSFutexContention # # to perf python scripting. # # Measures futex contention import os, sys sys.path.append(os.environ['PERF_EXEC_PATH'] + '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from Util import * process_names = {} thread_thislock = {} thread_blocktime = {} lock_waits = {} # long-lived stats on (tid,lock) blockage elapsed time process_names = {} # long-lived pid-to-execname mapping def syscalls__sys_enter_futex(event, ctxt, cpu, s, ns, tid, comm, nr, uaddr, op, val, utime, uaddr2, val3): cmd = op & FUTEX_CMD_MASK if cmd != FUTEX_WAIT: return # we don't care about originators of WAKE events process_names[tid] = comm thread_thislock[tid] = uaddr thread_blocktime[tid] = nsecs(s, ns) def syscalls__sys_exit_futex(event, ctxt, cpu, s, ns, tid, comm, nr, ret): if thread_blocktime.has_key(tid): elapsed = nsecs(s, ns) - thread_blocktime[tid] add_stats(lock_waits, (tid, thread_thislock[tid]), elapsed) del thread_blocktime[tid] del thread_thislock[tid] def trace_begin(): print "Press control+C to stop and show the summary" def trace_end(): for (tid, lock) in lock_waits: min, max, avg, count = lock_waits[tid, lock] print "%s[%d] lock %x contended %d times, %d avg ns" % \ (process_names[tid], tid, lock, count, avg)
gpl-2.0
TinLe/Diamond
src/collectors/snmpraw/snmpraw.py
56
6074
# coding=utf-8 """ The SNMPRawCollector is designed for collecting data from SNMP-enables devices, using a set of specified OIDs #### Configuration Below is an example configuration for the SNMPRawCollector. The collector can collect data any number of devices by adding configuration sections under the *devices* header. By default the collector will collect every 60 seconds. This might be a bit excessive and put unnecessary load on the devices being polled. You may wish to change this to every 300 seconds. However you need modify your graphite data retentions to handle this properly. ``` # Options for SNMPRawCollector enabled = True interval = 60 [devices] # Start the device configuration # Note: this name will be used in the metric path. [[my-identification-for-this-host]] host = localhost port = 161 community = public # Start the OID list for this device # Note: the value part will be used in the metric path. [[[oids]]] 1.3.6.1.4.1.2021.10.1.3.1 = cpu.load.1min 1.3.6.1.4.1.2021.10.1.3.2 = cpu.load.5min 1.3.6.1.4.1.2021.10.1.3.3 = cpu.load.15min # If you want another host, you can. But you probably won't need it. [[another-identification]] host = router1.example.com port = 161 community = public [[[oids]]] oid = metric.path oid = metric.path ``` Note: If you modify the SNMPRawCollector configuration, you will need to restart diamond. #### Dependencies * pysmnp (which depends on pyasn1 0.1.7 and pycrypto) """ import os import sys import time sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)), 'snmp')) from snmp import SNMPCollector as parent_SNMPCollector from diamond.metric import Metric class SNMPRawCollector(parent_SNMPCollector): def process_config(self): super(SNMPRawCollector, self).process_config() # list to save non-existing oid's per device, to avoid repetition of # errors in logging. Signal HUP to diamond/collector to flush this self.skip_list = [] def get_default_config(self): """ Override SNMPCollector.get_default_config method to provide default_config for the SNMPInterfaceCollector """ default_config = super(SNMPRawCollector, self).get_default_config() default_config.update({ 'oids': {}, 'path_prefix': 'servers', 'path_suffix': 'snmp', }) return default_config def _precision(self, value): """ Return the precision of the number """ value = str(value) decimal = value.rfind('.') if decimal == -1: return 0 return len(value) - decimal - 1 def _skip(self, device, oid, reason=None): self.skip_list.append((device, oid)) if reason is not None: self.log.warn('Muted \'{0}\' on \'{1}\', because: {2}'.format( oid, device, reason)) def _get_value_walk(self, device, oid, host, port, community): data = self.walk(oid, host, port, community) if data is None: self._skip(device, oid, 'device down (#2)') return self.log.debug('Data received from WALK \'{0}\': [{1}]'.format( device, data)) if len(data) != 1: self._skip( device, oid, 'unexpected response, data has {0} entries'.format( len(data))) return # because we only allow 1-key dicts, we can pick with absolute index value = data.items()[0][1] return value def _get_value(self, device, oid, host, port, community): data = self.get(oid, host, port, community) if data is None: self._skip(device, oid, 'device down (#1)') return self.log.debug('Data received from GET \'{0}\': [{1}]'.format( device, data)) if len(data) == 0: self._skip(device, oid, 'empty response, device down?') return if oid not in data: # oid is not even in hierarchy, happens when using 9.9.9.9 # but not when using 1.9.9.9 self._skip(device, oid, 'no object at OID (#1)') return value = data[oid] if value == 'No Such Object currently exists at this OID': self._skip(device, oid, 'no object at OID (#2)') return if value == 'No Such Instance currently exists at this OID': return self._get_value_walk(device, oid, host, port, community) return value def collect_snmp(self, device, host, port, community): """ Collect SNMP interface data from device """ self.log.debug( 'Collecting raw SNMP statistics from device \'{0}\''.format(device)) dev_config = self.config['devices'][device] if 'oids' in dev_config: for oid, metricName in dev_config['oids'].items(): if (device, oid) in self.skip_list: self.log.debug( 'Skipping OID \'{0}\' ({1}) on device \'{2}\''.format( oid, metricName, device)) continue timestamp = time.time() value = self._get_value(device, oid, host, port, community) if value is None: continue self.log.debug( '\'{0}\' ({1}) on device \'{2}\' - value=[{3}]'.format( oid, metricName, device, value)) path = '.'.join([self.config['path_prefix'], device, self.config['path_suffix'], metricName]) metric = Metric(path=path, value=value, timestamp=timestamp, precision=self._precision(value), metric_type='GAUGE') self.publish_metric(metric)
mit
sinhrks/scikit-learn
sklearn/externals/joblib/_memory_helpers.py
303
3605
try: # Available in Python 3 from tokenize import open as open_py_source except ImportError: # Copied from python3 tokenize from codecs import lookup, BOM_UTF8 import re from io import TextIOWrapper, open cookie_re = re.compile("coding[:=]\s*([-\w.]+)") def _get_normal_name(orig_enc): """Imitates get_normal_name in tokenizer.c.""" # Only care about the first 12 characters. enc = orig_enc[:12].lower().replace("_", "-") if enc == "utf-8" or enc.startswith("utf-8-"): return "utf-8" if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \ enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")): return "iso-8859-1" return orig_enc def _detect_encoding(readline): """ The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argment, readline, in the same way as the tokenize() generator. It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (left as bytes) it has read in. It detects the encoding from the presence of a utf-8 bom or an encoding cookie as specified in pep-0263. If both a bom and a cookie are present, but disagree, a SyntaxError will be raised. If the encoding cookie is an invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found, 'utf-8-sig' is returned. If no encoding is specified, then the default of 'utf-8' will be returned. """ bom_found = False encoding = None default = 'utf-8' def read_or_stop(): try: return readline() except StopIteration: return b'' def find_cookie(line): try: line_string = line.decode('ascii') except UnicodeDecodeError: return None matches = cookie_re.findall(line_string) if not matches: return None encoding = _get_normal_name(matches[0]) try: codec = lookup(encoding) except LookupError: # This behaviour mimics the Python interpreter raise SyntaxError("unknown encoding: " + encoding) if bom_found: if codec.name != 'utf-8': # This behaviour mimics the Python interpreter raise SyntaxError('encoding problem: utf-8') encoding += '-sig' return encoding first = read_or_stop() if first.startswith(BOM_UTF8): bom_found = True first = first[3:] default = 'utf-8-sig' if not first: return default, [] encoding = find_cookie(first) if encoding: return encoding, [first] second = read_or_stop() if not second: return default, [first] encoding = find_cookie(second) if encoding: return encoding, [first, second] return default, [first, second] def open_py_source(filename): """Open a file in read only mode using the encoding detected by detect_encoding(). """ buffer = open(filename, 'rb') encoding, lines = _detect_encoding(buffer.readline) buffer.seek(0) text = TextIOWrapper(buffer, encoding, line_buffering=True) text.mode = 'r' return text
bsd-3-clause
lexus42/2015cd_midterm2
static/Brython3.1.1-20150328-091302/Lib/unittest/test/test_skipping.py
744
5173
import unittest from .support import LoggingResult class Test_TestSkipping(unittest.TestCase): def test_skipping(self): class Foo(unittest.TestCase): def test_skip_me(self): self.skipTest("skip") events = [] result = LoggingResult(events) test = Foo("test_skip_me") test.run(result) self.assertEqual(events, ['startTest', 'addSkip', 'stopTest']) self.assertEqual(result.skipped, [(test, "skip")]) # Try letting setUp skip the test now. class Foo(unittest.TestCase): def setUp(self): self.skipTest("testing") def test_nothing(self): pass events = [] result = LoggingResult(events) test = Foo("test_nothing") test.run(result) self.assertEqual(events, ['startTest', 'addSkip', 'stopTest']) self.assertEqual(result.skipped, [(test, "testing")]) self.assertEqual(result.testsRun, 1) def test_skipping_decorators(self): op_table = ((unittest.skipUnless, False, True), (unittest.skipIf, True, False)) for deco, do_skip, dont_skip in op_table: class Foo(unittest.TestCase): @deco(do_skip, "testing") def test_skip(self): pass @deco(dont_skip, "testing") def test_dont_skip(self): pass test_do_skip = Foo("test_skip") test_dont_skip = Foo("test_dont_skip") suite = unittest.TestSuite([test_do_skip, test_dont_skip]) events = [] result = LoggingResult(events) suite.run(result) self.assertEqual(len(result.skipped), 1) expected = ['startTest', 'addSkip', 'stopTest', 'startTest', 'addSuccess', 'stopTest'] self.assertEqual(events, expected) self.assertEqual(result.testsRun, 2) self.assertEqual(result.skipped, [(test_do_skip, "testing")]) self.assertTrue(result.wasSuccessful()) def test_skip_class(self): @unittest.skip("testing") class Foo(unittest.TestCase): def test_1(self): record.append(1) record = [] result = unittest.TestResult() test = Foo("test_1") suite = unittest.TestSuite([test]) suite.run(result) self.assertEqual(result.skipped, [(test, "testing")]) self.assertEqual(record, []) def test_skip_non_unittest_class(self): @unittest.skip("testing") class Mixin: def test_1(self): record.append(1) class Foo(Mixin, unittest.TestCase): pass record = [] result = unittest.TestResult() test = Foo("test_1") suite = unittest.TestSuite([test]) suite.run(result) self.assertEqual(result.skipped, [(test, "testing")]) self.assertEqual(record, []) def test_expected_failure(self): class Foo(unittest.TestCase): @unittest.expectedFailure def test_die(self): self.fail("help me!") events = [] result = LoggingResult(events) test = Foo("test_die") test.run(result) self.assertEqual(events, ['startTest', 'addExpectedFailure', 'stopTest']) self.assertEqual(result.expectedFailures[0][0], test) self.assertTrue(result.wasSuccessful()) def test_unexpected_success(self): class Foo(unittest.TestCase): @unittest.expectedFailure def test_die(self): pass events = [] result = LoggingResult(events) test = Foo("test_die") test.run(result) self.assertEqual(events, ['startTest', 'addUnexpectedSuccess', 'stopTest']) self.assertFalse(result.failures) self.assertEqual(result.unexpectedSuccesses, [test]) self.assertTrue(result.wasSuccessful()) def test_skip_doesnt_run_setup(self): class Foo(unittest.TestCase): wasSetUp = False wasTornDown = False def setUp(self): Foo.wasSetUp = True def tornDown(self): Foo.wasTornDown = True @unittest.skip('testing') def test_1(self): pass result = unittest.TestResult() test = Foo("test_1") suite = unittest.TestSuite([test]) suite.run(result) self.assertEqual(result.skipped, [(test, "testing")]) self.assertFalse(Foo.wasSetUp) self.assertFalse(Foo.wasTornDown) def test_decorated_skip(self): def decorator(func): def inner(*a): return func(*a) return inner class Foo(unittest.TestCase): @decorator @unittest.skip('testing') def test_1(self): pass result = unittest.TestResult() test = Foo("test_1") suite = unittest.TestSuite([test]) suite.run(result) self.assertEqual(result.skipped, [(test, "testing")])
agpl-3.0
gaddman/ansible
lib/ansible/modules/storage/ibm/ibm_sa_domain.py
9
4173
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, IBM CORPORATION # Author(s): Tzur Eliyahu <tzure@il.ibm.com> # # GNU General Public License v3.0+ (see COPYING or # https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: ibm_sa_domain short_description: Manages domains on IBM Spectrum Accelerate Family storage systems version_added: "2.8" description: - "This module can be used to add domains to or removes them from IBM Spectrum Accelerate Family storage systems." options: domain: description: - Name of the domain to be managed. required: true state: description: - The desired state of the domain. required: true default: "present" choices: [ "present", "absent" ] ldap_id: description: - ldap id to add to the domain. required: false size: description: - Size of the domain. required: false hard_capacity: description: - Hard capacity of the domain. required: false soft_capacity: description: - Soft capacity of the domain. required: false max_cgs: description: - Number of max cgs. required: false max_dms: description: - Number of max dms. required: false max_mirrors: description: - Number of max_mirrors. required: false max_pools: description: - Number of max_pools. required: false max_volumes: description: - Number of max_volumes. required: false perf_class: description: - Add the domain to a performance class. required: false extends_documentation_fragment: - ibm_storage author: - Tzur Eliyahu (@tzure) ''' EXAMPLES = ''' - name: Define new domain. ibm_sa_domain: domain: domain_name size: domain_size state: present username: admin password: secret endpoints: hostdev-system - name: Delete domain. ibm_sa_domain: domain: domain_name state: absent username: admin password: secret endpoints: hostdev-system ''' RETURN = ''' msg: description: module return status. returned: as needed type: string sample: "domain 'domain_name' created successfully." ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ibm_sa_utils import execute_pyxcli_command, \ connect_ssl, spectrum_accelerate_spec, is_pyxcli_installed def main(): argument_spec = spectrum_accelerate_spec() argument_spec.update( dict( state=dict(default='present', choices=['present', 'absent']), domain=dict(required=True), size=dict(), max_dms=dict(), max_cgs=dict(), ldap_id=dict(), max_mirrors=dict(), max_pools=dict(), max_volumes=dict(), perf_class=dict(), hard_capacity=dict(), soft_capacity=dict() ) ) module = AnsibleModule(argument_spec) is_pyxcli_installed(module) xcli_client = connect_ssl(module) domain = xcli_client.cmd.domain_list( domain=module.params['domain']).as_single_element state = module.params['state'] state_changed = False msg = 'Domain \'{0}\''.format(module.params['domain']) if state == 'present' and not domain: state_changed = execute_pyxcli_command( module, 'domain_create', xcli_client) msg += " created successfully." elif state == 'absent' and domain: state_changed = execute_pyxcli_command( module, 'domain_delete', xcli_client) msg += " deleted successfully." else: msg += " state unchanged." module.exit_json(changed=state_changed, msg=msg) if __name__ == '__main__': main()
gpl-3.0
shakamunyi/nova
nova/tests/unit/db/test_migrations.py
1
32632
# Copyright 2010-2011 OpenStack Foundation # Copyright 2012-2013 IBM Corp. # 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 database migrations. There are "opportunistic" tests which allows testing against all 3 databases (sqlite in memory, mysql, pg) in a properly configured unit test environment. For the opportunistic testing you need to set up db's named 'openstack_citest' with user 'openstack_citest' and password 'openstack_citest' on localhost. The test will then use that db and u/p combo to run the tests. For postgres on Ubuntu this can be done with the following commands:: | sudo -u postgres psql | postgres=# create user openstack_citest with createdb login password | 'openstack_citest'; | postgres=# create database openstack_citest with owner openstack_citest; """ import glob import logging import os from migrate.versioning import repository import mock from oslo.db.sqlalchemy import test_base from oslo.db.sqlalchemy import test_migrations from oslo.db.sqlalchemy import utils as oslodbutils import sqlalchemy from sqlalchemy.engine import reflection import sqlalchemy.exc from sqlalchemy.sql import null from nova.db import migration from nova.db.sqlalchemy import migrate_repo from nova.db.sqlalchemy import migration as sa_migration from nova.db.sqlalchemy import utils as db_utils from nova import exception from nova import test LOG = logging.getLogger(__name__) class NovaMigrationsCheckers(test_migrations.WalkVersionsMixin): """Test sqlalchemy-migrate migrations.""" TIMEOUT_SCALING_FACTOR = 2 snake_walk = True downgrade = True @property def INIT_VERSION(self): return migration.db_initial_version() @property def REPOSITORY(self): return repository.Repository( os.path.abspath(os.path.dirname(migrate_repo.__file__))) @property def migration_api(self): return sa_migration.versioning_api @property def migrate_engine(self): return self.engine def setUp(self): super(NovaMigrationsCheckers, self).setUp() # NOTE(viktors): We should reduce log output because it causes issues, # when we run tests with testr migrate_log = logging.getLogger('migrate') old_level = migrate_log.level migrate_log.setLevel(logging.WARN) self.addCleanup(migrate_log.setLevel, old_level) def assertColumnExists(self, engine, table_name, column): self.assertTrue(oslodbutils.column_exists(engine, table_name, column)) def assertColumnNotExists(self, engine, table_name, column): self.assertFalse(oslodbutils.column_exists(engine, table_name, column)) def assertTableNotExists(self, engine, table): self.assertRaises(sqlalchemy.exc.NoSuchTableError, oslodbutils.get_table, engine, table) def assertIndexExists(self, engine, table_name, index): self.assertTrue(oslodbutils.index_exists(engine, table_name, index)) def assertIndexNotExists(self, engine, table_name, index): self.assertFalse(oslodbutils.index_exists(engine, table_name, index)) def assertIndexMembers(self, engine, table, index, members): # NOTE(johannes): Order of columns can matter. Most SQL databases # can use the leading columns for optimizing queries that don't # include all of the covered columns. self.assertIndexExists(engine, table, index) t = oslodbutils.get_table(engine, table) index_columns = None for idx in t.indexes: if idx.name == index: index_columns = [c.name for c in idx.columns] break self.assertEqual(members, index_columns) def _skippable_migrations(self): special = [ 216, # Havana 272, # NOOP migration due to revert ] havana_placeholders = range(217, 227) icehouse_placeholders = range(235, 244) juno_placeholders = range(255, 265) return (special + havana_placeholders + icehouse_placeholders + juno_placeholders) def migrate_up(self, version, with_data=False): if with_data: check = getattr(self, "_check_%03d" % version, None) if version not in self._skippable_migrations(): self.assertIsNotNone(check, ('DB Migration %i does not have a ' 'test. Please add one!') % version) super(NovaMigrationsCheckers, self).migrate_up(version, with_data) def test_walk_versions(self): self.walk_versions(self.snake_walk, self.downgrade) def _check_227(self, engine, data): table = oslodbutils.get_table(engine, 'project_user_quotas') # Insert fake_quotas with the longest resource name. fake_quotas = {'id': 5, 'project_id': 'fake_project', 'user_id': 'fake_user', 'resource': 'injected_file_content_bytes', 'hard_limit': 10} table.insert().execute(fake_quotas) # Check we can get the longest resource name. quota = table.select(table.c.id == 5).execute().first() self.assertEqual(quota['resource'], 'injected_file_content_bytes') def _check_228(self, engine, data): self.assertColumnExists(engine, 'compute_nodes', 'metrics') compute_nodes = oslodbutils.get_table(engine, 'compute_nodes') self.assertIsInstance(compute_nodes.c.metrics.type, sqlalchemy.types.Text) def _post_downgrade_228(self, engine): self.assertColumnNotExists(engine, 'compute_nodes', 'metrics') def _check_229(self, engine, data): self.assertColumnExists(engine, 'compute_nodes', 'extra_resources') compute_nodes = oslodbutils.get_table(engine, 'compute_nodes') self.assertIsInstance(compute_nodes.c.extra_resources.type, sqlalchemy.types.Text) def _post_downgrade_229(self, engine): self.assertColumnNotExists(engine, 'compute_nodes', 'extra_resources') def _check_230(self, engine, data): for table_name in ['instance_actions_events', 'shadow_instance_actions_events']: self.assertColumnExists(engine, table_name, 'host') self.assertColumnExists(engine, table_name, 'details') action_events = oslodbutils.get_table(engine, 'instance_actions_events') self.assertIsInstance(action_events.c.host.type, sqlalchemy.types.String) self.assertIsInstance(action_events.c.details.type, sqlalchemy.types.Text) def _post_downgrade_230(self, engine): for table_name in ['instance_actions_events', 'shadow_instance_actions_events']: self.assertColumnNotExists(engine, table_name, 'host') self.assertColumnNotExists(engine, table_name, 'details') def _check_231(self, engine, data): self.assertColumnExists(engine, 'instances', 'ephemeral_key_uuid') instances = oslodbutils.get_table(engine, 'instances') self.assertIsInstance(instances.c.ephemeral_key_uuid.type, sqlalchemy.types.String) self.assertTrue(db_utils.check_shadow_table(engine, 'instances')) def _post_downgrade_231(self, engine): self.assertColumnNotExists(engine, 'instances', 'ephemeral_key_uuid') self.assertTrue(db_utils.check_shadow_table(engine, 'instances')) def _check_232(self, engine, data): table_names = ['compute_node_stats', 'compute_nodes', 'instance_actions', 'instance_actions_events', 'instance_faults', 'migrations'] for table_name in table_names: self.assertTableNotExists(engine, 'dump_' + table_name) def _check_233(self, engine, data): self.assertColumnExists(engine, 'compute_nodes', 'stats') compute_nodes = oslodbutils.get_table(engine, 'compute_nodes') self.assertIsInstance(compute_nodes.c.stats.type, sqlalchemy.types.Text) self.assertRaises(sqlalchemy.exc.NoSuchTableError, oslodbutils.get_table, engine, 'compute_node_stats') def _post_downgrade_233(self, engine): self.assertColumnNotExists(engine, 'compute_nodes', 'stats') # confirm compute_node_stats exists oslodbutils.get_table(engine, 'compute_node_stats') def _check_234(self, engine, data): self.assertIndexMembers(engine, 'reservations', 'reservations_deleted_expire_idx', ['deleted', 'expire']) def _check_244(self, engine, data): volume_usage_cache = oslodbutils.get_table( engine, 'volume_usage_cache') self.assertEqual(64, volume_usage_cache.c.user_id.type.length) def _post_downgrade_244(self, engine): volume_usage_cache = oslodbutils.get_table( engine, 'volume_usage_cache') self.assertEqual(36, volume_usage_cache.c.user_id.type.length) def _pre_upgrade_245(self, engine): # create a fake network networks = oslodbutils.get_table(engine, 'networks') fake_network = {'id': 1} networks.insert().execute(fake_network) def _check_245(self, engine, data): networks = oslodbutils.get_table(engine, 'networks') network = networks.select(networks.c.id == 1).execute().first() # mtu should default to None self.assertIsNone(network.mtu) # dhcp_server should default to None self.assertIsNone(network.dhcp_server) # enable dhcp should default to true self.assertTrue(network.enable_dhcp) # share address should default to false self.assertFalse(network.share_address) def _post_downgrade_245(self, engine): self.assertColumnNotExists(engine, 'networks', 'mtu') self.assertColumnNotExists(engine, 'networks', 'dhcp_server') self.assertColumnNotExists(engine, 'networks', 'enable_dhcp') self.assertColumnNotExists(engine, 'networks', 'share_address') def _check_246(self, engine, data): pci_devices = oslodbutils.get_table(engine, 'pci_devices') self.assertEqual(1, len([fk for fk in pci_devices.foreign_keys if fk.parent.name == 'compute_node_id'])) def _post_downgrade_246(self, engine): pci_devices = oslodbutils.get_table(engine, 'pci_devices') self.assertEqual(0, len([fk for fk in pci_devices.foreign_keys if fk.parent.name == 'compute_node_id'])) def _check_247(self, engine, data): quota_usages = oslodbutils.get_table(engine, 'quota_usages') self.assertFalse(quota_usages.c.resource.nullable) pci_devices = oslodbutils.get_table(engine, 'pci_devices') self.assertTrue(pci_devices.c.deleted.nullable) self.assertFalse(pci_devices.c.product_id.nullable) self.assertFalse(pci_devices.c.vendor_id.nullable) self.assertFalse(pci_devices.c.dev_type.nullable) def _post_downgrade_247(self, engine): quota_usages = oslodbutils.get_table(engine, 'quota_usages') self.assertTrue(quota_usages.c.resource.nullable) pci_devices = oslodbutils.get_table(engine, 'pci_devices') self.assertFalse(pci_devices.c.deleted.nullable) self.assertTrue(pci_devices.c.product_id.nullable) self.assertTrue(pci_devices.c.vendor_id.nullable) self.assertTrue(pci_devices.c.dev_type.nullable) def _check_248(self, engine, data): self.assertIndexMembers(engine, 'reservations', 'reservations_deleted_expire_idx', ['deleted', 'expire']) def _post_downgrade_248(self, engine): reservations = oslodbutils.get_table(engine, 'reservations') index_names = [idx.name for idx in reservations.indexes] self.assertNotIn('reservations_deleted_expire_idx', index_names) def _check_249(self, engine, data): # Assert that only one index exists that covers columns # instance_uuid and device_name bdm = oslodbutils.get_table(engine, 'block_device_mapping') self.assertEqual(1, len([i for i in bdm.indexes if [c.name for c in i.columns] == ['instance_uuid', 'device_name']])) def _post_downgrade_249(self, engine): # The duplicate index is not created on downgrade, so this # asserts that only one index exists that covers columns # instance_uuid and device_name bdm = oslodbutils.get_table(engine, 'block_device_mapping') self.assertEqual(1, len([i for i in bdm.indexes if [c.name for c in i.columns] == ['instance_uuid', 'device_name']])) def _check_250(self, engine, data): self.assertTableNotExists(engine, 'instance_group_metadata') self.assertTableNotExists(engine, 'shadow_instance_group_metadata') def _post_downgrade_250(self, engine): oslodbutils.get_table(engine, 'instance_group_metadata') oslodbutils.get_table(engine, 'shadow_instance_group_metadata') def _check_251(self, engine, data): self.assertColumnExists(engine, 'compute_nodes', 'numa_topology') self.assertColumnExists(engine, 'shadow_compute_nodes', 'numa_topology') compute_nodes = oslodbutils.get_table(engine, 'compute_nodes') shadow_compute_nodes = oslodbutils.get_table(engine, 'shadow_compute_nodes') self.assertIsInstance(compute_nodes.c.numa_topology.type, sqlalchemy.types.Text) self.assertIsInstance(shadow_compute_nodes.c.numa_topology.type, sqlalchemy.types.Text) def _post_downgrade_251(self, engine): self.assertColumnNotExists(engine, 'compute_nodes', 'numa_topology') self.assertColumnNotExists(engine, 'shadow_compute_nodes', 'numa_topology') def _check_252(self, engine, data): oslodbutils.get_table(engine, 'instance_extra') oslodbutils.get_table(engine, 'shadow_instance_extra') self.assertIndexMembers(engine, 'instance_extra', 'instance_extra_idx', ['instance_uuid']) def _post_downgrade_252(self, engine): self.assertTableNotExists(engine, 'instance_extra') self.assertTableNotExists(engine, 'shadow_instance_extra') def _check_253(self, engine, data): self.assertColumnExists(engine, 'instance_extra', 'pci_requests') self.assertColumnExists( engine, 'shadow_instance_extra', 'pci_requests') instance_extra = oslodbutils.get_table(engine, 'instance_extra') shadow_instance_extra = oslodbutils.get_table(engine, 'shadow_instance_extra') self.assertIsInstance(instance_extra.c.pci_requests.type, sqlalchemy.types.Text) self.assertIsInstance(shadow_instance_extra.c.pci_requests.type, sqlalchemy.types.Text) def _post_downgrade_253(self, engine): self.assertColumnNotExists(engine, 'instance_extra', 'pci_requests') self.assertColumnNotExists(engine, 'shadow_instance_extra', 'pci_requests') def _check_254(self, engine, data): self.assertColumnExists(engine, 'pci_devices', 'request_id') self.assertColumnExists( engine, 'shadow_pci_devices', 'request_id') pci_devices = oslodbutils.get_table(engine, 'pci_devices') shadow_pci_devices = oslodbutils.get_table( engine, 'shadow_pci_devices') self.assertIsInstance(pci_devices.c.request_id.type, sqlalchemy.types.String) self.assertIsInstance(shadow_pci_devices.c.request_id.type, sqlalchemy.types.String) def _post_downgrade_254(self, engine): self.assertColumnNotExists(engine, 'pci_devices', 'request_id') self.assertColumnNotExists( engine, 'shadow_pci_devices', 'request_id') def _check_265(self, engine, data): # Assert that only one index exists that covers columns # host and deleted instances = oslodbutils.get_table(engine, 'instances') self.assertEqual(1, len([i for i in instances.indexes if [c.name for c in i.columns][:2] == ['host', 'deleted']])) # and only one index covers host column iscsi_targets = oslodbutils.get_table(engine, 'iscsi_targets') self.assertEqual(1, len([i for i in iscsi_targets.indexes if [c.name for c in i.columns][:1] == ['host']])) def _post_downgrade_265(self, engine): # The duplicated index is not created on downgrade, so this # asserts that only one index exists that covers columns # host and deleted instances = oslodbutils.get_table(engine, 'instances') self.assertEqual(1, len([i for i in instances.indexes if [c.name for c in i.columns][:2] == ['host', 'deleted']])) # and only one index covers host column iscsi_targets = oslodbutils.get_table(engine, 'iscsi_targets') self.assertEqual(1, len([i for i in iscsi_targets.indexes if [c.name for c in i.columns][:1] == ['host']])) def _check_266(self, engine, data): self.assertColumnExists(engine, 'tags', 'resource_id') self.assertColumnExists(engine, 'tags', 'tag') table = oslodbutils.get_table(engine, 'tags') self.assertIsInstance(table.c.resource_id.type, sqlalchemy.types.String) self.assertIsInstance(table.c.tag.type, sqlalchemy.types.String) def _post_downgrade_266(self, engine): self.assertTableNotExists(engine, 'tags') def _pre_upgrade_267(self, engine): # Create a fixed_ips row with a null instance_uuid (if not already # there) to make sure that's not deleted. fixed_ips = oslodbutils.get_table(engine, 'fixed_ips') fake_fixed_ip = {'id': 1} fixed_ips.insert().execute(fake_fixed_ip) # Create an instance record with a valid (non-null) UUID so we make # sure we don't do something stupid and delete valid records. instances = oslodbutils.get_table(engine, 'instances') fake_instance = {'id': 1, 'uuid': 'fake-non-null-uuid'} instances.insert().execute(fake_instance) # Add a null instance_uuid entry for the volumes table # since it doesn't have a foreign key back to the instances table. volumes = oslodbutils.get_table(engine, 'volumes') fake_volume = {'id': '9c3c317e-24db-4d57-9a6f-96e6d477c1da'} volumes.insert().execute(fake_volume) def _check_267(self, engine, data): # Make sure the column is non-nullable and the UC exists. fixed_ips = oslodbutils.get_table(engine, 'fixed_ips') self.assertTrue(fixed_ips.c.instance_uuid.nullable) fixed_ip = fixed_ips.select(fixed_ips.c.id == 1).execute().first() self.assertIsNone(fixed_ip.instance_uuid) instances = oslodbutils.get_table(engine, 'instances') self.assertFalse(instances.c.uuid.nullable) inspector = reflection.Inspector.from_engine(engine) constraints = inspector.get_unique_constraints('instances') constraint_names = [constraint['name'] for constraint in constraints] self.assertIn('uniq_instances0uuid', constraint_names) # Make sure the instances record with the valid uuid is still there. instance = instances.select(instances.c.id == 1).execute().first() self.assertIsNotNone(instance) # Check that the null entry in the volumes table is still there since # we skipped tables that don't have FK's back to the instances table. volumes = oslodbutils.get_table(engine, 'volumes') self.assertTrue(volumes.c.instance_uuid.nullable) volume = fixed_ips.select( volumes.c.id == '9c3c317e-24db-4d57-9a6f-96e6d477c1da' ).execute().first() self.assertIsNone(volume.instance_uuid) def _post_downgrade_267(self, engine): # Make sure the UC is gone and the column is nullable again. instances = oslodbutils.get_table(engine, 'instances') self.assertTrue(instances.c.uuid.nullable) inspector = reflection.Inspector.from_engine(engine) constraints = inspector.get_unique_constraints('instances') constraint_names = [constraint['name'] for constraint in constraints] self.assertNotIn('uniq_instances0uuid', constraint_names) def test_migration_267(self): # This is separate from test_walk_versions so we can test the case # where there are non-null instance_uuid entries in the database which # cause the 267 migration to fail. engine = self.migrate_engine self.migration_api.version_control( engine, self.REPOSITORY, self.INIT_VERSION) self.migration_api.upgrade(engine, self.REPOSITORY, 266) # Create a consoles record with a null instance_uuid so # we can test that the upgrade fails if that entry is found. # NOTE(mriedem): We use the consoles table since that's the only table # created in the 216 migration with a ForeignKey created on the # instance_uuid table for sqlite. consoles = oslodbutils.get_table(engine, 'consoles') fake_console = {'id': 1} consoles.insert().execute(fake_console) # NOTE(mriedem): We handle the 267 migration where we expect to # hit a ValidationError on the consoles table to have # a null instance_uuid entry ex = self.assertRaises(exception.ValidationError, self.migration_api.upgrade, engine, self.REPOSITORY, 267) self.assertIn("There are 1 records in the " "'consoles' table where the uuid or " "instance_uuid column is NULL.", ex.kwargs['detail']) # Remove the consoles entry with the null instance_uuid column. rows = consoles.delete().where( consoles.c['instance_uuid'] == null()).execute().rowcount self.assertEqual(1, rows) # Now run the 267 upgrade again. self.migration_api.upgrade(engine, self.REPOSITORY, 267) # Make sure the consoles entry with the null instance_uuid # was deleted. console = consoles.select(consoles.c.id == 1).execute().first() self.assertIsNone(console) def _check_268(self, engine, data): # We can only assert that the col exists, not the unique constraint # as the engine is running sqlite self.assertColumnExists(engine, 'compute_nodes', 'host') self.assertColumnExists(engine, 'shadow_compute_nodes', 'host') compute_nodes = oslodbutils.get_table(engine, 'compute_nodes') shadow_compute_nodes = oslodbutils.get_table( engine, 'shadow_compute_nodes') self.assertIsInstance(compute_nodes.c.host.type, sqlalchemy.types.String) self.assertIsInstance(shadow_compute_nodes.c.host.type, sqlalchemy.types.String) def _post_downgrade_268(self, engine): self.assertColumnNotExists(engine, 'compute_nodes', 'host') self.assertColumnNotExists(engine, 'shadow_compute_nodes', 'host') def _check_269(self, engine, data): self.assertColumnExists(engine, 'pci_devices', 'numa_node') self.assertColumnExists(engine, 'shadow_pci_devices', 'numa_node') pci_devices = oslodbutils.get_table(engine, 'pci_devices') shadow_pci_devices = oslodbutils.get_table( engine, 'shadow_pci_devices') self.assertIsInstance(pci_devices.c.numa_node.type, sqlalchemy.types.Integer) self.assertTrue(pci_devices.c.numa_node.nullable) self.assertIsInstance(shadow_pci_devices.c.numa_node.type, sqlalchemy.types.Integer) self.assertTrue(shadow_pci_devices.c.numa_node.nullable) def _post_downgrade_269(self, engine): self.assertColumnNotExists(engine, 'pci_devices', 'numa_node') self.assertColumnNotExists(engine, 'shadow_pci_devices', 'numa_node') def _check_270(self, engine, data): self.assertColumnExists(engine, 'instance_extra', 'flavor') self.assertColumnExists(engine, 'shadow_instance_extra', 'flavor') instance_extra = oslodbutils.get_table(engine, 'instance_extra') shadow_instance_extra = oslodbutils.get_table( engine, 'shadow_instance_extra') self.assertIsInstance(instance_extra.c.flavor.type, sqlalchemy.types.Text) self.assertIsInstance(shadow_instance_extra.c.flavor.type, sqlalchemy.types.Text) def _post_downgrade_270(self, engine): self.assertColumnNotExists(engine, 'instance_extra', 'flavor') self.assertColumnNotExists(engine, 'shadow_instance_extra', 'flavor') def _check_271(self, engine, data): self.assertIndexMembers(engine, 'block_device_mapping', 'snapshot_id', ['snapshot_id']) self.assertIndexMembers(engine, 'block_device_mapping', 'volume_id', ['volume_id']) self.assertIndexMembers(engine, 'dns_domains', 'dns_domains_project_id_idx', ['project_id']) self.assertIndexMembers(engine, 'fixed_ips', 'network_id', ['network_id']) self.assertIndexMembers(engine, 'fixed_ips', 'fixed_ips_instance_uuid_fkey', ['instance_uuid']) self.assertIndexMembers(engine, 'fixed_ips', 'fixed_ips_virtual_interface_id_fkey', ['virtual_interface_id']) self.assertIndexMembers(engine, 'floating_ips', 'fixed_ip_id', ['fixed_ip_id']) self.assertIndexMembers(engine, 'iscsi_targets', 'iscsi_targets_volume_id_fkey', ['volume_id']) self.assertIndexMembers(engine, 'virtual_interfaces', 'virtual_interfaces_network_id_idx', ['network_id']) self.assertIndexMembers(engine, 'virtual_interfaces', 'virtual_interfaces_instance_uuid_fkey', ['instance_uuid']) # Removed on MySQL, never existed on other databases self.assertIndexNotExists(engine, 'dns_domains', 'project_id') self.assertIndexNotExists(engine, 'virtual_interfaces', 'network_id') def _post_downgrade_271(self, engine): self.assertIndexNotExists(engine, 'dns_domains', 'dns_domains_project_id_idx') self.assertIndexNotExists(engine, 'virtual_interfaces', 'virtual_interfaces_network_id_idx') if engine.name == 'mysql': self.assertIndexMembers(engine, 'dns_domains', 'project_id', ['project_id']) self.assertIndexMembers(engine, 'virtual_interfaces', 'network_id', ['network_id']) # Rest of indexes will still exist on MySQL return # Never existed on non-MySQL databases, so shouldn't exist now self.assertIndexNotExists(engine, 'dns_domains', 'project_id') self.assertIndexNotExists(engine, 'virtual_interfaces', 'network_id') for table_name, index_name in [ ('block_device_mapping', 'snapshot_id'), ('block_device_mapping', 'volume_id'), ('dns_domains', 'dns_domains_project_id_idx'), ('fixed_ips', 'network_id'), ('fixed_ips', 'fixed_ips_instance_uuid_fkey'), ('fixed_ips', 'fixed_ips_virtual_interface_id_fkey'), ('floating_ips', 'fixed_ip_id'), ('iscsi_targets', 'iscsi_targets_volume_id_fkey'), ('virtual_interfaces', 'virtual_interfaces_network_id_idx'), ('virtual_interfaces', 'virtual_interfaces_instance_uuid_fkey')]: self.assertIndexNotExists(engine, table_name, index_name) class TestNovaMigrationsSQLite(NovaMigrationsCheckers, test.TestCase, test_base.DbTestCase): pass class TestNovaMigrationsMySQL(NovaMigrationsCheckers, test.TestCase, test_base.MySQLOpportunisticTestCase): def test_innodb_tables(self): with mock.patch.object(sa_migration, 'get_engine', return_value=self.migrate_engine): sa_migration.db_sync() total = self.migrate_engine.execute( "SELECT count(*) " "FROM information_schema.TABLES " "WHERE TABLE_SCHEMA = '%(database)s'" % {'database': self.migrate_engine.url.database}) self.assertTrue(total.scalar() > 0, "No tables found. Wrong schema?") noninnodb = self.migrate_engine.execute( "SELECT count(*) " "FROM information_schema.TABLES " "WHERE TABLE_SCHEMA='%(database)s' " "AND ENGINE != 'InnoDB' " "AND TABLE_NAME != 'migrate_version'" % {'database': self.migrate_engine.url.database}) count = noninnodb.scalar() self.assertEqual(count, 0, "%d non InnoDB tables created" % count) class TestNovaMigrationsPostgreSQL(NovaMigrationsCheckers, test.TestCase, test_base.PostgreSQLOpportunisticTestCase): pass class ProjectTestCase(test.NoDBTestCase): def test_all_migrations_have_downgrade(self): topdir = os.path.normpath(os.path.dirname(__file__) + '/../../../') py_glob = os.path.join(topdir, "nova", "db", "sqlalchemy", "migrate_repo", "versions", "*.py") missing_downgrade = [] for path in glob.iglob(py_glob): has_upgrade = False has_downgrade = False with open(path, "r") as f: for line in f: if 'def upgrade(' in line: has_upgrade = True if 'def downgrade(' in line: has_downgrade = True if has_upgrade and not has_downgrade: fname = os.path.basename(path) missing_downgrade.append(fname) helpful_msg = ("The following migrations are missing a downgrade:" "\n\t%s" % '\n\t'.join(sorted(missing_downgrade))) self.assertFalse(missing_downgrade, helpful_msg)
apache-2.0
jotes/ansible
v2/test/parsing/test_mod_args.py
109
4913
# (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 from ansible.parsing.mod_args import ModuleArgsParser from ansible.errors import AnsibleParserError from ansible.compat.tests import unittest class TestModArgsDwim(unittest.TestCase): # TODO: add tests that construct ModuleArgsParser with a task reference # TODO: verify the AnsibleError raised on failure knows the task # and the task knows the line numbers def setUp(self): pass def _debug(self, mod, args, to): print("RETURNED module = {0}".format(mod)) print(" args = {0}".format(args)) print(" to = {0}".format(to)) def tearDown(self): pass def test_basic_shell(self): m = ModuleArgsParser(dict(shell='echo hi')) mod, args, to = m.parse() self._debug(mod, args, to) self.assertEqual(mod, 'command') self.assertEqual(args, dict( _raw_params = 'echo hi', _uses_shell = True, )) self.assertIsNone(to) def test_basic_command(self): m = ModuleArgsParser(dict(command='echo hi')) mod, args, to = m.parse() self._debug(mod, args, to) self.assertEqual(mod, 'command') self.assertEqual(args, dict( _raw_params = 'echo hi', )) self.assertIsNone(to) def test_shell_with_modifiers(self): m = ModuleArgsParser(dict(shell='/bin/foo creates=/tmp/baz removes=/tmp/bleep')) mod, args, to = m.parse() self._debug(mod, args, to) self.assertEqual(mod, 'command') self.assertEqual(args, dict( creates = '/tmp/baz', removes = '/tmp/bleep', _raw_params = '/bin/foo', _uses_shell = True, )) self.assertIsNone(to) def test_normal_usage(self): m = ModuleArgsParser(dict(copy='src=a dest=b')) mod, args, to = m.parse() self._debug(mod, args, to) self.assertEqual(mod, 'copy') self.assertEqual(args, dict(src='a', dest='b')) self.assertIsNone(to) def test_complex_args(self): m = ModuleArgsParser(dict(copy=dict(src='a', dest='b'))) mod, args, to = m.parse() self._debug(mod, args, to) self.assertEqual(mod, 'copy') self.assertEqual(args, dict(src='a', dest='b')) self.assertIsNone(to) def test_action_with_complex(self): m = ModuleArgsParser(dict(action=dict(module='copy', src='a', dest='b'))) mod, args, to = m.parse() self._debug(mod, args, to) self.assertEqual(mod, 'copy') self.assertEqual(args, dict(src='a', dest='b')) self.assertIsNone(to) def test_action_with_complex_and_complex_args(self): m = ModuleArgsParser(dict(action=dict(module='copy', args=dict(src='a', dest='b')))) mod, args, to = m.parse() self._debug(mod, args, to) self.assertEqual(mod, 'copy') self.assertEqual(args, dict(src='a', dest='b')) self.assertIsNone(to) def test_local_action_string(self): m = ModuleArgsParser(dict(local_action='copy src=a dest=b')) mod, args, to = m.parse() self._debug(mod, args, to) self.assertEqual(mod, 'copy') self.assertEqual(args, dict(src='a', dest='b')) self.assertIs(to, 'localhost') def test_multiple_actions(self): m = ModuleArgsParser(dict(action='shell echo hi', local_action='shell echo hi')) self.assertRaises(AnsibleParserError, m.parse) m = ModuleArgsParser(dict(action='shell echo hi', shell='echo hi')) self.assertRaises(AnsibleParserError, m.parse) m = ModuleArgsParser(dict(local_action='shell echo hi', shell='echo hi')) self.assertRaises(AnsibleParserError, m.parse) m = ModuleArgsParser(dict(ping='data=hi', shell='echo hi')) self.assertRaises(AnsibleParserError, m.parse)
gpl-3.0
ryuunosukeyoshi/PartnerPoi-Bot
lib/youtube_dl/extractor/tvigle.py
48
4229
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( ExtractorError, float_or_none, int_or_none, parse_age_limit, ) class TvigleIE(InfoExtractor): IE_NAME = 'tvigle' IE_DESC = 'Интернет-телевидение Tvigle.ru' _VALID_URL = r'https?://(?:www\.)?(?:tvigle\.ru/(?:[^/]+/)+(?P<display_id>[^/]+)/$|cloud\.tvigle\.ru/video/(?P<id>\d+))' _GEO_BYPASS = False _GEO_COUNTRIES = ['RU'] _TESTS = [ { 'url': 'http://www.tvigle.ru/video/sokrat/', 'md5': '36514aed3657d4f70b4b2cef8eb520cd', 'info_dict': { 'id': '1848932', 'display_id': 'sokrat', 'ext': 'flv', 'title': 'Сократ', 'description': 'md5:d6b92ffb7217b4b8ebad2e7665253c17', 'duration': 6586, 'age_limit': 12, }, 'skip': 'georestricted', }, { 'url': 'http://www.tvigle.ru/video/vladimir-vysotskii/vedushchii-teleprogrammy-60-minut-ssha-o-vladimire-vysotskom/', 'md5': 'e7efe5350dd5011d0de6550b53c3ba7b', 'info_dict': { 'id': '5142516', 'ext': 'flv', 'title': 'Ведущий телепрограммы «60 минут» (США) о Владимире Высоцком', 'description': 'md5:027f7dc872948f14c96d19b4178428a4', 'duration': 186.080, 'age_limit': 0, }, 'skip': 'georestricted', }, { 'url': 'https://cloud.tvigle.ru/video/5267604/', 'only_matching': True, } ] def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') display_id = mobj.group('display_id') if not video_id: webpage = self._download_webpage(url, display_id) video_id = self._html_search_regex( (r'<div[^>]+class=["\']player["\'][^>]+id=["\'](\d+)', r'var\s+cloudId\s*=\s*["\'](\d+)', r'class="video-preview current_playing" id="(\d+)"'), webpage, 'video id') video_data = self._download_json( 'http://cloud.tvigle.ru/api/play/video/%s/' % video_id, display_id) item = video_data['playlist']['items'][0] videos = item.get('videos') error_message = item.get('errorMessage') if not videos and error_message: if item.get('isGeoBlocked') is True: self.raise_geo_restricted( msg=error_message, countries=self._GEO_COUNTRIES) else: raise ExtractorError( '%s returned error: %s' % (self.IE_NAME, error_message), expected=True) title = item['title'] description = item.get('description') thumbnail = item.get('thumbnail') duration = float_or_none(item.get('durationMilliseconds'), 1000) age_limit = parse_age_limit(item.get('ageRestrictions')) formats = [] for vcodec, fmts in item['videos'].items(): if vcodec == 'hls': continue for format_id, video_url in fmts.items(): if format_id == 'm3u8': continue height = self._search_regex( r'^(\d+)[pP]$', format_id, 'height', default=None) formats.append({ 'url': video_url, 'format_id': '%s-%s' % (vcodec, format_id), 'vcodec': vcodec, 'height': int_or_none(height), 'filesize': int_or_none(item.get('video_files_size', {}).get(vcodec, {}).get(format_id)), }) self._sort_formats(formats) return { 'id': video_id, 'display_id': display_id, 'title': title, 'description': description, 'thumbnail': thumbnail, 'duration': duration, 'age_limit': age_limit, 'formats': formats, }
gpl-3.0
ukanga/SickRage
sickbeard/show_queue.py
3
30406
# coding=utf-8 # Author: Nic Wolfe <nic@wolfeden.ca> # URL: https://sickrage.github.io # # This file is part of SickRage. # # SickRage is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # SickRage is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with SickRage. If not, see <http://www.gnu.org/licenses/>. from __future__ import unicode_literals from collections import namedtuple import os import traceback from imdb import _exceptions as imdb_exceptions from libtrakt import TraktAPI import sickbeard from sickbeard import generic_queue, logger, name_cache, notifiers, ui from sickbeard.blackandwhitelist import BlackAndWhiteList from sickbeard.common import WANTED from sickbeard.helpers import chmodAsParent, get_showname_from_indexer, makeDir, sortable_name from sickbeard.tv import TVShow from sickrage.helper.common import sanitize_filename from sickrage.helper.encoding import ek from sickrage.helper.exceptions import CantRefreshShowException, CantRemoveShowException, CantUpdateShowException, \ EpisodeDeletedException, MultipleShowObjectsException, ShowDirectoryNotFoundException from sickrage.show.Show import Show import six class ShowQueue(generic_queue.GenericQueue): def __init__(self): super(ShowQueue, self).__init__() self.queue_name = 'SHOWQUEUE' def _is_in_queue(self, show, actions): if not show: return False return show.indexerid in (x.show.indexerid if x.show else 0 for x in self.queue if x.action_id in actions) def _is_being_somethinged(self, show, actions): return self.currentItem is not None and show == self.currentItem.show and self.currentItem.action_id in actions # def is_in_add_queue(self, show): # return self._isInQueue(show, (ShowQueueActions.ADD,)) def is_in_update_queue(self, show): return self._is_in_queue(show, (ShowQueueActions.UPDATE, ShowQueueActions.FORCEUPDATE)) def is_in_refresh_queue(self, show): return self._is_in_queue(show, (ShowQueueActions.REFRESH,)) def is_in_rename_queue(self, show): return self._is_in_queue(show, (ShowQueueActions.RENAME,)) def is_in_remove_queue(self, show): return self._is_in_queue(show, (ShowQueueActions.REMOVE,)) def is_in_subtitle_queue(self, show): return self._is_in_queue(show, (ShowQueueActions.SUBTITLE,)) def is_being_added(self, show): return self._is_being_somethinged(show, (ShowQueueActions.ADD,)) def is_being_updated(self, show): return self._is_being_somethinged(show, (ShowQueueActions.UPDATE, ShowQueueActions.FORCEUPDATE)) def is_being_refreshed(self, show): return self._is_being_somethinged(show, (ShowQueueActions.REFRESH,)) def is_being_renamed(self, show): return self._is_being_somethinged(show, (ShowQueueActions.RENAME,)) def is_being_removed(self, show): return self._is_being_somethinged(show, (ShowQueueActions.REMOVE,)) def is_being_subtitled(self, show): return self._is_being_somethinged(show, (ShowQueueActions.SUBTITLE,)) @property def loading_show_list(self): return {x for x in self.queue + [self.currentItem] if x and x.is_loading} def update_show(self, show, force=False): if self.is_being_added(show): raise CantUpdateShowException( '{0} is still being added, wait until it is finished before you update.'.format(show.name) ) if self.is_being_updated(show): raise CantUpdateShowException( '{0} is already being updated by Post-processor or manually started, can\'t update again until it\'s done.'.format(show.name) ) if self.is_in_update_queue(show): raise CantUpdateShowException( '{0} is in process of being updated by Post-processor or manually started, can\'t update again until it\'s done.'.format(show.name) ) queue_item_obj = QueueItemUpdate(show, force=force) self.add_item(queue_item_obj) return queue_item_obj def refresh_show(self, show, force=False): if self.is_being_refreshed(show) and not force: raise CantRefreshShowException('This show is already being refreshed, not refreshing again.') if (self.is_being_updated(show) or self.is_in_update_queue(show)) and not force: logger.log( 'A refresh was attempted but there is already an update queued or in progress. Updates do a refresh at the end so I\'m skipping this request.', logger.DEBUG) return if show.paused and not force: logger.log('Skipping show [{0}] because it is paused.'.format(show.name), logger.DEBUG) return logger.log('Queueing show refresh for {0}'.format(show.name), logger.DEBUG) queue_item_obj = QueueItemRefresh(show, force=force) self.add_item(queue_item_obj) return queue_item_obj def rename_show_episodes(self, show, force=False): queue_item_obj = QueueItemRename(show) self.add_item(queue_item_obj) return queue_item_obj def download_subtitles(self, show, force=False): queue_item_obj = QueueItemSubtitle(show) self.add_item(queue_item_obj) return queue_item_obj def add_show(self, # pylint: disable=too-many-arguments, too-many-locals indexer, indexer_id, showDir, default_status=None, quality=None, season_folders=None, lang=None, subtitles=None, subtitles_sr_metadata=None, anime=None, scene=None, paused=None, blacklist=None, whitelist=None, default_status_after=None, root_dir=None): if lang is None: lang = sickbeard.INDEXER_DEFAULT_LANGUAGE if default_status_after is None: default_status_after = sickbeard.STATUS_DEFAULT_AFTER queue_item_obj = QueueItemAdd(indexer, indexer_id, showDir, default_status, quality, season_folders, lang, subtitles, subtitles_sr_metadata, anime, scene, paused, blacklist, whitelist, default_status_after, root_dir) self.add_item(queue_item_obj) return queue_item_obj def remove_show(self, show, full=False): if not show: raise CantRemoveShowException('Failed removing show: Show does not exist') if not hasattr(show, 'indexerid'): raise CantRemoveShowException('Failed removing show: Show does not have an indexer id') if self._is_in_queue(show, (ShowQueueActions.REMOVE,)): raise CantRemoveShowException('{0} is already queued to be removed'.format(show.name)) # remove other queued actions for this show. for item in self.queue: if item and item.show and item != self.currentItem and show.indexerid == item.show.indexerid: self.queue.remove(item) queue_item_obj = QueueItemRemove(show=show, full=full) self.add_item(queue_item_obj) return queue_item_obj class ShowQueueActions(object): # pylint: disable=too-few-public-methods def __init__(self): pass REFRESH = 1 ADD = 2 UPDATE = 3 FORCEUPDATE = 4 RENAME = 5 SUBTITLE = 6 REMOVE = 7 names = { REFRESH: 'Refresh', ADD: 'Add', UPDATE: 'Update', FORCEUPDATE: 'Force Update', RENAME: 'Rename', SUBTITLE: 'Subtitle', REMOVE: 'Remove Show' } class ShowQueueItem(generic_queue.QueueItem): """ Represents an item in the queue waiting to be executed Can be either: - show being added (may or may not be associated with a show object) - show being refreshed - show being updated - show being force updated - show being subtitled """ def __init__(self, action_id, show): super(ShowQueueItem, self).__init__(ShowQueueActions.names[action_id], action_id) self.show = show def is_in_queue(self): return self in sickbeard.showQueueScheduler.action.queue + [ sickbeard.showQueueScheduler.action.currentItem] @property def show_name(self): return self.show.name if self.show else 'UNSET' @property def is_loading(self): # pylint: disable=no-self-use return False class QueueItemAdd(ShowQueueItem): # pylint: disable=too-many-instance-attributes def __init__(self, # pylint: disable=too-many-arguments, too-many-locals indexer, indexer_id, showDir, default_status, quality, season_folders, lang, subtitles, subtitles_sr_metadata, anime, scene, paused, blacklist, whitelist, default_status_after, root_dir): super(QueueItemAdd, self).__init__(ShowQueueActions.ADD, None) if isinstance(showDir, bytes): self.showDir = showDir.decode('utf-8') else: self.showDir = showDir self.indexer = indexer self.indexer_id = indexer_id self.default_status = default_status self.quality = quality self.season_folders = season_folders self.lang = lang self.subtitles = subtitles self.subtitles_sr_metadata = subtitles_sr_metadata self.anime = anime self.scene = scene self.paused = paused self.blacklist = blacklist self.whitelist = whitelist self.default_status_after = default_status_after self.root_dir = root_dir self.show = None # Process add show in priority self.priority = generic_queue.QueuePriorities.HIGH @property def show_name(self): """ Returns the show name if there is a show object created, if not returns the dir that the show is being added to. """ return self.show.name if self.show else self.showDir.rsplit(os.sep)[-1] @property def is_loading(self): """ Returns True if we've gotten far enough to have a show object, or False if we still only know the folder name. """ return self.show not in sickbeard.showList or not self.show @property def info(self): info = namedtuple('LoadingShowInfo', 'id name sort_name network quality') if self.show: return info(id=self.show.indexerid, name=self.show.name, sort_name=self.show.sort_name, network=self.show.network, quality=self.show.quality) return info(id=self.show_name, name=self.show_name, sort_name=sortable_name(self.show_name), network=_('Loading'), quality=0) def run(self): # pylint: disable=too-many-branches, too-many-statements, too-many-return-statements super(QueueItemAdd, self).run() if self.showDir: try: assert isinstance(self.showDir, six.text_type) except AssertionError: logger.log(traceback.format_exc(), logger.WARNING) self._finish_early() return logger.log('Starting to add show {0}'.format('by ShowDir: {0}'.format(self.showDir) if self.showDir else 'by Indexer Id: {0}'.format(self.indexer_id))) # make sure the Indexer IDs are valid try: lINDEXER_API_PARMS = sickbeard.indexerApi(self.indexer).api_params.copy() lINDEXER_API_PARMS['language'] = self.lang or sickbeard.INDEXER_DEFAULT_LANGUAGE logger.log('{0}: {1!r}'.format(sickbeard.indexerApi(self.indexer).name, lINDEXER_API_PARMS)) t = sickbeard.indexerApi(self.indexer).indexer(**lINDEXER_API_PARMS) s = t[self.indexer_id] # Let's try to create the show Dir if it's not provided. This way we force the show dir to build build using the # Indexers provided series name if self.root_dir and not self.showDir: show_name = get_showname_from_indexer(self.indexer, self.indexer_id, self.lang) if not show_name: logger.log('Unable to get a show {0}, can\'t add the show'.format(self.showDir)) self._finish_early() return self.showDir = ek(os.path.join, self.root_dir, sanitize_filename(show_name)) dir_exists = makeDir(self.showDir) if not dir_exists: logger.log('Unable to create the folder {0}, can\'t add the show'.format(self.showDir)) self._finish_early() return chmodAsParent(self.showDir) # this usually only happens if they have an NFO in their show dir which gave us a Indexer ID that has no proper english version of the show if getattr(s, 'seriesname', None) is None: error_string = 'Show in {0} has no name on {1}, probably searched with the wrong language. Delete .nfo and add manually in the correct language.'.format( self.showDir, sickbeard.indexerApi(self.indexer).name) logger.log(error_string, logger.WARNING) ui.notifications.error('Unable to add show', error_string) self._finish_early() return # if the show has no episodes/seasons if not s: error_string = 'Show {0} is on {1} but contains no season/episode data.'.format( s[b'seriesname'], sickbeard.indexerApi(self.indexer).name) logger.log(error_string) ui.notifications.error('Unable to add show', error_string) self._finish_early() return except Exception as error: error_string = 'Unable to look up the show in {0} on {1} using ID {2}, not using the NFO. Delete .nfo and try adding manually again.'.format( self.showDir, sickbeard.indexerApi(self.indexer).name, self.indexer_id) logger.log('{0}: {1}'.format(error_string, error), logger.ERROR) ui.notifications.error( 'Unable to add show', error_string) if sickbeard.USE_TRAKT: trakt_id = sickbeard.indexerApi(self.indexer).config[b'trakt_id'] trakt_api = TraktAPI(sickbeard.SSL_VERIFY, sickbeard.TRAKT_TIMEOUT) title = self.showDir.split('/')[-1] data = { 'shows': [ { 'title': title, 'ids': {} } ] } if trakt_id == 'tvdb_id': data[b'shows'][0][b'ids'][b'tvdb'] = self.indexer_id else: data[b'shows'][0][b'ids'][b'tvrage'] = self.indexer_id trakt_api.traktRequest('sync/watchlist/remove', data, method='POST') self._finish_early() return try: try: newShow = TVShow(self.indexer, self.indexer_id, self.lang) except MultipleShowObjectsException as error: # If we have the show in our list, but the location is wrong, lets fix it and refresh! existing_show = Show.find(sickbeard.showList, self.indexer_id) if existing_show and not ek(os.path.isdir, existing_show._location): # pylint: disable=protected-access newShow = existing_show else: raise error newShow.loadFromIndexer() self.show = newShow # set up initial values self.show.location = self.showDir self.show.subtitles = self.subtitles if self.subtitles is not None else sickbeard.SUBTITLES_DEFAULT self.show.subtitles_sr_metadata = self.subtitles_sr_metadata self.show.quality = self.quality if self.quality else sickbeard.QUALITY_DEFAULT self.show.season_folders = self.season_folders if self.season_folders is not None else sickbeard.SEASON_FOLDERS_DEFAULT self.show.anime = self.anime if self.anime is not None else sickbeard.ANIME_DEFAULT self.show.scene = self.scene if self.scene is not None else sickbeard.SCENE_DEFAULT self.show.paused = self.paused if self.paused is not None else False # set up default new/missing episode status logger.log('Setting all episodes to the specified default status: {0}' .format(self.show.default_ep_status)) self.show.default_ep_status = self.default_status if self.show.anime: self.show.release_groups = BlackAndWhiteList(self.show.indexerid) if self.blacklist: self.show.release_groups.set_black_keywords(self.blacklist) if self.whitelist: self.show.release_groups.set_white_keywords(self.whitelist) # # be smartish about this # if self.show.genre and 'talk show' in self.show.genre.lower(): # self.show.air_by_date = 1 # if self.show.genre and 'documentary' in self.show.genre.lower(): # self.show.air_by_date = 0 # if self.show.classification and 'sports' in self.show.classification.lower(): # self.show.sports = 1 except sickbeard.indexer_exception as error: error_string = 'Unable to add {0} due to an error with {1}'.format( self.show.name if self.show else 'show', sickbeard.indexerApi(self.indexer).name) logger.log('{0}: {1}'.format(error_string, error), logger.ERROR) ui.notifications.error('Unable to add show', error_string) self._finish_early() return except MultipleShowObjectsException: error_string = 'The show in {0} is already in your show list, skipping'.format(self.showDir) logger.log(error_string, logger.WARNING) ui.notifications.error('Show skipped', error_string) self._finish_early() return except Exception as error: logger.log('Error trying to add show: {0}'.format(error), logger.ERROR) logger.log(traceback.format_exc(), logger.DEBUG) self._finish_early() raise logger.log('Retrieving show info from IMDb', logger.DEBUG) try: self.show.loadIMDbInfo() except imdb_exceptions.IMDbError as error: logger.log(' Something wrong on IMDb api: {0}'.format(error), logger.WARNING) except Exception as error: logger.log('Error loading IMDb info: {0}'.format(error), logger.ERROR) try: self.show.saveToDB() except Exception as error: logger.log('Error saving the show to the database: {0}'.format(error), logger.ERROR) logger.log(traceback.format_exc(), logger.DEBUG) self._finish_early() raise # add it to the show list if not Show.find(sickbeard.showList, self.indexer_id): sickbeard.showList.append(self.show) try: self.show.loadEpisodesFromIndexer() except Exception as error: logger.log( 'Error with {0}, not creating episode list: {1}'.format (sickbeard.indexerApi(self.show.indexer).name, error), logger.ERROR) logger.log(traceback.format_exc(), logger.DEBUG) # update internal name cache name_cache.buildNameCache(self.show) try: self.show.loadEpisodesFromDir() except Exception as error: logger.log('Error searching dir for episodes: {0}'.format(error), logger.ERROR) logger.log(traceback.format_exc(), logger.DEBUG) # if they set default ep status to WANTED then run the backlog to search for episodes # FIXME: This needs to be a backlog queue item!!! if self.show.default_ep_status == WANTED: logger.log('Launching backlog for this show since its episodes are WANTED') sickbeard.backlogSearchScheduler.action.searchBacklog([self.show]) self.show.writeMetadata() self.show.updateMetadata() self.show.populateCache() self.show.flushEpisodes() if sickbeard.USE_TRAKT: # if there are specific episodes that need to be added by trakt sickbeard.traktCheckerScheduler.action.manageNewShow(self.show) # add show to trakt.tv library if sickbeard.TRAKT_SYNC: sickbeard.traktCheckerScheduler.action.addShowToTraktLibrary(self.show) if sickbeard.TRAKT_SYNC_WATCHLIST: logger.log('update watchlist') notifiers.trakt_notifier.update_watchlist(show_obj=self.show) # Load XEM data to DB for show sickbeard.scene_numbering.xem_refresh(self.show.indexerid, self.show.indexer, force=True) # check if show has XEM mapping so we can determin if searches should go by scene numbering or indexer numbering. if not self.scene and sickbeard.scene_numbering.get_xem_numbering_for_show(self.show.indexerid, self.show.indexer): self.show.scene = 1 # After initial add, set to default_status_after. self.show.default_ep_status = self.default_status_after super(QueueItemAdd, self).finish() self.finish() def _finish_early(self): if self.show is not None: sickbeard.showQueueScheduler.action.remove_show(self.show) super(QueueItemAdd, self).finish() self.finish() class QueueItemRefresh(ShowQueueItem): def __init__(self, show=None, force=False): super(QueueItemRefresh, self).__init__(ShowQueueActions.REFRESH, show) # do refreshes first because they're quick self.priority = generic_queue.QueuePriorities.HIGH # force refresh certain items self.force = force def run(self): super(QueueItemRefresh, self).run() logger.log('Performing refresh on {0}'.format(self.show.name)) self.show.refreshDir() self.show.writeMetadata() if self.force: self.show.updateMetadata() self.show.populateCache() # Load XEM data to DB for show sickbeard.scene_numbering.xem_refresh(self.show.indexerid, self.show.indexer) super(QueueItemRefresh, self).finish() self.finish() class QueueItemRename(ShowQueueItem): def __init__(self, show=None): super(QueueItemRename, self).__init__(ShowQueueActions.RENAME, show) def run(self): super(QueueItemRename, self).run() logger.log('Performing rename on {0}'.format(self.show.name)) try: self.show.location except ShowDirectoryNotFoundException: logger.log('Can\'t perform rename on {0} when the show dir is missing.'.format(self.show.name), logger.WARNING) super(QueueItemRename, self).finish() self.finish() return ep_obj_rename_list = [] ep_obj_list = self.show.getAllEpisodes(has_location=True) for cur_ep_obj in ep_obj_list: # Only want to rename if we have a location if cur_ep_obj.location: if cur_ep_obj.relatedEps: # do we have one of multi-episodes in the rename list already have_already = False for cur_related_ep in cur_ep_obj.relatedEps + [cur_ep_obj]: if cur_related_ep in ep_obj_rename_list: have_already = True break if not have_already: ep_obj_rename_list.append(cur_ep_obj) else: ep_obj_rename_list.append(cur_ep_obj) for cur_ep_obj in ep_obj_rename_list: cur_ep_obj.rename() super(QueueItemRename, self).finish() self.finish() class QueueItemSubtitle(ShowQueueItem): def __init__(self, show=None): super(QueueItemSubtitle, self).__init__(ShowQueueActions.SUBTITLE, show) def run(self): super(QueueItemSubtitle, self).run() logger.log('Downloading subtitles for {0} '.format(self.show.name)) self.show.download_subtitles() super(QueueItemSubtitle, self).finish() self.finish() class QueueItemUpdate(ShowQueueItem): def __init__(self, show=None, force=False): action = ShowQueueActions.FORCEUPDATE if force else ShowQueueActions.UPDATE super(QueueItemUpdate, self).__init__(action, show) self.force = force self.priority = generic_queue.QueuePriorities.HIGH def run(self): # pylint: disable=too-many-branches, too-many-statements super(QueueItemUpdate, self).run() logger.log('Beginning update of {0}'.format(self.show.name), logger.DEBUG) logger.log('Retrieving show info from {0}'.format(sickbeard.indexerApi(self.show.indexer).name), logger.DEBUG) try: self.show.loadFromIndexer(cache=not self.force) except sickbeard.indexer_error as error: logger.log('Unable to contact {0}, aborting: {1}'.format (sickbeard.indexerApi(self.show.indexer).name, error), logger.WARNING) super(QueueItemUpdate, self).finish() self.finish() return except sickbeard.indexer_attributenotfound as error: logger.log('Data retrieved from {0} was incomplete, aborting: {1}'.format (sickbeard.indexerApi(self.show.indexer).name, error), logger.ERROR) super(QueueItemUpdate, self).finish() self.finish() return logger.log('Retrieving show info from IMDb', logger.DEBUG) try: self.show.loadIMDbInfo() except imdb_exceptions.IMDbError as error: logger.log('Something wrong on IMDb api: {0}'.format(error), logger.WARNING) except Exception as error: logger.log('Error loading IMDb info: {0}'.format(error), logger.ERROR) logger.log(traceback.format_exc(), logger.DEBUG) # have to save show before reading episodes from db try: self.show.saveToDB() except Exception as error: logger.log('Error saving show info to the database: {0}'.format(error), logger.ERROR) logger.log(traceback.format_exc(), logger.DEBUG) # get episode list from DB logger.log('Loading all episodes from the database', logger.DEBUG) DBEpList = self.show.loadEpisodesFromDB() # get episode list from TVDB logger.log('Loading all episodes from {0}'.format(sickbeard.indexerApi(self.show.indexer).name), logger.DEBUG) try: IndexerEpList = self.show.loadEpisodesFromIndexer(cache=not self.force) except sickbeard.indexer_exception as error: logger.log('Unable to get info from {0}, the show info will not be refreshed: {1}'.format (sickbeard.indexerApi(self.show.indexer).name, error), logger.ERROR) IndexerEpList = None if not IndexerEpList: logger.log('No data returned from {0}, unable to update this show.'.format (sickbeard.indexerApi(self.show.indexer).name), logger.ERROR) else: # for each ep we found on the Indexer delete it from the DB list for curSeason in IndexerEpList: for curEpisode in IndexerEpList[curSeason]: curEp = self.show.getEpisode(curSeason, curEpisode) curEp.saveToDB() if curSeason in DBEpList and curEpisode in DBEpList[curSeason]: del DBEpList[curSeason][curEpisode] # remaining episodes in the DB list are not on the indexer, just delete them from the DB for curSeason in DBEpList: for curEpisode in DBEpList[curSeason]: logger.log('Permanently deleting episode {0:02d}E{1:02d} from the database'.format (curSeason, curEpisode), logger.INFO) curEp = self.show.getEpisode(curSeason, curEpisode) try: curEp.deleteEpisode() except EpisodeDeletedException: pass # save show again, in case episodes have changed try: self.show.saveToDB() except Exception as error: logger.log('Error saving show info to the database: {0}'.format(error), logger.ERROR) logger.log(traceback.format_exc(), logger.DEBUG) logger.log('Finished update of {0}'.format(self.show.name), logger.DEBUG) sickbeard.showQueueScheduler.action.refresh_show(self.show, self.force) super(QueueItemUpdate, self).finish() self.finish() class QueueItemRemove(ShowQueueItem): def __init__(self, show=None, full=False): super(QueueItemRemove, self).__init__(ShowQueueActions.REMOVE, show) # lets make sure this happens before any other high priority actions self.priority = generic_queue.QueuePriorities.HIGH ** 2 self.full = full def run(self): super(QueueItemRemove, self).run() logger.log('Removing {0}'.format(self.show.name)) self.show.deleteShow(full=self.full) if sickbeard.USE_TRAKT: try: sickbeard.traktCheckerScheduler.action.removeShowFromTraktLibrary(self.show) except Exception as error: logger.log('Unable to delete show from Trakt: {0}. Error: {1}'.format(self.show.name, error), logger.WARNING) super(QueueItemRemove, self).finish() self.finish()
gpl-3.0
Kivvix/stage-LPC
compareSrc/searchSDSSdata.py
1
4221
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import os import glob from config import * import data.calexp import data.src ## @def attributs # @brief attributs which we select in SDSS DB and src fits file attributs = 'objid,run,camcol,field,ra,dec,u,g,r,i,z' ## Calexp treatment ## def coordCalexp( fitsNum , calexpFits , first=True ): coordMin, coordMax = data.calexp.coord( calexpFits , first ) if ( first ): return coordMin else: return coordMax def savCalexp( coordMin , coordMax , fitsNum ): global attributs , PATH_OUTPUT calexpLines = data.calexp.query( coordMin , coordMax , attributs , fitsNum ) data.calexp.write( calexpLines , attributs , fitsNum , PATH_OUTPUT , True ) def calexp( fitsNum , calexpFits , first=True ): """ find and write calexp data (id,ra,dec,mag) :param fitsNum: number of fits file (``rrrrrr-bc-ffff``) :param calexpFits: name of calexp fits file :param first: take all the picture or less 128 first pixels :type fitsNum: string :type calexpFits: string :type first: boolean """ global attributs , PATH_OUTPUT coordMin, coordMax = data.calexp.coord( calexpFits , first ) calexpLines = data.calexp.query( coordMin , coordMax , attributs , fitsNum ) data.calexp.write( calexpLines , attributs , fitsNum[0:9] , PATH_OUTPUT , first ) ## Src treatment ## def src( fitsNum , srcFits , first=True ): """ find and write src data (id,ra,dec,mag) :param fitsNum: number of fits file (``rrrrrr-bc-ffff``) :param srcFits: name of src fits file :param first: take all the picture or less 128 first pixels :type fitsNum: string :type srcFits: string :type first: boolean """ global attributs , PATH_OUTPUT srcCoord,srcMag = data.src.coord( srcFits , fitsNum , first ) srcLines = data.src.map( srcCoord , srcMag ) data.src.write( srcLines , attributs , fitsNum[0:9] , PATH_OUTPUT , first ) def analyCol( runNum , c ): """ function threaded calling research of data :param runNum_c: tupe with run number and column of the CCD (1-6) :type runNum_c: tuple of string """ global b , PATH_DATA , PWD print " " + str(c) + " ", # data of each pair of fits files first = True for fits in glob.glob( c + "/" + b + "/calexp/calexp*.fits" ): fitsNum = fits[18:32] ## @def calexpFits # @brief path and name of calexp fits file calexpFits = PATH_DATA + "/" + runNum + "/" + c + "/" + b + "/calexp/calexp-" + fitsNum + ".fits" ## @def srcFits # @brief path and name of src fits file #srcFits = PATH_DATA + "/" + runNum + "/" + c + "/" + b + "/src/src-" + fitsNum + ".fits" #calexp( fitsNum , calexpFits , first ) if ( first ): coordMin = coordCalexp( fitsNum , calexpFits , first ) else: coordMax = coordCalexp( fitsNum , calexpFits , first ) #src( fitsNum , srcFits , first ) first = False savCalexp( coordMin , coordMax , "%06d" % int(runNum) + "-" + b + c ) def analyRun( runNum ): global b , PWD , PATH_DATA , PATH_OUTPUT , attributs print "run : " + str(runNum ) + " : ", os.chdir( PATH_DATA + "/" + runNum ) columns = glob.glob( "*" ) for c in columns : analyCol( runNum , c ) if __name__ == '__main__': os.chdir( PATH_DATA ) runs = glob.glob( "*" ) #runs = ( 7158, 7112, 5924, 5566, 6421, 7057, 6430, 4895, 5895, 6474, 6383, 7038, 5642, 6409, 6513, 6501, 6552, 2650, 6559, 6355, 7177, 7121, 3465, 7170, 7051, 6283, 6458, 5853, 6484, 5765, 2708, 5786, 4253, 6934, 6508, 2662, 6518, 6584, 4188, 6976, 7202, 7173, 4153, 5820, 2649, 7140, 6330, 3388, 7117, 6504, 6314, 4128, 6596, 6564, 5807, 6367, 6373, 5622, 5882, 7034, 7136, 6577, 6600, 2768, 3437, 4927, 6414, 3434, 5813, 7084, 4858, 7124, 6982, 4917, 4192, 5898, 6479, 4868, 7106, 7195, 5744, 3360, 4198, 6963, 6533, 4933, 5603, 3384, 7155, 5619, 4207, 4849, 5582, 7024, 1755, 5709, 5781, 5770, 7145, 5754, 5646, 5800, 5759, 6287, 6568, 7054, 4203, 5776, 6433, 4247, 5823, 5052, 3325, 5836, 5590, 6580, 7161, 2728, 4145, 5633, 6461, 6555, 6955, 4874, 5792, 5918, 6425, 6377, 4263, 5878, 6441, 6447, 7080, 5905, 5713, 6618, 6537, 5637, 6402, 6530, 7047, 6524, 7101, 6293 ) for r in runs : analyRun( r ) print " " time.sleep(60)
mit
pinkavaj/gnuradio
gnuradio-runtime/python/gnuradio/gru/msgq_runner.py
94
2529
# # Copyright 2009 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # """ Convenience class for dequeuing messages from a gr.msg_queue and invoking a callback. Creates a Python thread that does a blocking read on the supplied gr.msg_queue, then invokes callback each time a msg is received. If the msg type is not 0, then it is treated as a signal to exit its loop. If the callback raises an exception, and the runner was created with 'exit_on_error' equal to True, then the runner will store the exception and exit its loop, otherwise the exception is ignored. To get the exception that the callback raised, if any, call exit_error() on the object. To manually stop the runner, call stop() on the object. To determine if the runner has exited, call exited() on the object. """ from gnuradio import gr import gnuradio.gr.gr_threading as _threading class msgq_runner(_threading.Thread): def __init__(self, msgq, callback, exit_on_error=False): _threading.Thread.__init__(self) self._msgq = msgq self._callback = callback self._exit_on_error = exit_on_error self._done = False self._exited = False self._exit_error = None self.setDaemon(1) self.start() def run(self): while not self._done: msg = self._msgq.delete_head() if msg.type() != 0: self.stop() else: try: self._callback(msg) except Exception, e: if self._exit_on_error: self._exit_error = e self.stop() self._exited = True def stop(self): self._done = True def exited(self): return self._exited def exit_error(self): return self._exit_error
gpl-3.0
yamila-moreno/django
tests/gis_tests/geoadmin/tests.py
304
3157
from __future__ import unicode_literals from django.contrib.gis import admin from django.contrib.gis.geos import Point from django.test import TestCase, override_settings, skipUnlessDBFeature from .admin import UnmodifiableAdmin from .models import City, site @skipUnlessDBFeature("gis_enabled") @override_settings(ROOT_URLCONF='django.contrib.gis.tests.geoadmin.urls') class GeoAdminTest(TestCase): def test_ensure_geographic_media(self): geoadmin = site._registry[City] admin_js = geoadmin.media.render_js() self.assertTrue(any(geoadmin.openlayers_url in js for js in admin_js)) def test_olmap_OSM_rendering(self): delete_all_btn = """<a href="javascript:geodjango_point.clearFeatures()">Delete all Features</a>""" original_geoadmin = site._registry[City] params = original_geoadmin.get_map_widget(City._meta.get_field('point')).params result = original_geoadmin.get_map_widget(City._meta.get_field('point'))( ).render('point', Point(-79.460734, 40.18476), params) self.assertIn( """geodjango_point.layers.base = new OpenLayers.Layer.OSM("OpenStreetMap (Mapnik)");""", result) self.assertIn(delete_all_btn, result) site.unregister(City) site.register(City, UnmodifiableAdmin) try: geoadmin = site._registry[City] params = geoadmin.get_map_widget(City._meta.get_field('point')).params result = geoadmin.get_map_widget(City._meta.get_field('point'))( ).render('point', Point(-79.460734, 40.18476), params) self.assertNotIn(delete_all_btn, result) finally: site.unregister(City) site.register(City, original_geoadmin.__class__) def test_olmap_WMS_rendering(self): geoadmin = admin.GeoModelAdmin(City, site) result = geoadmin.get_map_widget(City._meta.get_field('point'))( ).render('point', Point(-79.460734, 40.18476)) self.assertIn( """geodjango_point.layers.base = new OpenLayers.Layer.WMS("OpenLayers WMS", """ """"http://vmap0.tiles.osgeo.org/wms/vmap0", {layers: 'basic', format: 'image/jpeg'});""", result) def test_olwidget_has_changed(self): """ Check that changes are accurately noticed by OpenLayersWidget. """ geoadmin = site._registry[City] form = geoadmin.get_changelist_form(None)() has_changed = form.fields['point'].has_changed initial = Point(13.4197458572965953, 52.5194108501149799, srid=4326) data_same = "SRID=3857;POINT(1493879.2754093995 6894592.019687599)" data_almost_same = "SRID=3857;POINT(1493879.2754093990 6894592.019687590)" data_changed = "SRID=3857;POINT(1493884.0527237 6894593.8111804)" self.assertTrue(has_changed(None, data_changed)) self.assertTrue(has_changed(initial, "")) self.assertFalse(has_changed(None, "")) self.assertFalse(has_changed(initial, data_same)) self.assertFalse(has_changed(initial, data_almost_same)) self.assertTrue(has_changed(initial, data_changed))
bsd-3-clause
xaled/wunderous-analytics
wunderous/drive.py
1
5688
import os import sys import httplib2 from oauth2client.file import Storage from apiclient import discovery from oauth2client.client import OAuth2WebServerFlow from wunderous.config import config OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive' SHEETS_OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.readonly https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/spreadsheets https://www.googleapis.com/auth/spreadsheets.readonly' REDIRECT_URI = 'urn:ietf:wg:oauth:2.0:oob' CREDS_FILE = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), 'credentials.json') SHEETS_CREDS_FILE = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), 'sheets_credentials.json') # CONFIG_FILE = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), "wunderous.config.json") sheet_service = None drive_service = None # def load_configs(): # client_secret = config['client_secret'] # client_id = config['client_id'] # return client_id, client_secret def init_drive_service(): global drive_service if drive_service: return drive_service storage = Storage(CREDS_FILE) credentials = storage.get() if credentials is None: # Run through the OAuth flow and retrieve credentials # client_id, client_secret = load_configs() flow = OAuth2WebServerFlow(config['drive']['client_id'], config['drive']['client_secret'], OAUTH_SCOPE, REDIRECT_URI) authorize_url = flow.step1_get_authorize_url() print('Go to the following link in your browser: ' + authorize_url) code = input('Enter verification code: ').strip() credentials = flow.step2_exchange(code) storage.put(credentials) # Create an httplib2.Http object and authorize it with our credentials http = httplib2.Http() http = credentials.authorize(http) drive_service = discovery.build('drive', 'v2', http=http) return drive_service def init_sheet_service(): global sheet_service if sheet_service: return sheet_service storage = Storage(SHEETS_CREDS_FILE) credentials = storage.get() if credentials is None: # Run through the OAuth flow and retrieve credentials # client_id, client_secret = load_configs() flow = OAuth2WebServerFlow(config['drive']['client_id'], config['drive']['client_secret'], OAUTH_SCOPE, REDIRECT_URI) authorize_url = flow.step1_get_authorize_url() print('Go to the following link in your browser: ' + authorize_url) code = input('Enter verification code: ').strip() credentials = flow.step2_exchange(code) storage.put(credentials) # Create an httplib2.Http object and authorize it with our credentials http = httplib2.Http() http = credentials.authorize(http) sheet_service = discovery.build('sheets', 'v4', http=http) return sheet_service def list_files(service): page_token = None while True: param = {} if page_token: param['pageToken'] = page_token files = service.files().list(**param).execute() for item in files['items']: yield item page_token = files.get('nextPageToken') if not page_token: break def _download_file(drive_service, download_url, outfile): resp, content = drive_service._http.request(download_url) if resp.status == 200: with open(outfile, 'wb') as f: f.write(content) print("OK") return else: raise Exception("ERROR downloading %s, response code is not 200!" % outfile) def download_file(outfile, fileid): drive_service = init_drive_service() for item in list_files(drive_service): if fileid == item.get('id'): if 'downloadUrl' in item: _download_file(drive_service, item['downloadUrl'], outfile) return else: raise Exception("No download link is found for file: %s" % item['title']) raise Exception("No file with id: %s is found " % fileid) def get_sheet_metadata(spreadsheet_id): sheet_service = init_sheet_service() sheet_metadata = sheet_service.spreadsheets().get(spreadsheetId=spreadsheet_id).execute() return sheet_metadata def get_sheet_values(spreadsheet_id, range_): sheet_service = init_sheet_service() request = sheet_service.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range=range_, valueRenderOption='FORMATTED_VALUE', dateTimeRenderOption='SERIAL_NUMBER') response = request.execute() return response def get_sheet_value(spreadsheet_id, range_): response = get_sheet_values(spreadsheet_id, range_) try: return response['values'][0][0] except: return '' def update_sheet_values(spreadsheet_id, range_, values): sheet_service = init_sheet_service() body = {'values': values} result = sheet_service.spreadsheets().values().update(spreadsheetId=spreadsheet_id, range=range_, body=body, valueInputOption='USER_ENTERED').execute() return result.get('updatedCells') def append_sheet_values(spreadsheet_id, range_, values): sheet_service = init_sheet_service() body = {'values': values} result = sheet_service.spreadsheets().values().append(spreadsheetId=spreadsheet_id, range=range_, body=body, valueInputOption='USER_ENTERED').execute() return result.get('updates').get('updatedCells')
mit
astocko/statsmodels
statsmodels/tsa/varma_process.py
30
19986
# -*- coding: utf-8 -*- """ Helper and filter functions for VAR and VARMA, and basic VAR class Created on Mon Jan 11 11:04:23 2010 Author: josef-pktd License: BSD This is a new version, I didn't look at the old version again, but similar ideas. not copied/cleaned yet: * fftn based filtering, creating samples with fft * Tests: I ran examples but did not convert them to tests examples look good for parameter estimate and forecast, and filter functions main TODOs: * result statistics * see whether Bayesian dummy observation can be included without changing the single call to linalg.lstsq * impulse response function does not treat correlation, see Hamilton and jplv Extensions * constraints, Bayesian priors/penalization * Error Correction Form and Cointegration * Factor Models Stock-Watson, ??? see also VAR section in Notes.txt """ from __future__ import print_function import numpy as np from numpy.testing import assert_equal from scipy import signal #might not (yet) need the following from scipy.signal.signaltools import _centered as trim_centered from statsmodels.tsa.tsatools import lagmat def varfilter(x, a): '''apply an autoregressive filter to a series x Warning: I just found out that convolve doesn't work as I thought, this likely doesn't work correctly for nvars>3 x can be 2d, a can be 1d, 2d, or 3d Parameters ---------- x : array_like data array, 1d or 2d, if 2d then observations in rows a : array_like autoregressive filter coefficients, ar lag polynomial see Notes Returns ------- y : ndarray, 2d filtered array, number of columns determined by x and a Notes ----- In general form this uses the linear filter :: y = a(L)x where x : nobs, nvars a : nlags, nvars, npoly Depending on the shape and dimension of a this uses different Lag polynomial arrays case 1 : a is 1d or (nlags,1) one lag polynomial is applied to all variables (columns of x) case 2 : a is 2d, (nlags, nvars) each series is independently filtered with its own lag polynomial, uses loop over nvar case 3 : a is 3d, (nlags, nvars, npoly) the ith column of the output array is given by the linear filter defined by the 2d array a[:,:,i], i.e. :: y[:,i] = a(.,.,i)(L) * x y[t,i] = sum_p sum_j a(p,j,i)*x(t-p,j) for p = 0,...nlags-1, j = 0,...nvars-1, for all t >= nlags Note: maybe convert to axis=1, Not TODO: initial conditions ''' x = np.asarray(x) a = np.asarray(a) if x.ndim == 1: x = x[:,None] if x.ndim > 2: raise ValueError('x array has to be 1d or 2d') nvar = x.shape[1] nlags = a.shape[0] ntrim = nlags//2 # for x is 2d with ncols >1 if a.ndim == 1: # case: identical ar filter (lag polynomial) return signal.convolve(x, a[:,None], mode='valid') # alternative: #return signal.lfilter(a,[1],x.astype(float),axis=0) elif a.ndim == 2: if min(a.shape) == 1: # case: identical ar filter (lag polynomial) return signal.convolve(x, a, mode='valid') # case: independent ar #(a bit like recserar in gauss, but no x yet) #(no, reserar is inverse filter) result = np.zeros((x.shape[0]-nlags+1, nvar)) for i in range(nvar): # could also use np.convolve, but easier for swiching to fft result[:,i] = signal.convolve(x[:,i], a[:,i], mode='valid') return result elif a.ndim == 3: # case: vector autoregressive with lag matrices # #not necessary: # if np.any(a.shape[1:] != nvar): # raise ValueError('if 3d shape of a has to be (nobs,nvar,nvar)') yf = signal.convolve(x[:,:,None], a) yvalid = yf[ntrim:-ntrim, yf.shape[1]//2,:] return yvalid def varinversefilter(ar, nobs, version=1): '''creates inverse ar filter (MA representation) recursively The VAR lag polynomial is defined by :: ar(L) y_t = u_t or y_t = -ar_{-1}(L) y_{t-1} + u_t the returned lagpolynomial is arinv(L)=ar^{-1}(L) in :: y_t = arinv(L) u_t Parameters ---------- ar : array, (nlags,nvars,nvars) matrix lagpolynomial, currently no exog first row should be identity Returns ------- arinv : array, (nobs,nvars,nvars) Notes ----- ''' nlags, nvars, nvarsex = ar.shape if nvars != nvarsex: print('exogenous variables not implemented not tested') arinv = np.zeros((nobs+1, nvarsex, nvars)) arinv[0,:,:] = ar[0] arinv[1:nlags,:,:] = -ar[1:] if version == 1: for i in range(2,nobs+1): tmp = np.zeros((nvars,nvars)) for p in range(1,nlags): tmp += np.dot(-ar[p],arinv[i-p,:,:]) arinv[i,:,:] = tmp if version == 0: for i in range(nlags+1,nobs+1): print(ar[1:].shape, arinv[i-1:i-nlags:-1,:,:].shape) #arinv[i,:,:] = np.dot(-ar[1:],arinv[i-1:i-nlags:-1,:,:]) #print(np.tensordot(-ar[1:],arinv[i-1:i-nlags:-1,:,:],axes=([2],[1])).shape #arinv[i,:,:] = np.tensordot(-ar[1:],arinv[i-1:i-nlags:-1,:,:],axes=([2],[1])) raise NotImplementedError('waiting for generalized ufuncs or something') return arinv def vargenerate(ar, u, initvalues=None): '''generate an VAR process with errors u similar to gauss uses loop Parameters ---------- ar : array (nlags,nvars,nvars) matrix lagpolynomial u : array (nobs,nvars) exogenous variable, error term for VAR Returns ------- sar : array (1+nobs,nvars) sample of var process, inverse filtered u does not trim initial condition y_0 = 0 Examples -------- # generate random sample of VAR nobs, nvars = 10, 2 u = numpy.random.randn(nobs,nvars) a21 = np.array([[[ 1. , 0. ], [ 0. , 1. ]], [[-0.8, 0. ], [ 0., -0.6]]]) vargenerate(a21,u) # Impulse Response to an initial shock to the first variable imp = np.zeros((nobs, nvars)) imp[0,0] = 1 vargenerate(a21,imp) ''' nlags, nvars, nvarsex = ar.shape nlagsm1 = nlags - 1 nobs = u.shape[0] if nvars != nvarsex: print('exogenous variables not implemented not tested') if u.shape[1] != nvars: raise ValueError('u needs to have nvars columns') if initvalues is None: sar = np.zeros((nobs+nlagsm1, nvars)) start = nlagsm1 else: start = max(nlagsm1, initvalues.shape[0]) sar = np.zeros((nobs+start, nvars)) sar[start-initvalues.shape[0]:start] = initvalues #sar[nlagsm1:] = u sar[start:] = u #if version == 1: for i in range(start,start+nobs): for p in range(1,nlags): sar[i] += np.dot(sar[i-p,:],-ar[p]) return sar def padone(x, front=0, back=0, axis=0, fillvalue=0): '''pad with zeros along one axis, currently only axis=0 can be used sequentially to pad several axis Examples -------- >>> padone(np.ones((2,3)),1,3,axis=1) array([[ 0., 1., 1., 1., 0., 0., 0.], [ 0., 1., 1., 1., 0., 0., 0.]]) >>> padone(np.ones((2,3)),1,1, fillvalue=np.nan) array([[ NaN, NaN, NaN], [ 1., 1., 1.], [ 1., 1., 1.], [ NaN, NaN, NaN]]) ''' #primitive version shape = np.array(x.shape) shape[axis] += (front + back) shapearr = np.array(x.shape) out = np.empty(shape) out.fill(fillvalue) startind = np.zeros(x.ndim) startind[axis] = front endind = startind + shapearr myslice = [slice(startind[k], endind[k]) for k in range(len(endind))] #print(myslice #print(out.shape #print(out[tuple(myslice)].shape out[tuple(myslice)] = x return out def trimone(x, front=0, back=0, axis=0): '''trim number of array elements along one axis Examples -------- >>> xp = padone(np.ones((2,3)),1,3,axis=1) >>> xp array([[ 0., 1., 1., 1., 0., 0., 0.], [ 0., 1., 1., 1., 0., 0., 0.]]) >>> trimone(xp,1,3,1) array([[ 1., 1., 1.], [ 1., 1., 1.]]) ''' shape = np.array(x.shape) shape[axis] -= (front + back) #print(shape, front, back shapearr = np.array(x.shape) startind = np.zeros(x.ndim) startind[axis] = front endind = startind + shape myslice = [slice(startind[k], endind[k]) for k in range(len(endind))] #print(myslice #print(shape, endind #print(x[tuple(myslice)].shape return x[tuple(myslice)] def ar2full(ar): '''make reduced lagpolynomial into a right side lagpoly array ''' nlags, nvar,nvarex = ar.shape return np.r_[np.eye(nvar,nvarex)[None,:,:],-ar] def ar2lhs(ar): '''convert full (rhs) lagpolynomial into a reduced, left side lagpoly array this is mainly a reminder about the definition ''' return -ar[1:] class _Var(object): '''obsolete VAR class, use tsa.VAR instead, for internal use only Examples -------- >>> v = Var(ar2s) >>> v.fit(1) >>> v.arhat array([[[ 1. , 0. ], [ 0. , 1. ]], [[-0.77784898, 0.01726193], [ 0.10733009, -0.78665335]]]) ''' def __init__(self, y): self.y = y self.nobs, self.nvars = y.shape def fit(self, nlags): '''estimate parameters using ols Parameters ---------- nlags : integer number of lags to include in regression, same for all variables Returns ------- None, but attaches arhat : array (nlags, nvar, nvar) full lag polynomial array arlhs : array (nlags-1, nvar, nvar) reduced lag polynomial for left hand side other statistics as returned by linalg.lstsq : need to be completed This currently assumes all parameters are estimated without restrictions. In this case SUR is identical to OLS estimation results are attached to the class instance ''' self.nlags = nlags # without current period nvars = self.nvars #TODO: ar2s looks like a module variable, bug? #lmat = lagmat(ar2s, nlags, trim='both', original='in') lmat = lagmat(self.y, nlags, trim='both', original='in') self.yred = lmat[:,:nvars] self.xred = lmat[:,nvars:] res = np.linalg.lstsq(self.xred, self.yred) self.estresults = res self.arlhs = res[0].reshape(nlags, nvars, nvars) self.arhat = ar2full(self.arlhs) self.rss = res[1] self.xredrank = res[2] def predict(self): '''calculate estimated timeseries (yhat) for sample ''' if not hasattr(self, 'yhat'): self.yhat = varfilter(self.y, self.arhat) return self.yhat def covmat(self): ''' covariance matrix of estimate # not sure it's correct, need to check orientation everywhere # looks ok, display needs getting used to >>> v.rss[None,None,:]*np.linalg.inv(np.dot(v.xred.T,v.xred))[:,:,None] array([[[ 0.37247445, 0.32210609], [ 0.1002642 , 0.08670584]], [[ 0.1002642 , 0.08670584], [ 0.45903637, 0.39696255]]]) >>> >>> v.rss[0]*np.linalg.inv(np.dot(v.xred.T,v.xred)) array([[ 0.37247445, 0.1002642 ], [ 0.1002642 , 0.45903637]]) >>> v.rss[1]*np.linalg.inv(np.dot(v.xred.T,v.xred)) array([[ 0.32210609, 0.08670584], [ 0.08670584, 0.39696255]]) ''' #check if orientation is same as self.arhat self.paramcov = (self.rss[None,None,:] * np.linalg.inv(np.dot(self.xred.T, self.xred))[:,:,None]) def forecast(self, horiz=1, u=None): '''calculates forcast for horiz number of periods at end of sample Parameters ---------- horiz : int (optional, default=1) forecast horizon u : array (horiz, nvars) error term for forecast periods. If None, then u is zero. Returns ------- yforecast : array (nobs+horiz, nvars) this includes the sample and the forecasts ''' if u is None: u = np.zeros((horiz, self.nvars)) return vargenerate(self.arhat, u, initvalues=self.y) class VarmaPoly(object): '''class to keep track of Varma polynomial format Examples -------- ar23 = np.array([[[ 1. , 0. ], [ 0. , 1. ]], [[-0.6, 0. ], [ 0.2, -0.6]], [[-0.1, 0. ], [ 0.1, -0.1]]]) ma22 = np.array([[[ 1. , 0. ], [ 0. , 1. ]], [[ 0.4, 0. ], [ 0.2, 0.3]]]) ''' def __init__(self, ar, ma=None): self.ar = ar self.ma = ma nlags, nvarall, nvars = ar.shape self.nlags, self.nvarall, self.nvars = nlags, nvarall, nvars self.isstructured = not (ar[0,:nvars] == np.eye(nvars)).all() if self.ma is None: self.ma = np.eye(nvars)[None,...] self.isindependent = True else: self.isindependent = not (ma[0] == np.eye(nvars)).all() self.malags = ar.shape[0] self.hasexog = nvarall > nvars self.arm1 = -ar[1:] #@property def vstack(self, a=None, name='ar'): '''stack lagpolynomial vertically in 2d array ''' if not a is None: a = a elif name == 'ar': a = self.ar elif name == 'ma': a = self.ma else: raise ValueError('no array or name given') return a.reshape(-1, self.nvarall) #@property def hstack(self, a=None, name='ar'): '''stack lagpolynomial horizontally in 2d array ''' if not a is None: a = a elif name == 'ar': a = self.ar elif name == 'ma': a = self.ma else: raise ValueError('no array or name given') return a.swapaxes(1,2).reshape(-1, self.nvarall).T #@property def stacksquare(self, a=None, name='ar', orientation='vertical'): '''stack lagpolynomial vertically in 2d square array with eye ''' if not a is None: a = a elif name == 'ar': a = self.ar elif name == 'ma': a = self.ma else: raise ValueError('no array or name given') astacked = a.reshape(-1, self.nvarall) lenpk, nvars = astacked.shape #[0] amat = np.eye(lenpk, k=nvars) amat[:,:nvars] = astacked return amat #@property def vstackarma_minus1(self): '''stack ar and lagpolynomial vertically in 2d array ''' a = np.concatenate((self.ar[1:], self.ma[1:]),0) return a.reshape(-1, self.nvarall) #@property def hstackarma_minus1(self): '''stack ar and lagpolynomial vertically in 2d array this is the Kalman Filter representation, I think ''' a = np.concatenate((self.ar[1:], self.ma[1:]),0) return a.swapaxes(1,2).reshape(-1, self.nvarall) def getisstationary(self, a=None): '''check whether the auto-regressive lag-polynomial is stationary Returns ------- isstationary : boolean *attaches* areigenvalues : complex array eigenvalues sorted by absolute value References ---------- formula taken from NAG manual ''' if not a is None: a = a else: if self.isstructured: a = -self.reduceform(self.ar)[1:] else: a = -self.ar[1:] amat = self.stacksquare(a) ev = np.sort(np.linalg.eigvals(amat))[::-1] self.areigenvalues = ev return (np.abs(ev) < 1).all() def getisinvertible(self, a=None): '''check whether the auto-regressive lag-polynomial is stationary Returns ------- isinvertible : boolean *attaches* maeigenvalues : complex array eigenvalues sorted by absolute value References ---------- formula taken from NAG manual ''' if not a is None: a = a else: if self.isindependent: a = self.reduceform(self.ma)[1:] else: a = self.ma[1:] if a.shape[0] == 0: # no ma lags self.maeigenvalues = np.array([], np.complex) return True amat = self.stacksquare(a) ev = np.sort(np.linalg.eigvals(amat))[::-1] self.maeigenvalues = ev return (np.abs(ev) < 1).all() def reduceform(self, apoly): ''' this assumes no exog, todo ''' if apoly.ndim != 3: raise ValueError('apoly needs to be 3d') nlags, nvarsex, nvars = apoly.shape a = np.empty_like(apoly) try: a0inv = np.linalg.inv(a[0,:nvars, :]) except np.linalg.LinAlgError: raise ValueError('matrix not invertible', 'ask for implementation of pinv') for lag in range(nlags): a[lag] = np.dot(a0inv, apoly[lag]) return a if __name__ == "__main__": # some example lag polynomials a21 = np.array([[[ 1. , 0. ], [ 0. , 1. ]], [[-0.8, 0. ], [ 0., -0.6]]]) a22 = np.array([[[ 1. , 0. ], [ 0. , 1. ]], [[-0.8, 0. ], [ 0.1, -0.8]]]) a23 = np.array([[[ 1. , 0. ], [ 0. , 1. ]], [[-0.8, 0.2], [ 0.1, -0.6]]]) a24 = np.array([[[ 1. , 0. ], [ 0. , 1. ]], [[-0.6, 0. ], [ 0.2, -0.6]], [[-0.1, 0. ], [ 0.1, -0.1]]]) a31 = np.r_[np.eye(3)[None,:,:], 0.8*np.eye(3)[None,:,:]] a32 = np.array([[[ 1. , 0. , 0. ], [ 0. , 1. , 0. ], [ 0. , 0. , 1. ]], [[ 0.8, 0. , 0. ], [ 0.1, 0.6, 0. ], [ 0. , 0. , 0.9]]]) ######## ut = np.random.randn(1000,2) ar2s = vargenerate(a22,ut) #res = np.linalg.lstsq(lagmat(ar2s,1)[:,1:], ar2s) res = np.linalg.lstsq(lagmat(ar2s,1), ar2s) bhat = res[0].reshape(1,2,2) arhat = ar2full(bhat) #print(maxabs(arhat - a22) v = _Var(ar2s) v.fit(1) v.forecast() v.forecast(25)[-30:] ar23 = np.array([[[ 1. , 0. ], [ 0. , 1. ]], [[-0.6, 0. ], [ 0.2, -0.6]], [[-0.1, 0. ], [ 0.1, -0.1]]]) ma22 = np.array([[[ 1. , 0. ], [ 0. , 1. ]], [[ 0.4, 0. ], [ 0.2, 0.3]]]) ar23ns = np.array([[[ 1. , 0. ], [ 0. , 1. ]], [[-1.9, 0. ], [ 0.4, -0.6]], [[ 0.3, 0. ], [ 0.1, -0.1]]]) vp = VarmaPoly(ar23, ma22) print(vars(vp)) print(vp.vstack()) print(vp.vstack(a24)) print(vp.hstackarma_minus1()) print(vp.getisstationary()) print(vp.getisinvertible()) vp2 = VarmaPoly(ar23ns) print(vp2.getisstationary()) print(vp2.getisinvertible()) # no ma lags
bsd-3-clause
timesking/sublime-evernote
lib/pygments/lexers/templates.py
9
56066
# -*- coding: utf-8 -*- """ pygments.lexers.templates ~~~~~~~~~~~~~~~~~~~~~~~~~ Lexers for various template engines' markup. :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import re from pygments.lexers.web import \ PhpLexer, HtmlLexer, XmlLexer, JavascriptLexer, CssLexer, LassoLexer from pygments.lexers.agile import PythonLexer, PerlLexer from pygments.lexers.compiled import JavaLexer from pygments.lexers.jvm import TeaLangLexer from pygments.lexer import Lexer, DelegatingLexer, RegexLexer, bygroups, \ include, using, this from pygments.token import Error, Punctuation, \ Text, Comment, Operator, Keyword, Name, String, Number, Other, Token from pygments.util import html_doctype_matches, looks_like_xml __all__ = ['HtmlPhpLexer', 'XmlPhpLexer', 'CssPhpLexer', 'JavascriptPhpLexer', 'ErbLexer', 'RhtmlLexer', 'XmlErbLexer', 'CssErbLexer', 'JavascriptErbLexer', 'SmartyLexer', 'HtmlSmartyLexer', 'XmlSmartyLexer', 'CssSmartyLexer', 'JavascriptSmartyLexer', 'DjangoLexer', 'HtmlDjangoLexer', 'CssDjangoLexer', 'XmlDjangoLexer', 'JavascriptDjangoLexer', 'GenshiLexer', 'HtmlGenshiLexer', 'GenshiTextLexer', 'CssGenshiLexer', 'JavascriptGenshiLexer', 'MyghtyLexer', 'MyghtyHtmlLexer', 'MyghtyXmlLexer', 'MyghtyCssLexer', 'MyghtyJavascriptLexer', 'MasonLexer', 'MakoLexer', 'MakoHtmlLexer', 'MakoXmlLexer', 'MakoJavascriptLexer', 'MakoCssLexer', 'JspLexer', 'CheetahLexer', 'CheetahHtmlLexer', 'CheetahXmlLexer', 'CheetahJavascriptLexer', 'EvoqueLexer', 'EvoqueHtmlLexer', 'EvoqueXmlLexer', 'ColdfusionLexer', 'ColdfusionHtmlLexer', 'VelocityLexer', 'VelocityHtmlLexer', 'VelocityXmlLexer', 'SspLexer', 'TeaTemplateLexer', 'LassoHtmlLexer', 'LassoXmlLexer', 'LassoCssLexer', 'LassoJavascriptLexer'] class ErbLexer(Lexer): """ Generic `ERB <http://ruby-doc.org/core/classes/ERB.html>`_ (Ruby Templating) lexer. Just highlights ruby code between the preprocessor directives, other data is left untouched by the lexer. All options are also forwarded to the `RubyLexer`. """ name = 'ERB' aliases = ['erb'] mimetypes = ['application/x-ruby-templating'] _block_re = re.compile(r'(<%%|%%>|<%=|<%#|<%-|<%|-%>|%>|^%[^%].*?$)', re.M) def __init__(self, **options): from pygments.lexers.agile import RubyLexer self.ruby_lexer = RubyLexer(**options) Lexer.__init__(self, **options) def get_tokens_unprocessed(self, text): """ Since ERB doesn't allow "<%" and other tags inside of ruby blocks we have to use a split approach here that fails for that too. """ tokens = self._block_re.split(text) tokens.reverse() state = idx = 0 try: while True: # text if state == 0: val = tokens.pop() yield idx, Other, val idx += len(val) state = 1 # block starts elif state == 1: tag = tokens.pop() # literals if tag in ('<%%', '%%>'): yield idx, Other, tag idx += 3 state = 0 # comment elif tag == '<%#': yield idx, Comment.Preproc, tag val = tokens.pop() yield idx + 3, Comment, val idx += 3 + len(val) state = 2 # blocks or output elif tag in ('<%', '<%=', '<%-'): yield idx, Comment.Preproc, tag idx += len(tag) data = tokens.pop() r_idx = 0 for r_idx, r_token, r_value in \ self.ruby_lexer.get_tokens_unprocessed(data): yield r_idx + idx, r_token, r_value idx += len(data) state = 2 elif tag in ('%>', '-%>'): yield idx, Error, tag idx += len(tag) state = 0 # % raw ruby statements else: yield idx, Comment.Preproc, tag[0] r_idx = 0 for r_idx, r_token, r_value in \ self.ruby_lexer.get_tokens_unprocessed(tag[1:]): yield idx + 1 + r_idx, r_token, r_value idx += len(tag) state = 0 # block ends elif state == 2: tag = tokens.pop() if tag not in ('%>', '-%>'): yield idx, Other, tag else: yield idx, Comment.Preproc, tag idx += len(tag) state = 0 except IndexError: return def analyse_text(text): if '<%' in text and '%>' in text: return 0.4 class SmartyLexer(RegexLexer): """ Generic `Smarty <http://smarty.php.net/>`_ template lexer. Just highlights smarty code between the preprocessor directives, other data is left untouched by the lexer. """ name = 'Smarty' aliases = ['smarty'] filenames = ['*.tpl'] mimetypes = ['application/x-smarty'] flags = re.MULTILINE | re.DOTALL tokens = { 'root': [ (r'[^{]+', Other), (r'(\{)(\*.*?\*)(\})', bygroups(Comment.Preproc, Comment, Comment.Preproc)), (r'(\{php\})(.*?)(\{/php\})', bygroups(Comment.Preproc, using(PhpLexer, startinline=True), Comment.Preproc)), (r'(\{)(/?[a-zA-Z_][a-zA-Z0-9_]*)(\s*)', bygroups(Comment.Preproc, Name.Function, Text), 'smarty'), (r'\{', Comment.Preproc, 'smarty') ], 'smarty': [ (r'\s+', Text), (r'\}', Comment.Preproc, '#pop'), (r'#[a-zA-Z_][a-zA-Z0-9_]*#', Name.Variable), (r'\$[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z0-9_]+)*', Name.Variable), (r'[~!%^&*()+=|\[\]:;,.<>/?{}@-]', Operator), (r'(true|false|null)\b', Keyword.Constant), (r"[0-9](\.[0-9]*)?(eE[+-][0-9])?[flFLdD]?|" r"0[xX][0-9a-fA-F]+[Ll]?", Number), (r'"(\\\\|\\"|[^"])*"', String.Double), (r"'(\\\\|\\'|[^'])*'", String.Single), (r'[a-zA-Z_][a-zA-Z0-9_]*', Name.Attribute) ] } def analyse_text(text): rv = 0.0 if re.search('\{if\s+.*?\}.*?\{/if\}', text): rv += 0.15 if re.search('\{include\s+file=.*?\}', text): rv += 0.15 if re.search('\{foreach\s+.*?\}.*?\{/foreach\}', text): rv += 0.15 if re.search('\{\$.*?\}', text): rv += 0.01 return rv class VelocityLexer(RegexLexer): """ Generic `Velocity <http://velocity.apache.org/>`_ template lexer. Just highlights velocity directives and variable references, other data is left untouched by the lexer. """ name = 'Velocity' aliases = ['velocity'] filenames = ['*.vm','*.fhtml'] flags = re.MULTILINE | re.DOTALL identifier = r'[a-zA-Z_][a-zA-Z0-9_]*' tokens = { 'root': [ (r'[^{#$]+', Other), (r'(#)(\*.*?\*)(#)', bygroups(Comment.Preproc, Comment, Comment.Preproc)), (r'(##)(.*?$)', bygroups(Comment.Preproc, Comment)), (r'(#\{?)(' + identifier + r')(\}?)(\s?\()', bygroups(Comment.Preproc, Name.Function, Comment.Preproc, Punctuation), 'directiveparams'), (r'(#\{?)(' + identifier + r')(\}|\b)', bygroups(Comment.Preproc, Name.Function, Comment.Preproc)), (r'\$\{?', Punctuation, 'variable') ], 'variable': [ (identifier, Name.Variable), (r'\(', Punctuation, 'funcparams'), (r'(\.)(' + identifier + r')', bygroups(Punctuation, Name.Variable), '#push'), (r'\}', Punctuation, '#pop'), (r'', Other, '#pop') ], 'directiveparams': [ (r'(&&|\|\||==?|!=?|[-<>+*%&\|\^/])|\b(eq|ne|gt|lt|ge|le|not|in)\b', Operator), (r'\[', Operator, 'rangeoperator'), (r'\b' + identifier + r'\b', Name.Function), include('funcparams') ], 'rangeoperator': [ (r'\.\.', Operator), include('funcparams'), (r'\]', Operator, '#pop') ], 'funcparams': [ (r'\$\{?', Punctuation, 'variable'), (r'\s+', Text), (r',', Punctuation), (r'"(\\\\|\\"|[^"])*"', String.Double), (r"'(\\\\|\\'|[^'])*'", String.Single), (r"0[xX][0-9a-fA-F]+[Ll]?", Number), (r"\b[0-9]+\b", Number), (r'(true|false|null)\b', Keyword.Constant), (r'\(', Punctuation, '#push'), (r'\)', Punctuation, '#pop'), (r'\[', Punctuation, '#push'), (r'\]', Punctuation, '#pop'), ] } def analyse_text(text): rv = 0.0 if re.search(r'#\{?macro\}?\(.*?\).*?#\{?end\}?', text): rv += 0.25 if re.search(r'#\{?if\}?\(.+?\).*?#\{?end\}?', text): rv += 0.15 if re.search(r'#\{?foreach\}?\(.+?\).*?#\{?end\}?', text): rv += 0.15 if re.search(r'\$\{?[a-zA-Z_][a-zA-Z0-9_]*(\([^)]*\))?' r'(\.[a-zA-Z0-9_]+(\([^)]*\))?)*\}?', text): rv += 0.01 return rv class VelocityHtmlLexer(DelegatingLexer): """ Subclass of the `VelocityLexer` that highlights unlexer data with the `HtmlLexer`. """ name = 'HTML+Velocity' aliases = ['html+velocity'] alias_filenames = ['*.html','*.fhtml'] mimetypes = ['text/html+velocity'] def __init__(self, **options): super(VelocityHtmlLexer, self).__init__(HtmlLexer, VelocityLexer, **options) class VelocityXmlLexer(DelegatingLexer): """ Subclass of the `VelocityLexer` that highlights unlexer data with the `XmlLexer`. """ name = 'XML+Velocity' aliases = ['xml+velocity'] alias_filenames = ['*.xml','*.vm'] mimetypes = ['application/xml+velocity'] def __init__(self, **options): super(VelocityXmlLexer, self).__init__(XmlLexer, VelocityLexer, **options) def analyse_text(text): rv = VelocityLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.5 return rv class DjangoLexer(RegexLexer): """ Generic `django <http://www.djangoproject.com/documentation/templates/>`_ and `jinja <http://wsgiarea.pocoo.org/jinja/>`_ template lexer. It just highlights django/jinja code between the preprocessor directives, other data is left untouched by the lexer. """ name = 'Django/Jinja' aliases = ['django', 'jinja'] mimetypes = ['application/x-django-templating', 'application/x-jinja'] flags = re.M | re.S tokens = { 'root': [ (r'[^{]+', Other), (r'\{\{', Comment.Preproc, 'var'), # jinja/django comments (r'\{[*#].*?[*#]\}', Comment), # django comments (r'(\{%)(-?\s*)(comment)(\s*-?)(%\})(.*?)' r'(\{%)(-?\s*)(endcomment)(\s*-?)(%\})', bygroups(Comment.Preproc, Text, Keyword, Text, Comment.Preproc, Comment, Comment.Preproc, Text, Keyword, Text, Comment.Preproc)), # raw jinja blocks (r'(\{%)(-?\s*)(raw)(\s*-?)(%\})(.*?)' r'(\{%)(-?\s*)(endraw)(\s*-?)(%\})', bygroups(Comment.Preproc, Text, Keyword, Text, Comment.Preproc, Text, Comment.Preproc, Text, Keyword, Text, Comment.Preproc)), # filter blocks (r'(\{%)(-?\s*)(filter)(\s+)([a-zA-Z_][a-zA-Z0-9_]*)', bygroups(Comment.Preproc, Text, Keyword, Text, Name.Function), 'block'), (r'(\{%)(-?\s*)([a-zA-Z_][a-zA-Z0-9_]*)', bygroups(Comment.Preproc, Text, Keyword), 'block'), (r'\{', Other) ], 'varnames': [ (r'(\|)(\s*)([a-zA-Z_][a-zA-Z0-9_]*)', bygroups(Operator, Text, Name.Function)), (r'(is)(\s+)(not)?(\s+)?([a-zA-Z_][a-zA-Z0-9_]*)', bygroups(Keyword, Text, Keyword, Text, Name.Function)), (r'(_|true|false|none|True|False|None)\b', Keyword.Pseudo), (r'(in|as|reversed|recursive|not|and|or|is|if|else|import|' r'with(?:(?:out)?\s*context)?|scoped|ignore\s+missing)\b', Keyword), (r'(loop|block|super|forloop)\b', Name.Builtin), (r'[a-zA-Z][a-zA-Z0-9_-]*', Name.Variable), (r'\.[a-zA-Z0-9_]+', Name.Variable), (r':?"(\\\\|\\"|[^"])*"', String.Double), (r":?'(\\\\|\\'|[^'])*'", String.Single), (r'([{}()\[\]+\-*/,:~]|[><=]=?)', Operator), (r"[0-9](\.[0-9]*)?(eE[+-][0-9])?[flFLdD]?|" r"0[xX][0-9a-fA-F]+[Ll]?", Number), ], 'var': [ (r'\s+', Text), (r'(-?)(\}\})', bygroups(Text, Comment.Preproc), '#pop'), include('varnames') ], 'block': [ (r'\s+', Text), (r'(-?)(%\})', bygroups(Text, Comment.Preproc), '#pop'), include('varnames'), (r'.', Punctuation) ] } def analyse_text(text): rv = 0.0 if re.search(r'\{%\s*(block|extends)', text) is not None: rv += 0.4 if re.search(r'\{%\s*if\s*.*?%\}', text) is not None: rv += 0.1 if re.search(r'\{\{.*?\}\}', text) is not None: rv += 0.1 return rv class MyghtyLexer(RegexLexer): """ Generic `myghty templates`_ lexer. Code that isn't Myghty markup is yielded as `Token.Other`. .. versionadded:: 0.6 .. _myghty templates: http://www.myghty.org/ """ name = 'Myghty' aliases = ['myghty'] filenames = ['*.myt', 'autodelegate'] mimetypes = ['application/x-myghty'] tokens = { 'root': [ (r'\s+', Text), (r'(<%(?:def|method))(\s*)(.*?)(>)(.*?)(</%\2\s*>)(?s)', bygroups(Name.Tag, Text, Name.Function, Name.Tag, using(this), Name.Tag)), (r'(<%\w+)(.*?)(>)(.*?)(</%\2\s*>)(?s)', bygroups(Name.Tag, Name.Function, Name.Tag, using(PythonLexer), Name.Tag)), (r'(<&[^|])(.*?)(,.*?)?(&>)', bygroups(Name.Tag, Name.Function, using(PythonLexer), Name.Tag)), (r'(<&\|)(.*?)(,.*?)?(&>)(?s)', bygroups(Name.Tag, Name.Function, using(PythonLexer), Name.Tag)), (r'</&>', Name.Tag), (r'(<%!?)(.*?)(%>)(?s)', bygroups(Name.Tag, using(PythonLexer), Name.Tag)), (r'(?<=^)#[^\n]*(\n|\Z)', Comment), (r'(?<=^)(%)([^\n]*)(\n|\Z)', bygroups(Name.Tag, using(PythonLexer), Other)), (r"""(?sx) (.+?) # anything, followed by: (?: (?<=\n)(?=[%#]) | # an eval or comment line (?=</?[%&]) | # a substitution or block or # call start or end # - don't consume (\\\n) | # an escaped newline \Z # end of string )""", bygroups(Other, Operator)), ] } class MyghtyHtmlLexer(DelegatingLexer): """ Subclass of the `MyghtyLexer` that highlights unlexer data with the `HtmlLexer`. .. versionadded:: 0.6 """ name = 'HTML+Myghty' aliases = ['html+myghty'] mimetypes = ['text/html+myghty'] def __init__(self, **options): super(MyghtyHtmlLexer, self).__init__(HtmlLexer, MyghtyLexer, **options) class MyghtyXmlLexer(DelegatingLexer): """ Subclass of the `MyghtyLexer` that highlights unlexer data with the `XmlLexer`. .. versionadded:: 0.6 """ name = 'XML+Myghty' aliases = ['xml+myghty'] mimetypes = ['application/xml+myghty'] def __init__(self, **options): super(MyghtyXmlLexer, self).__init__(XmlLexer, MyghtyLexer, **options) class MyghtyJavascriptLexer(DelegatingLexer): """ Subclass of the `MyghtyLexer` that highlights unlexer data with the `JavascriptLexer`. .. versionadded:: 0.6 """ name = 'JavaScript+Myghty' aliases = ['js+myghty', 'javascript+myghty'] mimetypes = ['application/x-javascript+myghty', 'text/x-javascript+myghty', 'text/javascript+mygthy'] def __init__(self, **options): super(MyghtyJavascriptLexer, self).__init__(JavascriptLexer, MyghtyLexer, **options) class MyghtyCssLexer(DelegatingLexer): """ Subclass of the `MyghtyLexer` that highlights unlexer data with the `CssLexer`. .. versionadded:: 0.6 """ name = 'CSS+Myghty' aliases = ['css+myghty'] mimetypes = ['text/css+myghty'] def __init__(self, **options): super(MyghtyCssLexer, self).__init__(CssLexer, MyghtyLexer, **options) class MasonLexer(RegexLexer): """ Generic `mason templates`_ lexer. Stolen from Myghty lexer. Code that isn't Mason markup is HTML. .. _mason templates: http://www.masonhq.com/ .. versionadded:: 1.4 """ name = 'Mason' aliases = ['mason'] filenames = ['*.m', '*.mhtml', '*.mc', '*.mi', 'autohandler', 'dhandler'] mimetypes = ['application/x-mason'] tokens = { 'root': [ (r'\s+', Text), (r'(<%doc>)(.*?)(</%doc>)(?s)', bygroups(Name.Tag, Comment.Multiline, Name.Tag)), (r'(<%(?:def|method))(\s*)(.*?)(>)(.*?)(</%\2\s*>)(?s)', bygroups(Name.Tag, Text, Name.Function, Name.Tag, using(this), Name.Tag)), (r'(<%\w+)(.*?)(>)(.*?)(</%\2\s*>)(?s)', bygroups(Name.Tag, Name.Function, Name.Tag, using(PerlLexer), Name.Tag)), (r'(<&[^|])(.*?)(,.*?)?(&>)(?s)', bygroups(Name.Tag, Name.Function, using(PerlLexer), Name.Tag)), (r'(<&\|)(.*?)(,.*?)?(&>)(?s)', bygroups(Name.Tag, Name.Function, using(PerlLexer), Name.Tag)), (r'</&>', Name.Tag), (r'(<%!?)(.*?)(%>)(?s)', bygroups(Name.Tag, using(PerlLexer), Name.Tag)), (r'(?<=^)#[^\n]*(\n|\Z)', Comment), (r'(?<=^)(%)([^\n]*)(\n|\Z)', bygroups(Name.Tag, using(PerlLexer), Other)), (r"""(?sx) (.+?) # anything, followed by: (?: (?<=\n)(?=[%#]) | # an eval or comment line (?=</?[%&]) | # a substitution or block or # call start or end # - don't consume (\\\n) | # an escaped newline \Z # end of string )""", bygroups(using(HtmlLexer), Operator)), ] } def analyse_text(text): rv = 0.0 if re.search('<&', text) is not None: rv = 1.0 return rv class MakoLexer(RegexLexer): """ Generic `mako templates`_ lexer. Code that isn't Mako markup is yielded as `Token.Other`. .. versionadded:: 0.7 .. _mako templates: http://www.makotemplates.org/ """ name = 'Mako' aliases = ['mako'] filenames = ['*.mao'] mimetypes = ['application/x-mako'] tokens = { 'root': [ (r'(\s*)(%)(\s*end(?:\w+))(\n|\Z)', bygroups(Text, Comment.Preproc, Keyword, Other)), (r'(\s*)(%)([^\n]*)(\n|\Z)', bygroups(Text, Comment.Preproc, using(PythonLexer), Other)), (r'(\s*)(##[^\n]*)(\n|\Z)', bygroups(Text, Comment.Preproc, Other)), (r'(?s)<%doc>.*?</%doc>', Comment.Preproc), (r'(<%)([\w\.\:]+)', bygroups(Comment.Preproc, Name.Builtin), 'tag'), (r'(</%)([\w\.\:]+)(>)', bygroups(Comment.Preproc, Name.Builtin, Comment.Preproc)), (r'<%(?=([\w\.\:]+))', Comment.Preproc, 'ondeftags'), (r'(<%(?:!?))(.*?)(%>)(?s)', bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)), (r'(\$\{)(.*?)(\})', bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)), (r'''(?sx) (.+?) # anything, followed by: (?: (?<=\n)(?=%|\#\#) | # an eval or comment line (?=\#\*) | # multiline comment (?=</?%) | # a python block # call start or end (?=\$\{) | # a substitution (?<=\n)(?=\s*%) | # - don't consume (\\\n) | # an escaped newline \Z # end of string ) ''', bygroups(Other, Operator)), (r'\s+', Text), ], 'ondeftags': [ (r'<%', Comment.Preproc), (r'(?<=<%)(include|inherit|namespace|page)', Name.Builtin), include('tag'), ], 'tag': [ (r'((?:\w+)\s*=)(\s*)(".*?")', bygroups(Name.Attribute, Text, String)), (r'/?\s*>', Comment.Preproc, '#pop'), (r'\s+', Text), ], 'attr': [ ('".*?"', String, '#pop'), ("'.*?'", String, '#pop'), (r'[^\s>]+', String, '#pop'), ], } class MakoHtmlLexer(DelegatingLexer): """ Subclass of the `MakoLexer` that highlights unlexed data with the `HtmlLexer`. .. versionadded:: 0.7 """ name = 'HTML+Mako' aliases = ['html+mako'] mimetypes = ['text/html+mako'] def __init__(self, **options): super(MakoHtmlLexer, self).__init__(HtmlLexer, MakoLexer, **options) class MakoXmlLexer(DelegatingLexer): """ Subclass of the `MakoLexer` that highlights unlexer data with the `XmlLexer`. .. versionadded:: 0.7 """ name = 'XML+Mako' aliases = ['xml+mako'] mimetypes = ['application/xml+mako'] def __init__(self, **options): super(MakoXmlLexer, self).__init__(XmlLexer, MakoLexer, **options) class MakoJavascriptLexer(DelegatingLexer): """ Subclass of the `MakoLexer` that highlights unlexer data with the `JavascriptLexer`. .. versionadded:: 0.7 """ name = 'JavaScript+Mako' aliases = ['js+mako', 'javascript+mako'] mimetypes = ['application/x-javascript+mako', 'text/x-javascript+mako', 'text/javascript+mako'] def __init__(self, **options): super(MakoJavascriptLexer, self).__init__(JavascriptLexer, MakoLexer, **options) class MakoCssLexer(DelegatingLexer): """ Subclass of the `MakoLexer` that highlights unlexer data with the `CssLexer`. .. versionadded:: 0.7 """ name = 'CSS+Mako' aliases = ['css+mako'] mimetypes = ['text/css+mako'] def __init__(self, **options): super(MakoCssLexer, self).__init__(CssLexer, MakoLexer, **options) # Genshi and Cheetah lexers courtesy of Matt Good. class CheetahPythonLexer(Lexer): """ Lexer for handling Cheetah's special $ tokens in Python syntax. """ def get_tokens_unprocessed(self, text): pylexer = PythonLexer(**self.options) for pos, type_, value in pylexer.get_tokens_unprocessed(text): if type_ == Token.Error and value == '$': type_ = Comment.Preproc yield pos, type_, value class CheetahLexer(RegexLexer): """ Generic `cheetah templates`_ lexer. Code that isn't Cheetah markup is yielded as `Token.Other`. This also works for `spitfire templates`_ which use the same syntax. .. _cheetah templates: http://www.cheetahtemplate.org/ .. _spitfire templates: http://code.google.com/p/spitfire/ """ name = 'Cheetah' aliases = ['cheetah', 'spitfire'] filenames = ['*.tmpl', '*.spt'] mimetypes = ['application/x-cheetah', 'application/x-spitfire'] tokens = { 'root': [ (r'(##[^\n]*)$', (bygroups(Comment))), (r'#[*](.|\n)*?[*]#', Comment), (r'#end[^#\n]*(?:#|$)', Comment.Preproc), (r'#slurp$', Comment.Preproc), (r'(#[a-zA-Z]+)([^#\n]*)(#|$)', (bygroups(Comment.Preproc, using(CheetahPythonLexer), Comment.Preproc))), # TODO support other Python syntax like $foo['bar'] (r'(\$)([a-zA-Z_][a-zA-Z0-9_\.]*[a-zA-Z0-9_])', bygroups(Comment.Preproc, using(CheetahPythonLexer))), (r'(\$\{!?)(.*?)(\})(?s)', bygroups(Comment.Preproc, using(CheetahPythonLexer), Comment.Preproc)), (r'''(?sx) (.+?) # anything, followed by: (?: (?=[#][#a-zA-Z]*) | # an eval comment (?=\$[a-zA-Z_{]) | # a substitution \Z # end of string ) ''', Other), (r'\s+', Text), ], } class CheetahHtmlLexer(DelegatingLexer): """ Subclass of the `CheetahLexer` that highlights unlexer data with the `HtmlLexer`. """ name = 'HTML+Cheetah' aliases = ['html+cheetah', 'html+spitfire', 'htmlcheetah'] mimetypes = ['text/html+cheetah', 'text/html+spitfire'] def __init__(self, **options): super(CheetahHtmlLexer, self).__init__(HtmlLexer, CheetahLexer, **options) class CheetahXmlLexer(DelegatingLexer): """ Subclass of the `CheetahLexer` that highlights unlexer data with the `XmlLexer`. """ name = 'XML+Cheetah' aliases = ['xml+cheetah', 'xml+spitfire'] mimetypes = ['application/xml+cheetah', 'application/xml+spitfire'] def __init__(self, **options): super(CheetahXmlLexer, self).__init__(XmlLexer, CheetahLexer, **options) class CheetahJavascriptLexer(DelegatingLexer): """ Subclass of the `CheetahLexer` that highlights unlexer data with the `JavascriptLexer`. """ name = 'JavaScript+Cheetah' aliases = ['js+cheetah', 'javascript+cheetah', 'js+spitfire', 'javascript+spitfire'] mimetypes = ['application/x-javascript+cheetah', 'text/x-javascript+cheetah', 'text/javascript+cheetah', 'application/x-javascript+spitfire', 'text/x-javascript+spitfire', 'text/javascript+spitfire'] def __init__(self, **options): super(CheetahJavascriptLexer, self).__init__(JavascriptLexer, CheetahLexer, **options) class GenshiTextLexer(RegexLexer): """ A lexer that highlights `genshi <http://genshi.edgewall.org/>`_ text templates. """ name = 'Genshi Text' aliases = ['genshitext'] mimetypes = ['application/x-genshi-text', 'text/x-genshi'] tokens = { 'root': [ (r'[^#\$\s]+', Other), (r'^(\s*)(##.*)$', bygroups(Text, Comment)), (r'^(\s*)(#)', bygroups(Text, Comment.Preproc), 'directive'), include('variable'), (r'[#\$\s]', Other), ], 'directive': [ (r'\n', Text, '#pop'), (r'(?:def|for|if)\s+.*', using(PythonLexer), '#pop'), (r'(choose|when|with)([^\S\n]+)(.*)', bygroups(Keyword, Text, using(PythonLexer)), '#pop'), (r'(choose|otherwise)\b', Keyword, '#pop'), (r'(end\w*)([^\S\n]*)(.*)', bygroups(Keyword, Text, Comment), '#pop'), ], 'variable': [ (r'(?<!\$)(\$\{)(.+?)(\})', bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)), (r'(?<!\$)(\$)([a-zA-Z_][a-zA-Z0-9_\.]*)', Name.Variable), ] } class GenshiMarkupLexer(RegexLexer): """ Base lexer for Genshi markup, used by `HtmlGenshiLexer` and `GenshiLexer`. """ flags = re.DOTALL tokens = { 'root': [ (r'[^<\$]+', Other), (r'(<\?python)(.*?)(\?>)', bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)), # yield style and script blocks as Other (r'<\s*(script|style)\s*.*?>.*?<\s*/\1\s*>', Other), (r'<\s*py:[a-zA-Z0-9]+', Name.Tag, 'pytag'), (r'<\s*[a-zA-Z0-9:]+', Name.Tag, 'tag'), include('variable'), (r'[<\$]', Other), ], 'pytag': [ (r'\s+', Text), (r'[a-zA-Z0-9_:-]+\s*=', Name.Attribute, 'pyattr'), (r'/?\s*>', Name.Tag, '#pop'), ], 'pyattr': [ ('(")(.*?)(")', bygroups(String, using(PythonLexer), String), '#pop'), ("(')(.*?)(')", bygroups(String, using(PythonLexer), String), '#pop'), (r'[^\s>]+', String, '#pop'), ], 'tag': [ (r'\s+', Text), (r'py:[a-zA-Z0-9_-]+\s*=', Name.Attribute, 'pyattr'), (r'[a-zA-Z0-9_:-]+\s*=', Name.Attribute, 'attr'), (r'/?\s*>', Name.Tag, '#pop'), ], 'attr': [ ('"', String, 'attr-dstring'), ("'", String, 'attr-sstring'), (r'[^\s>]*', String, '#pop') ], 'attr-dstring': [ ('"', String, '#pop'), include('strings'), ("'", String) ], 'attr-sstring': [ ("'", String, '#pop'), include('strings'), ("'", String) ], 'strings': [ ('[^"\'$]+', String), include('variable') ], 'variable': [ (r'(?<!\$)(\$\{)(.+?)(\})', bygroups(Comment.Preproc, using(PythonLexer), Comment.Preproc)), (r'(?<!\$)(\$)([a-zA-Z_][a-zA-Z0-9_\.]*)', Name.Variable), ] } class HtmlGenshiLexer(DelegatingLexer): """ A lexer that highlights `genshi <http://genshi.edgewall.org/>`_ and `kid <http://kid-templating.org/>`_ kid HTML templates. """ name = 'HTML+Genshi' aliases = ['html+genshi', 'html+kid'] alias_filenames = ['*.html', '*.htm', '*.xhtml'] mimetypes = ['text/html+genshi'] def __init__(self, **options): super(HtmlGenshiLexer, self).__init__(HtmlLexer, GenshiMarkupLexer, **options) def analyse_text(text): rv = 0.0 if re.search('\$\{.*?\}', text) is not None: rv += 0.2 if re.search('py:(.*?)=["\']', text) is not None: rv += 0.2 return rv + HtmlLexer.analyse_text(text) - 0.01 class GenshiLexer(DelegatingLexer): """ A lexer that highlights `genshi <http://genshi.edgewall.org/>`_ and `kid <http://kid-templating.org/>`_ kid XML templates. """ name = 'Genshi' aliases = ['genshi', 'kid', 'xml+genshi', 'xml+kid'] filenames = ['*.kid'] alias_filenames = ['*.xml'] mimetypes = ['application/x-genshi', 'application/x-kid'] def __init__(self, **options): super(GenshiLexer, self).__init__(XmlLexer, GenshiMarkupLexer, **options) def analyse_text(text): rv = 0.0 if re.search('\$\{.*?\}', text) is not None: rv += 0.2 if re.search('py:(.*?)=["\']', text) is not None: rv += 0.2 return rv + XmlLexer.analyse_text(text) - 0.01 class JavascriptGenshiLexer(DelegatingLexer): """ A lexer that highlights javascript code in genshi text templates. """ name = 'JavaScript+Genshi Text' aliases = ['js+genshitext', 'js+genshi', 'javascript+genshitext', 'javascript+genshi'] alias_filenames = ['*.js'] mimetypes = ['application/x-javascript+genshi', 'text/x-javascript+genshi', 'text/javascript+genshi'] def __init__(self, **options): super(JavascriptGenshiLexer, self).__init__(JavascriptLexer, GenshiTextLexer, **options) def analyse_text(text): return GenshiLexer.analyse_text(text) - 0.05 class CssGenshiLexer(DelegatingLexer): """ A lexer that highlights CSS definitions in genshi text templates. """ name = 'CSS+Genshi Text' aliases = ['css+genshitext', 'css+genshi'] alias_filenames = ['*.css'] mimetypes = ['text/css+genshi'] def __init__(self, **options): super(CssGenshiLexer, self).__init__(CssLexer, GenshiTextLexer, **options) def analyse_text(text): return GenshiLexer.analyse_text(text) - 0.05 class RhtmlLexer(DelegatingLexer): """ Subclass of the ERB lexer that highlights the unlexed data with the html lexer. Nested Javascript and CSS is highlighted too. """ name = 'RHTML' aliases = ['rhtml', 'html+erb', 'html+ruby'] filenames = ['*.rhtml'] alias_filenames = ['*.html', '*.htm', '*.xhtml'] mimetypes = ['text/html+ruby'] def __init__(self, **options): super(RhtmlLexer, self).__init__(HtmlLexer, ErbLexer, **options) def analyse_text(text): rv = ErbLexer.analyse_text(text) - 0.01 if html_doctype_matches(text): # one more than the XmlErbLexer returns rv += 0.5 return rv class XmlErbLexer(DelegatingLexer): """ Subclass of `ErbLexer` which highlights data outside preprocessor directives with the `XmlLexer`. """ name = 'XML+Ruby' aliases = ['xml+erb', 'xml+ruby'] alias_filenames = ['*.xml'] mimetypes = ['application/xml+ruby'] def __init__(self, **options): super(XmlErbLexer, self).__init__(XmlLexer, ErbLexer, **options) def analyse_text(text): rv = ErbLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.4 return rv class CssErbLexer(DelegatingLexer): """ Subclass of `ErbLexer` which highlights unlexed data with the `CssLexer`. """ name = 'CSS+Ruby' aliases = ['css+erb', 'css+ruby'] alias_filenames = ['*.css'] mimetypes = ['text/css+ruby'] def __init__(self, **options): super(CssErbLexer, self).__init__(CssLexer, ErbLexer, **options) def analyse_text(text): return ErbLexer.analyse_text(text) - 0.05 class JavascriptErbLexer(DelegatingLexer): """ Subclass of `ErbLexer` which highlights unlexed data with the `JavascriptLexer`. """ name = 'JavaScript+Ruby' aliases = ['js+erb', 'javascript+erb', 'js+ruby', 'javascript+ruby'] alias_filenames = ['*.js'] mimetypes = ['application/x-javascript+ruby', 'text/x-javascript+ruby', 'text/javascript+ruby'] def __init__(self, **options): super(JavascriptErbLexer, self).__init__(JavascriptLexer, ErbLexer, **options) def analyse_text(text): return ErbLexer.analyse_text(text) - 0.05 class HtmlPhpLexer(DelegatingLexer): """ Subclass of `PhpLexer` that highlights unhandled data with the `HtmlLexer`. Nested Javascript and CSS is highlighted too. """ name = 'HTML+PHP' aliases = ['html+php'] filenames = ['*.phtml'] alias_filenames = ['*.php', '*.html', '*.htm', '*.xhtml', '*.php[345]'] mimetypes = ['application/x-php', 'application/x-httpd-php', 'application/x-httpd-php3', 'application/x-httpd-php4', 'application/x-httpd-php5'] def __init__(self, **options): super(HtmlPhpLexer, self).__init__(HtmlLexer, PhpLexer, **options) def analyse_text(text): rv = PhpLexer.analyse_text(text) - 0.01 if html_doctype_matches(text): rv += 0.5 return rv class XmlPhpLexer(DelegatingLexer): """ Subclass of `PhpLexer` that higlights unhandled data with the `XmlLexer`. """ name = 'XML+PHP' aliases = ['xml+php'] alias_filenames = ['*.xml', '*.php', '*.php[345]'] mimetypes = ['application/xml+php'] def __init__(self, **options): super(XmlPhpLexer, self).__init__(XmlLexer, PhpLexer, **options) def analyse_text(text): rv = PhpLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.4 return rv class CssPhpLexer(DelegatingLexer): """ Subclass of `PhpLexer` which highlights unmatched data with the `CssLexer`. """ name = 'CSS+PHP' aliases = ['css+php'] alias_filenames = ['*.css'] mimetypes = ['text/css+php'] def __init__(self, **options): super(CssPhpLexer, self).__init__(CssLexer, PhpLexer, **options) def analyse_text(text): return PhpLexer.analyse_text(text) - 0.05 class JavascriptPhpLexer(DelegatingLexer): """ Subclass of `PhpLexer` which highlights unmatched data with the `JavascriptLexer`. """ name = 'JavaScript+PHP' aliases = ['js+php', 'javascript+php'] alias_filenames = ['*.js'] mimetypes = ['application/x-javascript+php', 'text/x-javascript+php', 'text/javascript+php'] def __init__(self, **options): super(JavascriptPhpLexer, self).__init__(JavascriptLexer, PhpLexer, **options) def analyse_text(text): return PhpLexer.analyse_text(text) class HtmlSmartyLexer(DelegatingLexer): """ Subclass of the `SmartyLexer` that highighlights unlexed data with the `HtmlLexer`. Nested Javascript and CSS is highlighted too. """ name = 'HTML+Smarty' aliases = ['html+smarty'] alias_filenames = ['*.html', '*.htm', '*.xhtml', '*.tpl'] mimetypes = ['text/html+smarty'] def __init__(self, **options): super(HtmlSmartyLexer, self).__init__(HtmlLexer, SmartyLexer, **options) def analyse_text(text): rv = SmartyLexer.analyse_text(text) - 0.01 if html_doctype_matches(text): rv += 0.5 return rv class XmlSmartyLexer(DelegatingLexer): """ Subclass of the `SmartyLexer` that highlights unlexed data with the `XmlLexer`. """ name = 'XML+Smarty' aliases = ['xml+smarty'] alias_filenames = ['*.xml', '*.tpl'] mimetypes = ['application/xml+smarty'] def __init__(self, **options): super(XmlSmartyLexer, self).__init__(XmlLexer, SmartyLexer, **options) def analyse_text(text): rv = SmartyLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.4 return rv class CssSmartyLexer(DelegatingLexer): """ Subclass of the `SmartyLexer` that highlights unlexed data with the `CssLexer`. """ name = 'CSS+Smarty' aliases = ['css+smarty'] alias_filenames = ['*.css', '*.tpl'] mimetypes = ['text/css+smarty'] def __init__(self, **options): super(CssSmartyLexer, self).__init__(CssLexer, SmartyLexer, **options) def analyse_text(text): return SmartyLexer.analyse_text(text) - 0.05 class JavascriptSmartyLexer(DelegatingLexer): """ Subclass of the `SmartyLexer` that highlights unlexed data with the `JavascriptLexer`. """ name = 'JavaScript+Smarty' aliases = ['js+smarty', 'javascript+smarty'] alias_filenames = ['*.js', '*.tpl'] mimetypes = ['application/x-javascript+smarty', 'text/x-javascript+smarty', 'text/javascript+smarty'] def __init__(self, **options): super(JavascriptSmartyLexer, self).__init__(JavascriptLexer, SmartyLexer, **options) def analyse_text(text): return SmartyLexer.analyse_text(text) - 0.05 class HtmlDjangoLexer(DelegatingLexer): """ Subclass of the `DjangoLexer` that highighlights unlexed data with the `HtmlLexer`. Nested Javascript and CSS is highlighted too. """ name = 'HTML+Django/Jinja' aliases = ['html+django', 'html+jinja', 'htmldjango'] alias_filenames = ['*.html', '*.htm', '*.xhtml'] mimetypes = ['text/html+django', 'text/html+jinja'] def __init__(self, **options): super(HtmlDjangoLexer, self).__init__(HtmlLexer, DjangoLexer, **options) def analyse_text(text): rv = DjangoLexer.analyse_text(text) - 0.01 if html_doctype_matches(text): rv += 0.5 return rv class XmlDjangoLexer(DelegatingLexer): """ Subclass of the `DjangoLexer` that highlights unlexed data with the `XmlLexer`. """ name = 'XML+Django/Jinja' aliases = ['xml+django', 'xml+jinja'] alias_filenames = ['*.xml'] mimetypes = ['application/xml+django', 'application/xml+jinja'] def __init__(self, **options): super(XmlDjangoLexer, self).__init__(XmlLexer, DjangoLexer, **options) def analyse_text(text): rv = DjangoLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.4 return rv class CssDjangoLexer(DelegatingLexer): """ Subclass of the `DjangoLexer` that highlights unlexed data with the `CssLexer`. """ name = 'CSS+Django/Jinja' aliases = ['css+django', 'css+jinja'] alias_filenames = ['*.css'] mimetypes = ['text/css+django', 'text/css+jinja'] def __init__(self, **options): super(CssDjangoLexer, self).__init__(CssLexer, DjangoLexer, **options) def analyse_text(text): return DjangoLexer.analyse_text(text) - 0.05 class JavascriptDjangoLexer(DelegatingLexer): """ Subclass of the `DjangoLexer` that highlights unlexed data with the `JavascriptLexer`. """ name = 'JavaScript+Django/Jinja' aliases = ['js+django', 'javascript+django', 'js+jinja', 'javascript+jinja'] alias_filenames = ['*.js'] mimetypes = ['application/x-javascript+django', 'application/x-javascript+jinja', 'text/x-javascript+django', 'text/x-javascript+jinja', 'text/javascript+django', 'text/javascript+jinja'] def __init__(self, **options): super(JavascriptDjangoLexer, self).__init__(JavascriptLexer, DjangoLexer, **options) def analyse_text(text): return DjangoLexer.analyse_text(text) - 0.05 class JspRootLexer(RegexLexer): """ Base for the `JspLexer`. Yields `Token.Other` for area outside of JSP tags. .. versionadded:: 0.7 """ tokens = { 'root': [ (r'<%\S?', Keyword, 'sec'), # FIXME: I want to make these keywords but still parse attributes. (r'</?jsp:(forward|getProperty|include|plugin|setProperty|useBean).*?>', Keyword), (r'[^<]+', Other), (r'<', Other), ], 'sec': [ (r'%>', Keyword, '#pop'), # note: '\w\W' != '.' without DOTALL. (r'[\w\W]+?(?=%>|\Z)', using(JavaLexer)), ], } class JspLexer(DelegatingLexer): """ Lexer for Java Server Pages. .. versionadded:: 0.7 """ name = 'Java Server Page' aliases = ['jsp'] filenames = ['*.jsp'] mimetypes = ['application/x-jsp'] def __init__(self, **options): super(JspLexer, self).__init__(XmlLexer, JspRootLexer, **options) def analyse_text(text): rv = JavaLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.4 if '<%' in text and '%>' in text: rv += 0.1 return rv class EvoqueLexer(RegexLexer): """ For files using the Evoque templating system. .. versionadded:: 1.1 """ name = 'Evoque' aliases = ['evoque'] filenames = ['*.evoque'] mimetypes = ['application/x-evoque'] flags = re.DOTALL tokens = { 'root': [ (r'[^#$]+', Other), (r'#\[', Comment.Multiline, 'comment'), (r'\$\$', Other), # svn keywords (r'\$\w+:[^$\n]*\$', Comment.Multiline), # directives: begin, end (r'(\$)(begin|end)(\{(%)?)(.*?)((?(4)%)\})', bygroups(Punctuation, Name.Builtin, Punctuation, None, String, Punctuation)), # directives: evoque, overlay # see doc for handling first name arg: /directives/evoque/ #+ minor inconsistency: the "name" in e.g. $overlay{name=site_base} # should be using(PythonLexer), not passed out as String (r'(\$)(evoque|overlay)(\{(%)?)(\s*[#\w\-"\'.]+[^=,%}]+?)?' r'(.*?)((?(4)%)\})', bygroups(Punctuation, Name.Builtin, Punctuation, None, String, using(PythonLexer), Punctuation)), # directives: if, for, prefer, test (r'(\$)(\w+)(\{(%)?)(.*?)((?(4)%)\})', bygroups(Punctuation, Name.Builtin, Punctuation, None, using(PythonLexer), Punctuation)), # directive clauses (no {} expression) (r'(\$)(else|rof|fi)', bygroups(Punctuation, Name.Builtin)), # expressions (r'(\$\{(%)?)(.*?)((!)(.*?))?((?(2)%)\})', bygroups(Punctuation, None, using(PythonLexer), Name.Builtin, None, None, Punctuation)), (r'#', Other), ], 'comment': [ (r'[^\]#]', Comment.Multiline), (r'#\[', Comment.Multiline, '#push'), (r'\]#', Comment.Multiline, '#pop'), (r'[\]#]', Comment.Multiline) ], } class EvoqueHtmlLexer(DelegatingLexer): """ Subclass of the `EvoqueLexer` that highlights unlexed data with the `HtmlLexer`. .. versionadded:: 1.1 """ name = 'HTML+Evoque' aliases = ['html+evoque'] filenames = ['*.html'] mimetypes = ['text/html+evoque'] def __init__(self, **options): super(EvoqueHtmlLexer, self).__init__(HtmlLexer, EvoqueLexer, **options) class EvoqueXmlLexer(DelegatingLexer): """ Subclass of the `EvoqueLexer` that highlights unlexed data with the `XmlLexer`. .. versionadded:: 1.1 """ name = 'XML+Evoque' aliases = ['xml+evoque'] filenames = ['*.xml'] mimetypes = ['application/xml+evoque'] def __init__(self, **options): super(EvoqueXmlLexer, self).__init__(XmlLexer, EvoqueLexer, **options) class ColdfusionLexer(RegexLexer): """ Coldfusion statements """ name = 'cfstatement' aliases = ['cfs'] filenames = [] mimetypes = [] flags = re.IGNORECASE | re.MULTILINE tokens = { 'root': [ (r'//.*', Comment), (r'\+\+|--', Operator), (r'[-+*/^&=!]', Operator), (r'<=|>=|<|>', Operator), (r'mod\b', Operator), (r'(eq|lt|gt|lte|gte|not|is|and|or)\b', Operator), (r'\|\||&&', Operator), (r'"', String.Double, 'string'), # There is a special rule for allowing html in single quoted # strings, evidently. (r"'.*?'", String.Single), (r'\d+', Number), (r'(if|else|len|var|case|default|break|switch)\b', Keyword), (r'([A-Za-z_$][A-Za-z0-9_.]*)(\s*)(\()', bygroups(Name.Function, Text, Punctuation)), (r'[A-Za-z_$][A-Za-z0-9_.]*', Name.Variable), (r'[()\[\]{};:,.\\]', Punctuation), (r'\s+', Text), ], 'string': [ (r'""', String.Double), (r'#.+?#', String.Interp), (r'[^"#]+', String.Double), (r'#', String.Double), (r'"', String.Double, '#pop'), ], } class ColdfusionMarkupLexer(RegexLexer): """ Coldfusion markup only """ name = 'Coldfusion' aliases = ['cf'] filenames = [] mimetypes = [] tokens = { 'root': [ (r'[^<]+', Other), include('tags'), (r'<[^<>]*', Other), ], 'tags': [ (r'(?s)<!---.*?--->', Comment.Multiline), (r'(?s)<!--.*?-->', Comment), (r'<cfoutput.*?>', Name.Builtin, 'cfoutput'), (r'(?s)(<cfscript.*?>)(.+?)(</cfscript.*?>)', bygroups(Name.Builtin, using(ColdfusionLexer), Name.Builtin)), # negative lookbehind is for strings with embedded > (r'(?s)(</?cf(?:component|include|if|else|elseif|loop|return|' r'dbinfo|dump|abort|location|invoke|throw|file|savecontent|' r'mailpart|mail|header|content|zip|image|lock|argument|try|' r'catch|break|directory|http|set|function|param)\b)(.*?)((?<!\\)>)', bygroups(Name.Builtin, using(ColdfusionLexer), Name.Builtin)), ], 'cfoutput': [ (r'[^#<]+', Other), (r'(#)(.*?)(#)', bygroups(Punctuation, using(ColdfusionLexer), Punctuation)), #(r'<cfoutput.*?>', Name.Builtin, '#push'), (r'</cfoutput.*?>', Name.Builtin, '#pop'), include('tags'), (r'(?s)<[^<>]*', Other), (r'#', Other), ], } class ColdfusionHtmlLexer(DelegatingLexer): """ Coldfusion markup in html """ name = 'Coldfusion HTML' aliases = ['cfm'] filenames = ['*.cfm', '*.cfml', '*.cfc'] mimetypes = ['application/x-coldfusion'] def __init__(self, **options): super(ColdfusionHtmlLexer, self).__init__(HtmlLexer, ColdfusionMarkupLexer, **options) class SspLexer(DelegatingLexer): """ Lexer for Scalate Server Pages. .. versionadded:: 1.4 """ name = 'Scalate Server Page' aliases = ['ssp'] filenames = ['*.ssp'] mimetypes = ['application/x-ssp'] def __init__(self, **options): super(SspLexer, self).__init__(XmlLexer, JspRootLexer, **options) def analyse_text(text): rv = 0.0 if re.search('val \w+\s*:', text): rv += 0.6 if looks_like_xml(text): rv += 0.2 if '<%' in text and '%>' in text: rv += 0.1 return rv class TeaTemplateRootLexer(RegexLexer): """ Base for the `TeaTemplateLexer`. Yields `Token.Other` for area outside of code blocks. .. versionadded:: 1.5 """ tokens = { 'root': [ (r'<%\S?', Keyword, 'sec'), (r'[^<]+', Other), (r'<', Other), ], 'sec': [ (r'%>', Keyword, '#pop'), # note: '\w\W' != '.' without DOTALL. (r'[\w\W]+?(?=%>|\Z)', using(TeaLangLexer)), ], } class TeaTemplateLexer(DelegatingLexer): """ Lexer for `Tea Templates <http://teatrove.org/>`_. .. versionadded:: 1.5 """ name = 'Tea' aliases = ['tea'] filenames = ['*.tea'] mimetypes = ['text/x-tea'] def __init__(self, **options): super(TeaTemplateLexer, self).__init__(XmlLexer, TeaTemplateRootLexer, **options) def analyse_text(text): rv = TeaLangLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.4 if '<%' in text and '%>' in text: rv += 0.1 return rv class LassoHtmlLexer(DelegatingLexer): """ Subclass of the `LassoLexer` which highlights unhandled data with the `HtmlLexer`. Nested JavaScript and CSS is also highlighted. .. versionadded:: 1.6 """ name = 'HTML+Lasso' aliases = ['html+lasso'] alias_filenames = ['*.html', '*.htm', '*.xhtml', '*.lasso', '*.lasso[89]', '*.incl', '*.inc', '*.las'] mimetypes = ['text/html+lasso', 'application/x-httpd-lasso', 'application/x-httpd-lasso[89]'] def __init__(self, **options): super(LassoHtmlLexer, self).__init__(HtmlLexer, LassoLexer, **options) def analyse_text(text): rv = LassoLexer.analyse_text(text) - 0.01 if re.search(r'<\w+>', text, re.I): rv += 0.2 if html_doctype_matches(text): rv += 0.5 return rv class LassoXmlLexer(DelegatingLexer): """ Subclass of the `LassoLexer` which highlights unhandled data with the `XmlLexer`. .. versionadded:: 1.6 """ name = 'XML+Lasso' aliases = ['xml+lasso'] alias_filenames = ['*.xml', '*.lasso', '*.lasso[89]', '*.incl', '*.inc', '*.las'] mimetypes = ['application/xml+lasso'] def __init__(self, **options): super(LassoXmlLexer, self).__init__(XmlLexer, LassoLexer, **options) def analyse_text(text): rv = LassoLexer.analyse_text(text) - 0.01 if looks_like_xml(text): rv += 0.4 return rv class LassoCssLexer(DelegatingLexer): """ Subclass of the `LassoLexer` which highlights unhandled data with the `CssLexer`. .. versionadded:: 1.6 """ name = 'CSS+Lasso' aliases = ['css+lasso'] alias_filenames = ['*.css'] mimetypes = ['text/css+lasso'] def __init__(self, **options): options['requiredelimiters'] = True super(LassoCssLexer, self).__init__(CssLexer, LassoLexer, **options) def analyse_text(text): rv = LassoLexer.analyse_text(text) - 0.05 if re.search(r'\w+:.+?;', text): rv += 0.1 if 'padding:' in text: rv += 0.1 return rv class LassoJavascriptLexer(DelegatingLexer): """ Subclass of the `LassoLexer` which highlights unhandled data with the `JavascriptLexer`. .. versionadded:: 1.6 """ name = 'JavaScript+Lasso' aliases = ['js+lasso', 'javascript+lasso'] alias_filenames = ['*.js'] mimetypes = ['application/x-javascript+lasso', 'text/x-javascript+lasso', 'text/javascript+lasso'] def __init__(self, **options): options['requiredelimiters'] = True super(LassoJavascriptLexer, self).__init__(JavascriptLexer, LassoLexer, **options) def analyse_text(text): rv = LassoLexer.analyse_text(text) - 0.05 if 'function' in text: rv += 0.2 return rv
mit
dgladkov/django
django/db/models/signals.py
399
2734
from django.apps import apps from django.dispatch import Signal from django.utils import six class_prepared = Signal(providing_args=["class"]) class ModelSignal(Signal): """ Signal subclass that allows the sender to be lazily specified as a string of the `app_label.ModelName` form. """ def __init__(self, *args, **kwargs): super(ModelSignal, self).__init__(*args, **kwargs) self.unresolved_references = {} class_prepared.connect(self._resolve_references) def _resolve_references(self, sender, **kwargs): opts = sender._meta reference = (opts.app_label, opts.object_name) try: receivers = self.unresolved_references.pop(reference) except KeyError: pass else: for receiver, weak, dispatch_uid in receivers: super(ModelSignal, self).connect( receiver, sender=sender, weak=weak, dispatch_uid=dispatch_uid ) def connect(self, receiver, sender=None, weak=True, dispatch_uid=None): if isinstance(sender, six.string_types): try: app_label, model_name = sender.split('.') except ValueError: raise ValueError( "Specified sender must either be a model or a " "model name of the 'app_label.ModelName' form." ) try: sender = apps.get_registered_model(app_label, model_name) except LookupError: ref = (app_label, model_name) refs = self.unresolved_references.setdefault(ref, []) refs.append((receiver, weak, dispatch_uid)) return super(ModelSignal, self).connect( receiver, sender=sender, weak=weak, dispatch_uid=dispatch_uid ) pre_init = ModelSignal(providing_args=["instance", "args", "kwargs"], use_caching=True) post_init = ModelSignal(providing_args=["instance"], use_caching=True) pre_save = ModelSignal(providing_args=["instance", "raw", "using", "update_fields"], use_caching=True) post_save = ModelSignal(providing_args=["instance", "raw", "created", "using", "update_fields"], use_caching=True) pre_delete = ModelSignal(providing_args=["instance", "using"], use_caching=True) post_delete = ModelSignal(providing_args=["instance", "using"], use_caching=True) m2m_changed = ModelSignal( providing_args=["action", "instance", "reverse", "model", "pk_set", "using"], use_caching=True, ) pre_migrate = Signal(providing_args=["app_config", "verbosity", "interactive", "using"]) post_migrate = Signal(providing_args=["app_config", "verbosity", "interactive", "using"])
bsd-3-clause
DiptoDas8/Biponi
lib/python2.7/site-packages/django/template/backends/django.py
44
3018
# Since this package contains a "django" module, this is required on Python 2. from __future__ import absolute_import import warnings from django.conf import settings from django.template.context import Context, RequestContext, make_context from django.template.engine import Engine, _dirs_undefined from django.utils.deprecation import RemovedInDjango110Warning from .base import BaseEngine class DjangoTemplates(BaseEngine): app_dirname = 'templates' def __init__(self, params): params = params.copy() options = params.pop('OPTIONS').copy() options.setdefault('debug', settings.DEBUG) options.setdefault('file_charset', settings.FILE_CHARSET) super(DjangoTemplates, self).__init__(params) self.engine = Engine(self.dirs, self.app_dirs, **options) def from_string(self, template_code): return Template(self.engine.from_string(template_code)) def get_template(self, template_name, dirs=_dirs_undefined): return Template(self.engine.get_template(template_name, dirs)) class Template(object): def __init__(self, template): self.template = template @property def origin(self): # TODO: define the Origin API. For now simply forwarding to the # underlying Template preserves backwards-compatibility. return self.template.origin def render(self, context=None, request=None): # A deprecation path is required here to cover the following usage: # >>> from django.template import Context # >>> from django.template.loader import get_template # >>> template = get_template('hello.html') # >>> template.render(Context({'name': 'world'})) # In Django 1.7 get_template() returned a django.template.Template. # In Django 1.8 it returns a django.template.backends.django.Template. # In Django 1.10 the isinstance checks should be removed. If passing a # Context or a RequestContext works by accident, it won't be an issue # per se, but it won't be officially supported either. if isinstance(context, RequestContext): if request is not None and request is not context.request: raise ValueError( "render() was called with a RequestContext and a request " "argument which refer to different requests. Make sure " "that the context argument is a dict or at least that " "the two arguments refer to the same request.") warnings.warn( "render() must be called with a dict, not a RequestContext.", RemovedInDjango110Warning, stacklevel=2) elif isinstance(context, Context): warnings.warn( "render() must be called with a dict, not a Context.", RemovedInDjango110Warning, stacklevel=2) else: context = make_context(context, request) return self.template.render(context)
mit
ex1usive-m4d/TemplateDocx
controllers/phpdocx/lib/openoffice/openoffice.org/basis3.4/program/python-core-2.6.1/lib/encodings/__init__.py
60
5638
""" Standard "encodings" Package Standard Python encoding modules are stored in this package directory. Codec modules must have names corresponding to normalized encoding names as defined in the normalize_encoding() function below, e.g. 'utf-8' must be implemented by the module 'utf_8.py'. Each codec module must export the following interface: * getregentry() -> codecs.CodecInfo object The getregentry() API must a CodecInfo object with encoder, decoder, incrementalencoder, incrementaldecoder, streamwriter and streamreader atttributes which adhere to the Python Codec Interface Standard. In addition, a module may optionally also define the following APIs which are then used by the package's codec search function: * getaliases() -> sequence of encoding name strings to use as aliases Alias names returned by getaliases() must be normalized encoding names as defined by normalize_encoding(). Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """#" import codecs from encodings import aliases import __builtin__ _cache = {} _unknown = '--unknown--' _import_tail = ['*'] _norm_encoding_map = (' . ' '0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ ' ' abcdefghijklmnopqrstuvwxyz ' ' ' ' ' ' ') _aliases = aliases.aliases class CodecRegistryError(LookupError, SystemError): pass def normalize_encoding(encoding): """ Normalize an encoding name. Normalization works as follows: all non-alphanumeric characters except the dot used for Python package names are collapsed and replaced with a single underscore, e.g. ' -;#' becomes '_'. Leading and trailing underscores are removed. Note that encoding names should be ASCII only; if they do use non-ASCII characters, these must be Latin-1 compatible. """ # Make sure we have an 8-bit string, because .translate() works # differently for Unicode strings. if hasattr(__builtin__, "unicode") and isinstance(encoding, unicode): # Note that .encode('latin-1') does *not* use the codec # registry, so this call doesn't recurse. (See unicodeobject.c # PyUnicode_AsEncodedString() for details) encoding = encoding.encode('latin-1') return '_'.join(encoding.translate(_norm_encoding_map).split()) def search_function(encoding): # Cache lookup entry = _cache.get(encoding, _unknown) if entry is not _unknown: return entry # Import the module: # # First try to find an alias for the normalized encoding # name and lookup the module using the aliased name, then try to # lookup the module using the standard import scheme, i.e. first # try in the encodings package, then at top-level. # norm_encoding = normalize_encoding(encoding) aliased_encoding = _aliases.get(norm_encoding) or \ _aliases.get(norm_encoding.replace('.', '_')) if aliased_encoding is not None: modnames = [aliased_encoding, norm_encoding] else: modnames = [norm_encoding] for modname in modnames: if not modname or '.' in modname: continue try: # Import is absolute to prevent the possibly malicious import of a # module with side-effects that is not in the 'encodings' package. mod = __import__('encodings.' + modname, fromlist=_import_tail, level=0) except ImportError: pass else: break else: mod = None try: getregentry = mod.getregentry except AttributeError: # Not a codec module mod = None if mod is None: # Cache misses _cache[encoding] = None return None # Now ask the module for the registry entry entry = getregentry() if not isinstance(entry, codecs.CodecInfo): if not 4 <= len(entry) <= 7: raise CodecRegistryError,\ 'module "%s" (%s) failed to register' % \ (mod.__name__, mod.__file__) if not callable(entry[0]) or \ not callable(entry[1]) or \ (entry[2] is not None and not callable(entry[2])) or \ (entry[3] is not None and not callable(entry[3])) or \ (len(entry) > 4 and entry[4] is not None and not callable(entry[4])) or \ (len(entry) > 5 and entry[5] is not None and not callable(entry[5])): raise CodecRegistryError,\ 'incompatible codecs in module "%s" (%s)' % \ (mod.__name__, mod.__file__) if len(entry)<7 or entry[6] is None: entry += (None,)*(6-len(entry)) + (mod.__name__.split(".", 1)[1],) entry = codecs.CodecInfo(*entry) # Cache the codec registry entry _cache[encoding] = entry # Register its aliases (without overwriting previously registered # aliases) try: codecaliases = mod.getaliases() except AttributeError: pass else: for alias in codecaliases: if not _aliases.has_key(alias): _aliases[alias] = modname # Return the registry entry return entry # Register the search_function in the Python codec registry codecs.register(search_function)
bsd-3-clause
0k/OpenUpgrade
addons/purchase_double_validation/__init__.py
441
1090
# -*- 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 purchase_double_validation_installer # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
LuckDragon82/demo
boilerplate/external/babel/tests/core.py
61
1726
# -*- coding: utf-8 -*- # # Copyright (C) 2007 Edgewall Software # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. The terms # are also available at http://babel.edgewall.org/wiki/License. # # This software consists of voluntary contributions made by many # individuals. For the exact contribution history, see the revision # history and logs, available at http://babel.edgewall.org/log/. import doctest import os import unittest from babel import core from babel.core import default_locale class DefaultLocaleTest(unittest.TestCase): def setUp(self): self._old_locale_settings = self._current_locale_settings() def tearDown(self): self._set_locale_settings(self._old_locale_settings) def _current_locale_settings(self): settings = {} for name in ('LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LANG'): settings[name] = os.environ[name] return settings def _set_locale_settings(self, settings): for name, value in settings.items(): os.environ[name] = value def test_ignore_invalid_locales_in_lc_ctype(self): # This is a regression test specifically for a bad LC_CTYPE setting on # MacOS X 10.6 (#200) os.environ['LC_CTYPE'] = 'UTF-8' # must not throw an exception default_locale('LC_CTYPE') def suite(): suite = unittest.TestSuite() suite.addTest(doctest.DocTestSuite(core)) suite.addTest(unittest.makeSuite(DefaultLocaleTest)) return suite if __name__ == '__main__': unittest.main(defaultTest='suite')
lgpl-3.0
lnielsen/invenio
invenio/legacy/pdfchecker/arxiv.py
3
16346
# -*- coding: utf-8 -*- ## ## This file is part of Invenio. ## Copyright (C) 2011 CERN. ## ## Invenio is free software; you can redistribute it and/or ## modify it under the terms of the GNU General Public License as ## published by the Free Software Foundation; either version 2 of the ## License, or (at your option) any later version. ## ## Invenio is distributed in the hope that it will be useful, but ## WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ## General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Invenio; if not, write to the Free Software Foundation, Inc., ## 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """ ArXiv Pdf Checker Task Checks arxiv records for missing pdfs and downloads them from arXiv """ import os import time import re from datetime import datetime from tempfile import NamedTemporaryFile from xml.dom import minidom import socket from invenio.legacy.bibdocfile.cli import bibupload_ffts from invenio.legacy.docextract.task import store_last_updated, \ fetch_last_updated from invenio.utils.shell import split_cli_ids_arg from invenio.legacy.dbquery import run_sql from invenio.legacy.bibsched.bibtask import task_low_level_submission from invenio.legacy.refextract.api import record_has_fulltext, \ check_record_for_refextract from invenio.legacy.bibsched.bibtask import task_init, \ write_message, \ task_update_progress, \ task_get_option, \ task_set_option, \ task_sleep_now_if_required from invenio.legacy.bibrecord import get_fieldvalues from invenio.config import CFG_VERSION, \ CFG_TMPSHAREDDIR, \ CFG_TMPDIR, \ CFG_ARXIV_URL_PATTERN # Help message is the usage() print out of how to use Refextract from invenio.legacy.docextract.record import get_record from invenio.legacy.bibdocfile.api import BibRecDocs, \ calculate_md5 from invenio.legacy.oaiharvest import utils as oai_harvest_daemon from invenio.utils.filedownload import (download_external_url, InvenioFileDownloadError) NAME = 'arxiv-pdf-checker' ARXIV_VERSION_PATTERN = re.compile(ur'v\d$', re.UNICODE) STATUS_OK = 'ok' STATUS_MISSING = 'missing' class PdfNotAvailable(Exception): pass class FoundExistingPdf(Exception): pass class AlreadyHarvested(Exception): def __init__(self, status): Exception.__init__(self) self.status = status def build_arxiv_url(arxiv_id, version): return CFG_ARXIV_URL_PATTERN % (arxiv_id, version) def extract_arxiv_ids_from_recid(recid): """Extract arxiv # for given recid We get them from the record which has this format: 037__ $9arXiv$arXiv:1010.1111 """ record = get_record(recid) for report_number_field in record.get('037', []): try: source = report_number_field.get_subfield_values('9')[0] except IndexError: continue else: if source != 'arXiv': continue try: report_number = report_number_field.get_subfield_values('a')[0] except IndexError: continue else: # Extract arxiv id if report_number.startswith('arXiv'): report_number = report_number.split(':')[1] if ARXIV_VERSION_PATTERN.search(report_number): report_number = report_number[:-2] yield report_number def cb_parse_option(key, value, opts, args): """Parse command line options""" if args: # There should be no standalone arguments raise StandardError("Error: Unrecognised argument '%s'." % args[0]) if key in ('-i', '--id'): recids = task_get_option('recids') if not recids: recids = set() task_set_option('recids', recids) recids.update(split_cli_ids_arg(value)) return True def store_arxiv_pdf_status(recid, status, version): """Store pdf harvesting status in the database""" valid_status = (STATUS_OK, STATUS_MISSING) if status not in valid_status: raise ValueError('invalid status %s' % status) now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") run_sql("""REPLACE INTO bibARXIVPDF (id_bibrec, status, date_harvested, version) VALUES (%s, %s, %s, %s)""", (recid, status, now, version)) def fetch_arxiv_pdf_status(recid): """Fetch from the database the harvest status of given recid""" ret = run_sql("""SELECT status, version FROM bibARXIVPDF WHERE id_bibrec = %s""", [recid]) return ret and ret[0] or (None, None) def download_one(recid, version): """Download given version of the PDF from arxiv""" write_message('fetching %s' % recid) for count, arxiv_id in enumerate(extract_arxiv_ids_from_recid(recid)): if count != 0: write_message("Warning: %s has multiple arxiv #" % recid) continue url_for_pdf = build_arxiv_url(arxiv_id, version) filename_arxiv_id = arxiv_id.replace('/', '_') temp_file = NamedTemporaryFile(prefix="arxiv-pdf-checker", dir=CFG_TMPSHAREDDIR, suffix="%s.pdf" % filename_arxiv_id) write_message('downloading pdf from %s' % url_for_pdf) path = download_external_url(url_for_pdf, temp_file.name, content_type='pdf') # Check if it is not an html not found page filesize = os.path.getsize(path) if filesize < 25000: f = open(path) try: for line in f: if 'PDF unavailable' in line: raise PdfNotAvailable() finally: f.close() docs = BibRecDocs(recid) bibdocfiles = docs.list_latest_files(doctype="arXiv") needs_update = False try: bibdocfile = bibdocfiles[0] except IndexError: bibdocfile = None needs_update = True else: existing_md5 = calculate_md5(bibdocfile.fullpath) new_md5 = calculate_md5(path.encode('utf-8')) if new_md5 != existing_md5: write_message('md5 differs updating') needs_update = True else: write_message('md5 matches existing pdf, skipping') if needs_update: if bibdocfiles: write_message('adding as new version') docs.add_new_version(path, docname=bibdocfile.name) else: write_message('adding as new file') docs.add_new_file(path, doctype="arXiv", docname="arXiv:%s" % filename_arxiv_id) else: raise FoundExistingPdf() def oai_harvest_query(arxiv_id, prefix='arXivRaw', verb='GetRecord', max_retries=5, repositories=[]): """Wrapper of oai_harvest_daemon.oai_harvest_get that handles retries""" if not len(repositories): from invenio.modules.oaiharvester.models import OaiHARVEST repository = OaiHARVEST.query.filter( OaiHARVEST.name == 'arxiv' ).first().todict() else: repository = repositories[0] harvestpath = os.path.join(CFG_TMPDIR, "arxiv-pdf-checker-oai-") def get(): return oai_harvest_daemon.oai_harvest_get( prefix=prefix, baseurl=repository['baseurl'], harvestpath=harvestpath, verb=verb, identifier='oai:arXiv.org:%s' % arxiv_id) responses = None for retry_count in range(1, max_retries + 1): try: responses = get() except (socket.timeout, socket.error): write_message('socket error, arxiv is down?') else: if not responses: write_message('no responses from oai server') break if retry_count <= 2: write_message('sleeping for 10s') time.sleep(10) else: write_message('sleeping for 30 minutes') time.sleep(1800) if responses is None: raise Exception('arXiv is down') return responses def fetch_arxiv_version(recid): """Query arxiv and extract the version of the pdf from the response""" for count, arxiv_id in enumerate(extract_arxiv_ids_from_recid(recid)): if count != 0: write_message("Warning: %s has multiple arxiv #" % recid) continue responses = oai_harvest_query(arxiv_id) if not responses: return None # The response is roughly in this format # <OAI-PMH> # <GetRecord> # <metadata> # <version version="v1"> # <date>Mon, 15 Apr 2013 19:33:21 GMT</date> # <size>609kb</size> # <source_type>D</source_type> # <version version="v2"> # <date>Mon, 25 Apr 2013 19:33:21 GMT</date> # <size>620kb</size> # <source_type>D</source_type> # </version> # </<metadata> # </<GetRecord> # </<OAI-PMH> # We pass one arxiv id, we are assuming a single response file tree = minidom.parse(responses[0]) version_tags = tree.getElementsByTagName('version') if version_tags: version = version_tags[-1].getAttribute('version') else: version = 'v1' # We have to remove the responses files manually # For some written the response is written to disk instead of # being a string for file_path in responses: os.unlink(file_path) return int(version[1:]) def process_one(recid): """Checks given recid for updated pdfs on arxiv""" write_message('checking %s' % recid) # Last version we have harvested harvest_status, harvest_version = fetch_arxiv_pdf_status(recid) # Fetch arxiv version arxiv_version = fetch_arxiv_version(recid) if not arxiv_version: msg = 'version information unavailable' write_message(msg) raise PdfNotAvailable(msg) write_message('harvested_version %s' % harvest_version) write_message('arxiv_version %s' % arxiv_version) if record_has_fulltext(recid) and harvest_version == arxiv_version: write_message('our version matches arxiv') raise AlreadyHarvested(status=harvest_status) # We already tried to harvest this record but failed if harvest_status == STATUS_MISSING and harvest_version == arxiv_version: raise PdfNotAvailable() updated = False try: download_one(recid, arxiv_version) except PdfNotAvailable: store_arxiv_pdf_status(recid, STATUS_MISSING, arxiv_version) raise except FoundExistingPdf: store_arxiv_pdf_status(recid, STATUS_OK, arxiv_version) raise else: store_arxiv_pdf_status(recid, STATUS_OK, arxiv_version) updated = True return updated def submit_fixmarc_task(recids): """Submit a task that synchronizes the 8564 tags This should be done right after changing the files attached to a record""" field = [{'doctype' : 'FIX-MARC'}] ffts = {} for recid in recids: ffts[recid] = field bibupload_ffts(ffts, append=False, interactive=False) def submit_refextract_task(recids): """Submit a refextract task if needed""" # First filter out recids we cannot safely extract references from # (mostly because they have been curated) recids = [recid for recid in recids if check_record_for_refextract(recid)] if recids: recids_str = ','.join(str(recid) for recid in recids) task_low_level_submission('refextract', NAME, '-i', recids_str) def fetch_updated_arxiv_records(date): """Fetch all the arxiv records modified since the last run""" def check_arxiv(recid): """Returns True for arxiv papers""" for report_number in get_fieldvalues(recid, '037__9'): if report_number == 'arXiv': return True return False # Fetch all records inserted since last run sql = "SELECT `id`, `modification_date` FROM `bibrec` " \ "WHERE `modification_date` >= %s " \ "ORDER BY `modification_date`" records = run_sql(sql, [date.isoformat()]) records = [(r, mod_date) for r, mod_date in records if check_arxiv(r)] # Show all records for debugging purposes if task_get_option('verbose') >= 9: write_message('recids:', verbose=9) for recid, mod_date in records: write_message("* %s, %s" % (recid, mod_date), verbose=9) task_update_progress("Done fetching %s arxiv record ids" % len(records)) return records def task_run_core(name=NAME): """Entry point for the arxiv-pdf-checker task""" # First gather recids to process recids = task_get_option('recids') if recids: start_date = None recids = [(recid, None) for recid in recids] else: start_date = datetime.now() dummy, last_date = fetch_last_updated(name) recids = fetch_updated_arxiv_records(last_date) updated_recids = set() try: for count, (recid, dummy) in enumerate(recids): if count % 50 == 0: msg = 'Done %s of %s' % (count, len(recids)) write_message(msg) task_update_progress(msg) # BibTask sleep task_sleep_now_if_required(can_stop_too=True) write_message('processing %s' % recid, verbose=9) try: if process_one(recid): updated_recids.add(recid) time.sleep(6) except AlreadyHarvested: write_message('already harvested successfully') time.sleep(6) except FoundExistingPdf: write_message('pdf already attached (matching md5)') time.sleep(6) except PdfNotAvailable: write_message("no pdf available") time.sleep(20) except InvenioFileDownloadError, e: write_message("failed to download: %s" % e) time.sleep(20) finally: # We want to process updated records even in case we are interrupted msg = 'Updated %s records' % len(updated_recids) write_message(msg) task_update_progress(msg) write_message(repr(updated_recids)) # For all updated records, we want to sync the 8564 tags # and reextract references if updated_recids: submit_fixmarc_task(updated_recids) submit_refextract_task(updated_recids) # Store last run date of the daemon # not if it ran on specific recids from the command line with --id # but only if it ran on the modified records if start_date: store_last_updated(0, start_date, name) return True def main(): """Constructs the refextract bibtask.""" # Build and submit the task task_init(authorization_action='runarxivpdfchecker', authorization_msg="Arxiv Pdf Checker Task Submission", description="""Daemon that checks if we have the latest version of arxiv PDFs""", # get the global help_message variable imported from refextract.py help_specific_usage=""" Scheduled (daemon) options: -i, --id Record id to check. Examples: (run a daemon job) arxiv-pdf-checker """, version="Invenio v%s" % CFG_VERSION, specific_params=("i:", ["id="]), task_submit_elaborate_specific_parameter_fnc=cb_parse_option, task_run_fnc=task_run_core)
gpl-2.0
Red-M/CloudBot-legacy
util/http.py
7
3042
# convenience wrapper for urllib2 & friends import cookielib import json import urllib import urllib2 import urlparse from urllib import quote, quote_plus as _quote_plus from lxml import etree, html from bs4 import BeautifulSoup # used in plugins that import this from urllib2 import URLError, HTTPError ua_cloudbot = 'Cloudbot/DEV http://github.com/CloudDev/CloudBot' ua_firefox = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:17.0) Gecko/17.0' \ ' Firefox/17.0' ua_old_firefox = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; ' \ 'rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6' ua_internetexplorer = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' ua_chrome = 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.4 (KHTML, ' \ 'like Gecko) Chrome/22.0.1229.79 Safari/537.4' jar = cookielib.CookieJar() def get(*args, **kwargs): return open(*args, **kwargs).read() def get_url(*args, **kwargs): return open(*args, **kwargs).geturl() def get_html(*args, **kwargs): return html.fromstring(get(*args, **kwargs)) def get_soup(*args, **kwargs): return BeautifulSoup(get(*args, **kwargs), 'lxml') def get_xml(*args, **kwargs): return etree.fromstring(get(*args, **kwargs)) def get_json(*args, **kwargs): return json.loads(get(*args, **kwargs)) def open(url, query_params=None, user_agent=None, post_data=None, referer=None, get_method=None, cookies=False, timeout=None, headers=None, **kwargs): if query_params is None: query_params = {} if user_agent is None: user_agent = ua_cloudbot query_params.update(kwargs) url = prepare_url(url, query_params) request = urllib2.Request(url, post_data) if get_method is not None: request.get_method = lambda: get_method if headers is not None: for header_key, header_value in headers.iteritems(): request.add_header(header_key, header_value) request.add_header('User-Agent', user_agent) if referer is not None: request.add_header('Referer', referer) if cookies: opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar)) else: opener = urllib2.build_opener() if timeout: return opener.open(request, timeout=timeout) else: return opener.open(request) def prepare_url(url, queries): if queries: scheme, netloc, path, query, fragment = urlparse.urlsplit(url) query = dict(urlparse.parse_qsl(query)) query.update(queries) query = urllib.urlencode(dict((to_utf8(key), to_utf8(value)) for key, value in query.iteritems())) url = urlparse.urlunsplit((scheme, netloc, path, query, fragment)) return url def to_utf8(s): if isinstance(s, unicode): return s.encode('utf8', 'ignore') else: return str(s) def quote_plus(s): return _quote_plus(to_utf8(s)) def unescape(s): if not s.strip(): return s return html.fromstring(s).text_content()
gpl-3.0
dennisobrien/bokeh
examples/embed/autoload_static.py
5
2050
from jinja2 import Template from tornado.ioloop import IOLoop from tornado.web import Application, RequestHandler from bokeh.embed import autoload_static from bokeh.plotting import figure from bokeh.resources import CDN from bokeh.sampledata.iris import flowers from bokeh.util.browser import view template = Template(""" <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> </head> <body> <div> The plot embedded below is a standalone plot that was embedded using <fixed>autoload_static</fixed>. For more information see the <a target="_blank" href="https://bokeh.pydata.org/en/latest/docs/user_guide/embed.html#static-data"> documentation</a>. </div> {{ script|safe }} </body> </html> """) class IndexHandler(RequestHandler): def initialize(self, script): self.script = script def get(self): self.write(template.render(script=self.script)) # Normally, you might save the .js files to some location on disk, and serve # them from there. Here we us this request handler, just to make the example # completely self-contained. class JSHandler(RequestHandler): def initialize(self, js): self.js = js def get(self): self.write(self.js) def make_plot(): colormap = {'setosa': 'red', 'versicolor': 'green', 'virginica': 'blue'} colors = [colormap[x] for x in flowers['species']] p = figure(title = "Iris Morphology") p.xaxis.axis_label = 'Petal Length' p.yaxis.axis_label = 'Petal Width' p.circle(flowers["petal_length"], flowers["petal_width"], color=colors, fill_alpha=0.2, size=10) return p if __name__ == '__main__': print('Opening Tornado app with embedded Bokeh plot on http://localhost:8080/') js, script = autoload_static(make_plot(), CDN, "embed.js") app = Application([ (r"/", IndexHandler, dict(script=script)), (r"/embed.js", JSHandler, dict(js=js)) ]) app.listen(8080) io_loop = IOLoop.current() io_loop.add_callback(view, "http://localhost:8080/") io_loop.start()
bsd-3-clause
aaxelb/SHARE
share/harvesters/org_elife.py
3
3365
import time import logging import requests from django.conf import settings from furl import furl from lxml import etree from share.harvest import BaseHarvester logger = logging.getLogger(__name__) class ELifeHarvester(BaseHarvester): VERSION = 1 BASE_DATA_URL = 'https://raw.githubusercontent.com/elifesciences/elife-article-xml/master/{}' BASE_URL = 'https://api.github.com/repos/elifesciences/elife-article-xml/commits{}' def request(self, *args, **kwargs): if settings.GITHUB_API_KEY: kwargs.setdefault('headers', {})['Authorization'] = 'token {}'.format(settings.GITHUB_API_KEY) while True: response = self.requests.get(*args, **kwargs) if int(response.headers.get('X-RateLimit-Remaining', 0)) == 0: reset = int(response.headers.get('X-RateLimit-Reset', time.time())) - time.time() logger.warning('Hit GitHub ratelimit sleeping for %s seconds', reset) time.sleep(reset) if response.status_code != 403: response.raise_for_status() return response def do_harvest(self, start_date, end_date): end_date = end_date.date() start_date = start_date.date() logger.info("The data for each record must be requested individually - this may take a while... ") for sha in self.fetch_commits(start_date, end_date): for file_name in self.fetch_file_names(sha): if not file_name.endswith('.xml'): continue record = self.fetch_xml(file_name) if record is not None: continue doc = etree.tostring(record) doc_id = record.xpath('//article-id[@*]')[0].text yield (doc_id, doc) def fetch_commits(self, start_date, end_date): page = -1 url = self.BASE_URL.format('?') while True: page += 1 response = self.request(furl(url).set(query_params={ 'since': start_date.isoformat(), 'until': end_date.isoformat(), 'page': page, 'per_page': 100 }).url) commits = response.json() for commit in commits: if commit.get('sha'): yield commit['sha'] if len(commits) != 100: break def fetch_file_names(self, sha): page = -1 url = self.BASE_URL.format('/{}'.format(sha)) while True: page += 1 response = self.request(furl(url).set(query_params={ 'page': page, 'per_page': 100 })) files = response.json()['files'] for f in files: yield f['filename'] if len(files) != 100: break def fetch_xml(self, file_name): file_url = furl(self.BASE_DATA_URL.format(file_name)) # Not using self.requests when getting the file contents because the eLife rate limit (1, 60) does not apply resp = requests.get(file_url.url) if resp.status_code == 404: logger.warning('Could not download file %s', file_name) return None resp.raise_for_status() xml = etree.XML(resp.content) return xml
apache-2.0
angryrancor/kivy
examples/audio/main.py
40
2207
''' Audio example ============= This example plays sounds of different formats. You should see a grid of buttons labelled with filenames. Clicking on the buttons will play, or restart, each sound. Not all sound formats will play on all platforms. All the sounds are from the http://woolyss.com/chipmusic-samples.php "THE FREESOUND PROJECT", Under Creative Commons Sampling Plus 1.0 License. ''' import kivy kivy.require('1.0.8') from kivy.app import App from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.core.audio import SoundLoader from kivy.properties import StringProperty, ObjectProperty, NumericProperty from glob import glob from os.path import dirname, join, basename class AudioButton(Button): filename = StringProperty(None) sound = ObjectProperty(None, allownone=True) volume = NumericProperty(1.0) def on_press(self): if self.sound is None: self.sound = SoundLoader.load(self.filename) # stop the sound if it's currently playing if self.sound.status != 'stop': self.sound.stop() self.sound.volume = self.volume self.sound.play() def release_audio(self): if self.sound: self.sound.stop() self.sound.unload() self.sound = None def set_volume(self, volume): self.volume = volume if self.sound: self.sound.volume = volume class AudioBackground(BoxLayout): pass class AudioApp(App): def build(self): root = AudioBackground(spacing=5) for fn in glob(join(dirname(__file__), '*.wav')): btn = AudioButton( text=basename(fn[:-4]).replace('_', ' '), filename=fn, size_hint=(None, None), halign='center', size=(128, 128), text_size=(118, None)) root.ids.sl.add_widget(btn) return root def release_audio(self): for audiobutton in self.root.ids.sl.children: audiobutton.release_audio() def set_volume(self, value): for audiobutton in self.root.ids.sl.children: audiobutton.set_volume(value) if __name__ == '__main__': AudioApp().run()
mit
lattwood/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/layout_tests/servers/http_server.py
121
10730
# Copyright (C) 2011 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. """A class to help start/stop the lighttpd server used by layout tests.""" import logging import os import time from webkitpy.layout_tests.servers import http_server_base _log = logging.getLogger(__name__) class Lighttpd(http_server_base.HttpServerBase): def __init__(self, port_obj, output_dir, background=False, port=None, root=None, run_background=None, additional_dirs=None, layout_tests_dir=None, number_of_servers=None): """Args: output_dir: the absolute path to the layout test result directory """ # Webkit tests http_server_base.HttpServerBase.__init__(self, port_obj, number_of_servers) self._name = 'lighttpd' self._output_dir = output_dir self._port = port self._root = root self._run_background = run_background self._additional_dirs = additional_dirs self._layout_tests_dir = layout_tests_dir self._pid_file = self._filesystem.join(self._runtime_path, '%s.pid' % self._name) if self._port: self._port = int(self._port) if not self._layout_tests_dir: self._layout_tests_dir = self._port_obj.layout_tests_dir() self._webkit_tests = os.path.join(self._layout_tests_dir, 'http', 'tests') self._js_test_resource = os.path.join(self._layout_tests_dir, 'fast', 'js', 'resources') self._media_resource = os.path.join(self._layout_tests_dir, 'media') # Self generated certificate for SSL server (for client cert get # <base-path>\chrome\test\data\ssl\certs\root_ca_cert.crt) self._pem_file = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'httpd2.pem') # One mapping where we can get to everything self.VIRTUALCONFIG = [] if self._webkit_tests: self.VIRTUALCONFIG.extend( # Three mappings (one with SSL) for LayoutTests http tests [{'port': 8000, 'docroot': self._webkit_tests}, {'port': 8080, 'docroot': self._webkit_tests}, {'port': 8443, 'docroot': self._webkit_tests, 'sslcert': self._pem_file}]) def _prepare_config(self): base_conf_file = self._port_obj.path_from_webkit_base('Tools', 'Scripts', 'webkitpy', 'layout_tests', 'servers', 'lighttpd.conf') out_conf_file = os.path.join(self._output_dir, 'lighttpd.conf') time_str = time.strftime("%d%b%Y-%H%M%S") access_file_name = "access.log-" + time_str + ".txt" access_log = os.path.join(self._output_dir, access_file_name) log_file_name = "error.log-" + time_str + ".txt" error_log = os.path.join(self._output_dir, log_file_name) # Write out the config base_conf = self._filesystem.read_text_file(base_conf_file) # FIXME: This should be re-worked so that this block can # use with open() instead of a manual file.close() call. f = self._filesystem.open_text_file_for_writing(out_conf_file) f.write(base_conf) # Write out our cgi handlers. Run perl through env so that it # processes the #! line and runs perl with the proper command # line arguments. Emulate apache's mod_asis with a cat cgi handler. f.write(('cgi.assign = ( ".cgi" => "/usr/bin/env",\n' ' ".pl" => "/usr/bin/env",\n' ' ".asis" => "/bin/cat",\n' ' ".php" => "%s" )\n\n') % self._port_obj._path_to_lighttpd_php()) # Setup log files f.write(('server.errorlog = "%s"\n' 'accesslog.filename = "%s"\n\n') % (error_log, access_log)) # Setup upload folders. Upload folder is to hold temporary upload files # and also POST data. This is used to support XHR layout tests that # does POST. f.write(('server.upload-dirs = ( "%s" )\n\n') % (self._output_dir)) # Setup a link to where the js test templates are stored f.write(('alias.url = ( "/js-test-resources" => "%s" )\n\n') % (self._js_test_resource)) if self._additional_dirs: for alias, path in self._additional_dirs.iteritems(): f.write(('alias.url += ( "%s" => "%s" )\n\n') % (alias, path)) # Setup a link to where the media resources are stored. f.write(('alias.url += ( "/media-resources" => "%s" )\n\n') % (self._media_resource)) # dump out of virtual host config at the bottom. if self._root: if self._port: # Have both port and root dir. mappings = [{'port': self._port, 'docroot': self._root}] else: # Have only a root dir - set the ports as for LayoutTests. # This is used in ui_tests to run http tests against a browser. # default set of ports as for LayoutTests but with a # specified root. mappings = [{'port': 8000, 'docroot': self._root}, {'port': 8080, 'docroot': self._root}, {'port': 8443, 'docroot': self._root, 'sslcert': self._pem_file}] else: mappings = self.VIRTUALCONFIG for mapping in mappings: ssl_setup = '' if 'sslcert' in mapping: ssl_setup = (' ssl.engine = "enable"\n' ' ssl.pemfile = "%s"\n' % mapping['sslcert']) f.write(('$SERVER["socket"] == "127.0.0.1:%d" {\n' ' server.document-root = "%s"\n' + ssl_setup + '}\n\n') % (mapping['port'], mapping['docroot'])) f.close() executable = self._port_obj._path_to_lighttpd() module_path = self._port_obj._path_to_lighttpd_modules() start_cmd = [executable, # Newly written config file '-f', os.path.join(self._output_dir, 'lighttpd.conf'), # Where it can find its module dynamic libraries '-m', module_path] if not self._run_background: start_cmd.append(# Don't background '-D') # Copy liblightcomp.dylib to /tmp/lighttpd/lib to work around the # bug that mod_alias.so loads it from the hard coded path. if self._port_obj.host.platform.is_mac(): tmp_module_path = '/tmp/lighttpd/lib' if not self._filesystem.exists(tmp_module_path): self._filesystem.maybe_make_directory(tmp_module_path) lib_file = 'liblightcomp.dylib' self._filesystem.copyfile(self._filesystem.join(module_path, lib_file), self._filesystem.join(tmp_module_path, lib_file)) self._start_cmd = start_cmd self._env = self._port_obj.setup_environ_for_server('lighttpd') self._mappings = mappings def _remove_stale_logs(self): # Sometimes logs are open in other processes but they should clear eventually. for log_prefix in ('access.log-', 'error.log-'): try: self._remove_log_files(self._output_dir, log_prefix) except OSError, e: _log.warning('Failed to remove old %s %s files' % (self._name, log_prefix)) def _spawn_process(self): _log.debug('Starting %s server, cmd="%s"' % (self._name, self._start_cmd)) process = self._executive.popen(self._start_cmd, env=self._env, shell=False, stderr=self._executive.PIPE) pid = process.pid self._filesystem.write_text_file(self._pid_file, str(pid)) return pid def _stop_running_server(self): # FIXME: It would be nice if we had a cleaner way of killing this process. # Currently we throw away the process object created in _spawn_process, # since there doesn't appear to be any way to kill the server any more # cleanly using it than just killing the pid, and we need to support # killing a pid directly anyway for run-webkit-httpd and run-webkit-websocketserver. self._wait_for_action(self._check_and_kill) if self._filesystem.exists(self._pid_file): self._filesystem.remove(self._pid_file) def _check_and_kill(self): if self._executive.check_running_pid(self._pid): host = self._port_obj.host if host.platform.is_win() and not host.platform.is_cygwin(): # FIXME: https://bugs.webkit.org/show_bug.cgi?id=106838 # We need to kill all of the child processes as well as the # parent, so we can't use executive.kill_process(). # # If this is actually working, we should figure out a clean API. self._executive.run_command(["taskkill.exe", "/f", "/t", "/pid", self._pid], error_handler=self._executive.ignore_error) else: self._executive.kill_process(self._pid) return False return True
bsd-3-clause
jiangzhuo/kbengine
kbe/res/scripts/common/Lib/test/test_email/test_utils.py
87
5422
import datetime from email import utils import test.support import time import unittest import sys import os.path class DateTimeTests(unittest.TestCase): datestring = 'Sun, 23 Sep 2001 20:10:55' dateargs = (2001, 9, 23, 20, 10, 55) offsetstring = ' -0700' utcoffset = datetime.timedelta(hours=-7) tz = datetime.timezone(utcoffset) naive_dt = datetime.datetime(*dateargs) aware_dt = datetime.datetime(*dateargs, tzinfo=tz) def test_naive_datetime(self): self.assertEqual(utils.format_datetime(self.naive_dt), self.datestring + ' -0000') def test_aware_datetime(self): self.assertEqual(utils.format_datetime(self.aware_dt), self.datestring + self.offsetstring) def test_usegmt(self): utc_dt = datetime.datetime(*self.dateargs, tzinfo=datetime.timezone.utc) self.assertEqual(utils.format_datetime(utc_dt, usegmt=True), self.datestring + ' GMT') def test_usegmt_with_naive_datetime_raises(self): with self.assertRaises(ValueError): utils.format_datetime(self.naive_dt, usegmt=True) def test_usegmt_with_non_utc_datetime_raises(self): with self.assertRaises(ValueError): utils.format_datetime(self.aware_dt, usegmt=True) def test_parsedate_to_datetime(self): self.assertEqual( utils.parsedate_to_datetime(self.datestring + self.offsetstring), self.aware_dt) def test_parsedate_to_datetime_naive(self): self.assertEqual( utils.parsedate_to_datetime(self.datestring + ' -0000'), self.naive_dt) class LocaltimeTests(unittest.TestCase): def test_localtime_is_tz_aware_daylight_true(self): test.support.patch(self, time, 'daylight', True) t = utils.localtime() self.assertIsNotNone(t.tzinfo) def test_localtime_is_tz_aware_daylight_false(self): test.support.patch(self, time, 'daylight', False) t = utils.localtime() self.assertIsNotNone(t.tzinfo) def test_localtime_daylight_true_dst_false(self): test.support.patch(self, time, 'daylight', True) t0 = datetime.datetime(2012, 3, 12, 1, 1) t1 = utils.localtime(t0, isdst=-1) t2 = utils.localtime(t1) self.assertEqual(t1, t2) def test_localtime_daylight_false_dst_false(self): test.support.patch(self, time, 'daylight', False) t0 = datetime.datetime(2012, 3, 12, 1, 1) t1 = utils.localtime(t0, isdst=-1) t2 = utils.localtime(t1) self.assertEqual(t1, t2) def test_localtime_daylight_true_dst_true(self): test.support.patch(self, time, 'daylight', True) t0 = datetime.datetime(2012, 3, 12, 1, 1) t1 = utils.localtime(t0, isdst=1) t2 = utils.localtime(t1) self.assertEqual(t1, t2) def test_localtime_daylight_false_dst_true(self): test.support.patch(self, time, 'daylight', False) t0 = datetime.datetime(2012, 3, 12, 1, 1) t1 = utils.localtime(t0, isdst=1) t2 = utils.localtime(t1) self.assertEqual(t1, t2) @test.support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0') def test_localtime_epoch_utc_daylight_true(self): test.support.patch(self, time, 'daylight', True) t0 = datetime.datetime(1990, 1, 1, tzinfo = datetime.timezone.utc) t1 = utils.localtime(t0) t2 = t0 - datetime.timedelta(hours=5) t2 = t2.replace(tzinfo = datetime.timezone(datetime.timedelta(hours=-5))) self.assertEqual(t1, t2) @test.support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0') def test_localtime_epoch_utc_daylight_false(self): test.support.patch(self, time, 'daylight', False) t0 = datetime.datetime(1990, 1, 1, tzinfo = datetime.timezone.utc) t1 = utils.localtime(t0) t2 = t0 - datetime.timedelta(hours=5) t2 = t2.replace(tzinfo = datetime.timezone(datetime.timedelta(hours=-5))) self.assertEqual(t1, t2) def test_localtime_epoch_notz_daylight_true(self): test.support.patch(self, time, 'daylight', True) t0 = datetime.datetime(1990, 1, 1) t1 = utils.localtime(t0) t2 = utils.localtime(t0.replace(tzinfo=None)) self.assertEqual(t1, t2) def test_localtime_epoch_notz_daylight_false(self): test.support.patch(self, time, 'daylight', False) t0 = datetime.datetime(1990, 1, 1) t1 = utils.localtime(t0) t2 = utils.localtime(t0.replace(tzinfo=None)) self.assertEqual(t1, t2) # XXX: Need a more robust test for Olson's tzdata @unittest.skipIf(sys.platform.startswith('win'), "Windows does not use Olson's TZ database") @unittest.skipUnless(os.path.exists('/usr/share/zoneinfo') or os.path.exists('/usr/lib/zoneinfo'), "Can't find the Olson's TZ database") @test.support.run_with_tz('Europe/Kiev') def test_variable_tzname(self): t0 = datetime.datetime(1984, 1, 1, tzinfo=datetime.timezone.utc) t1 = utils.localtime(t0) self.assertEqual(t1.tzname(), 'MSK') t0 = datetime.datetime(1994, 1, 1, tzinfo=datetime.timezone.utc) t1 = utils.localtime(t0) self.assertEqual(t1.tzname(), 'EET') if __name__ == '__main__': unittest.main()
lgpl-3.0
Goamaral/SCC
inputWindow.py
1
31922
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'inputWindow.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(708, 428) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.verticalLayout_4 = QtGui.QVBoxLayout(self.centralwidget) self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4")) self.List = QtGui.QVBoxLayout() self.List.setObjectName(_fromUtf8("List")) self.listItem_3 = QtGui.QWidget(self.centralwidget) self.listItem_3.setMinimumSize(QtCore.QSize(0, 0)) self.listItem_3.setMaximumSize(QtCore.QSize(10000, 100)) self.listItem_3.setObjectName(_fromUtf8("listItem_3")) self.horizontalLayout_5 = QtGui.QHBoxLayout(self.listItem_3) self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5")) self.nameLabel_3 = QtGui.QLabel(self.listItem_3) self.nameLabel_3.setMinimumSize(QtCore.QSize(125, 0)) self.nameLabel_3.setMaximumSize(QtCore.QSize(75, 16777215)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.nameLabel_3.setFont(font) self.nameLabel_3.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.nameLabel_3.setObjectName(_fromUtf8("nameLabel_3")) self.horizontalLayout_5.addWidget(self.nameLabel_3) self.nameLabel_27 = QtGui.QLabel(self.listItem_3) self.nameLabel_27.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_27.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_27.setFont(font) self.nameLabel_27.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_27.setObjectName(_fromUtf8("nameLabel_27")) self.horizontalLayout_5.addWidget(self.nameLabel_27) self.mediaChegadaA = QtGui.QLineEdit(self.listItem_3) self.mediaChegadaA.setMinimumSize(QtCore.QSize(50, 25)) self.mediaChegadaA.setMaximumSize(QtCore.QSize(50, 25)) self.mediaChegadaA.setText(_fromUtf8("")) self.mediaChegadaA.setObjectName(_fromUtf8("mediaChegadaA")) self.horizontalLayout_5.addWidget(self.mediaChegadaA) spacerItem = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_5.addItem(spacerItem) self.List.addWidget(self.listItem_3) self.listItem_6 = QtGui.QWidget(self.centralwidget) self.listItem_6.setMinimumSize(QtCore.QSize(0, 0)) self.listItem_6.setMaximumSize(QtCore.QSize(10000, 100)) self.listItem_6.setObjectName(_fromUtf8("listItem_6")) self.horizontalLayout_7 = QtGui.QHBoxLayout(self.listItem_6) self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7")) self.nameLabel_7 = QtGui.QLabel(self.listItem_6) self.nameLabel_7.setMinimumSize(QtCore.QSize(125, 0)) self.nameLabel_7.setMaximumSize(QtCore.QSize(75, 16777215)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.nameLabel_7.setFont(font) self.nameLabel_7.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.nameLabel_7.setObjectName(_fromUtf8("nameLabel_7")) self.horizontalLayout_7.addWidget(self.nameLabel_7) self.nameLabel_8 = QtGui.QLabel(self.listItem_6) self.nameLabel_8.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_8.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_8.setFont(font) self.nameLabel_8.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_8.setObjectName(_fromUtf8("nameLabel_8")) self.horizontalLayout_7.addWidget(self.nameLabel_8) self.mediaPerfuracaoA = QtGui.QLineEdit(self.listItem_6) self.mediaPerfuracaoA.setMinimumSize(QtCore.QSize(50, 25)) self.mediaPerfuracaoA.setMaximumSize(QtCore.QSize(50, 25)) self.mediaPerfuracaoA.setText(_fromUtf8("")) self.mediaPerfuracaoA.setObjectName(_fromUtf8("mediaPerfuracaoA")) self.horizontalLayout_7.addWidget(self.mediaPerfuracaoA) self.nameLabel_9 = QtGui.QLabel(self.listItem_6) self.nameLabel_9.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_9.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_9.setFont(font) self.nameLabel_9.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_9.setObjectName(_fromUtf8("nameLabel_9")) self.horizontalLayout_7.addWidget(self.nameLabel_9) self.desvioPerfuracaoA = QtGui.QLineEdit(self.listItem_6) self.desvioPerfuracaoA.setMinimumSize(QtCore.QSize(50, 25)) self.desvioPerfuracaoA.setMaximumSize(QtCore.QSize(50, 25)) self.desvioPerfuracaoA.setText(_fromUtf8("")) self.desvioPerfuracaoA.setObjectName(_fromUtf8("desvioPerfuracaoA")) self.horizontalLayout_7.addWidget(self.desvioPerfuracaoA) self.nameLabel_10 = QtGui.QLabel(self.listItem_6) self.nameLabel_10.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_10.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_10.setFont(font) self.nameLabel_10.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_10.setObjectName(_fromUtf8("nameLabel_10")) self.horizontalLayout_7.addWidget(self.nameLabel_10) self.nMaquinasPerfuracaoA = QtGui.QLineEdit(self.listItem_6) self.nMaquinasPerfuracaoA.setMinimumSize(QtCore.QSize(50, 25)) self.nMaquinasPerfuracaoA.setMaximumSize(QtCore.QSize(50, 25)) self.nMaquinasPerfuracaoA.setText(_fromUtf8("")) self.nMaquinasPerfuracaoA.setObjectName(_fromUtf8("nMaquinasPerfuracaoA")) self.horizontalLayout_7.addWidget(self.nMaquinasPerfuracaoA) spacerItem1 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_7.addItem(spacerItem1) self.List.addWidget(self.listItem_6) self.listItem_7 = QtGui.QWidget(self.centralwidget) self.listItem_7.setMinimumSize(QtCore.QSize(0, 0)) self.listItem_7.setMaximumSize(QtCore.QSize(10000, 100)) self.listItem_7.setObjectName(_fromUtf8("listItem_7")) self.horizontalLayout_8 = QtGui.QHBoxLayout(self.listItem_7) self.horizontalLayout_8.setObjectName(_fromUtf8("horizontalLayout_8")) self.nameLabel_11 = QtGui.QLabel(self.listItem_7) self.nameLabel_11.setMinimumSize(QtCore.QSize(125, 0)) self.nameLabel_11.setMaximumSize(QtCore.QSize(75, 16777215)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.nameLabel_11.setFont(font) self.nameLabel_11.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.nameLabel_11.setObjectName(_fromUtf8("nameLabel_11")) self.horizontalLayout_8.addWidget(self.nameLabel_11) self.nameLabel_12 = QtGui.QLabel(self.listItem_7) self.nameLabel_12.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_12.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_12.setFont(font) self.nameLabel_12.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_12.setObjectName(_fromUtf8("nameLabel_12")) self.horizontalLayout_8.addWidget(self.nameLabel_12) self.mediaPolimentoA = QtGui.QLineEdit(self.listItem_7) self.mediaPolimentoA.setMinimumSize(QtCore.QSize(50, 25)) self.mediaPolimentoA.setMaximumSize(QtCore.QSize(50, 25)) self.mediaPolimentoA.setText(_fromUtf8("")) self.mediaPolimentoA.setObjectName(_fromUtf8("mediaPolimentoA")) self.horizontalLayout_8.addWidget(self.mediaPolimentoA) self.nameLabel_13 = QtGui.QLabel(self.listItem_7) self.nameLabel_13.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_13.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_13.setFont(font) self.nameLabel_13.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_13.setObjectName(_fromUtf8("nameLabel_13")) self.horizontalLayout_8.addWidget(self.nameLabel_13) self.desvioPolimentoA = QtGui.QLineEdit(self.listItem_7) self.desvioPolimentoA.setMinimumSize(QtCore.QSize(50, 25)) self.desvioPolimentoA.setMaximumSize(QtCore.QSize(50, 25)) self.desvioPolimentoA.setText(_fromUtf8("")) self.desvioPolimentoA.setObjectName(_fromUtf8("desvioPolimentoA")) self.horizontalLayout_8.addWidget(self.desvioPolimentoA) self.nameLabel_14 = QtGui.QLabel(self.listItem_7) self.nameLabel_14.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_14.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_14.setFont(font) self.nameLabel_14.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_14.setObjectName(_fromUtf8("nameLabel_14")) self.horizontalLayout_8.addWidget(self.nameLabel_14) self.nMaquinasPolimentoA = QtGui.QLineEdit(self.listItem_7) self.nMaquinasPolimentoA.setMinimumSize(QtCore.QSize(50, 25)) self.nMaquinasPolimentoA.setMaximumSize(QtCore.QSize(50, 25)) self.nMaquinasPolimentoA.setText(_fromUtf8("")) self.nMaquinasPolimentoA.setObjectName(_fromUtf8("nMaquinasPolimentoA")) self.horizontalLayout_8.addWidget(self.nMaquinasPolimentoA) spacerItem2 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_8.addItem(spacerItem2) self.List.addWidget(self.listItem_7) self.line_2 = QtGui.QFrame(self.centralwidget) self.line_2.setMinimumSize(QtCore.QSize(5, 0)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.line_2.setFont(font) self.line_2.setFrameShape(QtGui.QFrame.HLine) self.line_2.setFrameShadow(QtGui.QFrame.Sunken) self.line_2.setObjectName(_fromUtf8("line_2")) self.List.addWidget(self.line_2) self.listItem_4 = QtGui.QWidget(self.centralwidget) self.listItem_4.setMinimumSize(QtCore.QSize(0, 0)) self.listItem_4.setMaximumSize(QtCore.QSize(10000, 100)) self.listItem_4.setObjectName(_fromUtf8("listItem_4")) self.horizontalLayout_6 = QtGui.QHBoxLayout(self.listItem_4) self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6")) self.nameLabel_4 = QtGui.QLabel(self.listItem_4) self.nameLabel_4.setMinimumSize(QtCore.QSize(125, 0)) self.nameLabel_4.setMaximumSize(QtCore.QSize(75, 16777215)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.nameLabel_4.setFont(font) self.nameLabel_4.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.nameLabel_4.setObjectName(_fromUtf8("nameLabel_4")) self.horizontalLayout_6.addWidget(self.nameLabel_4) self.nameLabel_31 = QtGui.QLabel(self.listItem_4) self.nameLabel_31.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_31.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_31.setFont(font) self.nameLabel_31.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_31.setObjectName(_fromUtf8("nameLabel_31")) self.horizontalLayout_6.addWidget(self.nameLabel_31) self.mediaChegadaB = QtGui.QLineEdit(self.listItem_4) self.mediaChegadaB.setMinimumSize(QtCore.QSize(50, 25)) self.mediaChegadaB.setMaximumSize(QtCore.QSize(50, 25)) self.mediaChegadaB.setText(_fromUtf8("")) self.mediaChegadaB.setObjectName(_fromUtf8("mediaChegadaB")) self.horizontalLayout_6.addWidget(self.mediaChegadaB) spacerItem3 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_6.addItem(spacerItem3) self.List.addWidget(self.listItem_4) self.listItem_9 = QtGui.QWidget(self.centralwidget) self.listItem_9.setMinimumSize(QtCore.QSize(0, 0)) self.listItem_9.setMaximumSize(QtCore.QSize(10000, 100)) self.listItem_9.setObjectName(_fromUtf8("listItem_9")) self.horizontalLayout_13 = QtGui.QHBoxLayout(self.listItem_9) self.horizontalLayout_13.setObjectName(_fromUtf8("horizontalLayout_13")) self.nameLabel_36 = QtGui.QLabel(self.listItem_9) self.nameLabel_36.setMinimumSize(QtCore.QSize(125, 0)) self.nameLabel_36.setMaximumSize(QtCore.QSize(75, 16777215)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.nameLabel_36.setFont(font) self.nameLabel_36.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.nameLabel_36.setObjectName(_fromUtf8("nameLabel_36")) self.horizontalLayout_13.addWidget(self.nameLabel_36) self.nameLabel_37 = QtGui.QLabel(self.listItem_9) self.nameLabel_37.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_37.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_37.setFont(font) self.nameLabel_37.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_37.setObjectName(_fromUtf8("nameLabel_37")) self.horizontalLayout_13.addWidget(self.nameLabel_37) self.mediaPerfuracaoB = QtGui.QLineEdit(self.listItem_9) self.mediaPerfuracaoB.setMinimumSize(QtCore.QSize(50, 25)) self.mediaPerfuracaoB.setMaximumSize(QtCore.QSize(50, 25)) self.mediaPerfuracaoB.setText(_fromUtf8("")) self.mediaPerfuracaoB.setObjectName(_fromUtf8("mediaPerfuracaoB")) self.horizontalLayout_13.addWidget(self.mediaPerfuracaoB) self.nameLabel_38 = QtGui.QLabel(self.listItem_9) self.nameLabel_38.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_38.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_38.setFont(font) self.nameLabel_38.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_38.setObjectName(_fromUtf8("nameLabel_38")) self.horizontalLayout_13.addWidget(self.nameLabel_38) self.desvioPerfuracaoB = QtGui.QLineEdit(self.listItem_9) self.desvioPerfuracaoB.setMinimumSize(QtCore.QSize(50, 25)) self.desvioPerfuracaoB.setMaximumSize(QtCore.QSize(50, 25)) self.desvioPerfuracaoB.setText(_fromUtf8("")) self.desvioPerfuracaoB.setObjectName(_fromUtf8("desvioPerfuracaoB")) self.horizontalLayout_13.addWidget(self.desvioPerfuracaoB) self.nameLabel_39 = QtGui.QLabel(self.listItem_9) self.nameLabel_39.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_39.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_39.setFont(font) self.nameLabel_39.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_39.setObjectName(_fromUtf8("nameLabel_39")) self.horizontalLayout_13.addWidget(self.nameLabel_39) self.nMaquinasPerfuracaoB = QtGui.QLineEdit(self.listItem_9) self.nMaquinasPerfuracaoB.setMinimumSize(QtCore.QSize(50, 25)) self.nMaquinasPerfuracaoB.setMaximumSize(QtCore.QSize(50, 25)) self.nMaquinasPerfuracaoB.setText(_fromUtf8("")) self.nMaquinasPerfuracaoB.setObjectName(_fromUtf8("nMaquinasPerfuracaoB")) self.horizontalLayout_13.addWidget(self.nMaquinasPerfuracaoB) spacerItem4 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_13.addItem(spacerItem4) self.List.addWidget(self.listItem_9) self.listItem_8 = QtGui.QWidget(self.centralwidget) self.listItem_8.setMinimumSize(QtCore.QSize(0, 0)) self.listItem_8.setMaximumSize(QtCore.QSize(10000, 100)) self.listItem_8.setObjectName(_fromUtf8("listItem_8")) self.horizontalLayout_10 = QtGui.QHBoxLayout(self.listItem_8) self.horizontalLayout_10.setObjectName(_fromUtf8("horizontalLayout_10")) self.nameLabel_19 = QtGui.QLabel(self.listItem_8) self.nameLabel_19.setMinimumSize(QtCore.QSize(125, 0)) self.nameLabel_19.setMaximumSize(QtCore.QSize(75, 16777215)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.nameLabel_19.setFont(font) self.nameLabel_19.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.nameLabel_19.setObjectName(_fromUtf8("nameLabel_19")) self.horizontalLayout_10.addWidget(self.nameLabel_19) self.nameLabel_20 = QtGui.QLabel(self.listItem_8) self.nameLabel_20.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_20.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_20.setFont(font) self.nameLabel_20.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_20.setObjectName(_fromUtf8("nameLabel_20")) self.horizontalLayout_10.addWidget(self.nameLabel_20) self.mediaPolimentoB = QtGui.QLineEdit(self.listItem_8) self.mediaPolimentoB.setMinimumSize(QtCore.QSize(50, 25)) self.mediaPolimentoB.setMaximumSize(QtCore.QSize(50, 25)) self.mediaPolimentoB.setText(_fromUtf8("")) self.mediaPolimentoB.setObjectName(_fromUtf8("mediaPolimentoB")) self.horizontalLayout_10.addWidget(self.mediaPolimentoB) self.nameLabel_21 = QtGui.QLabel(self.listItem_8) self.nameLabel_21.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_21.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_21.setFont(font) self.nameLabel_21.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_21.setObjectName(_fromUtf8("nameLabel_21")) self.horizontalLayout_10.addWidget(self.nameLabel_21) self.desvioPolimentoB = QtGui.QLineEdit(self.listItem_8) self.desvioPolimentoB.setMinimumSize(QtCore.QSize(50, 25)) self.desvioPolimentoB.setMaximumSize(QtCore.QSize(50, 25)) self.desvioPolimentoB.setText(_fromUtf8("")) self.desvioPolimentoB.setObjectName(_fromUtf8("desvioPolimentoB")) self.horizontalLayout_10.addWidget(self.desvioPolimentoB) self.nameLabel_22 = QtGui.QLabel(self.listItem_8) self.nameLabel_22.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_22.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_22.setFont(font) self.nameLabel_22.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_22.setObjectName(_fromUtf8("nameLabel_22")) self.horizontalLayout_10.addWidget(self.nameLabel_22) self.nMaquinasPolimentoB = QtGui.QLineEdit(self.listItem_8) self.nMaquinasPolimentoB.setMinimumSize(QtCore.QSize(50, 25)) self.nMaquinasPolimentoB.setMaximumSize(QtCore.QSize(50, 25)) self.nMaquinasPolimentoB.setText(_fromUtf8("")) self.nMaquinasPolimentoB.setObjectName(_fromUtf8("nMaquinasPolimentoB")) self.horizontalLayout_10.addWidget(self.nMaquinasPolimentoB) spacerItem5 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_10.addItem(spacerItem5) self.List.addWidget(self.listItem_8) self.line = QtGui.QFrame(self.centralwidget) self.line.setMinimumSize(QtCore.QSize(0, 5)) self.line.setFrameShape(QtGui.QFrame.HLine) self.line.setFrameShadow(QtGui.QFrame.Sunken) self.line.setObjectName(_fromUtf8("line")) self.List.addWidget(self.line) self.listItem_11 = QtGui.QWidget(self.centralwidget) self.listItem_11.setMinimumSize(QtCore.QSize(0, 0)) self.listItem_11.setMaximumSize(QtCore.QSize(10000, 100)) self.listItem_11.setObjectName(_fromUtf8("listItem_11")) self.horizontalLayout_12 = QtGui.QHBoxLayout(self.listItem_11) self.horizontalLayout_12.setObjectName(_fromUtf8("horizontalLayout_12")) self.nameLabel_23 = QtGui.QLabel(self.listItem_11) self.nameLabel_23.setMinimumSize(QtCore.QSize(125, 0)) self.nameLabel_23.setMaximumSize(QtCore.QSize(125, 16777215)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.nameLabel_23.setFont(font) self.nameLabel_23.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.nameLabel_23.setObjectName(_fromUtf8("nameLabel_23")) self.horizontalLayout_12.addWidget(self.nameLabel_23) self.nameLabel_24 = QtGui.QLabel(self.listItem_11) self.nameLabel_24.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_24.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_24.setFont(font) self.nameLabel_24.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_24.setObjectName(_fromUtf8("nameLabel_24")) self.horizontalLayout_12.addWidget(self.nameLabel_24) self.mediaEnvernizamento = QtGui.QLineEdit(self.listItem_11) self.mediaEnvernizamento.setMinimumSize(QtCore.QSize(50, 25)) self.mediaEnvernizamento.setMaximumSize(QtCore.QSize(50, 25)) self.mediaEnvernizamento.setText(_fromUtf8("")) self.mediaEnvernizamento.setObjectName(_fromUtf8("mediaEnvernizamento")) self.horizontalLayout_12.addWidget(self.mediaEnvernizamento) self.nameLabel_25 = QtGui.QLabel(self.listItem_11) self.nameLabel_25.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_25.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_25.setFont(font) self.nameLabel_25.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_25.setObjectName(_fromUtf8("nameLabel_25")) self.horizontalLayout_12.addWidget(self.nameLabel_25) self.desvioEnvernizamento = QtGui.QLineEdit(self.listItem_11) self.desvioEnvernizamento.setMinimumSize(QtCore.QSize(50, 25)) self.desvioEnvernizamento.setMaximumSize(QtCore.QSize(50, 25)) self.desvioEnvernizamento.setText(_fromUtf8("")) self.desvioEnvernizamento.setObjectName(_fromUtf8("desvioEnvernizamento")) self.horizontalLayout_12.addWidget(self.desvioEnvernizamento) self.nameLabel_26 = QtGui.QLabel(self.listItem_11) self.nameLabel_26.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_26.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.nameLabel_26.setFont(font) self.nameLabel_26.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_26.setObjectName(_fromUtf8("nameLabel_26")) self.horizontalLayout_12.addWidget(self.nameLabel_26) self.nMaquinasEnvernizamento = QtGui.QLineEdit(self.listItem_11) self.nMaquinasEnvernizamento.setMinimumSize(QtCore.QSize(50, 25)) self.nMaquinasEnvernizamento.setMaximumSize(QtCore.QSize(50, 25)) self.nMaquinasEnvernizamento.setText(_fromUtf8("")) self.nMaquinasEnvernizamento.setObjectName(_fromUtf8("nMaquinasEnvernizamento")) self.horizontalLayout_12.addWidget(self.nMaquinasEnvernizamento) spacerItem6 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_12.addItem(spacerItem6) self.List.addWidget(self.listItem_11) self.verticalLayout_4.addLayout(self.List) self.footer = QtGui.QWidget(self.centralwidget) self.footer.setMaximumSize(QtCore.QSize(100000, 50)) self.footer.setObjectName(_fromUtf8("footer")) self.horizontalLayout = QtGui.QHBoxLayout(self.footer) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.nameLabel_30 = QtGui.QLabel(self.footer) self.nameLabel_30.setMinimumSize(QtCore.QSize(130, 0)) self.nameLabel_30.setMaximumSize(QtCore.QSize(130, 16777215)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.nameLabel_30.setFont(font) self.nameLabel_30.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.nameLabel_30.setObjectName(_fromUtf8("nameLabel_30")) self.horizontalLayout.addWidget(self.nameLabel_30) self.tipoLimite = QtGui.QComboBox(self.footer) self.tipoLimite.setMinimumSize(QtCore.QSize(125, 0)) self.tipoLimite.setMaximumSize(QtCore.QSize(125, 16777215)) self.tipoLimite.setObjectName(_fromUtf8("tipoLimite")) self.tipoLimite.addItem(_fromUtf8("")) self.tipoLimite.addItem(_fromUtf8("")) self.horizontalLayout.addWidget(self.tipoLimite) self.nameLabel_28 = QtGui.QLabel(self.footer) self.nameLabel_28.setMinimumSize(QtCore.QSize(50, 0)) self.nameLabel_28.setMaximumSize(QtCore.QSize(50, 16777215)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.nameLabel_28.setFont(font) self.nameLabel_28.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_28.setObjectName(_fromUtf8("nameLabel_28")) self.horizontalLayout.addWidget(self.nameLabel_28) self.valorLimite = QtGui.QLineEdit(self.footer) self.valorLimite.setMinimumSize(QtCore.QSize(75, 25)) self.valorLimite.setMaximumSize(QtCore.QSize(75, 25)) self.valorLimite.setText(_fromUtf8("")) self.valorLimite.setObjectName(_fromUtf8("valorLimite")) self.horizontalLayout.addWidget(self.valorLimite) spacerItem7 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem7) self.nameLabel_29 = QtGui.QLabel(self.footer) self.nameLabel_29.setMinimumSize(QtCore.QSize(100, 0)) self.nameLabel_29.setMaximumSize(QtCore.QSize(100, 16777215)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.nameLabel_29.setFont(font) self.nameLabel_29.setAlignment(QtCore.Qt.AlignCenter) self.nameLabel_29.setObjectName(_fromUtf8("nameLabel_29")) self.horizontalLayout.addWidget(self.nameLabel_29) self.nRepeticoes = QtGui.QLineEdit(self.footer) self.nRepeticoes.setMinimumSize(QtCore.QSize(50, 25)) self.nRepeticoes.setMaximumSize(QtCore.QSize(50, 25)) self.nRepeticoes.setText(_fromUtf8("")) self.nRepeticoes.setObjectName(_fromUtf8("nRepeticoes")) self.horizontalLayout.addWidget(self.nRepeticoes) self.botaoSimular = QtGui.QPushButton(self.footer) self.botaoSimular.setMinimumSize(QtCore.QSize(100, 25)) self.botaoSimular.setMaximumSize(QtCore.QSize(100, 25)) font = QtGui.QFont() font.setBold(True) font.setWeight(75) self.botaoSimular.setFont(font) self.botaoSimular.setLayoutDirection(QtCore.Qt.RightToLeft) self.botaoSimular.setAutoFillBackground(False) self.botaoSimular.setStyleSheet(_fromUtf8("")) self.botaoSimular.setFlat(False) self.botaoSimular.setObjectName(_fromUtf8("botaoSimular")) self.horizontalLayout.addWidget(self.botaoSimular) self.verticalLayout_4.addWidget(self.footer) MainWindow.setCentralWidget(self.centralwidget) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "Descriçao da simulaçao", None)) self.nameLabel_3.setText(_translate("MainWindow", "Peças grandes (A)", None)) self.nameLabel_27.setText(_translate("MainWindow", "Media chegada", None)) self.nameLabel_7.setText(_translate("MainWindow", "Perfuraçao", None)) self.nameLabel_8.setText(_translate("MainWindow", "Media", None)) self.nameLabel_9.setText(_translate("MainWindow", "Desvio padrao", None)) self.nameLabel_10.setText(_translate("MainWindow", "Nº maquinas", None)) self.nameLabel_11.setText(_translate("MainWindow", "Polimento", None)) self.nameLabel_12.setText(_translate("MainWindow", "Media", None)) self.nameLabel_13.setText(_translate("MainWindow", "Desvio padrao", None)) self.nameLabel_14.setText(_translate("MainWindow", "Nº maquinas", None)) self.nameLabel_4.setText(_translate("MainWindow", "Peças grandes (B)", None)) self.nameLabel_31.setText(_translate("MainWindow", "Media chegada", None)) self.nameLabel_36.setText(_translate("MainWindow", "Perfuraçao", None)) self.nameLabel_37.setText(_translate("MainWindow", "Media", None)) self.nameLabel_38.setText(_translate("MainWindow", "Desvio padrao", None)) self.nameLabel_39.setText(_translate("MainWindow", "Nº maquinas", None)) self.nameLabel_19.setText(_translate("MainWindow", "Polimento", None)) self.nameLabel_20.setText(_translate("MainWindow", "Media", None)) self.nameLabel_21.setText(_translate("MainWindow", "Desvio padrao", None)) self.nameLabel_22.setText(_translate("MainWindow", "Nº maquinas", None)) self.nameLabel_23.setText(_translate("MainWindow", "Envernizamento", None)) self.nameLabel_24.setText(_translate("MainWindow", "Media", None)) self.nameLabel_25.setText(_translate("MainWindow", "Desvio padrao", None)) self.nameLabel_26.setText(_translate("MainWindow", "Nº maquinas", None)) self.nameLabel_30.setText(_translate("MainWindow", "Limites da simulacao", None)) self.tipoLimite.setItemText(0, _translate("MainWindow", "Tempo simulacao", None)) self.tipoLimite.setItemText(1, _translate("MainWindow", "Nº Clientes", None)) self.nameLabel_28.setText(_translate("MainWindow", "Valor", None)) self.nameLabel_29.setText(_translate("MainWindow", "Nº Repeticoes", None)) self.botaoSimular.setText(_translate("MainWindow", "Simular", None))
mit
treejames/erpnext
erpnext/buying/doctype/quality_inspection/quality_inspection.py
61
2058
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe.model.document import Document class QualityInspection(Document): def get_item_specification_details(self): self.set('readings', []) variant_of = frappe.db.get_value("Item", self.item_code, "variant_of") if variant_of: specification = frappe.db.sql("select specification, value from `tabItem Quality Inspection Parameter` \ where parent in (%s, %s) order by idx", (self.item_code, variant_of)) else: specification = frappe.db.sql("select specification, value from `tabItem Quality Inspection Parameter` \ where parent = %s order by idx", self.item_code) for d in specification: child = self.append('readings', {}) child.specification = d[0] child.value = d[1] child.status = 'Accepted' def on_submit(self): if self.purchase_receipt_no: frappe.db.sql("""update `tabPurchase Receipt Item` t1, `tabPurchase Receipt` t2 set t1.qa_no = %s, t2.modified = %s where t1.parent = %s and t1.item_code = %s and t1.parent = t2.name""", (self.name, self.modified, self.purchase_receipt_no, self.item_code)) def on_cancel(self): if self.purchase_receipt_no: frappe.db.sql("""update `tabPurchase Receipt Item` t1, `tabPurchase Receipt` t2 set t1.qa_no = '', t2.modified = %s where t1.parent = %s and t1.item_code = %s and t1.parent = t2.name""", (self.modified, self.purchase_receipt_no, self.item_code)) def item_query(doctype, txt, searchfield, start, page_len, filters): if filters.get("from"): from frappe.desk.reportview import get_match_cond filters.update({ "txt": txt, "mcond": get_match_cond(filters["from"]), "start": start, "page_len": page_len }) return frappe.db.sql("""select item_code from `tab%(from)s` where parent='%(parent)s' and docstatus < 2 and item_code like '%%%(txt)s%%' %(mcond)s order by item_code limit %(start)s, %(page_len)s""" % filters)
agpl-3.0
kirca/odoo
addons/point_of_sale/wizard/pos_session_opening.py
40
5025
from openerp.osv import osv, fields from openerp.tools.translate import _ from openerp.addons.point_of_sale.point_of_sale import pos_session class pos_session_opening(osv.osv_memory): _name = 'pos.session.opening' _columns = { 'pos_config_id' : fields.many2one('pos.config', 'Point of Sale', required=True), 'pos_session_id' : fields.many2one('pos.session', 'PoS Session'), 'pos_state' : fields.related('pos_session_id', 'state', type='selection', selection=pos_session.POS_SESSION_STATE, string='Session Status', readonly=True), 'pos_state_str' : fields.char('Status', 32, readonly=True), 'show_config' : fields.boolean('Show Config', readonly=True), 'pos_session_name' : fields.related('pos_session_id', 'name', type='char', size=64, readonly=True), 'pos_session_username' : fields.related('pos_session_id', 'user_id', 'name', type='char', size=64, readonly=True) } def open_ui(self, cr, uid, ids, context=None): context = context or {} data = self.browse(cr, uid, ids[0], context=context) context['active_id'] = data.pos_session_id.id return { 'type' : 'ir.actions.act_url', 'url': '/pos/web/', 'target': 'self', } def open_existing_session_cb_close(self, cr, uid, ids, context=None): wizard = self.browse(cr, uid, ids[0], context=context) self.pool.get('pos.session').signal_cashbox_control(cr, uid, [wizard.pos_session_id.id]) return self.open_session_cb(cr, uid, ids, context) def open_session_cb(self, cr, uid, ids, context=None): assert len(ids) == 1, "you can open only one session at a time" proxy = self.pool.get('pos.session') wizard = self.browse(cr, uid, ids[0], context=context) if not wizard.pos_session_id: values = { 'user_id' : uid, 'config_id' : wizard.pos_config_id.id, } session_id = proxy.create(cr, uid, values, context=context) s = proxy.browse(cr, uid, session_id, context=context) if s.state=='opened': return self.open_ui(cr, uid, ids, context=context) return self._open_session(session_id) return self._open_session(wizard.pos_session_id.id) def open_existing_session_cb(self, cr, uid, ids, context=None): assert len(ids) == 1 wizard = self.browse(cr, uid, ids[0], context=context) return self._open_session(wizard.pos_session_id.id) def _open_session(self, session_id): return { 'name': _('Session'), 'view_type': 'form', 'view_mode': 'form,tree', 'res_model': 'pos.session', 'res_id': session_id, 'view_id': False, 'type': 'ir.actions.act_window', } def on_change_config(self, cr, uid, ids, config_id, context=None): result = { 'pos_session_id': False, 'pos_state': False, 'pos_state_str' : '', 'pos_session_username' : False, 'pos_session_name' : False, } if not config_id: return {'value' : result} proxy = self.pool.get('pos.session') session_ids = proxy.search(cr, uid, [ ('state', '!=', 'closed'), ('config_id', '=', config_id), ('user_id', '=', uid), ], context=context) if session_ids: session = proxy.browse(cr, uid, session_ids[0], context=context) result['pos_state'] = str(session.state) result['pos_state_str'] = dict(pos_session.POS_SESSION_STATE).get(session.state, '') result['pos_session_id'] = session.id result['pos_session_name'] = session.name result['pos_session_username'] = session.user_id.name return {'value' : result} def default_get(self, cr, uid, fieldnames, context=None): so = self.pool.get('pos.session') session_ids = so.search(cr, uid, [('state','<>','closed'), ('user_id','=',uid)], context=context) if session_ids: result = so.browse(cr, uid, session_ids[0], context=context).config_id.id else: current_user = self.pool.get('res.users').browse(cr, uid, uid, context=context) result = current_user.pos_config and current_user.pos_config.id or False if not result: r = self.pool.get('pos.config').search(cr, uid, [], context=context) result = r and r[0] or False count = self.pool.get('pos.config').search_count(cr, uid, [('state', '=', 'active')], context=context) show_config = bool(count > 1) return { 'pos_config_id' : result, 'show_config' : show_config, }
agpl-3.0
Product-Foundry/vaultier
vaultier/nodes/business/permissions.py
3
1731
from rest_framework import permissions from accounts.models import Member def _has_membership(user, node): return Member.objects.filter(node=node.get_root(), user=user).exists() def _get_membership(user, node): if not _has_membership(user, node): return return Member.objects.to_node(user, node) class NodePermission(permissions.BasePermission): """ Prepared permissions for Nodes. Returning True only at this point. """ def has_permission(self, request, view): """ Grant permission """ parent = view.kwargs.get('parent') or view.kwargs.get('node') if request.method == "GET" and parent: member = _get_membership(request.user, parent) if not member: return return parent.acl.has_permission('read', member) return True def has_object_permission(self, request, view, obj): """ Grant object permission """ member = _get_membership(request.user, obj) if not member: return if request.method == "GET": return obj.acl.has_permission('read', member) if request.method in ('PUT', 'PATCH', 'DELETE'): return obj.acl.has_permission('update', member) class PolicyPermission(NodePermission): def has_object_permission(self, request, view, obj): node = view.kwargs.get('node') member = _get_membership(request.user, obj) if not member: return if view.action == "retrieve": return node.acl.has_permission('read', member) if view.action in ('update', 'partial_update'): return node.acl.has_permission('update', member)
bsd-3-clause
ennoborg/gramps
gramps/gen/plug/_pluginreg.py
2
47851
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2009 Benny Malengier # Copyright (C) 2011 Tim G L Lyons # # 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. # """ This module provides the base class for plugin registration. It provides an object containing data about the plugin (version, filename, ...) and a register for the data of all plugins . """ #------------------------------------------------------------------------- # # Standard Python modules # #------------------------------------------------------------------------- import os import sys import re import traceback #------------------------------------------------------------------------- # # Gramps modules # #------------------------------------------------------------------------- from ...version import VERSION as GRAMPSVERSION, VERSION_TUPLE from ..const import IMAGE_DIR from ..const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext import logging LOG = logging.getLogger('._manager') #------------------------------------------------------------------------- # # PluginData # #------------------------------------------------------------------------- #a plugin is stable or unstable STABLE = 0 UNSTABLE = 1 STATUS = [STABLE, UNSTABLE] STATUSTEXT = {STABLE: _('Stable'), UNSTABLE: _('Unstable')} #possible plugin types REPORT = 0 QUICKREPORT = 1 # deprecated QUICKVIEW = 1 TOOL = 2 IMPORT = 3 EXPORT = 4 DOCGEN = 5 GENERAL = 6 MAPSERVICE = 7 VIEW = 8 RELCALC = 9 GRAMPLET = 10 SIDEBAR = 11 DATABASE = 12 PTYPE = [REPORT , QUICKREPORT, TOOL, IMPORT, EXPORT, DOCGEN, GENERAL, MAPSERVICE, VIEW, RELCALC, GRAMPLET, SIDEBAR, DATABASE] PTYPE_STR = { REPORT: _('Report') , QUICKREPORT: _('Quickreport'), TOOL: _('Tool'), IMPORT: _('Importer'), EXPORT: _('Exporter'), DOCGEN: _('Doc creator'), GENERAL: _('Plugin lib'), MAPSERVICE: _('Map service'), VIEW: _('Gramps View'), RELCALC: _('Relationships'), GRAMPLET: _('Gramplet'), SIDEBAR: _('Sidebar'), DATABASE: _('Database'), } #possible report categories CATEGORY_TEXT = 0 CATEGORY_DRAW = 1 CATEGORY_CODE = 2 CATEGORY_WEB = 3 CATEGORY_BOOK = 4 CATEGORY_GRAPHVIZ = 5 REPORT_CAT = [ CATEGORY_TEXT, CATEGORY_DRAW, CATEGORY_CODE, CATEGORY_WEB, CATEGORY_BOOK, CATEGORY_GRAPHVIZ] #possible tool categories TOOL_DEBUG = -1 TOOL_ANAL = 0 TOOL_DBPROC = 1 TOOL_DBFIX = 2 TOOL_REVCTL = 3 TOOL_UTILS = 4 TOOL_CAT = [ TOOL_DEBUG, TOOL_ANAL, TOOL_DBPROC, TOOL_DBFIX, TOOL_REVCTL, TOOL_UTILS] #possible quickreport categories CATEGORY_QR_MISC = -1 CATEGORY_QR_PERSON = 0 CATEGORY_QR_FAMILY = 1 CATEGORY_QR_EVENT = 2 CATEGORY_QR_SOURCE = 3 CATEGORY_QR_PLACE = 4 CATEGORY_QR_REPOSITORY = 5 CATEGORY_QR_NOTE = 6 CATEGORY_QR_DATE = 7 CATEGORY_QR_MEDIA = 8 CATEGORY_QR_CITATION = 9 CATEGORY_QR_SOURCE_OR_CITATION = 10 # Modes for generating reports REPORT_MODE_GUI = 1 # Standalone report using GUI REPORT_MODE_BKI = 2 # Book Item interface using GUI REPORT_MODE_CLI = 4 # Command line interface (CLI) REPORT_MODES = [REPORT_MODE_GUI, REPORT_MODE_BKI, REPORT_MODE_CLI] # Modes for running tools TOOL_MODE_GUI = 1 # Standard tool using GUI TOOL_MODE_CLI = 2 # Command line interface (CLI) TOOL_MODES = [TOOL_MODE_GUI, TOOL_MODE_CLI] # possible view orders START = 1 END = 2 #------------------------------------------------------------------------- # # Functions and classes # #------------------------------------------------------------------------- def myint(s): """ Protected version of int() """ try: v = int(s) except: v = s return v def version(sversion): """ Return the tuple version of a string version. """ return tuple([myint(x or "0") for x in (sversion + "..").split(".")]) def valid_plugin_version(plugin_version_string): """ Checks to see if string is a valid version string for this version of Gramps. """ if not isinstance(plugin_version_string, str): return False dots = plugin_version_string.count(".") if dots == 1: plugin_version = tuple(map(int, plugin_version_string.split(".", 1))) return plugin_version == VERSION_TUPLE[:2] elif dots == 2: plugin_version = tuple(map(int, plugin_version_string.split(".", 2))) return (plugin_version[:2] == VERSION_TUPLE[:2] and plugin_version <= VERSION_TUPLE) return False class PluginData: """ This is the base class for all plugin data objects. The workflow is: 1. plugin manager reads all register files, and stores plugin data objects in a plugin register 2. when plugin is needed, the plugin register creates the plugin, and the manager stores this, after which it can be executed. Attributes present for all plugins .. attribute:: id A unique identifier for the plugin. This is eg used to store the plugin settings. .. attribute:: name A friendly name to call this plugin (normally translated) .. attribute:: name_accell A friendly name to call this plugin (normally translated), with an accellerator present (eg '_Descendant report', with D to be accellerator key .. attribute:: description A friendly description of what the plugin does .. attribute:: version The version of the plugin .. attribute:: status The status of the plugin, STABLE or UNSTABLE UNSTABLE is only visible in development code, not in release .. attribute:: fname The python file where the plugin implementation can be found .. attribute:: fpath The python path where the plugin implementation can be found .. attribute:: ptype The plugin type. One of REPORT , QUICKREPORT, TOOL, IMPORT, EXPORT, DOCGEN, GENERAL, MAPSERVICE, VIEW, GRAMPLET, DATABASE .. attribute:: authors List of authors of the plugin, default=[] .. attribute:: authors_email List of emails of the authors of the plugin, default=[] .. attribute:: supported Bool value indicating if the plugin is still supported, default=True .. attribute:: load_on_reg bool value, if True, the plugin is loaded on Gramps startup. Some plugins. Only set this value if for testing you want the plugin to be loaded immediately on startup. default=False .. attribute: icons New stock icons to register. A list of tuples (stock_id, icon_label), eg: [('gramps_myplugin', _('My Plugin')), ('gramps_myplugin_open', _('Open Plugin')] The icon directory must contain the directories scalable, 48x48, 22x22 and 16x16 with the icons, eg: scalable/gramps_myplugin.svg 48x48/gramps_myplugin.png 22x22/gramps_myplugin.png .. attribute: icondir The directory to use for the icons. If icondir is not set or None, it reverts to the plugindirectory itself. Attributes for RELCALC plugins: .. attribute:: relcalcclass The class in the module that is the relationcalc class .. attribute:: lang_list List of languages this plugin handles Attributes for REPORT plugins: .. attribute:: require_active Bool, If the reports requries an active person to be set or not .. attribute:: reportclass The class in the module that is the report class .. attribute:: report_modes The report modes: list of REPORT_MODE_GUI ,REPORT_MODE_BKI,REPORT_MODE_CLI Attributes for REPORT and TOOL and QUICKREPORT and VIEW plugins .. attribute:: category Or the report category the plugin belongs to, default=CATEGORY_TEXT or the tool category a plugin belongs to, default=TOOL_UTILS or the quickreport category a plugin belongs to, default=CATEGORY_QR_PERSON or the view category a plugin belongs to, default=("Miscellaneous", _("Miscellaneous")) Attributes for REPORT and TOOL and DOCGEN plugins .. attribute:: optionclass The class in the module that is the option class Attributes for TOOL plugins .. attribute:: toolclass The class in the module that is the tool class .. attribute:: tool_modes The tool modes: list of TOOL_MODE_GUI, TOOL_MODE_CLI Attributes for DOCGEN plugins .. attribute :: docclass The class in the module that is the BaseDoc defined .. attribute :: paper bool, Indicates whether the plugin uses paper or not, default=True .. attribute :: style bool, Indicates whether the plugin uses styles or not, default=True Attribute for DOCGEN, EXPORT plugins .. attribute :: extension str, The file extension to use for output produced by the docgen/export, default='' Attributes for QUICKREPORT plugins .. attribute:: runfunc The function that executes the quick report Attributes for MAPSERVICE plugins .. attribute:: mapservice The class in the module that is a mapservice Attributes for EXPORT plugins .. attribute:: export_function Function that produces the export .. attribute:: export_options Class to set options .. attribute:: export_options_title Title for the option page Attributes for IMPORT plugins .. attribute:: import_function Function that starts an import Attributes for GRAMPLET plugins .. attribute:: gramplet The function or class that defines the gramplet. .. attribute:: height The height the gramplet should have in a column on GrampletView, default = 200 .. attribute:: detached_height The height the gramplet should have detached, default 300 .. attribute:: detached_width The width the gramplet should have detached, default 400 .. attribute:: expand If the attributed should be expanded on start, default False .. attribute:: gramplet_title Title to use for the gramplet, default = _('Gramplet') .. attribute:: navtypes Navigation types that the gramplet is appropriate for, default = [] .. attribute:: help_url The URL where documentation for the URL can be found Attributes for VIEW plugins .. attribute:: viewclass A class of type ViewCreator that holds the needed info of the view to be created: icon, viewclass that derives from pageview, ... .. attribute:: stock_icon The icon in the toolbar or sidebar used to select the view Attributes for SIDEBAR plugins .. attribute:: sidebarclass The class that defines the sidebar. .. attribute:: menu_label A label to use on the seltion menu. Attributes for VIEW and SIDEBAR plugins .. attribute:: order order can be START or END. Default is END. For END, on registering, the plugin is appended to the list of plugins. If START, then the plugin is prepended. Only set START if you want a plugin to be the first in the order of plugins Attributes for DATABASE plugins .. attribute:: databaseclass The class in the module that is the database class .. attribute:: reset_system Boolean to indicate that the system (sys.modules) should be reset. """ def __init__(self): #read/write attribute self.directory = None #base attributes self._id = None self._name = None self._name_accell = None self._version = None self._gramps_target_version = None self._description = None self._status = UNSTABLE self._fname = None self._fpath = None self._ptype = None self._authors = [] self._authors_email = [] self._supported = True self._load_on_reg = False self._icons = [] self._icondir = None self._depends_on = [] self._include_in_listing = True #derived var self.mod_name = None #RELCALC attr self._relcalcclass = None self._lang_list = None #REPORT attr self._reportclass = None self._require_active = True self._report_modes = [REPORT_MODE_GUI] #REPORT and TOOL and GENERAL attr self._category = None #REPORT and TOOL attr self._optionclass = None #TOOL attr self._toolclass = None self._tool_modes = [TOOL_MODE_GUI] #DOCGEN attr self._paper = True self._style = True self._extension = '' #QUICKREPORT attr self._runfunc = None #MAPSERVICE attr self._mapservice = None #EXPORT attr self._export_function = None self._export_options = None self._export_options_title = '' #IMPORT attr self._import_function = None #GRAMPLET attr self._gramplet = None self._height = 200 self._detached_height = 300 self._detached_width = 400 self._expand = False self._gramplet_title = _('Gramplet') self._navtypes = [] self._orientation = None self._help_url = None #VIEW attr self._viewclass = None self._stock_icon = None #SIDEBAR attr self._sidebarclass = None self._menu_label = '' #VIEW and SIDEBAR attr self._order = END #DATABASE attr self._databaseclass = None self._reset_system = False #GENERAL attr self._data = [] self._process = None def _set_id(self, id): self._id = id def _get_id(self): return self._id def _set_name(self, name): self._name = name def _get_name(self): return self._name def _set_name_accell(self, name): self._name_accell = name def _get_name_accell(self): if self._name_accell is None: return self._name else: return self._name_accell def _set_description(self, description): self._description = description def _get_description(self): return self._description def _set_version(self, version): self._version = version def _get_version(self): return self._version def _set_gramps_target_version(self, version): self._gramps_target_version = version def _get_gramps_target_version(self): return self._gramps_target_version def _set_status(self, status): if status not in STATUS: raise ValueError('plugin status cannot be %s' % str(status)) self._status = status def _get_status(self): return self._status def _set_fname(self, fname): self._fname = fname def _get_fname(self): return self._fname def _set_fpath(self, fpath): self._fpath = fpath def _get_fpath(self): return self._fpath def _set_ptype(self, ptype): if ptype not in PTYPE: raise ValueError('Plugin type cannot be %s' % str(ptype)) elif self._ptype is not None: raise ValueError('Plugin type may not be changed') self._ptype = ptype if self._ptype == REPORT: self._category = CATEGORY_TEXT elif self._ptype == TOOL: self._category = TOOL_UTILS elif self._ptype == QUICKREPORT: self._category = CATEGORY_QR_PERSON elif self._ptype == VIEW: self._category = ("Miscellaneous", _("Miscellaneous")) #if self._ptype == DOCGEN: # self._load_on_reg = True def _get_ptype(self): return self._ptype def _set_authors(self, authors): if not authors or not isinstance(authors, list): return self._authors = authors def _get_authors(self): return self._authors def _set_authors_email(self, authors_email): if not authors_email or not isinstance(authors_email, list): return self._authors_email = authors_email def _get_authors_email(self): return self._authors_email def _set_supported(self, supported): if not isinstance(supported, bool): raise ValueError('Plugin must have supported=True or False') self._supported = supported def _get_supported(self): return self._supported def _set_load_on_reg(self, load_on_reg): if not isinstance(load_on_reg, bool): raise ValueError('Plugin must have load_on_reg=True or False') self._load_on_reg = load_on_reg def _get_load_on_reg(self): return self._load_on_reg def _get_icons(self): return self._icons def _set_icons(self, icons): if not isinstance(icons, list): raise ValueError('Plugin must have icons as a list') self._icons = icons def _get_icondir(self): return self._icondir def _set_icondir(self, icondir): self._icondir = icondir def _get_depends_on(self): return self._depends_on def _set_depends_on(self, depends): if not isinstance(depends, list): raise ValueError('Plugin must have depends_on as a list') self._depends_on = depends def _get_include_in_listing(self): return self._include_in_listing def _set_include_in_listing(self, include): if not isinstance(include, bool): raise ValueError('Plugin must have include_in_listing as a bool') self._include_in_listing = include id = property(_get_id, _set_id) name = property(_get_name, _set_name) name_accell = property(_get_name_accell, _set_name_accell) description = property(_get_description, _set_description) version = property(_get_version, _set_version) gramps_target_version = property(_get_gramps_target_version, _set_gramps_target_version) status = property(_get_status, _set_status) fname = property(_get_fname, _set_fname) fpath = property(_get_fpath, _set_fpath) ptype = property(_get_ptype, _set_ptype) authors = property(_get_authors, _set_authors) authors_email = property(_get_authors_email, _set_authors_email) supported = property(_get_supported, _set_supported) load_on_reg = property(_get_load_on_reg, _set_load_on_reg) icons = property(_get_icons, _set_icons) icondir = property(_get_icondir, _set_icondir) depends_on = property(_get_depends_on, _set_depends_on) include_in_listing = property(_get_include_in_listing, _set_include_in_listing) def statustext(self): return STATUSTEXT[self.status] #type specific plugin attributes #RELCALC attributes def _set_relcalcclass(self, relcalcclass): if not self._ptype == RELCALC: raise ValueError('relcalcclass may only be set for RELCALC plugins') self._relcalcclass = relcalcclass def _get_relcalcclass(self): return self._relcalcclass def _set_lang_list(self, lang_list): if not self._ptype == RELCALC: raise ValueError('relcalcclass may only be set for RELCALC plugins') self._lang_list = lang_list def _get_lang_list(self): return self._lang_list relcalcclass = property(_get_relcalcclass, _set_relcalcclass) lang_list = property(_get_lang_list, _set_lang_list) #REPORT attributes def _set_require_active(self, require_active): if not self._ptype == REPORT: raise ValueError('require_active may only be set for REPORT plugins') if not isinstance(require_active, bool): raise ValueError('Report must have require_active=True or False') self._require_active = require_active def _get_require_active(self): return self._require_active def _set_reportclass(self, reportclass): if not self._ptype == REPORT: raise ValueError('reportclass may only be set for REPORT plugins') self._reportclass = reportclass def _get_reportclass(self): return self._reportclass def _set_report_modes(self, report_modes): if not self._ptype == REPORT: raise ValueError('report_modes may only be set for REPORT plugins') if not isinstance(report_modes, list): raise ValueError('report_modes must be a list') self._report_modes = [x for x in report_modes if x in REPORT_MODES] if not self._report_modes: raise ValueError('report_modes not a valid list of modes') def _get_report_modes(self): return self._report_modes #REPORT or TOOL or QUICKREPORT or GENERAL attributes def _set_category(self, category): if self._ptype not in [REPORT, TOOL, QUICKREPORT, VIEW, GENERAL]: raise ValueError('category may only be set for ' \ 'REPORT/TOOL/QUICKREPORT/VIEW/GENERAL plugins') self._category = category def _get_category(self): return self._category #REPORT OR TOOL attributes def _set_optionclass(self, optionclass): if not (self._ptype == REPORT or self.ptype == TOOL or self._ptype == DOCGEN): raise ValueError('optionclass may only be set for REPORT/TOOL/DOCGEN plugins') self._optionclass = optionclass def _get_optionclass(self): return self._optionclass #TOOL attributes def _set_toolclass(self, toolclass): if not self._ptype == TOOL: raise ValueError('toolclass may only be set for TOOL plugins') self._toolclass = toolclass def _get_toolclass(self): return self._toolclass def _set_tool_modes(self, tool_modes): if not self._ptype == TOOL: raise ValueError('tool_modes may only be set for TOOL plugins') if not isinstance(tool_modes, list): raise ValueError('tool_modes must be a list') self._tool_modes = [x for x in tool_modes if x in TOOL_MODES] if not self._tool_modes: raise ValueError('tool_modes not a valid list of modes') def _get_tool_modes(self): return self._tool_modes require_active = property(_get_require_active, _set_require_active) reportclass = property(_get_reportclass, _set_reportclass) report_modes = property(_get_report_modes, _set_report_modes) category = property(_get_category, _set_category) optionclass = property(_get_optionclass, _set_optionclass) toolclass = property(_get_toolclass, _set_toolclass) tool_modes = property(_get_tool_modes, _set_tool_modes) #DOCGEN attributes def _set_paper(self, paper): if not self._ptype == DOCGEN: raise ValueError('paper may only be set for DOCGEN plugins') if not isinstance(paper, bool): raise ValueError('Plugin must have paper=True or False') self._paper = paper def _get_paper(self): return self._paper def _set_style(self, style): if not self._ptype == DOCGEN: raise ValueError('style may only be set for DOCGEN plugins') if not isinstance(style, bool): raise ValueError('Plugin must have style=True or False') self._style = style def _get_style(self): return self._style def _set_extension(self, extension): if not (self._ptype == DOCGEN or self._ptype == EXPORT or self._ptype == IMPORT): raise ValueError('extension may only be set for DOCGEN/EXPORT/'\ 'IMPORT plugins') self._extension = extension def _get_extension(self): return self._extension paper = property(_get_paper, _set_paper) style = property(_get_style, _set_style) extension = property(_get_extension, _set_extension) #QUICKREPORT attributes def _set_runfunc(self, runfunc): if not self._ptype == QUICKREPORT: raise ValueError('runfunc may only be set for QUICKREPORT plugins') self._runfunc = runfunc def _get_runfunc(self): return self._runfunc runfunc = property(_get_runfunc, _set_runfunc) #MAPSERVICE attributes def _set_mapservice(self, mapservice): if not self._ptype == MAPSERVICE: raise ValueError('mapservice may only be set for MAPSERVICE plugins') self._mapservice = mapservice def _get_mapservice(self): return self._mapservice mapservice = property(_get_mapservice, _set_mapservice) #EXPORT attributes def _set_export_function(self, export_function): if not self._ptype == EXPORT: raise ValueError('export_function may only be set for EXPORT plugins') self._export_function = export_function def _get_export_function(self): return self._export_function def _set_export_options(self, export_options): if not self._ptype == EXPORT: raise ValueError('export_options may only be set for EXPORT plugins') self._export_options = export_options def _get_export_options(self): return self._export_options def _set_export_options_title(self, export_options_title): if not self._ptype == EXPORT: raise ValueError('export_options_title may only be set for EXPORT plugins') self._export_options_title = export_options_title def _get_export_options_title(self): return self._export_options_title export_function = property(_get_export_function, _set_export_function) export_options = property(_get_export_options, _set_export_options) export_options_title = property(_get_export_options_title, _set_export_options_title) #IMPORT attributes def _set_import_function(self, import_function): if not self._ptype == IMPORT: raise ValueError('import_function may only be set for IMPORT plugins') self._import_function = import_function def _get_import_function(self): return self._import_function import_function = property(_get_import_function, _set_import_function) #GRAMPLET attributes def _set_gramplet(self, gramplet): if not self._ptype == GRAMPLET: raise ValueError('gramplet may only be set for GRAMPLET plugins') self._gramplet = gramplet def _get_gramplet(self): return self._gramplet def _set_height(self, height): if not self._ptype == GRAMPLET: raise ValueError('height may only be set for GRAMPLET plugins') if not isinstance(height, int): raise ValueError('Plugin must have height an integer') self._height = height def _get_height(self): return self._height def _set_detached_height(self, detached_height): if not self._ptype == GRAMPLET: raise ValueError('detached_height may only be set for GRAMPLET plugins') if not isinstance(detached_height, int): raise ValueError('Plugin must have detached_height an integer') self._detached_height = detached_height def _get_detached_height(self): return self._detached_height def _set_detached_width(self, detached_width): if not self._ptype == GRAMPLET: raise ValueError('detached_width may only be set for GRAMPLET plugins') if not isinstance(detached_width, int): raise ValueError('Plugin must have detached_width an integer') self._detached_width = detached_width def _get_detached_width(self): return self._detached_width def _set_expand(self, expand): if not self._ptype == GRAMPLET: raise ValueError('expand may only be set for GRAMPLET plugins') if not isinstance(expand, bool): raise ValueError('Plugin must have expand as a bool') self._expand = expand def _get_expand(self): return self._expand def _set_gramplet_title(self, gramplet_title): if not self._ptype == GRAMPLET: raise ValueError('gramplet_title may only be set for GRAMPLET plugins') if not isinstance(gramplet_title, str): raise ValueError('gramplet_title is type %s, string or unicode required' % type(gramplet_title)) self._gramplet_title = gramplet_title def _get_gramplet_title(self): return self._gramplet_title def _set_help_url(self, help_url): if not self._ptype == GRAMPLET: raise ValueError('help_url may only be set for GRAMPLET plugins') self._help_url = help_url def _get_help_url(self): return self._help_url def _set_navtypes(self, navtypes): if not self._ptype == GRAMPLET: raise ValueError('navtypes may only be set for GRAMPLET plugins') self._navtypes = navtypes def _get_navtypes(self): return self._navtypes def _set_orientation(self, orientation): if not self._ptype == GRAMPLET: raise ValueError('orientation may only be set for GRAMPLET plugins') self._orientation = orientation def _get_orientation(self): return self._orientation gramplet = property(_get_gramplet, _set_gramplet) height = property(_get_height, _set_height) detached_height = property(_get_detached_height, _set_detached_height) detached_width = property(_get_detached_width, _set_detached_width) expand = property(_get_expand, _set_expand) gramplet_title = property(_get_gramplet_title, _set_gramplet_title) navtypes = property(_get_navtypes, _set_navtypes) orientation = property(_get_orientation, _set_orientation) help_url = property(_get_help_url, _set_help_url) def _set_viewclass(self, viewclass): if not self._ptype == VIEW: raise ValueError('viewclass may only be set for VIEW plugins') self._viewclass = viewclass def _get_viewclass(self): return self._viewclass def _set_stock_icon(self, stock_icon): if not self._ptype == VIEW: raise ValueError('stock_icon may only be set for VIEW plugins') self._stock_icon = stock_icon def _get_stock_icon(self): return self._stock_icon viewclass = property(_get_viewclass, _set_viewclass) stock_icon = property(_get_stock_icon, _set_stock_icon) #SIDEBAR attributes def _set_sidebarclass(self, sidebarclass): if not self._ptype == SIDEBAR: raise ValueError('sidebarclass may only be set for SIDEBAR plugins') self._sidebarclass = sidebarclass def _get_sidebarclass(self): return self._sidebarclass def _set_menu_label(self, menu_label): if not self._ptype == SIDEBAR: raise ValueError('menu_label may only be set for SIDEBAR plugins') self._menu_label = menu_label def _get_menu_label(self): return self._menu_label sidebarclass = property(_get_sidebarclass, _set_sidebarclass) menu_label = property(_get_menu_label, _set_menu_label) #VIEW and SIDEBAR attributes def _set_order(self, order): if not self._ptype in (VIEW, SIDEBAR): raise ValueError('order may only be set for VIEW and SIDEBAR plugins') self._order = order def _get_order(self): return self._order order = property(_get_order, _set_order) #DATABASE attributes def _set_databaseclass(self, databaseclass): if not self._ptype == DATABASE: raise ValueError('databaseclass may only be set for DATABASE plugins') self._databaseclass = databaseclass def _get_databaseclass(self): return self._databaseclass def _set_reset_system(self, reset_system): if not self._ptype == DATABASE: raise ValueError('reset_system may only be set for DATABASE plugins') self._reset_system = reset_system def _get_reset_system(self): return self._reset_system databaseclass = property(_get_databaseclass, _set_databaseclass) reset_system = property(_get_reset_system, _set_reset_system) #GENERAL attr def _set_data(self, data): if not self._ptype in (GENERAL,): raise ValueError('data may only be set for GENERAL plugins') self._data = data def _get_data(self): return self._data def _set_process(self, process): if not self._ptype in (GENERAL,): raise ValueError('process may only be set for GENERAL plugins') self._process = process def _get_process(self): return self._process data = property(_get_data, _set_data) process = property(_get_process, _set_process) def newplugin(): """ Function to create a new plugindata object, add it to list of registered plugins :returns: a newly created PluginData which is already part of the register """ gpr = PluginRegister.get_instance() pgd = PluginData() gpr.add_plugindata(pgd) return pgd def register(ptype, **kwargs): """ Convenience function to register a new plugin using a dictionary as input. The register functions will call newplugin() function, and use the dictionary kwargs to assign data to the PluginData newplugin() created, as in: plugindata.key = data :param ptype: the plugin type, one of REPORT, TOOL, ... :param kwargs: dictionary with keys attributes of the plugin, and data the value :returns: a newly created PluginData which is already part of the register and which has kwargs assigned as attributes """ plg = newplugin() plg.ptype = ptype for prop in kwargs: #check it is a valid attribute with getattr getattr(plg, prop) #set the value setattr(plg, prop, kwargs[prop]) return plg def make_environment(**kwargs): env = { 'newplugin': newplugin, 'register': register, 'STABLE': STABLE, 'UNSTABLE': UNSTABLE, 'REPORT': REPORT, 'QUICKREPORT': QUICKREPORT, 'TOOL': TOOL, 'IMPORT': IMPORT, 'EXPORT': EXPORT, 'DOCGEN': DOCGEN, 'GENERAL': GENERAL, 'MAPSERVICE': MAPSERVICE, 'VIEW': VIEW, 'RELCALC': RELCALC, 'GRAMPLET': GRAMPLET, 'SIDEBAR': SIDEBAR, 'CATEGORY_TEXT': CATEGORY_TEXT, 'CATEGORY_DRAW': CATEGORY_DRAW, 'CATEGORY_CODE': CATEGORY_CODE, 'CATEGORY_WEB': CATEGORY_WEB, 'CATEGORY_BOOK': CATEGORY_BOOK, 'CATEGORY_GRAPHVIZ': CATEGORY_GRAPHVIZ, 'TOOL_DEBUG': TOOL_DEBUG, 'TOOL_ANAL': TOOL_ANAL, 'TOOL_DBPROC': TOOL_DBPROC, 'TOOL_DBFIX': TOOL_DBFIX, 'TOOL_REVCTL': TOOL_REVCTL, 'TOOL_UTILS': TOOL_UTILS, 'CATEGORY_QR_MISC': CATEGORY_QR_MISC, 'CATEGORY_QR_PERSON': CATEGORY_QR_PERSON, 'CATEGORY_QR_FAMILY': CATEGORY_QR_FAMILY, 'CATEGORY_QR_EVENT': CATEGORY_QR_EVENT, 'CATEGORY_QR_SOURCE': CATEGORY_QR_SOURCE, 'CATEGORY_QR_CITATION': CATEGORY_QR_CITATION, 'CATEGORY_QR_SOURCE_OR_CITATION': CATEGORY_QR_SOURCE_OR_CITATION, 'CATEGORY_QR_PLACE': CATEGORY_QR_PLACE, 'CATEGORY_QR_MEDIA': CATEGORY_QR_MEDIA, 'CATEGORY_QR_REPOSITORY': CATEGORY_QR_REPOSITORY, 'CATEGORY_QR_NOTE': CATEGORY_QR_NOTE, 'CATEGORY_QR_DATE': CATEGORY_QR_DATE, 'REPORT_MODE_GUI': REPORT_MODE_GUI, 'REPORT_MODE_BKI': REPORT_MODE_BKI, 'REPORT_MODE_CLI': REPORT_MODE_CLI, 'TOOL_MODE_GUI': TOOL_MODE_GUI, 'TOOL_MODE_CLI': TOOL_MODE_CLI, 'DATABASE': DATABASE, 'GRAMPSVERSION': GRAMPSVERSION, 'START': START, 'END': END, 'IMAGE_DIR': IMAGE_DIR, } env.update(kwargs) return env #------------------------------------------------------------------------- # # PluginRegister # #------------------------------------------------------------------------- class PluginRegister: """ PluginRegister is a Singleton which holds plugin data .. attribute : stable_only Bool, include stable plugins only or not. Default True """ __instance = None def get_instance(): """ Use this function to get the instance of the PluginRegister """ if PluginRegister.__instance is None: PluginRegister.__instance = 1 # Set to 1 for __init__() PluginRegister.__instance = PluginRegister() return PluginRegister.__instance get_instance = staticmethod(get_instance) def __init__(self): """ This function should only be run once by get_instance() """ if PluginRegister.__instance is not 1: raise Exception("This class is a singleton. " "Use the get_instance() method") self.stable_only = True if __debug__: self.stable_only = False self.__plugindata = [] self.__id_to_pdata = {} def add_plugindata(self, plugindata): """ This is used to add an entry to the registration list. The way it is used, this entry is not yet filled in, so we cannot use the id to add to the __id_to_pdata dict at this time. """ self.__plugindata.append(plugindata) def scan_dir(self, dir, filenames, uistate=None): """ The dir name will be scanned for plugin registration code, which will be loaded in :class:`PluginData` objects if they satisfy some checks. :returns: A list with :class:`PluginData` objects """ # if the directory does not exist, do nothing if not (os.path.isdir(dir) or os.path.islink(dir)): return [] ext = r".gpr.py" extlen = -len(ext) pymod = re.compile(r"^(.*)\.py$") for filename in filenames: if not filename[extlen:] == ext: continue lenpd = len(self.__plugindata) full_filename = os.path.join(dir, filename) try: with open(full_filename, "r", encoding='utf-8') as fd: stream = fd.read() except Exception as msg: print(_('ERROR: Failed reading plugin registration %(filename)s') % \ {'filename' : filename}) print(msg) continue if os.path.exists(os.path.join(os.path.dirname(full_filename), 'locale')): try: local_gettext = glocale.get_addon_translator(full_filename).gettext except ValueError: print(_('WARNING: Plugin %(plugin_name)s has no translation' ' for any of your configured languages, using US' ' English instead') % {'plugin_name' : filename.split('.')[0] }) local_gettext = glocale.translation.gettext else: local_gettext = glocale.translation.gettext try: exec (compile(stream, filename, 'exec'), make_environment(_=local_gettext), {'uistate': uistate}) for pdata in self.__plugindata[lenpd:]: # should not be duplicate IDs in different plugins assert pdata.id not in self.__id_to_pdata # if pdata.id in self.__id_to_pdata: # print("Error: %s is duplicated!" % pdata.id) self.__id_to_pdata[pdata.id] = pdata except ValueError as msg: print(_('ERROR: Failed reading plugin registration %(filename)s') % \ {'filename' : filename}) print(msg) self.__plugindata = self.__plugindata[:lenpd] except: print(_('ERROR: Failed reading plugin registration %(filename)s') % \ {'filename' : filename}) print("".join(traceback.format_exception(*sys.exc_info()))) self.__plugindata = self.__plugindata[:lenpd] #check if: # 1. plugin exists, if not remove, otherwise set module name # 2. plugin not stable, if stable_only=True, remove # 3. TOOL_DEBUG only if __debug__ True rmlist = [] ind = lenpd-1 for plugin in self.__plugindata[lenpd:]: #LOG.warning("\nPlugin scanned %s at registration", plugin.id) ind += 1 plugin.directory = dir if not valid_plugin_version(plugin.gramps_target_version): print(_('ERROR: Plugin file %(filename)s has a version of ' '"%(gramps_target_version)s" which is invalid for Gramps ' '"%(gramps_version)s".' % {'filename': os.path.join(dir, plugin.fname), 'gramps_version': GRAMPSVERSION, 'gramps_target_version': plugin.gramps_target_version,} )) rmlist.append(ind) continue if not plugin.status == STABLE and self.stable_only: rmlist.append(ind) continue if plugin.ptype == TOOL and plugin.category == TOOL_DEBUG \ and not __debug__: rmlist.append(ind) continue if plugin.fname is None: continue match = pymod.match(plugin.fname) if not match: rmlist.append(ind) print(_('ERROR: Wrong python file %(filename)s in register file ' '%(regfile)s') % { 'filename': os.path.join(dir, plugin.fname), 'regfile': os.path.join(dir, filename) }) continue if not os.path.isfile(os.path.join(dir, plugin.fname)): rmlist.append(ind) print(_('ERROR: Python file %(filename)s in register file ' '%(regfile)s does not exist') % { 'filename': os.path.join(dir, plugin.fname), 'regfile': os.path.join(dir, filename) }) continue module = match.groups()[0] plugin.mod_name = module plugin.fpath = dir #LOG.warning("\nPlugin added %s at registration", plugin.id) rmlist.reverse() for ind in rmlist: del self.__id_to_pdata[self.__plugindata[ind].id] del self.__plugindata[ind] def get_plugin(self, id): """ Return the :class:`PluginData` for the plugin with id """ assert(len(self.__id_to_pdata) == len(self.__plugindata)) # if len(self.__id_to_pdata) != len(self.__plugindata): # print(len(self.__id_to_pdata), len(self.__plugindata)) return self.__id_to_pdata.get(id, None) def type_plugins(self, ptype): """ Return a list of :class:`PluginData` that are of type ptype """ return [self.get_plugin(id) for id in set([x.id for x in self.__plugindata if x.ptype == ptype])] def report_plugins(self, gui=True): """ Return a list of gui or cli :class:`PluginData` that are of type REPORT :param gui: bool, if True then gui plugin, otherwise cli plugin """ if gui: return [x for x in self.type_plugins(REPORT) if REPORT_MODE_GUI in x.report_modes] else: return [x for x in self.type_plugins(REPORT) if REPORT_MODE_CLI in x.report_modes] def tool_plugins(self, gui=True): """ Return a list of :class:`PluginData` that are of type TOOL """ if gui: return [x for x in self.type_plugins(TOOL) if TOOL_MODE_GUI in x.tool_modes] else: return [x for x in self.type_plugins(TOOL) if TOOL_MODE_CLI in x.tool_modes] def bookitem_plugins(self): """ Return a list of REPORT :class:`PluginData` that are can be used as bookitem """ return [x for x in self.type_plugins(REPORT) if REPORT_MODE_BKI in x.report_modes] def quickreport_plugins(self): """ Return a list of :class:`PluginData` that are of type QUICKREPORT """ return self.type_plugins(QUICKREPORT) def import_plugins(self): """ Return a list of :class:`PluginData` that are of type IMPORT """ return self.type_plugins(IMPORT) def export_plugins(self): """ Return a list of :class:`PluginData` that are of type EXPORT """ return self.type_plugins(EXPORT) def docgen_plugins(self): """ Return a list of :class:`PluginData` that are of type DOCGEN """ return self.type_plugins(DOCGEN) def general_plugins(self, category=None): """ Return a list of :class:`PluginData` that are of type GENERAL """ plugins = self.type_plugins(GENERAL) if category: return [plugin for plugin in plugins if plugin.category == category] return plugins def mapservice_plugins(self): """ Return a list of :class:`PluginData` that are of type MAPSERVICE """ return self.type_plugins(MAPSERVICE) def view_plugins(self): """ Return a list of :class:`PluginData` that are of type VIEW """ return self.type_plugins(VIEW) def relcalc_plugins(self): """ Return a list of :class:`PluginData` that are of type RELCALC """ return self.type_plugins(RELCALC) def gramplet_plugins(self): """ Return a list of :class:`PluginData` that are of type GRAMPLET """ return self.type_plugins(GRAMPLET) def sidebar_plugins(self): """ Return a list of :class:`PluginData` that are of type SIDEBAR """ return self.type_plugins(SIDEBAR) def database_plugins(self): """ Return a list of :class:`PluginData` that are of type DATABASE """ return self.type_plugins(DATABASE) def filter_load_on_reg(self): """ Return a list of :class:`PluginData` that have load_on_reg == True """ return [self.get_plugin(id) for id in set([x.id for x in self.__plugindata if x.load_on_reg == True])]
gpl-2.0
iglootools/genconf
genconf/filegenerator/_filegenerator.py
2
2425
""" Copyright 2011 Sami Dalouche Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import codecs from genconf.filegenerator._defaulteventlistener import DefaultEventListener from genconf.filegenerator._defaulterrorlistener import DefaultErrorListener from genconf.manifest import TemplateNotFoundException, TemplateProcessingException class FileGenerator(object): def __init__(self, template_loader, targetdir): assert template_loader is not None, "template_loader is required" assert targetdir is not None, "targetdir is required" self._template_loader = template_loader self._targetdir = targetdir def generate_files(self, manifest, error_listener=DefaultErrorListener(), event_listener=DefaultEventListener()): profiles = manifest.concrete_profiles() for p in profiles: event_listener.on_before_profile(p) for f in p.output_files: filename = os.path.join(self._targetdir, f.target_path) event_listener.on_before_file_update(filename) try: directory = os.path.dirname(filename) if not os.path.exists(directory): os.makedirs(directory) content = f.render(self._template_loader) with codecs.open(filename, "wb", encoding="utf-8") as f: f.write(content) event_listener.on_after_file_update(filename, content) except TemplateNotFoundException as e: error_listener.on_template_not_found(e) except TemplateProcessingException as e: error_listener.on_template_processing_error(e) except Exception as e: error_listener.on_write_error(filename, e) event_listener.on_after_profile(p)
apache-2.0
shakalaca/ASUS_ZenFone_ZE500CL
linux/kernel/tools/perf/util/setup.py
2079
1438
#!/usr/bin/python2 from distutils.core import setup, Extension from os import getenv from distutils.command.build_ext import build_ext as _build_ext from distutils.command.install_lib import install_lib as _install_lib class build_ext(_build_ext): def finalize_options(self): _build_ext.finalize_options(self) self.build_lib = build_lib self.build_temp = build_tmp class install_lib(_install_lib): def finalize_options(self): _install_lib.finalize_options(self) self.build_dir = build_lib cflags = ['-fno-strict-aliasing', '-Wno-write-strings'] cflags += getenv('CFLAGS', '').split() build_lib = getenv('PYTHON_EXTBUILD_LIB') build_tmp = getenv('PYTHON_EXTBUILD_TMP') libtraceevent = getenv('LIBTRACEEVENT') liblk = getenv('LIBLK') ext_sources = [f.strip() for f in file('util/python-ext-sources') if len(f.strip()) > 0 and f[0] != '#'] perf = Extension('perf', sources = ext_sources, include_dirs = ['util/include'], extra_compile_args = cflags, extra_objects = [libtraceevent, liblk], ) setup(name='perf', version='0.1', description='Interface with the Linux profiling infrastructure', author='Arnaldo Carvalho de Melo', author_email='acme@redhat.com', license='GPLv2', url='http://perf.wiki.kernel.org', ext_modules=[perf], cmdclass={'build_ext': build_ext, 'install_lib': install_lib})
gpl-2.0
wgcv/SWW-Crashphone
lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py
63
7419
""" Management utility to create superusers. """ from __future__ import unicode_literals import getpass import sys from optparse import make_option from django.contrib.auth import get_user_model from django.contrib.auth.management import get_default_username from django.core import exceptions from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS from django.utils.encoding import force_str from django.utils.six.moves import input from django.utils.text import capfirst class NotRunningInTTYException(Exception): pass class Command(BaseCommand): def __init__(self, *args, **kwargs): # Options are defined in an __init__ method to support swapping out # custom user models in tests. super(Command, self).__init__(*args, **kwargs) self.UserModel = get_user_model() self.username_field = self.UserModel._meta.get_field(self.UserModel.USERNAME_FIELD) self.option_list = BaseCommand.option_list + ( make_option('--%s' % self.UserModel.USERNAME_FIELD, dest=self.UserModel.USERNAME_FIELD, default=None, help='Specifies the login for the superuser.'), make_option('--noinput', action='store_false', dest='interactive', default=True, help=('Tells Django to NOT prompt the user for input of any kind. ' 'You must use --%s with --noinput, along with an option for ' 'any other required field. Superusers created with --noinput will ' ' not be able to log in until they\'re given a valid password.' % self.UserModel.USERNAME_FIELD)), make_option('--database', action='store', dest='database', default=DEFAULT_DB_ALIAS, help='Specifies the database to use. Default is "default".'), ) + tuple( make_option('--%s' % field, dest=field, default=None, help='Specifies the %s for the superuser.' % field) for field in self.UserModel.REQUIRED_FIELDS ) option_list = BaseCommand.option_list help = 'Used to create a superuser.' def execute(self, *args, **options): self.stdin = options.get('stdin', sys.stdin) # Used for testing return super(Command, self).execute(*args, **options) def handle(self, *args, **options): username = options.get(self.UserModel.USERNAME_FIELD, None) interactive = options.get('interactive') verbosity = int(options.get('verbosity', 1)) database = options.get('database') # If not provided, create the user with an unusable password password = None user_data = {} # Do quick and dirty validation if --noinput if not interactive: try: if not username: raise CommandError("You must use --%s with --noinput." % self.UserModel.USERNAME_FIELD) username = self.username_field.clean(username, None) for field_name in self.UserModel.REQUIRED_FIELDS: if options.get(field_name): field = self.UserModel._meta.get_field(field_name) user_data[field_name] = field.clean(options[field_name], None) else: raise CommandError("You must use --%s with --noinput." % field_name) except exceptions.ValidationError as e: raise CommandError('; '.join(e.messages)) else: # Prompt for username/password, and any other required fields. # Enclose this whole thing in a try/except to trap for a # keyboard interrupt and exit gracefully. default_username = get_default_username() try: if hasattr(self.stdin, 'isatty') and not self.stdin.isatty(): raise NotRunningInTTYException("Not running in a TTY") # Get a username verbose_field_name = self.username_field.verbose_name while username is None: if not username: input_msg = capfirst(verbose_field_name) if default_username: input_msg = "%s (leave blank to use '%s')" % ( input_msg, default_username) raw_value = input(force_str('%s: ' % input_msg)) if default_username and raw_value == '': raw_value = default_username try: username = self.username_field.clean(raw_value, None) except exceptions.ValidationError as e: self.stderr.write("Error: %s" % '; '.join(e.messages)) username = None continue try: self.UserModel._default_manager.db_manager(database).get_by_natural_key(username) except self.UserModel.DoesNotExist: pass else: self.stderr.write("Error: That %s is already taken." % verbose_field_name) username = None for field_name in self.UserModel.REQUIRED_FIELDS: field = self.UserModel._meta.get_field(field_name) user_data[field_name] = options.get(field_name) while user_data[field_name] is None: raw_value = input(force_str('%s: ' % capfirst(field.verbose_name))) try: user_data[field_name] = field.clean(raw_value, None) except exceptions.ValidationError as e: self.stderr.write("Error: %s" % '; '.join(e.messages)) user_data[field_name] = None # Get a password while password is None: if not password: password = getpass.getpass() password2 = getpass.getpass(force_str('Password (again): ')) if password != password2: self.stderr.write("Error: Your passwords didn't match.") password = None continue if password.strip() == '': self.stderr.write("Error: Blank passwords aren't allowed.") password = None continue except KeyboardInterrupt: self.stderr.write("\nOperation cancelled.") sys.exit(1) except NotRunningInTTYException: self.stdout.write( "Superuser creation skipped due to not running in a TTY. " "You can run `manage.py createsuperuser` in your project " "to create one manually." ) if username: user_data[self.UserModel.USERNAME_FIELD] = username user_data['password'] = password self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) if verbosity >= 1: self.stdout.write("Superuser created successfully.")
apache-2.0
redbear/micropython
tests/extmod/ure1.py
35
1169
try: import ure as re except ImportError: import re r = re.compile(".+") m = r.match("abc") print(m.group(0)) try: m.group(1) except IndexError: print("IndexError") r = re.compile("(.+)1") m = r.match("xyz781") print(m.group(0)) print(m.group(1)) try: m.group(2) except IndexError: print("IndexError") r = re.compile("[a-cu-z]") m = r.match("a") print(m.group(0)) m = r.match("z") print(m.group(0)) m = r.match("d") print(m) m = r.match("A") print(m) print("===") r = re.compile("[^a-cu-z]") m = r.match("a") print(m) m = r.match("z") print(m) m = r.match("d") print(m.group(0)) m = r.match("A") print(m.group(0)) r = re.compile("o+") m = r.search("foobar") print(m.group(0)) try: m.group(1) except IndexError: print("IndexError") m = re.match(".*", "foo") print(m.group(0)) m = re.search("w.r", "hello world") print(m.group(0)) m = re.match('a+?', 'ab'); print(m.group(0)) m = re.match('a*?', 'ab'); print(m.group(0)) m = re.match('^ab$', 'ab'); print(m.group(0)) m = re.match('a|b', 'b'); print(m.group(0)) m = re.match('a|b|c', 'c'); print(m.group(0)) try: re.compile("*") except: print("Caught invalid regex")
mit