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
timm/timmnix
pypy3-v5.5.0-linux64/lib-python/3/encodings/tis_620.py
272
12300
""" Python Character Mapping Codec tis_620 generated from 'python-mappings/TIS-620.TXT' with gencodec.py. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_table) def decode(self,input,errors='strict'): return codecs.charmap_decode(input,errors,decoding_table) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.charmap_encode(input,self.errors,encoding_table)[0] class IncrementalDecoder(codecs.IncrementalDecoder): def decode(self, input, final=False): return codecs.charmap_decode(input,self.errors,decoding_table)[0] class StreamWriter(Codec,codecs.StreamWriter): pass class StreamReader(Codec,codecs.StreamReader): pass ### encodings module API def getregentry(): return codecs.CodecInfo( name='tis-620', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Table decoding_table = ( '\x00' # 0x00 -> NULL '\x01' # 0x01 -> START OF HEADING '\x02' # 0x02 -> START OF TEXT '\x03' # 0x03 -> END OF TEXT '\x04' # 0x04 -> END OF TRANSMISSION '\x05' # 0x05 -> ENQUIRY '\x06' # 0x06 -> ACKNOWLEDGE '\x07' # 0x07 -> BELL '\x08' # 0x08 -> BACKSPACE '\t' # 0x09 -> HORIZONTAL TABULATION '\n' # 0x0A -> LINE FEED '\x0b' # 0x0B -> VERTICAL TABULATION '\x0c' # 0x0C -> FORM FEED '\r' # 0x0D -> CARRIAGE RETURN '\x0e' # 0x0E -> SHIFT OUT '\x0f' # 0x0F -> SHIFT IN '\x10' # 0x10 -> DATA LINK ESCAPE '\x11' # 0x11 -> DEVICE CONTROL ONE '\x12' # 0x12 -> DEVICE CONTROL TWO '\x13' # 0x13 -> DEVICE CONTROL THREE '\x14' # 0x14 -> DEVICE CONTROL FOUR '\x15' # 0x15 -> NEGATIVE ACKNOWLEDGE '\x16' # 0x16 -> SYNCHRONOUS IDLE '\x17' # 0x17 -> END OF TRANSMISSION BLOCK '\x18' # 0x18 -> CANCEL '\x19' # 0x19 -> END OF MEDIUM '\x1a' # 0x1A -> SUBSTITUTE '\x1b' # 0x1B -> ESCAPE '\x1c' # 0x1C -> FILE SEPARATOR '\x1d' # 0x1D -> GROUP SEPARATOR '\x1e' # 0x1E -> RECORD SEPARATOR '\x1f' # 0x1F -> UNIT SEPARATOR ' ' # 0x20 -> SPACE '!' # 0x21 -> EXCLAMATION MARK '"' # 0x22 -> QUOTATION MARK '#' # 0x23 -> NUMBER SIGN '$' # 0x24 -> DOLLAR SIGN '%' # 0x25 -> PERCENT SIGN '&' # 0x26 -> AMPERSAND "'" # 0x27 -> APOSTROPHE '(' # 0x28 -> LEFT PARENTHESIS ')' # 0x29 -> RIGHT PARENTHESIS '*' # 0x2A -> ASTERISK '+' # 0x2B -> PLUS SIGN ',' # 0x2C -> COMMA '-' # 0x2D -> HYPHEN-MINUS '.' # 0x2E -> FULL STOP '/' # 0x2F -> SOLIDUS '0' # 0x30 -> DIGIT ZERO '1' # 0x31 -> DIGIT ONE '2' # 0x32 -> DIGIT TWO '3' # 0x33 -> DIGIT THREE '4' # 0x34 -> DIGIT FOUR '5' # 0x35 -> DIGIT FIVE '6' # 0x36 -> DIGIT SIX '7' # 0x37 -> DIGIT SEVEN '8' # 0x38 -> DIGIT EIGHT '9' # 0x39 -> DIGIT NINE ':' # 0x3A -> COLON ';' # 0x3B -> SEMICOLON '<' # 0x3C -> LESS-THAN SIGN '=' # 0x3D -> EQUALS SIGN '>' # 0x3E -> GREATER-THAN SIGN '?' # 0x3F -> QUESTION MARK '@' # 0x40 -> COMMERCIAL AT 'A' # 0x41 -> LATIN CAPITAL LETTER A 'B' # 0x42 -> LATIN CAPITAL LETTER B 'C' # 0x43 -> LATIN CAPITAL LETTER C 'D' # 0x44 -> LATIN CAPITAL LETTER D 'E' # 0x45 -> LATIN CAPITAL LETTER E 'F' # 0x46 -> LATIN CAPITAL LETTER F 'G' # 0x47 -> LATIN CAPITAL LETTER G 'H' # 0x48 -> LATIN CAPITAL LETTER H 'I' # 0x49 -> LATIN CAPITAL LETTER I 'J' # 0x4A -> LATIN CAPITAL LETTER J 'K' # 0x4B -> LATIN CAPITAL LETTER K 'L' # 0x4C -> LATIN CAPITAL LETTER L 'M' # 0x4D -> LATIN CAPITAL LETTER M 'N' # 0x4E -> LATIN CAPITAL LETTER N 'O' # 0x4F -> LATIN CAPITAL LETTER O 'P' # 0x50 -> LATIN CAPITAL LETTER P 'Q' # 0x51 -> LATIN CAPITAL LETTER Q 'R' # 0x52 -> LATIN CAPITAL LETTER R 'S' # 0x53 -> LATIN CAPITAL LETTER S 'T' # 0x54 -> LATIN CAPITAL LETTER T 'U' # 0x55 -> LATIN CAPITAL LETTER U 'V' # 0x56 -> LATIN CAPITAL LETTER V 'W' # 0x57 -> LATIN CAPITAL LETTER W 'X' # 0x58 -> LATIN CAPITAL LETTER X 'Y' # 0x59 -> LATIN CAPITAL LETTER Y 'Z' # 0x5A -> LATIN CAPITAL LETTER Z '[' # 0x5B -> LEFT SQUARE BRACKET '\\' # 0x5C -> REVERSE SOLIDUS ']' # 0x5D -> RIGHT SQUARE BRACKET '^' # 0x5E -> CIRCUMFLEX ACCENT '_' # 0x5F -> LOW LINE '`' # 0x60 -> GRAVE ACCENT 'a' # 0x61 -> LATIN SMALL LETTER A 'b' # 0x62 -> LATIN SMALL LETTER B 'c' # 0x63 -> LATIN SMALL LETTER C 'd' # 0x64 -> LATIN SMALL LETTER D 'e' # 0x65 -> LATIN SMALL LETTER E 'f' # 0x66 -> LATIN SMALL LETTER F 'g' # 0x67 -> LATIN SMALL LETTER G 'h' # 0x68 -> LATIN SMALL LETTER H 'i' # 0x69 -> LATIN SMALL LETTER I 'j' # 0x6A -> LATIN SMALL LETTER J 'k' # 0x6B -> LATIN SMALL LETTER K 'l' # 0x6C -> LATIN SMALL LETTER L 'm' # 0x6D -> LATIN SMALL LETTER M 'n' # 0x6E -> LATIN SMALL LETTER N 'o' # 0x6F -> LATIN SMALL LETTER O 'p' # 0x70 -> LATIN SMALL LETTER P 'q' # 0x71 -> LATIN SMALL LETTER Q 'r' # 0x72 -> LATIN SMALL LETTER R 's' # 0x73 -> LATIN SMALL LETTER S 't' # 0x74 -> LATIN SMALL LETTER T 'u' # 0x75 -> LATIN SMALL LETTER U 'v' # 0x76 -> LATIN SMALL LETTER V 'w' # 0x77 -> LATIN SMALL LETTER W 'x' # 0x78 -> LATIN SMALL LETTER X 'y' # 0x79 -> LATIN SMALL LETTER Y 'z' # 0x7A -> LATIN SMALL LETTER Z '{' # 0x7B -> LEFT CURLY BRACKET '|' # 0x7C -> VERTICAL LINE '}' # 0x7D -> RIGHT CURLY BRACKET '~' # 0x7E -> TILDE '\x7f' # 0x7F -> DELETE '\x80' # 0x80 -> <control> '\x81' # 0x81 -> <control> '\x82' # 0x82 -> <control> '\x83' # 0x83 -> <control> '\x84' # 0x84 -> <control> '\x85' # 0x85 -> <control> '\x86' # 0x86 -> <control> '\x87' # 0x87 -> <control> '\x88' # 0x88 -> <control> '\x89' # 0x89 -> <control> '\x8a' # 0x8A -> <control> '\x8b' # 0x8B -> <control> '\x8c' # 0x8C -> <control> '\x8d' # 0x8D -> <control> '\x8e' # 0x8E -> <control> '\x8f' # 0x8F -> <control> '\x90' # 0x90 -> <control> '\x91' # 0x91 -> <control> '\x92' # 0x92 -> <control> '\x93' # 0x93 -> <control> '\x94' # 0x94 -> <control> '\x95' # 0x95 -> <control> '\x96' # 0x96 -> <control> '\x97' # 0x97 -> <control> '\x98' # 0x98 -> <control> '\x99' # 0x99 -> <control> '\x9a' # 0x9A -> <control> '\x9b' # 0x9B -> <control> '\x9c' # 0x9C -> <control> '\x9d' # 0x9D -> <control> '\x9e' # 0x9E -> <control> '\x9f' # 0x9F -> <control> '\ufffe' '\u0e01' # 0xA1 -> THAI CHARACTER KO KAI '\u0e02' # 0xA2 -> THAI CHARACTER KHO KHAI '\u0e03' # 0xA3 -> THAI CHARACTER KHO KHUAT '\u0e04' # 0xA4 -> THAI CHARACTER KHO KHWAI '\u0e05' # 0xA5 -> THAI CHARACTER KHO KHON '\u0e06' # 0xA6 -> THAI CHARACTER KHO RAKHANG '\u0e07' # 0xA7 -> THAI CHARACTER NGO NGU '\u0e08' # 0xA8 -> THAI CHARACTER CHO CHAN '\u0e09' # 0xA9 -> THAI CHARACTER CHO CHING '\u0e0a' # 0xAA -> THAI CHARACTER CHO CHANG '\u0e0b' # 0xAB -> THAI CHARACTER SO SO '\u0e0c' # 0xAC -> THAI CHARACTER CHO CHOE '\u0e0d' # 0xAD -> THAI CHARACTER YO YING '\u0e0e' # 0xAE -> THAI CHARACTER DO CHADA '\u0e0f' # 0xAF -> THAI CHARACTER TO PATAK '\u0e10' # 0xB0 -> THAI CHARACTER THO THAN '\u0e11' # 0xB1 -> THAI CHARACTER THO NANGMONTHO '\u0e12' # 0xB2 -> THAI CHARACTER THO PHUTHAO '\u0e13' # 0xB3 -> THAI CHARACTER NO NEN '\u0e14' # 0xB4 -> THAI CHARACTER DO DEK '\u0e15' # 0xB5 -> THAI CHARACTER TO TAO '\u0e16' # 0xB6 -> THAI CHARACTER THO THUNG '\u0e17' # 0xB7 -> THAI CHARACTER THO THAHAN '\u0e18' # 0xB8 -> THAI CHARACTER THO THONG '\u0e19' # 0xB9 -> THAI CHARACTER NO NU '\u0e1a' # 0xBA -> THAI CHARACTER BO BAIMAI '\u0e1b' # 0xBB -> THAI CHARACTER PO PLA '\u0e1c' # 0xBC -> THAI CHARACTER PHO PHUNG '\u0e1d' # 0xBD -> THAI CHARACTER FO FA '\u0e1e' # 0xBE -> THAI CHARACTER PHO PHAN '\u0e1f' # 0xBF -> THAI CHARACTER FO FAN '\u0e20' # 0xC0 -> THAI CHARACTER PHO SAMPHAO '\u0e21' # 0xC1 -> THAI CHARACTER MO MA '\u0e22' # 0xC2 -> THAI CHARACTER YO YAK '\u0e23' # 0xC3 -> THAI CHARACTER RO RUA '\u0e24' # 0xC4 -> THAI CHARACTER RU '\u0e25' # 0xC5 -> THAI CHARACTER LO LING '\u0e26' # 0xC6 -> THAI CHARACTER LU '\u0e27' # 0xC7 -> THAI CHARACTER WO WAEN '\u0e28' # 0xC8 -> THAI CHARACTER SO SALA '\u0e29' # 0xC9 -> THAI CHARACTER SO RUSI '\u0e2a' # 0xCA -> THAI CHARACTER SO SUA '\u0e2b' # 0xCB -> THAI CHARACTER HO HIP '\u0e2c' # 0xCC -> THAI CHARACTER LO CHULA '\u0e2d' # 0xCD -> THAI CHARACTER O ANG '\u0e2e' # 0xCE -> THAI CHARACTER HO NOKHUK '\u0e2f' # 0xCF -> THAI CHARACTER PAIYANNOI '\u0e30' # 0xD0 -> THAI CHARACTER SARA A '\u0e31' # 0xD1 -> THAI CHARACTER MAI HAN-AKAT '\u0e32' # 0xD2 -> THAI CHARACTER SARA AA '\u0e33' # 0xD3 -> THAI CHARACTER SARA AM '\u0e34' # 0xD4 -> THAI CHARACTER SARA I '\u0e35' # 0xD5 -> THAI CHARACTER SARA II '\u0e36' # 0xD6 -> THAI CHARACTER SARA UE '\u0e37' # 0xD7 -> THAI CHARACTER SARA UEE '\u0e38' # 0xD8 -> THAI CHARACTER SARA U '\u0e39' # 0xD9 -> THAI CHARACTER SARA UU '\u0e3a' # 0xDA -> THAI CHARACTER PHINTHU '\ufffe' '\ufffe' '\ufffe' '\ufffe' '\u0e3f' # 0xDF -> THAI CURRENCY SYMBOL BAHT '\u0e40' # 0xE0 -> THAI CHARACTER SARA E '\u0e41' # 0xE1 -> THAI CHARACTER SARA AE '\u0e42' # 0xE2 -> THAI CHARACTER SARA O '\u0e43' # 0xE3 -> THAI CHARACTER SARA AI MAIMUAN '\u0e44' # 0xE4 -> THAI CHARACTER SARA AI MAIMALAI '\u0e45' # 0xE5 -> THAI CHARACTER LAKKHANGYAO '\u0e46' # 0xE6 -> THAI CHARACTER MAIYAMOK '\u0e47' # 0xE7 -> THAI CHARACTER MAITAIKHU '\u0e48' # 0xE8 -> THAI CHARACTER MAI EK '\u0e49' # 0xE9 -> THAI CHARACTER MAI THO '\u0e4a' # 0xEA -> THAI CHARACTER MAI TRI '\u0e4b' # 0xEB -> THAI CHARACTER MAI CHATTAWA '\u0e4c' # 0xEC -> THAI CHARACTER THANTHAKHAT '\u0e4d' # 0xED -> THAI CHARACTER NIKHAHIT '\u0e4e' # 0xEE -> THAI CHARACTER YAMAKKAN '\u0e4f' # 0xEF -> THAI CHARACTER FONGMAN '\u0e50' # 0xF0 -> THAI DIGIT ZERO '\u0e51' # 0xF1 -> THAI DIGIT ONE '\u0e52' # 0xF2 -> THAI DIGIT TWO '\u0e53' # 0xF3 -> THAI DIGIT THREE '\u0e54' # 0xF4 -> THAI DIGIT FOUR '\u0e55' # 0xF5 -> THAI DIGIT FIVE '\u0e56' # 0xF6 -> THAI DIGIT SIX '\u0e57' # 0xF7 -> THAI DIGIT SEVEN '\u0e58' # 0xF8 -> THAI DIGIT EIGHT '\u0e59' # 0xF9 -> THAI DIGIT NINE '\u0e5a' # 0xFA -> THAI CHARACTER ANGKHANKHU '\u0e5b' # 0xFB -> THAI CHARACTER KHOMUT '\ufffe' '\ufffe' '\ufffe' '\ufffe' ) ### Encoding table encoding_table=codecs.charmap_build(decoding_table)
mit
vhda/ctags
Test/simple.py
85
1037
"""A long string literal """ from bsddb import btopen # Public global constants VERSION = '1.2.0' # Flags for list() and children() ALL = 0xff KEY = 0x01 TREEID = 0x02 INDENT = 0x04 DATA = 0x08 # Used by dbtreedata class one: x = lambda x: x y = 0 def __init__(self, filename, pathsep='', treegap=64): """Another string literal""" def __private_function__(self, key, data): def public_function(self, key): class this_is_ignored: def _pack(self, i, s): '''this is''' """a""" '''string literal'''""" class inside_string: """ class so_is_this: def _test(test, code, outcome, exception): def ignored_function(): def more_nesting(): class deeply_nested(): def even_more(): @blah class this is seen??? @bleh def this also? good! if __name__ == '__main__': class two (one): def only(arg): # line continuation class\ three\ (A, B, C): def\ foo( x , y, z):
gpl-2.0
JAOSP/aosp_platform_external_chromium_org
native_client_sdk/src/build_tools/sdk_tools/command/info.py
160
1162
# 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. import command_common import logging import manifest_util def Info(manifest, bundle_names): valid_bundles, invalid_bundles = command_common.GetValidBundles(manifest, bundle_names) if invalid_bundles: logging.warn('Unknown bundle(s): %s\n' % (', '.join(invalid_bundles))) if not valid_bundles: logging.warn('No valid bundles given.') return for bundle_name in valid_bundles: bundle = manifest.GetBundle(bundle_name) print bundle.name for key in sorted(bundle.iterkeys()): value = bundle[key] if key == manifest_util.ARCHIVES_KEY: for archive in bundle.GetArchives(): print ' Archive:' if archive: for archive_key in sorted(archive.iterkeys()): print ' %s: %s' % (archive_key, archive[archive_key]) elif key not in (manifest_util.ARCHIVES_KEY, manifest_util.NAME_KEY): print ' %s: %s' % (key, value) print
bsd-3-clause
yafeunteun/wikipedia-spam-classifier
revscoring/revscoring/utilities/fit.py
1
2484
""" ``revscoring fit -h`` :: Fits a dependent (an extractable value like a Datasource or Feature) to observed data. These are often used along with bag-of-words methods to reduce the feature space prior to training and testing a model or to train a sub-model. Usage: fit -h | --help fit <dependent> <label> [--input=<path>] [--datasource-file=<path>] [--debug] Options: -h --help Prints this documentation <dependent> The classpath to `Dependent` that can be fit to observations <label> The label that should be predicted --input=<path> Path to a file containing observations [default: <stdin>] --datasource-file=<math> Path to a file for writing out the trained datasource [default: <stdout>] --debug Print debug logging. """ import logging import sys import docopt import yamlconf from ..dependencies import solve from .util import read_observations logger = logging.getLogger(__name__) def main(argv=None): args = docopt.docopt(__doc__, argv=argv) logging.basicConfig( level=logging.INFO if not args['--debug'] else logging.DEBUG, format='%(asctime)s %(levelname)s:%(name)s -- %(message)s' ) dependent = yamlconf.import_path(args['<dependent>']) label_name = args['<label>'] if args['--input'] == "<stdin>": observations = read_observations(sys.stdin) else: observations = read_observations(open(args['--input'])) logger.info("Reading observations...") value_labels = [ (list(solve(dependent.dependencies, cache=ob['cache'])), ob[label_name]) for ob in observations] logger.debug(" -- {0} observations gathered".format(len(value_labels))) if args['--datasource-file'] == "<stdout>": datasource_f = sys.stdout else: datasource_f = open(args['--datasource-file'], 'w') debug = args['--debug'] run(dependent, label_name, value_labels, datasource_f, debug) def run(dependent, label_name, value_labels, datasource_f, debug): logger.info("Fitting {0} ({1})".format(dependent, type(dependent))) dependent.fit(value_labels) logger.info("Writing fitted selector to {0}".format(datasource_f)) dependent.dump(datasource_f)
mit
indevgr/django
django/conf/locale/en_AU/formats.py
504
2117
# -*- encoding: utf-8 -*- # This file is distributed under the same license as the Django package. # from __future__ import unicode_literals # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = 'j M Y' # '25 Oct 2006' TIME_FORMAT = 'P' # '2:30 p.m.' DATETIME_FORMAT = 'j M Y, P' # '25 Oct 2006, 2:30 p.m.' YEAR_MONTH_FORMAT = 'F Y' # 'October 2006' MONTH_DAY_FORMAT = 'j F' # '25 October' SHORT_DATE_FORMAT = 'd/m/Y' # '25/10/2006' SHORT_DATETIME_FORMAT = 'd/m/Y P' # '25/10/2006 2:30 p.m.' FIRST_DAY_OF_WEEK = 0 # Sunday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ '%d/%m/%Y', '%d/%m/%y', # '25/10/2006', '25/10/06' # '%b %d %Y', '%b %d, %Y', # 'Oct 25 2006', 'Oct 25, 2006' # '%d %b %Y', '%d %b, %Y', # '25 Oct 2006', '25 Oct, 2006' # '%B %d %Y', '%B %d, %Y', # 'October 25 2006', 'October 25, 2006' # '%d %B %Y', '%d %B, %Y', # '25 October 2006', '25 October, 2006' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%d %H:%M:%S', # '2006-10-25 14:30:59' '%Y-%m-%d %H:%M:%S.%f', # '2006-10-25 14:30:59.000200' '%Y-%m-%d %H:%M', # '2006-10-25 14:30' '%Y-%m-%d', # '2006-10-25' '%d/%m/%Y %H:%M:%S', # '25/10/2006 14:30:59' '%d/%m/%Y %H:%M:%S.%f', # '25/10/2006 14:30:59.000200' '%d/%m/%Y %H:%M', # '25/10/2006 14:30' '%d/%m/%Y', # '25/10/2006' '%d/%m/%y %H:%M:%S', # '25/10/06 14:30:59' '%d/%m/%y %H:%M:%S.%f', # '25/10/06 14:30:59.000200' '%d/%m/%y %H:%M', # '25/10/06 14:30' '%d/%m/%y', # '25/10/06' ] DECIMAL_SEPARATOR = '.' THOUSAND_SEPARATOR = ',' NUMBER_GROUPING = 3
bsd-3-clause
eethomas/eucalyptus
clc/eucadmin/eucadmin/deregisterarbitrator.py
7
1487
# Copyright 2011-2012 Eucalyptus Systems, Inc. # # Redistribution and use of this software 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. # # 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 eucadmin.deregisterrequest class DeregisterArbitrator(eucadmin.deregisterrequest.DeregisterRequest): ServiceName = 'Arbitrator'
gpl-3.0
yotchang4s/cafebabepy
src/main/python/test/test_importlib/source/test_path_hook.py
11
1190
from .. import util machinery = util.import_importlib('importlib.machinery') import unittest class PathHookTest: """Test the path hook for source.""" def path_hook(self): return self.machinery.FileFinder.path_hook((self.machinery.SourceFileLoader, self.machinery.SOURCE_SUFFIXES)) def test_success(self): with util.create_modules('dummy') as mapping: self.assertTrue(hasattr(self.path_hook()(mapping['.root']), 'find_spec')) def test_success_legacy(self): with util.create_modules('dummy') as mapping: self.assertTrue(hasattr(self.path_hook()(mapping['.root']), 'find_module')) def test_empty_string(self): # The empty string represents the cwd. self.assertTrue(hasattr(self.path_hook()(''), 'find_spec')) def test_empty_string_legacy(self): # The empty string represents the cwd. self.assertTrue(hasattr(self.path_hook()(''), 'find_module')) (Frozen_PathHookTest, Source_PathHooktest ) = util.test_both(PathHookTest, machinery=machinery) if __name__ == '__main__': unittest.main()
bsd-3-clause
hkariti/ansible
test/runner/lib/http.py
81
4729
""" Primitive replacement for requests to avoid extra dependency. Avoids use of urllib2 due to lack of SNI support. """ from __future__ import absolute_import, print_function import json import time try: from urllib import urlencode except ImportError: # noinspection PyCompatibility, PyUnresolvedReferences from urllib.parse import urlencode # pylint: disable=locally-disabled, import-error, no-name-in-module try: # noinspection PyCompatibility from urlparse import urlparse, urlunparse, parse_qs except ImportError: # noinspection PyCompatibility, PyUnresolvedReferences from urllib.parse import urlparse, urlunparse, parse_qs # pylint: disable=locally-disabled, ungrouped-imports from lib.util import ( CommonConfig, ApplicationError, run_command, SubprocessError, display, ) class HttpClient(object): """Make HTTP requests via curl.""" def __init__(self, args, always=False, insecure=False): """ :type args: CommonConfig :type always: bool :type insecure: bool """ self.args = args self.always = always self.insecure = insecure self.username = None self.password = None def get(self, url): """ :type url: str :rtype: HttpResponse """ return self.request('GET', url) def delete(self, url): """ :type url: str :rtype: HttpResponse """ return self.request('DELETE', url) def put(self, url, data=None, headers=None): """ :type url: str :type data: str | None :type headers: dict[str, str] | None :rtype: HttpResponse """ return self.request('PUT', url, data, headers) def request(self, method, url, data=None, headers=None): """ :type method: str :type url: str :type data: str | None :type headers: dict[str, str] | None :rtype: HttpResponse """ cmd = ['curl', '-s', '-S', '-i', '-X', method] if self.insecure: cmd += ['--insecure'] if headers is None: headers = {} headers['Expect'] = '' # don't send expect continue header if self.username: if self.password: display.sensitive.add(self.password) cmd += ['-u', '%s:%s' % (self.username, self.password)] else: cmd += ['-u', self.username] for header in headers.keys(): cmd += ['-H', '%s: %s' % (header, headers[header])] if data is not None: cmd += ['-d', data] cmd += [url] attempts = 0 max_attempts = 3 sleep_seconds = 3 # curl error codes which are safe to retry (request never sent to server) retry_on_status = ( 6, # CURLE_COULDNT_RESOLVE_HOST ) while True: attempts += 1 try: stdout, _ = run_command(self.args, cmd, capture=True, always=self.always, cmd_verbosity=2) break except SubprocessError as ex: if ex.status in retry_on_status and attempts < max_attempts: display.warning(u'%s' % ex) time.sleep(sleep_seconds) continue raise if self.args.explain and not self.always: return HttpResponse(method, url, 200, '') header, body = stdout.split('\r\n\r\n', 1) response_headers = header.split('\r\n') first_line = response_headers[0] http_response = first_line.split(' ') status_code = int(http_response[1]) return HttpResponse(method, url, status_code, body) class HttpResponse(object): """HTTP response from curl.""" def __init__(self, method, url, status_code, response): """ :type method: str :type url: str :type status_code: int :type response: str """ self.method = method self.url = url self.status_code = status_code self.response = response def json(self): """ :rtype: any """ try: return json.loads(self.response) except ValueError: raise HttpError(self.status_code, 'Cannot parse response to %s %s as JSON:\n%s' % (self.method, self.url, self.response)) class HttpError(ApplicationError): """HTTP response as an error.""" def __init__(self, status, message): """ :type status: int :type message: str """ super(HttpError, self).__init__('%s: %s' % (status, message)) self.status = status
gpl-3.0
mbroadst/rethinkdb
drivers/python/rethinkdb/_restore.py
7
9211
#!/usr/bin/env python '''`rethinkdb restore` loads data into a RethinkDB cluster from an archive''' from __future__ import print_function import copy, datetime, multiprocessing, optparse, os, shutil, sys, tarfile, tempfile, time, traceback from . import net, utils_common, _import usage = "rethinkdb restore FILE [-c HOST:PORT] [--tls-cert FILENAME] [-p] [--password-file FILENAME] [--clients NUM] [--shards NUM_SHARDS] [--replicas NUM_REPLICAS] [--force] [-i (DB | DB.TABLE)]..." help_epilog = ''' FILE: the archive file to restore data from; if FILE is -, use standard input (note that intermediate files will still be written to the --temp-dir directory) EXAMPLES: rethinkdb restore rdb_dump.tar.gz -c mnemosyne:39500 Import data into a cluster running on host 'mnemosyne' with a client port at 39500 using the named archive file. rethinkdb restore rdb_dump.tar.gz -i test Import data into a local cluster from only the 'test' database in the named archive file. rethinkdb restore rdb_dump.tar.gz -i test.subscribers -c hades -p Import data into a cluster running on host 'hades' which requires a password from only a specific table from the named archive file. rethinkdb restore rdb_dump.tar.gz --clients 4 --force Import data to a local cluster from the named archive file using only 4 client connections and overwriting any existing rows with the same primary key. ''' def parse_options(argv, prog=None): parser = utils_common.CommonOptionsParser(usage=usage, epilog=help_epilog, prog=prog) parser.add_option("-i", "--import", dest="db_tables", metavar="DB|DB.TABLE", default=[], help="limit restore to the given database or table (may be specified multiple times)", action="append", type="db_table") parser.add_option("--temp-dir", dest="temp_dir", metavar="DIR", default=None, help="directory to use for intermediary results") parser.add_option("--clients", dest="clients", metavar="CLIENTS", default=8, help="client connections to use (default: 8)", type="pos_int") parser.add_option("--hard-durability", dest="durability", action="store_const", default="soft", help="use hard durability writes (slower, uses less memory)", const="hard") parser.add_option("--force", dest="force", action="store_true", default=False, help="import data even if a table already exists") parser.add_option("--no-secondary-indexes", dest="indexes", action="store_false", default=None, help="do not create secondary indexes for the restored tables") parser.add_option("--writers-per-table", dest="writers", default=multiprocessing.cpu_count(), help=optparse.SUPPRESS_HELP, type="pos_int") parser.add_option("--batch-size", dest="batch_size", default=utils_common.default_batch_size, help=optparse.SUPPRESS_HELP, type="pos_int") # Replication settings replicationOptionsGroup = optparse.OptionGroup(parser, 'Replication Options') replicationOptionsGroup.add_option("--shards", dest="create_args", metavar="SHARDS", help="shards to setup on created tables (default: 1)", type="pos_int", action="add_key") replicationOptionsGroup.add_option("--replicas", dest="create_args", metavar="REPLICAS", help="replicas to setup on created tables (default: 1)", type="pos_int", action="add_key") parser.add_option_group(replicationOptionsGroup) options, args = parser.parse_args(argv) # -- Check validity of arguments # - archive if len(args) == 0: parser.error("Archive to import not specified. Provide an archive file created by rethinkdb-dump.") elif len(args) != 1: parser.error("Only one positional argument supported") options.in_file = args[0] if options.in_file == '-': options.in_file = sys.stdin else: if not os.path.isfile(options.in_file): parser.error("Archive file does not exist: %s" % options.in_file) options.in_file = os.path.realpath(options.in_file) # - temp_dir if options.temp_dir: if not os.path.isdir(options.temp_dir): parser.error("Temporary directory doesn't exist or is not a directory: %s" % options.temp_dir) if not os.access(res["temp_dir"], os.W_OK): parser.error("Temporary directory inaccessible: %s" % options.temp_dir) # - create_args if options.create_args is None: options.create_args = {} # -- return options def do_unzip(temp_dir, options): '''extract the tarfile to the filesystem''' tables_to_export = set(options.db_tables) top_level = None files_ignored = [] files_found = False archive = None tarfileOptions = { "mode": "r|*", "fileobj" if hasattr(options.in_file, "read") else "name": options.in_file } try: archive = tarfile.open(**tarfileOptions) for tarinfo in archive: # skip without comment anything but files if not tarinfo.isfile(): continue # skip everything but files # normalize the path relpath = os.path.relpath(os.path.realpath(tarinfo.name.strip().lstrip(os.sep))) # skip things that try to jump out of the folder if relpath.startswith(os.path.pardir): files_ignored.append(tarinfo.name) continue # skip files types other than what we use if not os.path.splitext(relpath)[1] in (".json", ".csv", ".info"): files_ignored.append(tarinfo.name) continue # ensure this looks like our structure try: top, db, file_name = relpath.split(os.sep) except ValueError: raise RuntimeError("Error: Archive file has an unexpected directory structure: %s" % tarinfo.name) if not top_level: top_level = top elif top != top_level: raise RuntimeError("Error: Archive file has an unexpected directory structure (%s vs %s)" % (top, top_level)) # filter out tables we are not looking for table = os.path.splitext(file_name) if tables_to_export and not ((db, table) in tables_to_export or (db, None) in tables_to_export): continue # skip without comment # write the file out files_found = True dest_path = os.path.join(temp_dir, db, file_name) if not os.path.exists(os.path.dirname(dest_path)): os.makedirs(os.path.dirname(dest_path)) with open(dest_path, 'wb') as dest: source = archive.extractfile(tarinfo) chunk = True while chunk: chunk = source.read(1024 * 128) dest.write(chunk) source.close() assert os.path.isfile(os.path.join(temp_dir, db, file_name)) finally: if archive: archive.close() if not files_found: raise RuntimeError("Error: Archive file had no files") # - send the location and ignored list back to our caller return files_ignored def do_restore(options): # Create a temporary directory to store the extracted data temp_dir = tempfile.mkdtemp(dir=options.temp_dir) try: # - extract the archive if not options.quiet: print("Extracting archive file...") start_time = time.time() files_ignored = do_unzip(temp_dir, options) if not options.quiet: print(" Done (%d seconds)" % (time.time() - start_time)) # - default _import options options = copy.copy(options) options.fields = None options.directory = temp_dir options.file = None sources = _import.parse_sources(options) # - run the import if not options.quiet: print("Importing from directory...") try: _import.import_tables(options, sources) except RuntimeError as ex: if options.debug: traceback.print_exc() if str(ex) == "Warnings occurred during import": raise RuntimeError("Warning: import did not create some secondary indexes.") else: errorString = str(ex) if errorString.startswith('Error: '): errorString = errorString[len('Error: '):] raise RuntimeError("Error: import failed: %s" % errorString) # 'Done' message will be printed by the import script finally: shutil.rmtree(temp_dir) def main(argv=None, prog=None): if argv is None: argv = sys.argv[1:] options = parse_options(argv, prog=prog) try: do_restore(options) except RuntimeError as ex: print(ex, file=sys.stderr) return 1 return 0 if __name__ == "__main__": exit(main())
agpl-3.0
ojake/django
tests/template_tests/templatetags/inclusion.py
174
8479
import operator from django.template import Engine, Library from django.utils import six engine = Engine(app_dirs=True) register = Library() @register.inclusion_tag('inclusion.html') def inclusion_no_params(): """Expected inclusion_no_params __doc__""" return {"result": "inclusion_no_params - Expected result"} inclusion_no_params.anything = "Expected inclusion_no_params __dict__" @register.inclusion_tag(engine.get_template('inclusion.html')) def inclusion_no_params_from_template(): """Expected inclusion_no_params_from_template __doc__""" return {"result": "inclusion_no_params_from_template - Expected result"} inclusion_no_params_from_template.anything = "Expected inclusion_no_params_from_template __dict__" @register.inclusion_tag('inclusion.html') def inclusion_one_param(arg): """Expected inclusion_one_param __doc__""" return {"result": "inclusion_one_param - Expected result: %s" % arg} inclusion_one_param.anything = "Expected inclusion_one_param __dict__" @register.inclusion_tag(engine.get_template('inclusion.html')) def inclusion_one_param_from_template(arg): """Expected inclusion_one_param_from_template __doc__""" return {"result": "inclusion_one_param_from_template - Expected result: %s" % arg} inclusion_one_param_from_template.anything = "Expected inclusion_one_param_from_template __dict__" @register.inclusion_tag('inclusion.html', takes_context=False) def inclusion_explicit_no_context(arg): """Expected inclusion_explicit_no_context __doc__""" return {"result": "inclusion_explicit_no_context - Expected result: %s" % arg} inclusion_explicit_no_context.anything = "Expected inclusion_explicit_no_context __dict__" @register.inclusion_tag(engine.get_template('inclusion.html'), takes_context=False) def inclusion_explicit_no_context_from_template(arg): """Expected inclusion_explicit_no_context_from_template __doc__""" return {"result": "inclusion_explicit_no_context_from_template - Expected result: %s" % arg} inclusion_explicit_no_context_from_template.anything = "Expected inclusion_explicit_no_context_from_template __dict__" @register.inclusion_tag('inclusion.html', takes_context=True) def inclusion_no_params_with_context(context): """Expected inclusion_no_params_with_context __doc__""" return {"result": "inclusion_no_params_with_context - Expected result (context value: %s)" % context['value']} inclusion_no_params_with_context.anything = "Expected inclusion_no_params_with_context __dict__" @register.inclusion_tag(engine.get_template('inclusion.html'), takes_context=True) def inclusion_no_params_with_context_from_template(context): """Expected inclusion_no_params_with_context_from_template __doc__""" return {"result": "inclusion_no_params_with_context_from_template - Expected result (context value: %s)" % context['value']} inclusion_no_params_with_context_from_template.anything = "Expected inclusion_no_params_with_context_from_template __dict__" @register.inclusion_tag('inclusion.html', takes_context=True) def inclusion_params_and_context(context, arg): """Expected inclusion_params_and_context __doc__""" return {"result": "inclusion_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)} inclusion_params_and_context.anything = "Expected inclusion_params_and_context __dict__" @register.inclusion_tag(engine.get_template('inclusion.html'), takes_context=True) def inclusion_params_and_context_from_template(context, arg): """Expected inclusion_params_and_context_from_template __doc__""" return {"result": "inclusion_params_and_context_from_template - Expected result (context value: %s): %s" % (context['value'], arg)} inclusion_params_and_context_from_template.anything = "Expected inclusion_params_and_context_from_template __dict__" @register.inclusion_tag('inclusion.html') def inclusion_two_params(one, two): """Expected inclusion_two_params __doc__""" return {"result": "inclusion_two_params - Expected result: %s, %s" % (one, two)} inclusion_two_params.anything = "Expected inclusion_two_params __dict__" @register.inclusion_tag(engine.get_template('inclusion.html')) def inclusion_two_params_from_template(one, two): """Expected inclusion_two_params_from_template __doc__""" return {"result": "inclusion_two_params_from_template - Expected result: %s, %s" % (one, two)} inclusion_two_params_from_template.anything = "Expected inclusion_two_params_from_template __dict__" @register.inclusion_tag('inclusion.html') def inclusion_one_default(one, two='hi'): """Expected inclusion_one_default __doc__""" return {"result": "inclusion_one_default - Expected result: %s, %s" % (one, two)} inclusion_one_default.anything = "Expected inclusion_one_default __dict__" @register.inclusion_tag(engine.get_template('inclusion.html')) def inclusion_one_default_from_template(one, two='hi'): """Expected inclusion_one_default_from_template __doc__""" return {"result": "inclusion_one_default_from_template - Expected result: %s, %s" % (one, two)} inclusion_one_default_from_template.anything = "Expected inclusion_one_default_from_template __dict__" @register.inclusion_tag('inclusion.html') def inclusion_unlimited_args(one, two='hi', *args): """Expected inclusion_unlimited_args __doc__""" return {"result": "inclusion_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args)))} inclusion_unlimited_args.anything = "Expected inclusion_unlimited_args __dict__" @register.inclusion_tag(engine.get_template('inclusion.html')) def inclusion_unlimited_args_from_template(one, two='hi', *args): """Expected inclusion_unlimited_args_from_template __doc__""" return {"result": "inclusion_unlimited_args_from_template - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args)))} inclusion_unlimited_args_from_template.anything = "Expected inclusion_unlimited_args_from_template __dict__" @register.inclusion_tag('inclusion.html') def inclusion_only_unlimited_args(*args): """Expected inclusion_only_unlimited_args __doc__""" return {"result": "inclusion_only_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in args))} inclusion_only_unlimited_args.anything = "Expected inclusion_only_unlimited_args __dict__" @register.inclusion_tag(engine.get_template('inclusion.html')) def inclusion_only_unlimited_args_from_template(*args): """Expected inclusion_only_unlimited_args_from_template __doc__""" return {"result": "inclusion_only_unlimited_args_from_template - Expected result: %s" % (', '.join(six.text_type(arg) for arg in args))} inclusion_only_unlimited_args_from_template.anything = "Expected inclusion_only_unlimited_args_from_template __dict__" @register.inclusion_tag('test_incl_tag_current_app.html', takes_context=True) def inclusion_tag_current_app(context): """Expected inclusion_tag_current_app __doc__""" return {} inclusion_tag_current_app.anything = "Expected inclusion_tag_current_app __dict__" @register.inclusion_tag('test_incl_tag_use_l10n.html', takes_context=True) def inclusion_tag_use_l10n(context): """Expected inclusion_tag_use_l10n __doc__""" return {} inclusion_tag_use_l10n.anything = "Expected inclusion_tag_use_l10n __dict__" @register.inclusion_tag('inclusion.html') def inclusion_unlimited_args_kwargs(one, two='hi', *args, **kwargs): """Expected inclusion_unlimited_args_kwargs __doc__""" # Sort the dictionary by key to guarantee the order for testing. sorted_kwarg = sorted(six.iteritems(kwargs), key=operator.itemgetter(0)) return {"result": "inclusion_unlimited_args_kwargs - Expected result: %s / %s" % ( ', '.join(six.text_type(arg) for arg in [one, two] + list(args)), ', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg) )} inclusion_unlimited_args_kwargs.anything = "Expected inclusion_unlimited_args_kwargs __dict__" @register.inclusion_tag('inclusion.html', takes_context=True) def inclusion_tag_without_context_parameter(arg): """Expected inclusion_tag_without_context_parameter __doc__""" return {} inclusion_tag_without_context_parameter.anything = "Expected inclusion_tag_without_context_parameter __dict__" @register.inclusion_tag('inclusion_extends1.html') def inclusion_extends1(): return {} @register.inclusion_tag('inclusion_extends2.html') def inclusion_extends2(): return {}
bsd-3-clause
xzturn/tensorflow
tensorflow/python/ops/signal/shape_ops.py
3
9270
# Copyright 2017 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. # ============================================================================== """General shape ops for frames.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops.signal import util_ops from tensorflow.python.util.tf_export import tf_export def _infer_frame_shape(signal, frame_length, frame_step, pad_end, axis): """Infers the shape of the return value of `frame`.""" frame_length = tensor_util.constant_value(frame_length) frame_step = tensor_util.constant_value(frame_step) axis = tensor_util.constant_value(axis) if signal.shape.ndims is None: return None if axis is None: return [None] * (signal.shape.ndims + 1) signal_shape = signal.shape.as_list() num_frames = None frame_axis = signal_shape[axis] outer_dimensions = signal_shape[:axis] inner_dimensions = signal_shape[axis:][1:] if signal_shape and frame_axis is not None: if frame_step is not None and pad_end: # Double negative is so that we round up. num_frames = max(0, -(-frame_axis // frame_step)) elif frame_step is not None and frame_length is not None: assert not pad_end num_frames = max( 0, (frame_axis - frame_length + frame_step) // frame_step) return outer_dimensions + [num_frames, frame_length] + inner_dimensions @tf_export("signal.frame") def frame(signal, frame_length, frame_step, pad_end=False, pad_value=0, axis=-1, name=None): """Expands `signal`'s `axis` dimension into frames of `frame_length`. Slides a window of size `frame_length` over `signal`'s `axis` dimension with a stride of `frame_step`, replacing the `axis` dimension with `[frames, frame_length]` frames. If `pad_end` is True, window positions that are past the end of the `axis` dimension are padded with `pad_value` until the window moves fully past the end of the dimension. Otherwise, only window positions that fully overlap the `axis` dimension are produced. For example: ```python # A batch size 3 tensor of 9152 audio samples. audio = tf.random.normal([3, 9152]) # Compute overlapping frames of length 512 with a step of 180 (frames overlap # by 332 samples). By default, only 50 frames are generated since the last # 152 samples do not form a full frame. frames = tf.signal.frame(audio, 512, 180) frames.shape.assert_is_compatible_with([3, 50, 512]) # When pad_end is enabled, the final frame is kept (padded with zeros). frames = tf.signal.frame(audio, 512, 180, pad_end=True) frames.shape.assert_is_compatible_with([3, 51, 512]) ``` Args: signal: A `[..., samples, ...]` `Tensor`. The rank and dimensions may be unknown. Rank must be at least 1. frame_length: The frame length in samples. An integer or scalar `Tensor`. frame_step: The frame hop size in samples. An integer or scalar `Tensor`. pad_end: Whether to pad the end of `signal` with `pad_value`. pad_value: An optional scalar `Tensor` to use where the input signal does not exist when `pad_end` is True. axis: A scalar integer `Tensor` indicating the axis to frame. Defaults to the last axis. Supports negative values for indexing from the end. name: An optional name for the operation. Returns: A `Tensor` of frames with shape `[..., frames, frame_length, ...]`. Raises: ValueError: If `frame_length`, `frame_step`, `pad_value`, or `axis` are not scalar. """ with ops.name_scope(name, "frame", [signal, frame_length, frame_step, pad_value]): signal = ops.convert_to_tensor(signal, name="signal") frame_length = ops.convert_to_tensor(frame_length, name="frame_length") frame_step = ops.convert_to_tensor(frame_step, name="frame_step") axis = ops.convert_to_tensor(axis, name="axis") signal.shape.with_rank_at_least(1) frame_length.shape.assert_has_rank(0) frame_step.shape.assert_has_rank(0) axis.shape.assert_has_rank(0) result_shape = _infer_frame_shape(signal, frame_length, frame_step, pad_end, axis) def maybe_constant(val): val_static = tensor_util.constant_value(val) return (val_static, True) if val_static is not None else (val, False) signal_shape, signal_shape_is_static = maybe_constant( array_ops.shape(signal)) axis, axis_is_static = maybe_constant(axis) if signal_shape_is_static and axis_is_static: # Axis can be negative. Convert it to positive. axis = range(len(signal_shape))[axis] outer_dimensions, length_samples, inner_dimensions = np.split( signal_shape, indices_or_sections=[axis, axis + 1]) length_samples = length_samples.item() else: signal_rank = array_ops.rank(signal) # Axis can be negative. Convert it to positive. axis = math_ops.range(signal_rank)[axis] outer_dimensions, length_samples, inner_dimensions = array_ops.split( signal_shape, [axis, 1, signal_rank - 1 - axis]) length_samples = array_ops.reshape(length_samples, []) num_outer_dimensions = array_ops.size(outer_dimensions) num_inner_dimensions = array_ops.size(inner_dimensions) # If padding is requested, pad the input signal tensor with pad_value. if pad_end: pad_value = ops.convert_to_tensor(pad_value, signal.dtype) pad_value.shape.assert_has_rank(0) # Calculate number of frames, using double negatives to round up. num_frames = -(-length_samples // frame_step) # Pad the signal by up to frame_length samples based on how many samples # are remaining starting from last_frame_position. pad_samples = math_ops.maximum( 0, frame_length + frame_step * (num_frames - 1) - length_samples) # Pad the inner dimension of signal by pad_samples. paddings = array_ops.concat( [array_ops.zeros([num_outer_dimensions, 2], dtype=pad_samples.dtype), [[0, pad_samples]], array_ops.zeros([num_inner_dimensions, 2], dtype=pad_samples.dtype)], 0) signal = array_ops.pad(signal, paddings, constant_values=pad_value) signal_shape = array_ops.shape(signal) length_samples = signal_shape[axis] else: num_frames = math_ops.maximum( 0, 1 + (length_samples - frame_length) // frame_step) subframe_length, _ = maybe_constant(util_ops.gcd(frame_length, frame_step)) subframes_per_frame = frame_length // subframe_length subframes_per_hop = frame_step // subframe_length num_subframes = length_samples // subframe_length slice_shape = array_ops.concat([outer_dimensions, [num_subframes * subframe_length], inner_dimensions], 0) subframe_shape = array_ops.concat([outer_dimensions, [num_subframes, subframe_length], inner_dimensions], 0) subframes = array_ops.reshape(array_ops.strided_slice( signal, array_ops.zeros_like(signal_shape), slice_shape), subframe_shape) # frame_selector is a [num_frames, subframes_per_frame] tensor # that indexes into the appropriate frame in subframes. For example: # [[0, 0, 0, 0], [2, 2, 2, 2], [4, 4, 4, 4]] frame_selector = array_ops.reshape( math_ops.range(num_frames) * subframes_per_hop, [num_frames, 1]) # subframe_selector is a [num_frames, subframes_per_frame] tensor # that indexes into the appropriate subframe within a frame. For example: # [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]] subframe_selector = array_ops.reshape( math_ops.range(subframes_per_frame), [1, subframes_per_frame]) # Adding the 2 selector tensors together produces a [num_frames, # subframes_per_frame] tensor of indices to use with tf.gather to select # subframes from subframes. We then reshape the inner-most # subframes_per_frame dimension to stitch the subframes together into # frames. For example: [[0, 1, 2, 3], [2, 3, 4, 5], [4, 5, 6, 7]]. selector = frame_selector + subframe_selector frames = array_ops.reshape( array_ops.gather(subframes, selector, axis=axis), array_ops.concat([outer_dimensions, [num_frames, frame_length], inner_dimensions], 0)) if result_shape: frames.set_shape(result_shape) return frames
apache-2.0
blackzw/openwrt_sdk_dev1
staging_dir/target-mips_r2_uClibc-0.9.33.2/usr/lib/python2.7/test/test_netrc.py
69
3715
import netrc, os, unittest, sys, textwrap from test import test_support temp_filename = test_support.TESTFN class NetrcTestCase(unittest.TestCase): def tearDown(self): os.unlink(temp_filename) def make_nrc(self, test_data): test_data = textwrap.dedent(test_data) mode = 'w' if sys.platform != 'cygwin': mode += 't' with open(temp_filename, mode) as fp: fp.write(test_data) return netrc.netrc(temp_filename) def test_default(self): nrc = self.make_nrc("""\ machine host1.domain.com login log1 password pass1 account acct1 default login log2 password pass2 """) self.assertEqual(nrc.hosts['host1.domain.com'], ('log1', 'acct1', 'pass1')) self.assertEqual(nrc.hosts['default'], ('log2', None, 'pass2')) def test_macros(self): nrc = self.make_nrc("""\ macdef macro1 line1 line2 macdef macro2 line3 line4 """) self.assertEqual(nrc.macros, {'macro1': ['line1\n', 'line2\n'], 'macro2': ['line3\n', 'line4\n']}) def _test_passwords(self, nrc, passwd): nrc = self.make_nrc(nrc) self.assertEqual(nrc.hosts['host.domain.com'], ('log', 'acct', passwd)) def test_password_with_leading_hash(self): self._test_passwords("""\ machine host.domain.com login log password #pass account acct """, '#pass') def test_password_with_trailing_hash(self): self._test_passwords("""\ machine host.domain.com login log password pass# account acct """, 'pass#') def test_password_with_internal_hash(self): self._test_passwords("""\ machine host.domain.com login log password pa#ss account acct """, 'pa#ss') def _test_comment(self, nrc, passwd='pass'): nrc = self.make_nrc(nrc) self.assertEqual(nrc.hosts['foo.domain.com'], ('bar', None, passwd)) self.assertEqual(nrc.hosts['bar.domain.com'], ('foo', None, 'pass')) def test_comment_before_machine_line(self): self._test_comment("""\ # comment machine foo.domain.com login bar password pass machine bar.domain.com login foo password pass """) def test_comment_before_machine_line_no_space(self): self._test_comment("""\ #comment machine foo.domain.com login bar password pass machine bar.domain.com login foo password pass """) def test_comment_before_machine_line_hash_only(self): self._test_comment("""\ # machine foo.domain.com login bar password pass machine bar.domain.com login foo password pass """) def test_comment_at_end_of_machine_line(self): self._test_comment("""\ machine foo.domain.com login bar password pass # comment machine bar.domain.com login foo password pass """) def test_comment_at_end_of_machine_line_no_space(self): self._test_comment("""\ machine foo.domain.com login bar password pass #comment machine bar.domain.com login foo password pass """) def test_comment_at_end_of_machine_line_pass_has_hash(self): self._test_comment("""\ machine foo.domain.com login bar password #pass #comment machine bar.domain.com login foo password pass """, '#pass') def test_main(): test_support.run_unittest(NetrcTestCase) if __name__ == "__main__": test_main()
gpl-2.0
mwv/scikit-learn
sklearn/utils/sparsetools/_graph_validation.py
364
2407
from __future__ import division, print_function, absolute_import import numpy as np from scipy.sparse import csr_matrix, isspmatrix, isspmatrix_csc from ._graph_tools import csgraph_to_dense, csgraph_from_dense,\ csgraph_masked_from_dense, csgraph_from_masked DTYPE = np.float64 def validate_graph(csgraph, directed, dtype=DTYPE, csr_output=True, dense_output=True, copy_if_dense=False, copy_if_sparse=False, null_value_in=0, null_value_out=np.inf, infinity_null=True, nan_null=True): """Routine for validation and conversion of csgraph inputs""" if not (csr_output or dense_output): raise ValueError("Internal: dense or csr output must be true") # if undirected and csc storage, then transposing in-place # is quicker than later converting to csr. if (not directed) and isspmatrix_csc(csgraph): csgraph = csgraph.T if isspmatrix(csgraph): if csr_output: csgraph = csr_matrix(csgraph, dtype=DTYPE, copy=copy_if_sparse) else: csgraph = csgraph_to_dense(csgraph, null_value=null_value_out) elif np.ma.is_masked(csgraph): if dense_output: mask = csgraph.mask csgraph = np.array(csgraph.data, dtype=DTYPE, copy=copy_if_dense) csgraph[mask] = null_value_out else: csgraph = csgraph_from_masked(csgraph) else: if dense_output: csgraph = csgraph_masked_from_dense(csgraph, copy=copy_if_dense, null_value=null_value_in, nan_null=nan_null, infinity_null=infinity_null) mask = csgraph.mask csgraph = np.asarray(csgraph.data, dtype=DTYPE) csgraph[mask] = null_value_out else: csgraph = csgraph_from_dense(csgraph, null_value=null_value_in, infinity_null=infinity_null, nan_null=nan_null) if csgraph.ndim != 2: raise ValueError("compressed-sparse graph must be two dimensional") if csgraph.shape[0] != csgraph.shape[1]: raise ValueError("compressed-sparse graph must be shape (N, N)") return csgraph
bsd-3-clause
ppries/tensorflow
tensorflow/contrib/slim/python/slim/evaluation.py
6
10502
# 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. # ============================================================================== """Contains functions for evaluation and summarization of metrics. The evaluation.py module contains helper functions for evaluating TensorFlow modules using a variety of metrics and summarizing the results. ********************** * Evaluating Metrics * ********************** In the simplest use case, we use a model to create the predictions, then specify the metrics and finally call the `evaluation` method: # Create model and obtain the predictions: images, labels = LoadData(...) predictions = MyModel(images) # Choose the metrics to compute: names_to_values, names_to_updates = slim.metrics.aggregate_metric_map({ "accuracy": slim.metrics.accuracy(predictions, labels), "mse": slim.metrics.mean_squared_error(predictions, labels), }) inital_op = tf.group( tf.global_variables_initializer(), tf.local_variables_initializer()) with tf.Session() as sess: metric_values = slim.evaluation( sess, num_evals=1, inital_op=initial_op, eval_op=names_to_updates.values(), final_op=name_to_values.values()) for metric, value in zip(names_to_values.keys(), metric_values): logging.info('Metric %s has value: %f', metric, value) ************************************************ * Evaluating a Checkpointed Model with Metrics * ************************************************ Often, one wants to evaluate a model checkpoint saved on disk. This can be performed once or repeatedly on a set schedule. To evaluate a particular model, users define zero or more metrics and zero or more summaries and call the evaluation_loop method: # Create model and obtain the predictions: images, labels = LoadData(...) predictions = MyModel(images) # Choose the metrics to compute: names_to_values, names_to_updates = slim.metrics.aggregate_metric_map({ "accuracy": slim.metrics.accuracy(predictions, labels), "mse": slim.metrics.mean_squared_error(predictions, labels), }) # Define the summaries to write: for metric_name, metric_value in metrics_to_values.iteritems(): tf.summary.scalar(metric_name, metric_value) checkpoint_dir = '/tmp/my_model_dir/' log_dir = '/tmp/my_model_eval/' # We'll evaluate 1000 batches: num_evals = 1000 # Evaluate every 10 minutes: slim.evaluation_loop( master='', checkpoint_dir, logdir, num_evals=num_evals, eval_op=names_to_updates.values(), summary_op=tf.contrib.deprecated.merge_summary(summary_ops), eval_interval_secs=600) ************************************************** * Evaluating a Checkpointed Model with Summaries * ************************************************** At times, an evaluation can be performed without metrics at all but rather with only summaries. The user need only leave out the 'eval_op' argument: # Create model and obtain the predictions: images, labels = LoadData(...) predictions = MyModel(images) # Define the summaries to write: tf.summary.scalar(...) tf.summary.histogram(...) checkpoint_dir = '/tmp/my_model_dir/' log_dir = '/tmp/my_model_eval/' # Evaluate once every 10 minutes. slim.evaluation_loop( master='', checkpoint_dir, logdir, num_evals=1, summary_op=tf.contrib.deprecated.merge_summary(summary_ops), eval_interval_secs=600) """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.training.python.training import evaluation from tensorflow.python import summary from tensorflow.python.training import monitored_session __all__ = [ 'evaluate_once', 'evaluation_loop', 'wait_for_new_checkpoint', 'checkpoints_iterator', ] wait_for_new_checkpoint = evaluation.wait_for_new_checkpoint checkpoints_iterator = evaluation.checkpoints_iterator _USE_DEFAULT = 0 def evaluate_once(master, checkpoint_path, logdir, num_evals=1, initial_op=None, initial_op_feed_dict=None, eval_op=None, eval_op_feed_dict=None, final_op=None, final_op_feed_dict=None, summary_op=_USE_DEFAULT, summary_op_feed_dict=None, variables_to_restore=None, session_config=None): """Evaluates the model at the given checkpoint path. Args: master: The BNS address of the TensorFlow master. checkpoint_path: The path to a checkpoint to use for evaluation. logdir: The directory where the TensorFlow summaries are written to. num_evals: The number of times to run `eval_op`. initial_op: An operation run at the beginning of evaluation. initial_op_feed_dict: A feed dictionary to use when executing `initial_op`. eval_op: A operation run `num_evals` times. eval_op_feed_dict: The feed dictionary to use when executing the `eval_op`. final_op: An operation to execute after all of the `eval_op` executions. The value of `final_op` is returned. final_op_feed_dict: A feed dictionary to use when executing `final_op`. summary_op: The summary_op to evaluate after running TF-Slims metric ops. By default the summary_op is set to tf.summary.merge_all(). summary_op_feed_dict: An optional feed dictionary to use when running the `summary_op`. variables_to_restore: A list of TensorFlow variables to restore during evaluation. If the argument is left as `None` then slim.variables.GetVariablesToRestore() is used. session_config: An instance of `tf.ConfigProto` that will be used to configure the `Session`. If left as `None`, the default will be used. Returns: The value of `final_op` or `None` if `final_op` is `None`. """ if summary_op == _USE_DEFAULT: summary_op = summary.merge_all() hooks = [ evaluation.StopAfterNEvalsHook(num_evals), ] if summary_op is not None: hooks.append( evaluation.SummaryAtEndHook(logdir, summary_op, summary_op_feed_dict)) return evaluation.evaluate_once( checkpoint_path, master=master, scaffold=monitored_session.Scaffold( init_op=initial_op, init_feed_dict=initial_op_feed_dict), eval_ops=eval_op, feed_dict=eval_op_feed_dict, final_ops=final_op, final_ops_feed_dict=final_op_feed_dict, variables_to_restore=variables_to_restore, hooks=hooks, config=session_config) def evaluation_loop(master, checkpoint_dir, logdir, num_evals=1, initial_op=None, initial_op_feed_dict=None, eval_op=None, eval_op_feed_dict=None, final_op=None, final_op_feed_dict=None, summary_op=_USE_DEFAULT, summary_op_feed_dict=None, variables_to_restore=None, eval_interval_secs=60, max_number_of_evaluations=None, session_config=None, timeout=None): """Runs TF-Slim's Evaluation Loop. Args: master: The BNS address of the TensorFlow master. checkpoint_dir: The directory where checkpoints are stored. logdir: The directory where the TensorFlow summaries are written to. num_evals: The number of times to run `eval_op`. initial_op: An operation run at the beginning of evaluation. initial_op_feed_dict: A feed dictionary to use when executing `initial_op`. eval_op: A operation run `num_evals` times. eval_op_feed_dict: The feed dictionary to use when executing the `eval_op`. final_op: An operation to execute after all of the `eval_op` executions. The value of `final_op` is returned. final_op_feed_dict: A feed dictionary to use when executing `final_op`. summary_op: The summary_op to evaluate after running TF-Slims metric ops. By default the summary_op is set to tf.summary.merge_all(). summary_op_feed_dict: An optional feed dictionary to use when running the `summary_op`. variables_to_restore: A list of TensorFlow variables to restore during evaluation. If the argument is left as `None` then slim.variables.GetVariablesToRestore() is used. eval_interval_secs: The minimum number of seconds between evaluations. max_number_of_evaluations: the max number of iterations of the evaluation. If the value is left as 'None', the evaluation continues indefinitely. session_config: An instance of `tf.ConfigProto` that will be used to configure the `Session`. If left as `None`, the default will be used. timeout: The maximum amount of time to wait between checkpoints. If left as `None`, then the process will wait indefinitely. Returns: The value of `final_op` or `None` if `final_op` is `None`. """ if summary_op == _USE_DEFAULT: summary_op = summary.merge_all() hooks = [ evaluation.StopAfterNEvalsHook(num_evals), ] if summary_op is not None: hooks.append( evaluation.SummaryAtEndHook(logdir, summary_op, summary_op_feed_dict)) return evaluation.evaluate_repeatedly( checkpoint_dir, master=master, scaffold=monitored_session.Scaffold( init_op=initial_op, init_feed_dict=initial_op_feed_dict), eval_ops=eval_op, feed_dict=eval_op_feed_dict, final_ops=final_op, final_ops_feed_dict=final_op_feed_dict, variables_to_restore=variables_to_restore, eval_interval_secs=eval_interval_secs, hooks=hooks, config=session_config, max_number_of_evaluations=max_number_of_evaluations, timeout=timeout)
apache-2.0
icclab/hurtle_sample_runtime_so
wsgi.py
18
40851
#!/usr/bin/python import os virtenv = os.environ['OPENSHIFT_PYTHON_DIR'] + '/virtenv/' virtualenv = os.path.join(virtenv, 'bin/activate_this.py') try: execfile(virtualenv, dict(__file__=virtualenv)) except IOError: pass # # IMPORTANT: Put any additional includes below this line. If placed above this # line, it's possible required libraries won't be in your searchable path # def application(environ, start_response): ctype = 'text/plain' if environ['PATH_INFO'] == '/health': response_body = "1" elif environ['PATH_INFO'] == '/env': response_body = ['%s: %s' % (key, value) for key, value in sorted(environ.items())] response_body = '\n'.join(response_body) else: ctype = 'text/html' response_body = '''<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Welcome to OpenShift</title> <style> /*! * Bootstrap v3.0.0 * * Copyright 2013 Twitter, Inc * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Designed and built with all the love in the world @twitter by @mdo and @fat. */ .logo { background-size: cover; height: 58px; width: 180px; margin-top: 6px; background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNC4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDQzMzYzKSAgLS0+DQo8IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPg0KPHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4IiB3aWR0aD0iMTgwcHgiDQoJIGhlaWdodD0iNThweCIgdmlld0JveD0iLTEyNy4zOTEgNDMyLjAxOSAxODAgNTgiIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgLTEyNy4zOTEgNDMyLjAxOSAxODAgNTgiIHhtbDpzcGFjZT0icHJlc2VydmUiPg0KPGcgaWQ9IkxheWVyXzEiIGRpc3BsYXk9Im5vbmUiPg0KCTxnIGRpc3BsYXk9ImlubGluZSI+DQoJCTxwYXRoIGQ9Ik0tMTIxLjM4NSw0MzguNzQ5Yy0wLjQxNiwwLjM2MS0xLjAwNiwwLjU0MS0xLjc3MSwwLjU0MWgtMi43NzR2LTdoMi44NzRjMC42MTIsMCwxLjA5OSwwLjE1NSwxLjQ2MiwwLjQ2NA0KCQkJYzAuMzYyLDAuMzEsMC41NDQsMC43NiwwLjU0NCwxLjM1M2MwLDAuMzU5LTAuMDg0LDAuNjUxLTAuMjUzLDAuODc0Yy0wLjE2OCwwLjIyMy0wLjM3OCwwLjM5OC0wLjYyOSwwLjUyNA0KCQkJYzAuMTM5LDAuMDQsMC4yNzgsMC4xMDIsMC40MTcsMC4xODVzMC4yNjUsMC4xOTIsMC4zNzcsMC4zMjZjMC4xMTIsMC4xMzMsMC4yMDQsMC4yOTMsMC4yNzMsMC40OHMwLjEwNCwwLjQwMSwwLjEwNCwwLjY0MQ0KCQkJQy0xMjAuNzYxLDQzNy44NTItMTIwLjk2OSw0MzguMzg5LTEyMS4zODUsNDM4Ljc0OXogTS0xMjIuMzEyLDQzMy41MTRjLTAuMTQ2LTAuMTc2LTAuMzk2LTAuMjY0LTAuNzUtMC4yNjRoLTEuODh2MS44aDEuODgNCgkJCWMwLjE3MywwLDAuMzIyLTAuMDI0LDAuNDQ1LTAuMDc0YzAuMTIzLTAuMDUsMC4yMjMtMC4xMTYsMC4zLTAuMTk5YzAuMDc3LTAuMDgzLDAuMTMzLTAuMTc3LDAuMTctMC4yODNzMC4wNTUtMC4yMTUsMC4wNTUtMC4zMjgNCgkJCUMtMTIyLjA5MSw0MzMuOTA2LTEyMi4xNjUsNDMzLjY4OS0xMjIuMzEyLDQzMy41MTR6IE0tMTIyLjEyMSw0MzYuMzJjLTAuMjE0LTAuMjA3LTAuNTItMC4zMS0wLjkyLTAuMzFoLTEuOXYyLjMyaDEuODcNCgkJCWMwLjQ2NiwwLDAuNzk1LTAuMTA2LDAuOTg1LTAuMzJzMC4yODUtMC40OTQsMC4yODUtMC44NEMtMTIxLjgwMSw0MzYuODEtMTIxLjkwOCw0MzYuNTI3LTEyMi4xMjEsNDM2LjMyeiIvPg0KCQk8cGF0aCBkPSJNLTExNi4yODEsNDM5LjI5di0wLjUwNmMtMC4xMzQsMC4xOTUtMC4zMTgsMC4zNDctMC41NTUsMC40NTVzLTAuNDkyLDAuMTYyLTAuNzY1LDAuMTYyYy0wLjYxMywwLTEuMDc4LTAuMTk2LTEuMzk1LTAuNTkNCgkJCWMtMC4zMTYtMC4zOTMtMC40NzUtMC45OC0wLjQ3NS0xLjc2di0zLjAxaDEuMDR2Mi45NjNjMCwwLjUzMiwwLjA5NSwwLjkwNSwwLjI4NCwxLjExN2MwLjE4OSwwLjIxMywwLjQ1MywwLjMxOSwwLjc5MiwwLjMxOQ0KCQkJYzAuMzQ1LDAsMC42MS0wLjExNiwwLjc5Ni0wLjM0OWMwLjE4Ni0wLjIzMywwLjI3OS0wLjU2MiwwLjI3OS0wLjk4OHYtMy4wNjNoMS4wNHY1LjI1SC0xMTYuMjgxeiIvPg0KCQk8cGF0aCBkPSJNLTExMi42OTcsNDMzLjE2NWMtMC4xMywwLjEzLTAuMjg1LDAuMTk1LTAuNDY1LDAuMTk1Yy0wLjE4NywwLTAuMzQ1LTAuMDY1LTAuNDc1LTAuMTk1cy0wLjE5NS0wLjI4NS0wLjE5NS0wLjQ2NQ0KCQkJYzAtMC4xODcsMC4wNjUtMC4zNDUsMC4xOTUtMC40NzVzMC4yODgtMC4xOTUsMC40NzUtMC4xOTVjMC4xOCwwLDAuMzM1LDAuMDY1LDAuNDY1LDAuMTk1czAuMTk1LDAuMjg5LDAuMTk1LDAuNDc1DQoJCQlDLTExMi41MDEsNDMyLjg4LTExMi41NjcsNDMzLjAzNS0xMTIuNjk3LDQzMy4xNjV6IE0tMTEzLjY4Miw0MzkuMjl2LTUuMjVoMS4wNHY1LjI1SC0xMTMuNjgyeiIvPg0KCQk8cGF0aCBkPSJNLTExMS4wMzEsNDM5LjI5di02Ljc1bDEuMDQtMC41NHY3LjI5SC0xMTEuMDMxeiIvPg0KCQk8cGF0aCBkPSJNLTEwNS45MjEsNDM5LjE2Yy0wLjEyNywwLjA3My0wLjI3NSwwLjEzMS0wLjQ0NSwwLjE3NWMtMC4xNywwLjA0My0wLjM1OCwwLjA2NS0wLjU2NSwwLjA2NQ0KCQkJYy0wLjM2NywwLTAuNjU1LTAuMTEzLTAuODY1LTAuMzRzLTAuMzE1LTAuNTc3LTAuMzE1LTEuMDV2LTMuMDNoLTAuNzV2LTAuOTRoMC43NXYtMS41bDEuMDEtMC41NHYyLjA0aDEuM3YwLjk0aC0xLjN2Mi44NQ0KCQkJYzAsMC4yNDcsMC4wNDIsMC40MTQsMC4xMjUsMC41YzAuMDgzLDAuMDg3LDAuMjIyLDAuMTMsMC40MTUsMC4xM2MwLjEzMywwLDAuMjctMC4wMjEsMC40MS0wLjA2NXMwLjI1Ni0wLjA5MSwwLjM1LTAuMTQ1DQoJCQlMLTEwNS45MjEsNDM5LjE2eiIvPg0KCQk8cGF0aCBkPSJNLTk3LjQ1Miw0MzcuODA1Yy0wLjEyLDAuMzQzLTAuMjg3LDAuNjMzLTAuNSwwLjg3Yy0wLjIxMywwLjIzNy0wLjQ2MywwLjQxNy0wLjc1LDAuNTQNCgkJCWMtMC4yODcsMC4xMjQtMC42LDAuMTg1LTAuOTQsMC4xODVjLTAuMzMzLDAtMC42NC0wLjA2NS0wLjkyLTAuMTk1Yy0wLjI4LTAuMTMtMC41MjMtMC4zMTUtMC43My0wLjU1NQ0KCQkJYy0wLjIwNy0wLjI0LTAuMzY4LTAuNTI2LTAuNDg1LTAuODZzLTAuMTc1LTAuNzA3LTAuMTc1LTEuMTJjMC0wLjQyNiwwLjA2LTAuODEsMC4xOC0xLjE1czAuMjg1LTAuNjI4LDAuNDk1LTAuODY1DQoJCQljMC4yMS0wLjIzNywwLjQ1Ny0wLjQxNywwLjc0LTAuNTRjMC4yODQtMC4xMjQsMC41OTItMC4xODUsMC45MjUtMC4xODVjMC4zMzMsMCwwLjY0MywwLjA2NSwwLjkzLDAuMTk1czAuNTM1LDAuMzEyLDAuNzQ1LDAuNTQ1DQoJCQlzMC4zNzQsMC41MTksMC40OSwwLjg1NWMwLjExNiwwLjMzNywwLjE3NSwwLjcwOCwwLjE3NSwxLjExNUMtOTcuMjcxLDQzNy4wNzMtOTcuMzMyLDQzNy40NjItOTcuNDUyLDQzNy44MDV6IE0tOTguNjY3LDQzNS4zODUNCgkJCWMtMC4yMzctMC4zMTctMC41NjUtMC40NzUtMC45ODUtMC40NzVjLTAuMzk0LDAtMC43MDIsMC4xNTgtMC45MjUsMC40NzVjLTAuMjIzLDAuMzE2LTAuMzM1LDAuNzM1LTAuMzM1LDEuMjU1DQoJCQljMCwwLjU4LDAuMTIsMS4wMjEsMC4zNiwxLjMyNWMwLjI0LDAuMzA0LDAuNTU3LDAuNDU1LDAuOTUsMC40NTVjMC4xOTMsMCwwLjM3LTAuMDQ2LDAuNTMtMC4xNA0KCQkJYzAuMTYtMC4wOTQsMC4yOTYtMC4yMTksMC40MS0wLjM3NWMwLjExMy0wLjE1NywwLjItMC4zNDIsMC4yNi0wLjU1NXMwLjA5LTAuNDQsMC4wOS0wLjY4DQoJCQlDLTk4LjMxMiw0MzYuMTMtOTguNDMsNDM1LjcwMi05OC42NjcsNDM1LjM4NXoiLz4NCgkJPHBhdGggZD0iTS05Mi44MTIsNDM5LjI5di0yLjk2M2MwLTAuNTMyLTAuMDk1LTAuOTA0LTAuMjg0LTEuMTE3Yy0wLjE4OS0wLjIxMy0wLjQ1My0wLjMxOS0wLjc5MS0wLjMxOQ0KCQkJYy0wLjM0NSwwLTAuNjExLDAuMTE2LTAuNzk2LDAuMzQ5Yy0wLjE4NiwwLjIzMy0wLjI3OSwwLjU2Mi0wLjI3OSwwLjk4OHYzLjA2M2gtMS4wNHYtNS4yNWgxLjA0djAuNTA2DQoJCQljMC4xMzMtMC4xOTUsMC4zMTgtMC4zNDcsMC41NTUtMC40NTVzMC40OTItMC4xNjIsMC43NjUtMC4xNjJjMC42MTMsMCwxLjA3OCwwLjE5NywxLjM5NSwwLjU5YzAuMzE2LDAuMzk0LDAuNDc1LDAuOTgsMC40NzUsMS43Ng0KCQkJdjMuMDFILTkyLjgxMnoiLz4NCgk8L2c+DQo8L2c+DQo8ZyBpZD0iTGF5ZXJfNiI+DQoJPGc+DQoJCTxwYXRoIGQ9Ik0tMTIyLjI2Niw0MzguOTg0Yy0wLjM5LDAuMzQ0LTAuOTU1LDAuNTE2LTEuNjk1LDAuNTE2aC0yLjUxdi03aDIuNTZjMC4yOCwwLDAuNTM1LDAuMDM1LDAuNzY1LDAuMTA1DQoJCQlzMC40MywwLjE3NiwwLjYsMC4zMTljMC4xNywwLjE0MywwLjMwMSwwLjMyNCwwLjM5NSwwLjU0NGMwLjA5MywwLjIyLDAuMTQsMC40NzksMC4xNCwwLjc3OWMwLDAuMzg2LTAuMDkzLDAuNjkzLTAuMjgsMC45MjMNCgkJCWMtMC4xODcsMC4yMy0wLjQzLDAuMzk4LTAuNzMsMC41MDRjMC4xNiwwLjA0LDAuMzIsMC4xMDIsMC40OCwwLjE4NWMwLjE2LDAuMDgzLDAuMzAzLDAuMTk0LDAuNDMsMC4zMzENCgkJCWMwLjEyNywwLjEzNywwLjIzLDAuMzA3LDAuMzEsMC41MTFzMC4xMiwwLjQ0NiwwLjEyLDAuNzI2Qy0xMjEuNjgxLDQzOC4xMjEtMTIxLjg3NSw0MzguNjQxLTEyMi4yNjYsNDM4Ljk4NHogTS0xMjMuMDcxLDQzMy41MDQNCgkJCWMtMC4xODctMC4xOTYtMC40NzctMC4yOTQtMC44Ny0wLjI5NGgtMS43NXYyLjE3aDEuNjljMC40MzMsMCwwLjc0My0wLjEwOCwwLjkzLTAuMzIzYzAuMTg3LTAuMjE2LDAuMjgtMC40NzYsMC4yOC0wLjc4MQ0KCQkJQy0xMjIuNzkxLDQzMy45NTctMTIyLjg4NCw0MzMuNy0xMjMuMDcxLDQzMy41MDR6IE0tMTIyLjg2MSw0MzYuNDVjLTAuMjY3LTAuMjQtMC42My0wLjM2LTEuMDktMC4zNmgtMS43NHYyLjdoMS43OA0KCQkJYzAuNTI2LDAsMC45LTAuMTIsMS4xMi0wLjM2YzAuMjItMC4yNCwwLjMzLTAuNTYsMC4zMy0wLjk2Qy0xMjIuNDYsNDM3LjAzLTEyMi41OTQsNDM2LjY5LTEyMi44NjEsNDM2LjQ1eiIvPg0KCQk8cGF0aCBkPSJNLTExNy4xMjEsNDM5LjV2LTAuNjRjLTAuMTUzLDAuMjItMC4zNSwwLjQtMC41OSwwLjU0cy0wLjUyNywwLjIxLTAuODYsMC4yMWMtMC4yOCwwLTAuNTM0LTAuMDQyLTAuNzYtMC4xMjUNCgkJCWMtMC4yMjctMC4wODMtMC40Mi0wLjIxMy0wLjU4LTAuMzljLTAuMTYtMC4xNzctMC4yODMtMC40LTAuMzctMC42N2MtMC4wODctMC4yNy0wLjEzLTAuNTk1LTAuMTMtMC45NzV2LTMuMmgwLjc2djMuMDc3DQoJCQljMCwwLjU2OCwwLjEwMSwwLjk4NCwwLjMwNCwxLjI0OHMwLjUxMywwLjM5NiwwLjkzMSwwLjM5NmMwLjM2NSwwLDAuNjcyLTAuMTMsMC45MjEtMC4zOTFzMC4zNzQtMC42NzgsMC4zNzQtMS4yNTJ2LTMuMDc3aDAuNzYNCgkJCXY1LjI1SC0xMTcuMTIxeiIvPg0KCQk8cGF0aCBkPSJNLTExMy45MDYsNDMzLjE1NWMtMC4xMDMsMC4xMDQtMC4yMjUsMC4xNTUtMC4zNjUsMC4xNTVjLTAuMTUzLDAtMC4yODQtMC4wNTItMC4zOS0wLjE1NQ0KCQkJYy0wLjEwNi0wLjEwMy0wLjE2LTAuMjI4LTAuMTYtMC4zNzVjMC0wLjE1MywwLjA1My0wLjI4MSwwLjE2LTAuMzg1czAuMjM3LTAuMTU1LDAuMzktMC4xNTVjMC4xNCwwLDAuMjYyLDAuMDUxLDAuMzY1LDAuMTU1DQoJCQljMC4xMDQsMC4xMDQsMC4xNTUsMC4yMzIsMC4xNTUsMC4zODVDLTExMy43NTEsNDMyLjkyNy0xMTMuODAzLDQzMy4wNTItMTEzLjkwNiw0MzMuMTU1eiBNLTExNC42NjEsNDM5LjV2LTUuMjVoMC43NnY1LjI1DQoJCQlILTExNC42NjF6Ii8+DQoJCTxwYXRoIGQ9Ik0tMTEyLjE1MSw0MzkuNXYtNi44N2wwLjc2LTAuNDJ2Ny4yOUgtMTEyLjE1MXoiLz4NCgkJPHBhdGggZD0iTS0xMDguNzIxLDQzNC44OXYzLjQxMmMwLDAuMjMyLDAuMDM5LDAuMzk2LDAuMTE1LDAuNDg5YzAuMDc3LDAuMDkzLDAuMjE1LDAuMTQsMC40MTUsMC4xNA0KCQkJYzAuMTUzLDAsMC4yODUtMC4wMTIsMC4zOTUtMC4wMzVzMC4yMjUtMC4wNjIsMC4zNDUtMC4xMTVsLTAuMDUsMC42NWMtMC4xNDcsMC4wNi0wLjI5NSwwLjEwNS0wLjQ0NSwwLjEzNQ0KCQkJYy0wLjE1LDAuMDMtMC4zMjUsMC4wNDUtMC41MjUsMC4wNDVjLTAuMzI5LDAtMC41NzktMC4wODgtMC43NTEtMC4yNjRjLTAuMTcyLTAuMTc2LTAuMjU4LTAuNDg0LTAuMjU4LTAuOTIzdi0zLjUzMmgtMC42NXYtMC42NA0KCQkJaDAuNjV2LTEuNjJsMC43Ni0wLjQydjIuMDRoMS4zdjAuNjRILTEwOC43MjF6Ii8+DQoJCTxwYXRoIGQ9Ik0tOTkuMjcxLDQzOC4wMjVjLTAuMTIsMC4zNDQtMC4yODQsMC42MzMtMC40OSwwLjg3cy0wLjQ1LDAuNDE1LTAuNzMsMC41MzVjLTAuMjgsMC4xMi0wLjU4LDAuMTgtMC45LDAuMTgNCgkJCXMtMC42MTktMC4wNTgtMC44OTUtMC4xNzVjLTAuMjc3LTAuMTE3LTAuNTE1LTAuMjktMC43MTUtMC41MmMtMC4yLTAuMjMtMC4zNTgtMC41MTUtMC40NzUtMC44NTVzLTAuMTc1LTAuNzMzLTAuMTc1LTEuMTgNCgkJCWMwLTAuNDQ2LDAuMDYtMC44NCwwLjE4LTEuMThjMC4xMi0wLjM0LDAuMjgzLTAuNjI1LDAuNDktMC44NTVjMC4yMDctMC4yMywwLjQ1LTAuNDA1LDAuNzMtMC41MjVjMC4yOC0wLjEyLDAuNTgtMC4xOCwwLjktMC4xOA0KCQkJYzAuMzIsMCwwLjYxOCwwLjA1NywwLjg5NSwwLjE3YzAuMjc2LDAuMTEzLDAuNTE1LDAuMjgzLDAuNzE1LDAuNTFjMC4yLDAuMjI3LDAuMzU4LDAuNTA5LDAuNDc1LDAuODQ1DQoJCQljMC4xMTcsMC4zMzcsMC4xNzUsMC43MjksMC4xNzUsMS4xNzVDLTk5LjA5MSw0MzcuMjg3LTk5LjE1MSw0MzcuNjgyLTk5LjI3MSw0MzguMDI1eiBNLTEwMC4yNyw0MzUuMjk3DQoJCQljLTAuMjc5LTAuMzQ1LTAuNjQ4LTAuNTE4LTEuMTA2LTAuNTE4Yy0wLjQ1OCwwLTAuODI2LDAuMTczLTEuMTAyLDAuNTE4Yy0wLjI3NiwwLjM0NS0wLjQxNCwwLjg2Ni0wLjQxNCwxLjU2Mg0KCQkJYzAsMC42OTcsMC4xMzgsMS4yMjMsMC40MTQsMS41NzhzMC42NDMsMC41MzMsMS4xMDIsMC41MzNjMC40NTgsMCwwLjgyNy0wLjE3OCwxLjEwNi0wLjUzM2MwLjI3OS0wLjM1NSwwLjQxOC0wLjg4MSwwLjQxOC0xLjU3OA0KCQkJQy05OS44NTEsNDM2LjE2NC05OS45OTEsNDM1LjY0My0xMDAuMjcsNDM1LjI5N3oiLz4NCgkJPHBhdGggZD0iTS05NC40MjEsNDM5LjV2LTMuMDc3YzAtMC41NjgtMC4xMDItMC45ODMtMC4zMDQtMS4yNDhjLTAuMjAyLTAuMjY0LTAuNTEzLTAuMzk2LTAuOTMxLTAuMzk2DQoJCQljLTAuMzY1LDAtMC42NzIsMC4xMy0wLjkyMSwwLjM5MXMtMC4zNzQsMC42NzgtMC4zNzQsMS4yNTJ2My4wNzdoLTAuNzZ2LTUuMjVoMC43NnYwLjY0YzAuMTUzLTAuMjIsMC4zNS0wLjQsMC41OS0wLjU0DQoJCQljMC4yNC0wLjE0LDAuNTI2LTAuMjEsMC44Ni0wLjIxYzAuMjgsMCwwLjUzMywwLjA0MiwwLjc2LDAuMTI1czAuNDIsMC4yMTMsMC41OCwwLjM5YzAuMTYsMC4xNzcsMC4yODMsMC40LDAuMzcsMC42Nw0KCQkJYzAuMDg2LDAuMjcsMC4xMywwLjU5NSwwLjEzLDAuOTc1djMuMkgtOTQuNDIxeiIvPg0KCTwvZz4NCjwvZz4NCjxnIGlkPSJMYXllcl81Ij4NCgk8Zz4NCgkJPHBhdGggZmlsbD0iI0RCMjEyRiIgZD0iTS0xMTkuMDYzLDQ2NS42OThsLTQuNjA0LDEuNjc4YzAuMDU5LDAuNzM4LDAuMTg1LDEuNDY2LDAuMzY0LDIuMTgxbDQuMzc2LTEuNTkyDQoJCQlDLTExOS4wNjgsNDY3LjIyNC0xMTkuMTIsNDY2LjQ2Mi0xMTkuMDYzLDQ2NS42OTgiLz4NCgkJPGc+DQoJCQk8Zz4NCgkJCQk8cGF0aCBmaWxsPSIjREIyMTJGIiBkPSJNLTk4LjcxLDQ2MC42MDZjLTAuMzIxLTAuNjYzLTAuNjkzLTEuMzAzLTEuMTIyLTEuOTA1bC00LjYwNiwxLjY3NQ0KCQkJCQljMC41MzgsMC41NDcsMC45ODYsMS4xNjQsMS4zNTQsMS44MjNMLTk4LjcxLDQ2MC42MDZ6Ii8+DQoJCQk8L2c+DQoJCQk8Zz4NCgkJCQk8cGF0aCBmaWxsPSIjREIyMTJGIiBkPSJNLTEwOC44NDEsNDU5LjMwMWMwLjk1OSwwLjQ0OSwxLjc4NywxLjA1NywyLjQ4OCwxLjc3M2w0LjYwNC0xLjY3Nw0KCQkJCQljLTEuMjc2LTEuNzktMy4wMTItMy4yODYtNS4xNDEtNC4yNzdjLTYuNTgzLTMuMDcxLTE0LjQzNC0wLjIxMy0xNy41MDUsNi4zNjljLTAuOTkyLDIuMTI5LTEuMzYyLDQuMzkyLTEuMTg4LDYuNTgyDQoJCQkJCWw0LjYwNi0xLjY3NWMwLjA3NS0wLjk5OCwwLjMxOC0xLjk5OCwwLjc2Ni0yLjk1N0MtMTE4LjIxOCw0NTkuMTY0LTExMy4xMTYsNDU3LjMwOS0xMDguODQxLDQ1OS4zMDEiLz4NCgkJCTwvZz4NCgkJPC9nPg0KCQk8cGF0aCBmaWxsPSIjRUEyMjI3IiBkPSJNLTEyMy4wMTUsNDY5LjQ1MmwtNC4zNzYsMS41OTRjMC40MDEsMS41OTQsMS4xMDEsMy4xMSwyLjA1Nyw0LjQ1OGw0LjU5Ni0xLjY3DQoJCQlDLTEyMS45MTksNDcyLjYyMS0xMjIuNzAyLDQ3MS4wOS0xMjMuMDE1LDQ2OS40NTIiLz4NCgkJPHBhdGggZmlsbD0iI0RCMjEyRiIgZD0iTS0xMDMuOTMsNDY3LjcxNWMtMC4wNzMsMC45OTktMC4zMjUsMS45OTgtMC43NzQsMi45NTdjLTEuOTk0LDQuMjc3LTcuMDk0LDYuMTM0LTExLjM3MSw0LjE0DQoJCQljLTAuOTU4LTAuNDQ5LTEuNzk1LTEuMDUzLTIuNDkyLTEuNzdsLTQuNTk0LDEuNjczYzEuMjcxLDEuNzg5LDMuMDA3LDMuMjg1LDUuMTM3LDQuMjc5YzYuNTgyLDMuMDY5LDE0LjQzNCwwLjIxMSwxNy41MDItNi4zNzINCgkJCWMwLjk5NC0yLjEyOSwxLjM2Mi00LjM5MSwxLjE4NS02LjU3OEwtMTAzLjkzLDQ2Ny43MTV6Ii8+DQoJCTxwYXRoIGZpbGw9IiNFQTIyMjciIGQ9Ik0tMTAyLjc5OCw0NjIuMDk0bC00LjM3NCwxLjU5MmMwLjgxMSwxLjQ1NywxLjE5NSwzLjEzNCwxLjA3MSw0LjgxOWw0LjU5NC0xLjY3Mg0KCQkJQy0xMDEuNjM5LDQ2NS4xODUtMTAyLjA3OCw0NjMuNTc1LTEwMi43OTgsNDYyLjA5NCIvPg0KCQk8cGF0aCBmaWxsPSIjMjMxRjIwIiBkPSJNLTcyLjI3MSw0NjcuMDMxYzAtMS4zMzEtMC4xOC0yLjUxMi0wLjU0LTMuNTQzYy0wLjM0NC0xLjA0OS0wLjgzNy0xLjkzMS0xLjQ3OC0yLjY1MQ0KCQkJYy0wLjYyNC0wLjczNC0xLjM4NC0xLjI5LTIuMjc1LTEuNjY2Yy0wLjg3Ni0wLjM5Mi0xLjg0NS0wLjU4Ni0yLjkwOS0wLjU4NmMtMS4wNzksMC0yLjA2MywwLjE5NS0yLjk1NSwwLjU4Ng0KCQkJYy0wLjg5MiwwLjM5LTEuNjU5LDAuOTU1LTIuMjk5LDEuNjg5Yy0wLjY0MiwwLjcxOC0xLjE0MiwxLjYwMi0xLjUwMiwyLjY1MWMtMC4zNDUsMS4wNDctMC41MTYsMi4yMzYtMC41MTYsMy41NjUNCgkJCWMwLDEuMzMsMC4xNzEsMi41MiwwLjUxNiwzLjU2NmMwLjM2LDEuMDMxLDAuODUzLDEuOTE1LDEuNDc5LDIuNjUxYzAuNjQsMC43MTgsMS4zOTksMS4yNzMsMi4yNzUsMS42NjUNCgkJCWMwLjg5MiwwLjM3NiwxLjg3NSwwLjU2MywyLjk1NiwwLjU2M2MxLjA2MiwwLDIuMDM5LTAuMTk1LDIuOTMxLTAuNTg2YzAuODkyLTAuMzkxLDEuNjU5LTAuOTQ3LDIuMy0xLjY2NQ0KCQkJYzAuNjQyLTAuNzM2LDEuMTM0LTEuNjI2LDEuNDc4LTIuNjc1Qy03Mi40NTEsNDY5LjU0OC03Mi4yNzEsNDY4LjM1OS03Mi4yNzEsNDY3LjAzMUwtNzIuMjcxLDQ2Ny4wMzF6IE0tNzUuNjQ5LDQ2Ny4wNzYNCgkJCWMwLDEuNjc1LTAuMzUzLDIuOTU2LTEuMDU1LDMuODQ4Yy0wLjY4OSwwLjg5Mi0xLjYxMiwxLjMzNy0yLjc3LDEuMzM3Yy0xLjE1OCwwLTIuMDk1LTAuNDUzLTIuODE1LTEuMzYNCgkJCWMtMC43MTgtMC45MDctMS4wNzgtMi4xOTctMS4wNzgtMy44N2MwLTEuNjc1LDAuMzQ1LTIuOTU3LDEuMDMxLTMuODQ4YzAuNzA0LTAuODkyLDEuNjM2LTEuMzM2LDIuNzkzLTEuMzM2DQoJCQlzMi4wOTQsMC40NTMsMi44MTQsMS4zNkMtNzYuMDA5LDQ2NC4xMTQtNzUuNjQ5LDQ2NS40MDMtNzUuNjQ5LDQ2Ny4wNzZMLTc1LjY0OSw0NjcuMDc2eiIvPg0KCQk8cGF0aCBmaWxsPSIjMjMxRjIwIiBkPSJNLTU1LjA3NSw0NjQuMDUxYzAtMC44NzYtMC4xNDktMS42MzQtMC40NDYtMi4yNzVjLTAuMjk4LTAuNjU4LTAuNzAzLTEuMjA1LTEuMjE5LTEuNjQ0DQoJCQljLTAuNTE4LTAuNDM3LTEuMTItMC43NTgtMS44MDctMC45NmMtMC42ODktMC4yMTgtMS40MTUtMC4zMjktMi4xODMtMC4zMjloLTcuMTc5djE2LjQyMmgzLjI4NXYtNS44MThoMy42MTENCgkJCWMwLjg0NSwwLDEuNjI4LTAuMSwyLjM0Ny0wLjMwNWMwLjczNi0wLjIwMywxLjM2OC0wLjUyMywxLjkwMS0wLjk2YzAuNTMxLTAuNDM5LDAuOTQ0LTAuOTk0LDEuMjQyLTEuNjY3DQoJCQlDLTU1LjIyNCw0NjUuODI2LTU1LjA3NSw0NjUuMDA1LTU1LjA3NSw0NjQuMDUxTC01NS4wNzUsNDY0LjA1MXogTS01OC40NTQsNDY0LjEyMWMwLDEuNDI0LTAuNzgyLDIuMTM0LTIuMzQ1LDIuMTM0aC0zLjgyNA0KCQkJdi00LjIyMmgzLjc3N2MwLjczMywwLDEuMzEyLDAuMTcxLDEuNzM1LDAuNTE2Qy01OC42NzIsNDYyLjg3Ny01OC40NTQsNDYzLjQwMS01OC40NTQsNDY0LjEyMUwtNTguNDU0LDQ2NC4xMjF6Ii8+DQoJCTxwb2x5Z29uIGZpbGw9IiMyMzFGMjAiIHBvaW50cz0iLTM5LjE0Nyw0NzUuMjY0IC0zOS4xNDcsNDcyLjA1IC00Ny42MTUsNDcyLjA1IC00Ny42MTUsNDY4LjA4NiAtNDIuOSw0NjguMDg2IC00Mi45LDQ2NC44OTYgDQoJCQktNDcuNjE1LDQ2NC44OTYgLTQ3LjYxNSw0NjIuMDU3IC0zOS40OTcsNDYyLjA1NyAtMzkuNDk3LDQ1OC44NDIgLTUwLjksNDU4Ljg0MiAtNTAuOSw0NzUuMjY0IAkJIi8+DQoJCTxwYXRoIGZpbGw9IiMyMzFGMjAiIGQ9Ik0tMjEuMjkyLDQ3NS4yNjR2LTE2LjQyMmgtMy4yMzh2Ny44MTJjMC4wMTYsMC4zNDQsMC4wMjMsMC42OTUsMC4wMjMsMS4wNTV2MC45ODYNCgkJCWMwLjAxNiwwLjI5NywwLjAyMywwLjUyNCwwLjAyMywwLjY3OWMtMC4xMDktMC4yMTgtMC4yODEtMC41LTAuNTE3LTAuODQ1Yy0wLjIxOS0wLjM1OC0wLjQzLTAuNjk1LTAuNjMzLTEuMDA4bC01LjgxOC04LjY4DQoJCQloLTMuMTQ0djE2LjQyMmgzLjIzNnYtNy4yMjZjMC0wLjIzNC0wLjAwOC0wLjUyMy0wLjAyMS0wLjg2OHYtMS4wMzJjMC0wLjM2LTAuMDA4LTAuNjg4LTAuMDIzLTAuOTg2di0wLjcwMw0KCQkJYzAuMTA3LDAuMjE4LDAuMjczLDAuNTA4LDAuNDkyLDAuODY2YzAuMjMzLDAuMzQ1LDAuNDUyLDAuNjczLDAuNjU3LDAuOTg2bDYuMDI4LDguOTYySC0yMS4yOTJ6Ii8+DQoJCTxwYXRoIGZpbGw9IiMyMzFGMjAiIGQ9Ik0tNS44NzksNDcwLjk0N2MwLTAuNjEtMC4wNzktMS4xNDktMC4yMzQtMS42MThjLTAuMTU3LTAuNDctMC40MjQtMC44OTktMC43OTgtMS4yOTENCgkJCWMtMC4zNTktMC4zOTItMC44NDQtMC43NS0xLjQ1NC0xLjA3OWMtMC42MS0wLjMyOC0xLjM3LTAuNjU3LTIuMjc1LTAuOTg2Yy0wLjgzMS0wLjI5Ny0xLjUwMi0wLjU3MS0yLjAxOC0wLjgyMQ0KCQkJYy0wLjUwMi0wLjI1LTAuODkyLTAuNS0xLjE3My0wLjc1Yy0wLjI4Mi0wLjI2Ni0wLjQ3MS0wLjUzMi0wLjU2My0wLjc5OWMtMC4wOTUtMC4yODItMC4xNDItMC41OTMtMC4xNDItMC45MzcNCgkJCWMwLTAuMzI5LDAuMDU2LTAuNjM0LDAuMTYzLTAuOTE2YzAuMTI2LTAuMjk3LDAuMzEzLTAuNTU1LDAuNTY1LTAuNzczYzAuMjY2LTAuMjIsMC42MDEtMC4zOTIsMS4wMDgtMC41MTgNCgkJCWMwLjQwNy0wLjE0LDAuODkyLTAuMjEsMS40NTQtMC4yMWMwLjgyOSwwLDEuNTQxLDAuMTMzLDIuMTM2LDAuMzk5YzAuNjA4LDAuMjUsMS4yMTEsMC42MjYsMS44MDUsMS4xMjZsMS4xNzQtMS40MzENCgkJCWMtMC42ODgtMC41NDctMS40MjMtMC45NzgtMi4yMDUtMS4yOTFjLTAuNzY2LTAuMzEzLTEuNjk2LTAuNDY5LTIuNzkxLTAuNDY5Yy0wLjc2OCwwLTEuNDcsMC4wOTUtMi4xMTEsMC4yODINCgkJCWMtMC42MjYsMC4xODctMS4xNjYsMC40NjgtMS42MTgsMC44NDRjLTAuNDM5LDAuMzYtMC43ODMsMC43OTctMS4wMzMsMS4zMTNjLTAuMjUsMC41MTgtMC4zNzYsMS4xMDQtMC4zNzYsMS43Ng0KCQkJYzAsMC41OTQsMC4wNzgsMS4xMTgsMC4yMzUsMS41NzJjMC4xNzIsMC40NTMsMC40MzgsMC44NjgsMC43OTgsMS4yNDRjMC4zNzYsMC4zNTgsMC44NiwwLjcwMywxLjQ1NCwxLjAzMg0KCQkJYzAuNjEsMC4zMTMsMS4zNiwwLjYyNiwyLjI1MiwwLjkzOGMwLjc1LDAuMjY2LDEuMzc2LDAuNTMyLDEuODc3LDAuNzk3YzAuNTAyLDAuMjUsMC44OTksMC41MDgsMS4xOTYsMC43NzMNCgkJCWMwLjMxMywwLjI2NiwwLjUzMiwwLjU1NSwwLjY1OCwwLjg2OHMwLjE4NywwLjY1NywwLjE4NywxLjAzM2MwLDAuODc2LTAuMzIsMS41NjMtMC45NjEsMi4wNjMNCgkJCWMtMC42MjUsMC41MDItMS40ODUsMC43NTItMi41OCwwLjc1MmMtMC44NDUsMC0xLjYyOC0wLjE4MS0yLjM0Ni0wLjU0Yy0wLjcyMS0wLjM2LTEuMzkzLTAuODM2LTIuMDE4LTEuNDNsLTEuMjIxLDEuMzYNCgkJCWMwLjY1NywwLjY1NywxLjQ1NCwxLjIwNSwyLjM5NCwxLjY0MmMwLjk1MiwwLjQyMiwxLjk5NCwwLjYzNCwzLjEyLDAuNjM0YzAuODU5LDAsMS42MjUtMC4xMTgsMi4yOTktMC4zNTINCgkJCWMwLjY3Mi0wLjIzNCwxLjI0NC0wLjU1NSwxLjcxMS0wLjk2YzAuNDY5LTAuNDA4LDAuODIxLTAuODkyLDEuMDU2LTEuNDU1Qy02LjAwNSw0NzIuMTkyLTUuODc5LDQ3MS41ODktNS44NzksNDcwLjk0Nw0KCQkJTC01Ljg3OSw0NzAuOTQ3eiIvPg0KCQk8cG9seWdvbiBmaWxsPSIjMjMxRjIwIiBwb2ludHM9IjEwLjgwMSw0NzUuMjY0IDEwLjgwMSw0NTguODQyIDguOTcxLDQ1OC44NDIgOC45NzEsNDY1Ljg1NyAwLjgwNiw0NjUuODU3IDAuODA2LDQ1OC44NDIgDQoJCQktMS4wMjQsNDU4Ljg0MiAtMS4wMjQsNDc1LjI2NCAwLjgwNiw0NzUuMjY0IDAuODA2LDQ2Ny41MjIgOC45NzEsNDY3LjUyMiA4Ljk3MSw0NzUuMjY0IAkJIi8+DQoJCTxyZWN0IHg9IjE2LjI4OSIgeT0iNDU4Ljg0MiIgZmlsbD0iIzIzMUYyMCIgd2lkdGg9IjEuODMyIiBoZWlnaHQ9IjE2LjQyMiIvPg0KCQk8cG9seWdvbiBmaWxsPSIjMjMxRjIwIiBwb2ludHM9IjMzLjI1LDQ2MC41MDcgMzMuMjUsNDU4Ljg0MiAyMy42MDksNDU4Ljg0MiAyMy42MDksNDc1LjI2NCAyNS40MzgsNDc1LjI2NCAyNS40MzgsNDY3LjYxNyANCgkJCTI5Ljk0Myw0NjcuNjE3IDI5Ljk0Myw0NjUuOTUgMjUuNDM4LDQ2NS45NSAyNS40MzgsNDYwLjUwNyAJCSIvPg0KCQk8cG9seWdvbiBmaWxsPSIjMjMxRjIwIiBwb2ludHM9IjQ4LjAwOCw0NjAuNTA3IDQ4LjAwOCw0NTguODQyIDM2LjUxMiw0NTguODQyIDM2LjUxMiw0NjAuNTA3IDQxLjM0NCw0NjAuNTA3IDQxLjM0NCw0NzUuMjY0IA0KCQkJNDMuMTc2LDQ3NS4yNjQgNDMuMTc2LDQ2MC41MDcgCQkiLz4NCgkJPHBhdGggZmlsbD0iIzIzMUYyMCIgZD0iTS00MS41MjYsNDg4LjI2MWMtMC4yMjMsMC4xMjQtMC41MzQsMC4yMTItMC44OTYsMC4yMTJjLTAuNjQ5LDAtMS4wNDktMC4zOTktMS4wNDktMS4yMzR2LTIuNjkxaC0wLjY2NQ0KCQkJdi0wLjgzNmgwLjY2NXYtMS4zMzFsMC44OTYtMC40Nzl2MS44MDloMS4xNTV2MC44MzZoLTEuMTU1djIuNTMxYzAsMC40MzUsMC4xNDQsMC41NTksMC40OCwwLjU1OQ0KCQkJYzAuMjM4LDAsMC41MDYtMC4wODksMC42NzUtMC4xODdMLTQxLjUyNiw0ODguMjYxeiBNLTQ1Ljg0Myw0ODYuMzg3Yy0wLjI0OC0wLjEyNC0wLjU2Ni0wLjIwNS0xLjA2NC0wLjIwNQ0KCQkJYy0wLjU4NywwLTAuOTU5LDAuMjY4LTAuOTU5LDAuNjkzYzAsMC40NjIsMC4yOTQsMC43NzMsMC44OTYsMC43NzNjMC40OSwwLDAuOTE2LTAuMzAzLDEuMTI4LTAuNTk2VjQ4Ni4zODd6IE0tNDUuODQzLDQ4OC4zNzUNCgkJCXYtMC40NjFjLTAuMzE4LDAuMzE5LTAuNzczLDAuNTU4LTEuMjc5LDAuNTU4Yy0wLjc1NCwwLTEuNjE0LTAuNDI3LTEuNjE0LTEuNTczYzAtMS4wMzcsMC44LTEuNTA3LDEuODU2LTEuNTA3DQoJCQljMC40MzYsMCwwLjc3OSwwLjA2MSwxLjAzNywwLjE3N3YtMC4zNDZjMC0wLjUwNi0wLjMxMS0wLjc5Mi0wLjg3OC0wLjc5MmMtMC40NzksMC0wLjg1MiwwLjA5MS0xLjIxNiwwLjI5NWwtMC4zNTQtMC42OTMNCgkJCWMwLjQ0My0wLjI3NSwwLjk0LTAuNDE5LDEuNTk3LTAuNDE5YzEuMDM5LDAsMS43NDksMC41MDgsMS43NDksMS41NjV2My4xOTVILTQ1Ljg0M3ogTS01MC44MDcsNDg4LjM3NXYtMi43ODdoLTIuODU3djIuNzg3DQoJCQloLTAuOTMydi02LjIxNmgwLjkzMnYyLjUxNWgyLjg1N3YtMi41MTVoMC45MzR2Ni4yMTZILTUwLjgwN3ogTS01OS4xMjcsNDg1LjA3MmMtMC4yMDQtMC4yNzUtMC42My0wLjYxLTEuMDkyLTAuNjENCgkJCWMtMC42NTgsMC0xLjAxMiwwLjQ5Ni0xLjAxMiwxLjQ4YzAsMS4xNzMsMC4zNzIsMS42ODcsMS4wNDcsMS42ODdjMC40MzUsMCwwLjgxOC0wLjI5MSwxLjA1Ny0wLjU5NVY0ODUuMDcyTC01OS4xMjcsNDg1LjA3MnoNCgkJCSBNLTU5LjEzNyw0ODguMzc1di0wLjQ0M2MtMC4zMzYsMC4zMDktMC43MjcsMC41NC0xLjIxNCwwLjU0Yy0xLjAwNiwwLTEuNzk2LTAuNzI3LTEuNzk2LTIuNTAzYzAtMS41OTksMC44NzItMi4zNTQsMS44NDEtMi4zNTQNCgkJCWMwLjQ3MSwwLDAuOTEzLDAuMjUsMS4xNjksMC41MzN2LTEuNzc0bDAuOTA3LTAuNDcydjYuNDczSC01OS4xMzd6IE0tNjQuOTc5LDQ4NC40NDJjLTAuNjExLDAtMC45ODQsMC40MjgtMS4wNjQsMS4xNzFoMi4xNjUNCgkJCUMtNjMuOTIxLDQ4NC45NzYtNjQuMjIzLDQ4NC40NDItNjQuOTc5LDQ4NC40NDIgTS02Mi45ODEsNDg2LjM3aC0zLjA4YzAuMDk4LDAuODk2LDAuNjAyLDEuMjc5LDEuMTcxLDEuMjc5DQoJCQljMC4zOTIsMCwwLjcwMy0wLjE0MiwxLjAxMi0wLjM3NGwwLjU0MywwLjU4N2MtMC40MDksMC4zOS0wLjg5NywwLjYxMi0xLjYwNywwLjYxMmMtMS4wOTMsMC0yLjAxNi0wLjg4LTIuMDE2LTIuNDI1DQoJCQljMC0xLjU4MSwwLjgzNi0yLjQzMywyLjA0Mi0yLjQzM2MxLjMyMywwLDEuOTYxLDEuMDc1LDEuOTYxLDIuMzM2Qy02Mi45NTYsNDg2LjEyMi02Mi45NzEsNDg2LjI3MS02Mi45ODEsNDg2LjM3DQoJCQkgTS02OS42OTUsNDgzLjAzOWgtMS44MTJ2MS45OThoMS44MTJjMC42MjIsMCwxLjA1OC0wLjMxOSwxLjA1OC0wLjk5NEMtNjguNjM3LDQ4My4zOTYtNjkuMDYzLDQ4My4wMzktNjkuNjk1LDQ4My4wMzkNCgkJCSBNLTY5LjA2Myw0ODUuODM2bDEuMjcsMi41NDFoLTEuMDcybC0xLjIzNy0yLjQ2aC0xLjQwM3YyLjQ2aC0wLjkxM3YtNi4yMThoMi43MjVjMS4wODQsMCwxLjk5OCwwLjU3OCwxLjk5OCwxLjg1OA0KCQkJQy02Ny42OTcsNDg1LjAxMS02OC4yMiw0ODUuNjI0LTY5LjA2Myw0ODUuODM2IE0tNzguMDEzLDQ5MC4wMTloLTAuOTY5bDAuNjc2LTEuNzMybC0xLjcxNS00LjU3MmgxLjAwNGwwLjc2MiwyLjI4MQ0KCQkJYzAuMTQ2LDAuNDA5LDAuMzU2LDEuMTAyLDAuNDExLDEuMzZjMC4wNzktMC4yNzgsMC4yNzQtMC45NCwwLjQxOC0xLjM0M2wwLjc4OS0yLjI5OGgwLjk2OUwtNzguMDEzLDQ5MC4wMTl6IE0tODIuNDQ2LDQ4NC40Ng0KCQkJYy0wLjQzNSwwLTAuODE0LDAuMjkzLTEuMDU3LDAuNTk0djEuOTYzYzAuMjA0LDAuMjc2LDAuNjMyLDAuNjE0LDEuMDk1LDAuNjE0YzAuNjU0LDAsMS4wMTEtMC40OTgsMS4wMTEtMS40ODINCgkJCUMtODEuMzk3LDQ4NC45NzQtODEuNzcxLDQ4NC40Ni04Mi40NDYsNDg0LjQ2IE0tODIuMzIsNDg4LjQ3NGMtMC40NzMsMC0wLjkxNS0wLjI0OC0xLjE3My0wLjUzM3YwLjQzNWgtMC45MDZ2LTYuMDAxbDAuOTA2LTAuNDcyDQoJCQl2Mi4yNTVjMC4zMzgtMC4zMDksMC43MjgtMC41NCwxLjIxNi0wLjU0YzEuMDA0LDAsMS43OTYsMC43MjksMS43OTYsMi41MDRDLTgwLjQ4MSw0ODcuNzItODEuMzUxLDQ4OC40NzQtODIuMzIsNDg4LjQ3NCIvPg0KCQk8cGF0aCBmaWxsPSIjMjMxRjIwIiBkPSJNLTM5LjM0Nyw0ODIuNzM2Yy0wLjAyOS0wLjAyMy0wLjA2OS0wLjAzNS0wLjEyNC0wLjAzNWgtMC4yMjd2MC4yODdoMC4yMTMNCgkJCWMwLjEyLDAsMC4xNzktMC4wNDcsMC4xNzktMC4xNDRDLTM5LjMwNiw0ODIuNzk3LTM5LjMyLDQ4Mi43NjItMzkuMzQ3LDQ4Mi43MzYgTS0zOS4yNDcsNDgzLjAwNA0KCQkJYy0wLjAzNCwwLjA0MS0wLjA4MywwLjA2OS0wLjE0MywwLjA4M2wwLjE5MSwwLjM2NGgtMC4xMzRsLTAuMTg0LTAuMzU0aC0wLjE4M3YwLjM1NGgtMC4xMTJWNDgyLjZoMC4zNDUNCgkJCWMwLjA3NiwwLDAuMTQyLDAuMDIsMC4xOTQsMC4wNjFjMC4wNTQsMC4wMzgsMC4wNzksMC4xMDEsMC4wNzksMC4xODNDLTM5LjE5Miw0ODIuOTA5LTM5LjIwOSw0ODIuOTYyLTM5LjI0Nyw0ODMuMDA0DQoJCQkgTS0zOC45Miw0ODIuNzY4Yy0wLjAzMy0wLjA4My0wLjA4LTAuMTU0LTAuMTQtMC4yMTNjLTAuMDU5LTAuMDU4LTAuMTMtMC4xMDQtMC4yMTEtMC4xMzZjLTAuMDgtMC4wMzUtMC4xNjktMC4wNTEtMC4yNjQtMC4wNTENCgkJCWMtMC4wOTIsMC0wLjE3OSwwLjAxNi0wLjI2MiwwLjA1MWMtMC4wOCwwLjAzMS0wLjE0OSwwLjA3Ny0wLjIxLDAuMTM2Yy0wLjA2LDAuMDYtMC4xMDYsMC4xMzEtMC4xNDMsMC4yMTMNCgkJCWMtMC4wMzMsMC4wOC0wLjA0OSwwLjE3My0wLjA0OSwwLjI3M2MwLDAuMDk5LDAuMDE2LDAuMTg5LDAuMDQ5LDAuMjcyYzAuMDM2LDAuMDgzLDAuMDgzLDAuMTUzLDAuMTQzLDAuMjENCgkJCWMwLjA2MSwwLjA1OCwwLjEzLDAuMTA2LDAuMjEsMC4xMzljMC4wODMsMC4wMzIsMC4xNywwLjA0OCwwLjI2MiwwLjA0OGMwLjA5NSwwLDAuMTg0LTAuMDE2LDAuMjY0LTAuMDQ4DQoJCQljMC4wODEtMC4wMzMsMC4xNTItMC4wODEsMC4yMTEtMC4xMzljMC4wNi0wLjA1NywwLjEwNi0wLjEyOCwwLjE0LTAuMjFjMC4wMzUtMC4wODMsMC4wNTItMC4xNzMsMC4wNTItMC4yNzINCgkJCUMtMzguODY5LDQ4Mi45NDEtMzguODg1LDQ4Mi44NDgtMzguOTIsNDgyLjc2OCBNLTM4LjgyMiw0ODMuMzU0Yy0wLjA0MSwwLjA5My0wLjA5NSwwLjE3NS0wLjE2MywwLjI0NA0KCQkJYy0wLjA2OSwwLjA2NS0wLjE1LDAuMTE4LTAuMjQ0LDAuMTU2Yy0wLjA5NSwwLjAzNS0wLjE5NSwwLjA1NC0wLjMwNiwwLjA1NGMtMC4xMDgsMC0wLjIwOC0wLjAyLTAuMzAzLTAuMDU0DQoJCQljLTAuMDk1LTAuMDM4LTAuMTc3LTAuMDkxLTAuMjQ0LTAuMTU2Yy0wLjA2OS0wLjA2OS0wLjEyNC0wLjE1MS0wLjE2My0wLjI0NGMtMC4wMzgtMC4wOTUtMC4wNTgtMC4yMDEtMC4wNTgtMC4zMTMNCgkJCWMwLTAuMTE4LDAuMDItMC4yMjEsMC4wNTgtMC4zMTVjMC4wMzktMC4wOTYsMC4wOTQtMC4xNzgsMC4xNjMtMC4yNDRjMC4wNjctMC4wNjksMC4xNDktMC4xMiwwLjI0NC0wLjE1Nw0KCQkJYzAuMDk1LTAuMDM3LDAuMTk0LTAuMDU1LDAuMzAzLTAuMDU1YzAuMTEsMCwwLjIxMSwwLjAxOCwwLjMwNiwwLjA1NWMwLjA5NCwwLjAzOCwwLjE3NSwwLjA4OSwwLjI0NCwwLjE1Nw0KCQkJYzAuMDY4LDAuMDY3LDAuMTIyLDAuMTQ4LDAuMTYzLDAuMjQ0YzAuMDM3LDAuMDk1LDAuMDU3LDAuMTk3LDAuMDU3LDAuMzE1Qy0zOC43NjUsNDgzLjE1My0zOC43ODUsNDgzLjI2LTM4LjgyMiw0ODMuMzU0Ii8+DQoJCTxwYXRoIGZpbGw9IiMyMjFEMUQiIGQ9Ik01MS43MTcsNDU5LjI2MmMtMC4wNDMtMC4wMzgtMC4xMDQtMC4wNTctMC4xODYtMC4wNTdoLTAuMzQ2djAuNDQxaDAuMzI2DQoJCQljMC4xODIsMCwwLjI3MS0wLjA3NSwwLjI3MS0wLjIyMUM1MS43ODMsNDU5LjM1Myw1MS43NjQsNDU5LjI5Nyw1MS43MTcsNDU5LjI2MiBNNTEuODc1LDQ1OS42NjcNCgkJCWMtMC4wNTUsMC4wNjEtMC4xMjksMC4xMDQtMC4yMTksMC4xMjdsMC4yODksMC41NTNoLTAuMjAxbC0wLjI3OS0wLjU0MWgtMC4yNzl2MC41NDFoLTAuMTd2LTEuMjk1aDAuNTIzDQoJCQljMC4xMTcsMCwwLjIxNywwLjAyOSwwLjI5NSwwLjA5YzAuMDgyLDAuMDYyLDAuMTIxLDAuMTU2LDAuMTIxLDAuMjgyQzUxLjk1NSw0NTkuNTIzLDUxLjkyNiw0NTkuNjA0LDUxLjg3NSw0NTkuNjY3DQoJCQkgTTUyLjM3MSw0NTkuMzA3Yy0wLjA1MS0wLjEyNi0wLjEyMy0wLjIzNC0wLjIxNS0wLjMyM2MtMC4wODgtMC4wOTEtMC4xOTctMC4xNjItMC4zMjItMC4yMTFjLTAuMTIzLTAuMDUxLTAuMjU2LTAuMDc1LTAuNC0wLjA3NQ0KCQkJYy0wLjE0MSwwLTAuMjczLDAuMDI0LTAuMzk2LDAuMDc1Yy0wLjEyNSwwLjA0OS0wLjIzLDAuMTItMC4zMjIsMC4yMTFjLTAuMDkyLDAuMDg4LTAuMTYyLDAuMTk3LTAuMjEzLDAuMzIzDQoJCQljLTAuMDU1LDAuMTI0LTAuMDgsMC4yNjQtMC4wOCwwLjQxNWMwLDAuMTUyLDAuMDI1LDAuMjksMC4wOCwwLjQxNmMwLjA1MSwwLjEyNiwwLjEyMSwwLjIzNCwwLjIxMywwLjMyMw0KCQkJYzAuMDkyLDAuMDksMC4xOTcsMC4xNTksMC4zMjIsMC4yMDhjMC4xMjMsMC4wNTEsMC4yNTYsMC4wNzUsMC4zOTYsMC4wNzVjMC4xNDUsMCwwLjI3Ny0wLjAyMywwLjQtMC4wNzUNCgkJCWMwLjEyNS0wLjA0OSwwLjIzNC0wLjExOCwwLjMyMi0wLjIwOGMwLjA5Mi0wLjA4OCwwLjE2NC0wLjE5NywwLjIxNS0wLjMyM3MwLjA3OC0wLjI2NCwwLjA3OC0wLjQxNg0KCQkJQzUyLjQ0OSw0NTkuNTcxLDUyLjQyMiw0NTkuNDMxLDUyLjM3MSw0NTkuMzA3IE01Mi41Miw0NjAuMjAzYy0wLjA2MSwwLjE0Mi0wLjE0MywwLjI2Ni0wLjI0NiwwLjM2OA0KCQkJYy0wLjEwNywwLjEwNS0wLjIyOSwwLjE4NC0wLjM3MywwLjIzOGMtMC4xNDEsMC4wNTctMC4yOTcsMC4wODUtMC40NjcsMC4wODVjLTAuMTY2LDAtMC4zMi0wLjAyOC0wLjQ2NS0wLjA4NQ0KCQkJYy0wLjE0MS0wLjA1NS0wLjI2Mi0wLjEzMy0wLjM3MS0wLjIzOGMtMC4xMDItMC4xMDItMC4xODYtMC4yMjYtMC4yNDQtMC4zNjhjLTAuMDYxLTAuMTQ2LTAuMDkyLTAuMzA1LTAuMDkyLTAuNDgNCgkJCWMwLTAuMTc1LDAuMDMxLTAuMzM0LDAuMDkyLTAuNDhjMC4wNTktMC4xNDQsMC4xNDMtMC4yNjYsMC4yNDQtMC4zNjljMC4xMDktMC4xMDQsMC4yMy0wLjE4MywwLjM3MS0wLjI0DQoJCQljMC4xNDUtMC4wNTUsMC4yOTktMC4wODQsMC40NjUtMC4wODRjMC4xNywwLDAuMzI2LDAuMDI5LDAuNDY3LDAuMDg0YzAuMTQ1LDAuMDU3LDAuMjY2LDAuMTM2LDAuMzczLDAuMjQNCgkJCWMwLjEwNCwwLjEwMywwLjE4NiwwLjIyNSwwLjI0NiwwLjM2OWMwLjA1OSwwLjE0NiwwLjA5LDAuMzA1LDAuMDksMC40OEM1Mi42MDksNDU5Ljg5OCw1Mi41NzgsNDYwLjA1Nyw1Mi41Miw0NjAuMjAzIi8+DQoJPC9nPg0KPC9nPg0KPGcgaWQ9IkxheWVyXzIiPg0KPC9nPg0KPGcgaWQ9IkxheWVyXzQiIGRpc3BsYXk9Im5vbmUiPg0KCTxnIGRpc3BsYXk9ImlubGluZSI+DQoJCTxwYXRoIGQ9Ik0tODUuMTkzLDUxMy4zNTNjLTMuMjk1LDAtNS40ODMsMi42NTUtNS40ODMsNy40MjVjMCw0Ljc3MSwyLjI4OCw3LjQ5Miw1LjU4OCw3LjQ5MmMzLjI5NSwwLDUuNDc4LTIuNjU0LDUuNDc4LTcuNDI2DQoJCQlDLTc5LjYxLDUxNi4wNzUtODEuODk5LDUxMy4zNTMtODUuMTkzLDUxMy4zNTMgTS04NS4xNiw1MzIuOTM4Yy02LjE1NCwwLTEwLjM1OS00LjUtMTAuMzU5LTEyLjA5NA0KCQkJYzAtNy41ODcsNC4yNzItMTIuMTYsMTAuNDMyLTEyLjE2YzYuMTE2LDAsMTAuMzI0LDQuNTAxLDEwLjMyNCwxMi4wOTNTLTc5LjAzOSw1MzIuOTM4LTg1LjE2LDUzMi45MzgiLz4NCgkJPHBhdGggZD0iTS02MC4xNCw1MTMuNjIxaC01LjQxNXY2LjA0OWg1LjQ4NWMyLjE4NCwwLDMuMzYyLTEuMDA5LDMuMzYyLTMuMDYxQy01Ni43MDksNTE0LjU2MS01OC4wNTYsNTEzLjYyMS02MC4xNCw1MTMuNjIxDQoJCQkgTS02MC4zNzQsNTI0LjI0MWgtNS4xODJ2OC4zMjhoLTQuNzA4di0yMy41MTZoMTAuMjkxYzQuNDM5LDAsOC4xMDcsMi40NTQsOC4xMDcsNy40NTkNCgkJCUMtNTEuODY3LDUyMS45NTgtNTUuNDk4LDUyNC4yNDEtNjAuMzc0LDUyNC4yNDEiLz4NCgkJPHBvbHlnb24gcG9pbnRzPSItNDYuOTk0LDUzMi41NjcgLTQ2Ljk5NCw1MDkuMDUzIC0zMC42NSw1MDkuMDUzIC0zMC42NSw1MTMuNjU3IC00Mi4yODksNTEzLjY1NyAtNDIuMjg5LDUxNy43MjEgDQoJCQktMzUuNTI5LDUxNy43MjEgLTM1LjUyOSw1MjIuMjg4IC00Mi4yODksNTIyLjI4OCAtNDIuMjg5LDUyNy45NjMgLTMwLjE0NSw1MjcuOTYzIC0zMC4xNDUsNTMyLjU2NyAJCSIvPg0KCQk8cGF0aCBkPSJNLTkuODcxLDUzMi41NjdsLTguNjQ3LTEyLjgzYy0wLjU3My0wLjg3MS0xLjM0My0yLjA0OS0xLjY0Ni0yLjY1M2MwLDAuODczLDAuMDY0LDMuODI5LDAuMDY0LDUuMTQydjEwLjM0MWgtNC42MzcNCgkJCXYtMjMuNTE0aDQuNTAybDguMzQzLDEyLjQzMmMwLjU3MywwLjg3MSwxLjM0NSwyLjA1MSwxLjY0NywyLjY1M2MwLTAuODc5LTAuMDY1LTMuODI5LTAuMDY1LTUuMTR2LTkuOTQ3aDQuNjM4djIzLjUxNGgtNC4xOTkNCgkJCVY1MzIuNTY3eiIvPg0KCQk8cGF0aCBkPSJNOC4wMjEsNTMyLjkzOGMtMy4xOTMsMC02LjA1My0xLjM4MS03LjktMy4yNThsMS43NDYtMS45NDljMS43ODMsMS43MTMsMy44MzYsMi44MjMsNi4yNTgsMi44MjMNCgkJCWMzLjEyOSwwLDUuMDgtMS41NDQsNS4wOC00LjAzMWMwLTIuMTg3LTEuMzEyLTMuNDI2LTUuNjE3LTQuOTcxYy01LjA3Ny0xLjgxNS02Ljc5OC0zLjQ2MS02Ljc5OC02Ljg1NA0KCQkJYzAtMy43NjcsMi45Ni02LjAxNCw3LjM2Ny02LjAxNGMzLjE2NiwwLDUuMTg0LDAuOTM4LDcuMTY4LDIuNTIybC0xLjY4MiwyLjA0OWMtMS43MTUtMS40MTMtMy4yOTktMi4xODctNS42NTQtMi4xODcNCgkJCWMtMy4yMjYsMC00LjU3NCwxLjYxMi00LjU3NCwzLjQ2YzAsMS45NTMsMC44NzgsMy4wNTcsNS41ODUsNC43MzhjNS4yMTUsMS44ODEsNi44MjksMy42MjksNi44MjksNy4xMjENCgkJCUMxNS44MjgsNTMwLjA4NSwxMi45MzQsNTMyLjkzOCw4LjAyMSw1MzIuOTM4Ii8+DQoJCTxwb2x5Z29uIHBvaW50cz0iMzUuOTk5LDUzMi41NjcgMzUuOTk5LDUyMS40ODUgMjQuMjk1LDUyMS40ODUgMjQuMjk1LDUzMi41NjcgMjEuNjcyLDUzMi41NjcgMjEuNjcyLDUwOS4wNTMgMjQuMjk1LDUwOS4wNTMgDQoJCQkyNC4yOTUsNTE5LjA5OCAzNS45OTksNTE5LjA5OCAzNS45OTksNTA5LjA1MyAzOC42MjMsNTA5LjA1MyAzOC42MjMsNTMyLjU2NyAJCSIvPg0KCQk8cmVjdCB4PSI0NS4zNzEiIHk9IjUwOS4wNTUiIHdpZHRoPSIyLjYyMyIgaGVpZ2h0PSIyMy41MTQiLz4NCgkJPHBvbHlnb24gcG9pbnRzPSI1Ny4zNzUsNTExLjQzOCA1Ny4zNzUsNTE5LjIzMyA2My44Myw1MTkuMjMzIDYzLjgzLDUyMS42MiA1Ny4zNzUsNTIxLjYyIDU3LjM3NSw1MzIuNTY3IDU0Ljc1LDUzMi41NjcgDQoJCQk1NC43NSw1MDkuMDUzIDY4LjU3Niw1MDkuMDUzIDY4LjU3Niw1MTEuNDM4IAkJIi8+DQoJCTxwb2x5Z29uIHBvaW50cz0iODIuODM0LDUxMS40MzggODIuODM0LDUzMi41NjcgODAuMjExLDUzMi41NjcgODAuMjExLDUxMS40MzggNzMuMjg1LDUxMS40MzggNzMuMjg1LDUwOS4wNTMgODkuNzY0LDUwOS4wNTMgDQoJCQk4OS43NjQsNTExLjQzOCAJCSIvPg0KCQk8cGF0aCBmaWxsPSIjQkMxQzI5IiBkPSJNLTE0Mi4zNDEsNTE4LjQ5OGwtNy44NzIsMi44NjFjMC4xMDMsMS4yNiwwLjMxOCwyLjUwNCwwLjYyMywzLjcyNWw3LjQ3My0yLjcyMw0KCQkJQy0xNDIuMzU3LDUyMS4xMDMtMTQyLjQ0Miw1MTkuODAzLTE0Mi4zNDEsNTE4LjQ5OCIvPg0KCQk8cGF0aCBmaWxsPSIjQkMxQzI5IiBkPSJNLTEwNy41NzEsNTA5LjgxYy0wLjU0OC0xLjEyOS0xLjE4MS0yLjIyNC0xLjkxOS0zLjI1NmwtNy44NjgsMi44NjFjMC45MTYsMC45MzgsMS42ODUsMS45ODcsMi4zMTIsMy4xMTMNCgkJCUwtMTA3LjU3MSw1MDkuODF6Ii8+DQoJCTxwYXRoIGZpbGw9IiNFMjI0MzQiIGQ9Ik0tMTI0Ljg4Miw1MDcuNTg2YzEuNjM2LDAuNzYzLDMuMDU3LDEuODAxLDQuMjUsMy4wMjNsNy44NjktMi44NjRjLTIuMTgyLTMuMDUyLTUuMTQ4LTUuNjA0LTguNzgyLTcuMjk3DQoJCQljLTExLjI0Ni01LjI0LTI0LjY2Ny0wLjM2NC0yOS45MDUsMTAuODdjLTEuNzAxLDMuNjMxLTIuMzMyLDcuNDk0LTIuMDM4LDExLjIzMWw3Ljg3MS0yLjg2YzAuMTI4LTEuNywwLjU0Ny0zLjQwNywxLjMxMS01LjA0NA0KCQkJQy0xNDAuOTAzLDUwNy4zNS0xMzIuMTg0LDUwNC4xODEtMTI0Ljg4Miw1MDcuNTg2Ii8+DQoJCTxwYXRoIGZpbGw9IiNFMjI0MzQiIGQ9Ik0tMTQ5LjA5OSw1MjQuOTA5bC03LjQ3NSwyLjcxN2MwLjY4OCwyLjcxOSwxLjg4LDUuMzA5LDMuNTE2LDcuNjA3bDcuODUzLTIuODUxDQoJCQlDLTE0Ny4yMjEsNTMwLjMxMS0xNDguNTY0LDUyNy43LTE0OS4wOTksNTI0LjkwOSIvPg0KCQk8cGF0aCBmaWxsPSIjRTIyNDM0IiBkPSJNLTExNi40OTEsNTIxLjk0NGMtMC4xMjYsMS42OTgtMC41NTEsMy40MDgtMS4zMTksNS4wNDVjLTMuNDA2LDcuMjk5LTEyLjEyMywxMC40NjctMTkuNDMxLDcuMDYyDQoJCQljLTEuNjM2LTAuNzY2LTMuMDY3LTEuNzk5LTQuMjU4LTMuMDJsLTcuODQ5LDIuODU0YzIuMTc1LDMuMDUzLDUuMTQxLDUuNjA0LDguNzc2LDcuMzAyYzExLjI0Niw1LjIzNywyNC42NjQsMC4zNiwyOS45MS0xMC44NzMNCgkJCWMxLjY5Ni0zLjYzMiwyLjMyMi03LjQ5MiwyLjAyNC0xMS4yMjhMLTExNi40OTEsNTIxLjk0NHoiLz4NCgkJPHBhdGggZmlsbD0iI0UyMjQzNCIgZD0iTS0xMTQuNTU1LDUxMi4zNDZsLTcuNDc1LDIuNzI0YzEuMzksMi40ODEsMi4wNDMsNS4zNDQsMS44MzMsOC4yMjFsNy44NS0yLjg1NA0KCQkJQy0xMTIuNTc0LDUxNy42MjItMTEzLjMyNSw1MTQuODc2LTExNC41NTUsNTEyLjM0NiIvPg0KCQk8cGF0aCBmaWxsPSIjOTcxMDFCIiBkPSJNLTE0Mi4zNzMsNTIwLjA3OGMtMC4wMTktMC41MjQtMC4wMTItMS4wNTEsMC4wMzItMS41OGwtNy44NzIsMi44NjFjMC4wMzgsMC41MDQsMC4xMDMsMS4wMDIsMC4xNzgsMS41DQoJCQlMLTE0Mi4zNzMsNTIwLjA3OHoiLz4NCgkJPHBhdGggZmlsbD0iIzk3MTAxQiIgZD0iTS0xMDguNzA3LDUwNy43NDFjLTAuMjUtMC40LTAuNTA3LTAuOC0wLjc4MS0xLjE4N2wtNy44NjYsMi44NjFjMC4zNDUsMC4zNTQsMC42NjYsMC43MzIsMC45NjksMS4xMTQNCgkJCUwtMTA4LjcwNyw1MDcuNzQxeiIvPg0KCQk8cGF0aCBmaWxsPSIjQkMxQzI5IiBkPSJNLTE0OS4zNDcsNTMzLjg4NmMwLjYwNCwwLjg0OSwxLjI3NCwxLjY2MywyLDIuNDI2bDguNTQ1LTMuMTEyYy0xLTAuNjI3LTEuOTAyLTEuMzUzLTIuNjk5LTIuMTY2DQoJCQlMLTE0OS4zNDcsNTMzLjg4NnogTS0xMDguNjM3LDUxOS4wODlsLTcuODU0LDIuODU2Yy0wLjA4MywxLjEyOS0wLjMwMywyLjI2LTAuNjY0LDMuMzcxbDguNTQyLTMuMTEzDQoJCQlDLTEwOC41NDcsNTIxLjE1OS0xMDguNTU5LDUyMC4xMTktMTA4LjYzNyw1MTkuMDg5Ii8+DQoJCTxwYXRoIGQ9Ik05Ni4xMjQsNTExLjAxYy0wLjA4MiwwLjE5OC0wLjE5NCwwLjM2OC0wLjMzOSwwLjUxMWMtMC4xNDcsMC4xMzktMC4zMTYsMC4yNS0wLjUxMiwwLjMyOA0KCQkJYy0wLjE5NywwLjA3OC0wLjQxLDAuMTE1LTAuNjQ2LDAuMTE1Yy0wLjIyNywwLTAuNDM5LTAuMDM4LTAuNjM3LTAuMTE1Yy0wLjE5Ni0wLjA3OS0wLjM2Ni0wLjE4OC0wLjUxNi0wLjMyOA0KCQkJYy0wLjE0MS0wLjE0My0wLjI1Ni0wLjMxMy0wLjMzNC0wLjUxMWMtMC4wODctMC4xOTctMC4xMjgtMC40MTctMC4xMjgtMC42NTljMC0wLjI0MSwwLjA0MS0wLjQ2MSwwLjEyOC0wLjY1Nw0KCQkJYzAuMDc4LTAuMiwwLjE5My0wLjM3LDAuMzM0LTAuNTExYzAuMTQ4LTAuMTQ0LDAuMzE4LTAuMjUsMC41MTYtMC4zMjljMC4xOTctMC4wNzcsMC40MTItMC4xMTYsMC42MzctMC4xMTYNCgkJCWMwLjIzNiwwLDAuNDQ5LDAuMDM5LDAuNjQ2LDAuMTE2YzAuMTk0LDAuMDc5LDAuMzYzLDAuMTg2LDAuNTEyLDAuMzI5YzAuMTQ1LDAuMTQxLDAuMjU3LDAuMzExLDAuMzM5LDAuNTExDQoJCQljMC4wODEsMC4xOTYsMC4xMjIsMC40MTcsMC4xMjIsMC42NTdDOTYuMjQ2LDUxMC41OTMsOTYuMjA1LDUxMC44MTMsOTYuMTI0LDUxMS4wMSBNOTUuOTIsNTA5Ljc4DQoJCQljLTAuMDczLTAuMTc1LTAuMTctMC4zMjMtMC4yOTYtMC40NDRjLTAuMTIyLTAuMTI2LTAuMjcxLTAuMjIyLTAuNDQyLTAuMjkyYy0wLjE2OS0wLjA2Ny0wLjM1NC0wLjEwNC0wLjU1NC0wLjEwNA0KCQkJYy0wLjE5MiwwLTAuMzc1LDAuMDM3LTAuNTQ4LDAuMTA0Yy0wLjE2OCwwLjA3LTAuMzE1LDAuMTY2LTAuNDM4LDAuMjkyYy0wLjEyNywwLjEyMS0wLjIyOCwwLjI2OS0wLjI5OCwwLjQ0NA0KCQkJYy0wLjA3MiwwLjE3My0wLjEwOSwwLjM2MS0wLjEwOSwwLjU3MWMwLDAuMjA3LDAuMDM3LDAuNCwwLjEwOSwwLjU3M2MwLjA3LDAuMTczLDAuMTcxLDAuMzIxLDAuMjk4LDAuNDQ1DQoJCQljMC4xMjQsMC4xMjMsMC4yNzIsMC4yMTcsMC40MzgsMC4yODZjMC4xNzQsMC4wNzIsMC4zNTQsMC4xMDQsMC41NDgsMC4xMDRjMC4xOTgsMCwwLjM4NS0wLjAzMywwLjU1NC0wLjEwNA0KCQkJYzAuMTcyLTAuMDY5LDAuMzIxLTAuMTY0LDAuNDQyLTAuMjg2YzAuMTI2LTAuMTI0LDAuMjI0LTAuMjcyLDAuMjk2LTAuNDQ1YzAuMDc0LTAuMTczLDAuMTA3LTAuMzY0LDAuMTA3LTAuNTczDQoJCQlDOTYuMDI5LDUxMC4xNDEsOTUuOTk0LDUwOS45NSw5NS45Miw1MDkuNzggTTk1LjIzNCw1MTAuMjc1Yy0wLjA3MiwwLjA4Ni0wLjE3MiwwLjE0My0wLjI5NywwLjE3NGwwLjM5OSwwLjc2M2gtMC4yNzgNCgkJCWwtMC4zODQtMC43NDZoLTAuMzg2djAuNzQ2aC0wLjIzNXYtMS43ODNoMC43MjRjMC4xNjQsMCwwLjI5NywwLjA0MywwLjQwNiwwLjEyNWMwLjExMiwwLjA4NSwwLjE2OCwwLjIxNCwwLjE2OCwwLjM4OA0KCQkJQzk1LjM0OCw1MTAuMDc2LDk1LjMwOSw1MTAuMTg4LDk1LjIzNCw1MTAuMjc1IE05NS4wMiw1MDkuNzE3Yy0wLjA1OC0wLjA1MS0wLjE0NS0wLjA3Ny0wLjI1OC0wLjA3N2gtMC40Nzd2MC42MDRoMC40NDcNCgkJCWMwLjI1MiwwLDAuMzc3LTAuMTAxLDAuMzc3LTAuMzAxQzk1LjExMSw1MDkuODQyLDk1LjA3OCw1MDkuNzY0LDk1LjAyLDUwOS43MTciLz4NCgk8L2c+DQo8L2c+DQo8ZyBpZD0iTGF5ZXJfMyIgZGlzcGxheT0ibm9uZSI+DQoJDQoJCTxpbWFnZSBkaXNwbGF5PSJpbmxpbmUiIG92ZXJmbG93PSJ2aXNpYmxlIiB3aWR0aD0iMjE3IiBoZWlnaHQ9Ijk2IiB4bGluazpocmVmPSIuLi9EZXNrdG9wL1NjcmVlbiBTaG90IDIwMTMtMTEtMTkgYXQgNC41MS4zNyBQTS5wbmciICB0cmFuc2Zvcm09Im1hdHJpeCgxIDAgMCAxIC0xNDUuMjI3NSA0MDUuMjkpIj4NCgk8L2ltYWdlPg0KPC9nPg0KPC9zdmc+DQo=); } .logo a { display: block; width: 100%; height: 100%; } *, *:before, *:after { -moz-box-sizing: border-box; box-sizing: border-box; } aside, footer, header, hgroup, section{ display: block; } body { color: #404040; font-family: "Helvetica Neue",Helvetica,"Liberation Sans",Arial,sans-serif; font-size: 14px; line-height: 1.4; } html { font-family: sans-serif; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%; } ul { margin-top: 0; } .container { margin-right: auto; margin-left: auto; padding-left: 15px; padding-right: 15px; } .container:before, .container:after { content: " "; /* 1 */ display: table; /* 2 */ } .container:after { clear: both; } .row { margin-left: -15px; margin-right: -15px; } .row:before, .row:after { content: " "; /* 1 */ display: table; /* 2 */ } .row:after { clear: both; } .col-sm-6, .col-md-6, .col-xs-12 { position: relative; min-height: 1px; padding-left: 15px; padding-right: 15px; } .col-xs-12 { width: 100%; } @media (min-width: 768px) { .container { width: 750px; } .col-sm-6 { float: left; } .col-sm-6 { width: 50%; } } @media (min-width: 992px) { .container { width: 970px; } .col-md-6 { float: left; } .col-md-6 { width: 50%; } } @media (min-width: 1200px) { .container { width: 1170px; } } a { color: #069; text-decoration: none; } a:hover { color: #EA0011; text-decoration: underline; } hgroup { margin-top: 50px; } footer { margin: 50px 0 25px; font-size: 11px } h1, h2, h3 { color: #000; line-height: 1.38em; margin: 1.5em 0 .3em; } h1 { font-size: 25px; font-weight: 300; border-bottom: 1px solid #fff; margin-bottom: .5em; } h1:after { content: ""; display: block; width: 100%; height: 1px; background-color: #ddd; } h2 { font-size: 19px; font-weight: 400; } h3 { font-size: 15px; font-weight: 400; margin: 0 0 .3em; } p { margin: 0 0 2em; } p + h2 { margin-top: 2em; } html { background: #f5f5f5; height: 100%; } code { background-color: white; border: 1px solid #ccc; padding: 1px 5px; color: #888; } pre { display: block; padding: 13.333px 20px; margin: 0 0 20px; font-size: 13px; line-height: 1.4; background-color: #fff; border-left: 2px solid rgba(120,120,120,0.35); white-space: pre; white-space: pre-wrap; word-break: normal; word-wrap: break-word; overflow: auto; font-family: Menlo,Monaco,"Liberation Mono",Consolas,monospace !important; } </style> </head> <body> <section class='container'> <hgroup> <h1>Welcome to your Python application on OpenShift</h1> </hgroup> <div class="row"> <section class='col-xs-12 col-sm-6 col-md-6'> <section> <h2>Deploying code changes</h2> <p>OpenShift uses the <a href="http://git-scm.com/">Git version control system</a> for your source code, and grants you access to it via the Secure Shell (SSH) protocol. In order to upload and download code to your application you need to give us your <a href="https://www.openshift.com/developers/remote-access">public SSH key</a>. You can upload it within the web console or install the <a href="https://www.openshift.com/developers/rhc-client-tools-install">RHC command line tool</a> and run <code>rhc setup</code> to generate and upload your key automatically.</p> <h3>Working in your local Git repository</h3> <p>If you created your application from the command line and uploaded your SSH key, rhc will automatically download a copy of that source code repository (Git calls this 'cloning') to your local system.</p> <p>If you created the application from the web console, you'll need to manually clone the repository to your local system. Copy the application's source code Git URL and then run:</p> <pre>$ git clone &lt;git_url&gt; &lt;directory_to_create&gt; # Within your project directory # Commit your changes and push to OpenShift $ git commit -a -m 'Some commit message' $ git push</pre> <ul> <li><a href="https://www.openshift.com/developers/deploying-and-building-applications">Learn more about deploying and building your application</a></li> <li>See the README file in your local application Git repository for more information on the options for deploying applications.</li> </ul> </section> </section> <section class="col-xs-12 col-sm-6 col-md-6"> <h2>Managing your application</h2> <h3>Web Console</h3> <p>You can use the OpenShift web console to enable additional capabilities via cartridges, add collaborator access authorizations, designate custom domain aliases, and manage domain memberships.</p> <h3>Command Line Tools</h3> <p>Installing the <a href="https://www.openshift.com/developers/rhc-client-tools-install">OpenShift RHC client tools</a> allows you complete control of your cloud environment. Read more on how to manage your application from the command line in our <a href="https://www.openshift.com/user-guide">User Guide</a>. </p> <h2>Development Resources</h2> <ul> <li><a href="https://www.openshift.com/developers">Developer Center</a></li> <li><a href="https://www.openshift.com/user-guide">User Guide</a></li> <li><a href="https://www.openshift.com/support">OpenShift Support</a></li> <li><a href="http://stackoverflow.com/questions/tagged/openshift">Stack Overflow questions for OpenShift</a></li> <li><a href="http://webchat.freenode.net/?randomnick=1&channels=openshift&uio=d4">IRC channel at #openshift on freenode.net</a></li> <li><a href="http://git-scm.com/documentation">Git documentation</a></li> </ul> </section> </div> <footer> <div class="logo"><a href="https://www.openshift.com/"></a></div> </footer> </section> </body> </html>''' status = '200 OK' response_headers = [('Content-Type', ctype), ('Content-Length', str(len(response_body)))] # start_response(status, response_headers) return [response_body] # # Below for testing only # if __name__ == '__main__': from wsgiref.simple_server import make_server httpd = make_server('localhost', 8051, application) # Wait for a single request, serve it and quit. httpd.handle_request()
apache-2.0
stensonowen/spim-grader
spim-grader.py
2
3172
#!/usr/bin/python ''' SPIM Auto-grader Owen Stenson Grades every file in the 'submissions' folder using every test in the 'samples' folder. Writes to 'results' folder. ''' import os, time, re from subprocess import Popen, PIPE, STDOUT def run(fn, sample_input='\n'): #start process and write input proc = Popen(["spim", "-file", "submissions/"+fn], stdin=PIPE, stdout=PIPE, stderr=PIPE) if sample_input[-1:] != '\n': print "Warning: last line (of file below) must end with newline char to be submitted. Assuming it should..." sample_input = sample_input + '\n' proc.stdin.write(sample_input) return proc def grade(p, f): #arg = process running homework file, file to write results to print "Writing to ", f f = open("results/" + f, 'w') time.sleep(.1) if p.poll() is None: #process is either hanging or being slow time.sleep(5) if p.poll() is None: p.kill() f.write("Process hung; no results to report\n") f.close() return output = p.stdout.read() #remove output header hdrs = [] hdrs.append(re.compile("SPIM Version .* of .*\n")) hdrs.append(re.compile("Copyright .*, James R. Larus.\n")) hdrs.append(re.compile("All Rights Reserved.\n")) hdrs.append(re.compile("See the file README for a full copyright notice.\n")) hdrs.append(re.compile("Loaded: .*/spim/.*\n")) for hdr in hdrs: output = re.sub(hdr, "", output) errors = p.stderr.read() if errors == "": f.write("\t**PROCESS COMPLETED**\n") f.write(output + '\n'*2) else: f.write("\t**PROCESS FAILED TO COMPILE**\n") f.write(output + '\n' + errors + '\n'*2) f.close() def generate_filename(submission, sample): #extract RCS id from submission title try: rcs_start = submission.index('_') + 1 rcs_end = min(submission.index('attempt'), submission.index('.')) - 1 rcs = submission[rcs_start:rcs_end] except: rcs = submission return rcs + '__' + sample def main(): #no use in running if content directories aren't present assert os.path.isdir("samples") assert os.path.isdir("submissions") if os.path.isdir("results") is False: assert os.path.isfile("results") == False os.makedirs("results") #cycle through files to grade: for submission in os.listdir('submissions'): #cycle through samples to test (ignore .example): for sample in os.listdir('samples'): #ignore example files if submission == ".example" or sample == ".example": continue sample_file = open('samples/'+sample, 'r') #read sample input; fix windows EOL char sample_input = sample_file.read() sample_input = sample_input.replace('\r', '') #create process p = run(submission, sample_input) output_file = generate_filename(submission, sample) grade(p, output_file) if __name__ == "__main__": main()
gpl-2.0
j29rios/flinchbot
requests/packages/chardet/gb2312freq.py
3132
36011
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is Mozilla Communicator client code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### # GB2312 most frequently used character table # # Char to FreqOrder table , from hz6763 # 512 --> 0.79 -- 0.79 # 1024 --> 0.92 -- 0.13 # 2048 --> 0.98 -- 0.06 # 6768 --> 1.00 -- 0.02 # # Ideal Distribution Ratio = 0.79135/(1-0.79135) = 3.79 # Random Distribution Ration = 512 / (3755 - 512) = 0.157 # # Typical Distribution Ratio about 25% of Ideal one, still much higher that RDR GB2312_TYPICAL_DISTRIBUTION_RATIO = 0.9 GB2312_TABLE_SIZE = 3760 GB2312CharToFreqOrder = ( 1671, 749,1443,2364,3924,3807,2330,3921,1704,3463,2691,1511,1515, 572,3191,2205, 2361, 224,2558, 479,1711, 963,3162, 440,4060,1905,2966,2947,3580,2647,3961,3842, 2204, 869,4207, 970,2678,5626,2944,2956,1479,4048, 514,3595, 588,1346,2820,3409, 249,4088,1746,1873,2047,1774, 581,1813, 358,1174,3590,1014,1561,4844,2245, 670, 1636,3112, 889,1286, 953, 556,2327,3060,1290,3141, 613, 185,3477,1367, 850,3820, 1715,2428,2642,2303,2732,3041,2562,2648,3566,3946,1349, 388,3098,2091,1360,3585, 152,1687,1539, 738,1559, 59,1232,2925,2267,1388,1249,1741,1679,2960, 151,1566, 1125,1352,4271, 924,4296, 385,3166,4459, 310,1245,2850, 70,3285,2729,3534,3575, 2398,3298,3466,1960,2265, 217,3647, 864,1909,2084,4401,2773,1010,3269,5152, 853, 3051,3121,1244,4251,1895, 364,1499,1540,2313,1180,3655,2268, 562, 715,2417,3061, 544, 336,3768,2380,1752,4075, 950, 280,2425,4382, 183,2759,3272, 333,4297,2155, 1688,2356,1444,1039,4540, 736,1177,3349,2443,2368,2144,2225, 565, 196,1482,3406, 927,1335,4147, 692, 878,1311,1653,3911,3622,1378,4200,1840,2969,3149,2126,1816, 2534,1546,2393,2760, 737,2494, 13, 447, 245,2747, 38,2765,2129,2589,1079, 606, 360, 471,3755,2890, 404, 848, 699,1785,1236, 370,2221,1023,3746,2074,2026,2023, 2388,1581,2119, 812,1141,3091,2536,1519, 804,2053, 406,1596,1090, 784, 548,4414, 1806,2264,2936,1100, 343,4114,5096, 622,3358, 743,3668,1510,1626,5020,3567,2513, 3195,4115,5627,2489,2991, 24,2065,2697,1087,2719, 48,1634, 315, 68, 985,2052, 198,2239,1347,1107,1439, 597,2366,2172, 871,3307, 919,2487,2790,1867, 236,2570, 1413,3794, 906,3365,3381,1701,1982,1818,1524,2924,1205, 616,2586,2072,2004, 575, 253,3099, 32,1365,1182, 197,1714,2454,1201, 554,3388,3224,2748, 756,2587, 250, 2567,1507,1517,3529,1922,2761,2337,3416,1961,1677,2452,2238,3153, 615, 911,1506, 1474,2495,1265,1906,2749,3756,3280,2161, 898,2714,1759,3450,2243,2444, 563, 26, 3286,2266,3769,3344,2707,3677, 611,1402, 531,1028,2871,4548,1375, 261,2948, 835, 1190,4134, 353, 840,2684,1900,3082,1435,2109,1207,1674, 329,1872,2781,4055,2686, 2104, 608,3318,2423,2957,2768,1108,3739,3512,3271,3985,2203,1771,3520,1418,2054, 1681,1153, 225,1627,2929, 162,2050,2511,3687,1954, 124,1859,2431,1684,3032,2894, 585,4805,3969,2869,2704,2088,2032,2095,3656,2635,4362,2209, 256, 518,2042,2105, 3777,3657, 643,2298,1148,1779, 190, 989,3544, 414, 11,2135,2063,2979,1471, 403, 3678, 126, 770,1563, 671,2499,3216,2877, 600,1179, 307,2805,4937,1268,1297,2694, 252,4032,1448,1494,1331,1394, 127,2256, 222,1647,1035,1481,3056,1915,1048, 873, 3651, 210, 33,1608,2516, 200,1520, 415, 102, 0,3389,1287, 817, 91,3299,2940, 836,1814, 549,2197,1396,1669,2987,3582,2297,2848,4528,1070, 687, 20,1819, 121, 1552,1364,1461,1968,2617,3540,2824,2083, 177, 948,4938,2291, 110,4549,2066, 648, 3359,1755,2110,2114,4642,4845,1693,3937,3308,1257,1869,2123, 208,1804,3159,2992, 2531,2549,3361,2418,1350,2347,2800,2568,1291,2036,2680, 72, 842,1990, 212,1233, 1154,1586, 75,2027,3410,4900,1823,1337,2710,2676, 728,2810,1522,3026,4995, 157, 755,1050,4022, 710, 785,1936,2194,2085,1406,2777,2400, 150,1250,4049,1206, 807, 1910, 534, 529,3309,1721,1660, 274, 39,2827, 661,2670,1578, 925,3248,3815,1094, 4278,4901,4252, 41,1150,3747,2572,2227,4501,3658,4902,3813,3357,3617,2884,2258, 887, 538,4187,3199,1294,2439,3042,2329,2343,2497,1255, 107, 543,1527, 521,3478, 3568, 194,5062, 15, 961,3870,1241,1192,2664, 66,5215,3260,2111,1295,1127,2152, 3805,4135, 901,1164,1976, 398,1278, 530,1460, 748, 904,1054,1966,1426, 53,2909, 509, 523,2279,1534, 536,1019, 239,1685, 460,2353, 673,1065,2401,3600,4298,2272, 1272,2363, 284,1753,3679,4064,1695, 81, 815,2677,2757,2731,1386, 859, 500,4221, 2190,2566, 757,1006,2519,2068,1166,1455, 337,2654,3203,1863,1682,1914,3025,1252, 1409,1366, 847, 714,2834,2038,3209, 964,2970,1901, 885,2553,1078,1756,3049, 301, 1572,3326, 688,2130,1996,2429,1805,1648,2930,3421,2750,3652,3088, 262,1158,1254, 389,1641,1812, 526,1719, 923,2073,1073,1902, 468, 489,4625,1140, 857,2375,3070, 3319,2863, 380, 116,1328,2693,1161,2244, 273,1212,1884,2769,3011,1775,1142, 461, 3066,1200,2147,2212, 790, 702,2695,4222,1601,1058, 434,2338,5153,3640, 67,2360, 4099,2502, 618,3472,1329, 416,1132, 830,2782,1807,2653,3211,3510,1662, 192,2124, 296,3979,1739,1611,3684, 23, 118, 324, 446,1239,1225, 293,2520,3814,3795,2535, 3116, 17,1074, 467,2692,2201, 387,2922, 45,1326,3055,1645,3659,2817, 958, 243, 1903,2320,1339,2825,1784,3289, 356, 576, 865,2315,2381,3377,3916,1088,3122,1713, 1655, 935, 628,4689,1034,1327, 441, 800, 720, 894,1979,2183,1528,5289,2702,1071, 4046,3572,2399,1571,3281, 79, 761,1103, 327, 134, 758,1899,1371,1615, 879, 442, 215,2605,2579, 173,2048,2485,1057,2975,3317,1097,2253,3801,4263,1403,1650,2946, 814,4968,3487,1548,2644,1567,1285, 2, 295,2636, 97, 946,3576, 832, 141,4257, 3273, 760,3821,3521,3156,2607, 949,1024,1733,1516,1803,1920,2125,2283,2665,3180, 1501,2064,3560,2171,1592, 803,3518,1416, 732,3897,4258,1363,1362,2458, 119,1427, 602,1525,2608,1605,1639,3175, 694,3064, 10, 465, 76,2000,4846,4208, 444,3781, 1619,3353,2206,1273,3796, 740,2483, 320,1723,2377,3660,2619,1359,1137,1762,1724, 2345,2842,1850,1862, 912, 821,1866, 612,2625,1735,2573,3369,1093, 844, 89, 937, 930,1424,3564,2413,2972,1004,3046,3019,2011, 711,3171,1452,4178, 428, 801,1943, 432, 445,2811, 206,4136,1472, 730, 349, 73, 397,2802,2547, 998,1637,1167, 789, 396,3217, 154,1218, 716,1120,1780,2819,4826,1931,3334,3762,2139,1215,2627, 552, 3664,3628,3232,1405,2383,3111,1356,2652,3577,3320,3101,1703, 640,1045,1370,1246, 4996, 371,1575,2436,1621,2210, 984,4033,1734,2638, 16,4529, 663,2755,3255,1451, 3917,2257,1253,1955,2234,1263,2951, 214,1229, 617, 485, 359,1831,1969, 473,2310, 750,2058, 165, 80,2864,2419, 361,4344,2416,2479,1134, 796,3726,1266,2943, 860, 2715, 938, 390,2734,1313,1384, 248, 202, 877,1064,2854, 522,3907, 279,1602, 297, 2357, 395,3740, 137,2075, 944,4089,2584,1267,3802, 62,1533,2285, 178, 176, 780, 2440, 201,3707, 590, 478,1560,4354,2117,1075, 30, 74,4643,4004,1635,1441,2745, 776,2596, 238,1077,1692,1912,2844, 605, 499,1742,3947, 241,3053, 980,1749, 936, 2640,4511,2582, 515,1543,2162,5322,2892,2993, 890,2148,1924, 665,1827,3581,1032, 968,3163, 339,1044,1896, 270, 583,1791,1720,4367,1194,3488,3669, 43,2523,1657, 163,2167, 290,1209,1622,3378, 550, 634,2508,2510, 695,2634,2384,2512,1476,1414, 220,1469,2341,2138,2852,3183,2900,4939,2865,3502,1211,3680, 854,3227,1299,2976, 3172, 186,2998,1459, 443,1067,3251,1495, 321,1932,3054, 909, 753,1410,1828, 436, 2441,1119,1587,3164,2186,1258, 227, 231,1425,1890,3200,3942, 247, 959, 725,5254, 2741, 577,2158,2079, 929, 120, 174, 838,2813, 591,1115, 417,2024, 40,3240,1536, 1037, 291,4151,2354, 632,1298,2406,2500,3535,1825,1846,3451, 205,1171, 345,4238, 18,1163, 811, 685,2208,1217, 425,1312,1508,1175,4308,2552,1033, 587,1381,3059, 2984,3482, 340,1316,4023,3972, 792,3176, 519, 777,4690, 918, 933,4130,2981,3741, 90,3360,2911,2200,5184,4550, 609,3079,2030, 272,3379,2736, 363,3881,1130,1447, 286, 779, 357,1169,3350,3137,1630,1220,2687,2391, 747,1277,3688,2618,2682,2601, 1156,3196,5290,4034,3102,1689,3596,3128, 874, 219,2783, 798, 508,1843,2461, 269, 1658,1776,1392,1913,2983,3287,2866,2159,2372, 829,4076, 46,4253,2873,1889,1894, 915,1834,1631,2181,2318, 298, 664,2818,3555,2735, 954,3228,3117, 527,3511,2173, 681,2712,3033,2247,2346,3467,1652, 155,2164,3382, 113,1994, 450, 899, 494, 994, 1237,2958,1875,2336,1926,3727, 545,1577,1550, 633,3473, 204,1305,3072,2410,1956, 2471, 707,2134, 841,2195,2196,2663,3843,1026,4940, 990,3252,4997, 368,1092, 437, 3212,3258,1933,1829, 675,2977,2893, 412, 943,3723,4644,3294,3283,2230,2373,5154, 2389,2241,2661,2323,1404,2524, 593, 787, 677,3008,1275,2059, 438,2709,2609,2240, 2269,2246,1446, 36,1568,1373,3892,1574,2301,1456,3962, 693,2276,5216,2035,1143, 2720,1919,1797,1811,2763,4137,2597,1830,1699,1488,1198,2090, 424,1694, 312,3634, 3390,4179,3335,2252,1214, 561,1059,3243,2295,2561, 975,5155,2321,2751,3772, 472, 1537,3282,3398,1047,2077,2348,2878,1323,3340,3076, 690,2906, 51, 369, 170,3541, 1060,2187,2688,3670,2541,1083,1683, 928,3918, 459, 109,4427, 599,3744,4286, 143, 2101,2730,2490, 82,1588,3036,2121, 281,1860, 477,4035,1238,2812,3020,2716,3312, 1530,2188,2055,1317, 843, 636,1808,1173,3495, 649, 181,1002, 147,3641,1159,2414, 3750,2289,2795, 813,3123,2610,1136,4368, 5,3391,4541,2174, 420, 429,1728, 754, 1228,2115,2219, 347,2223,2733, 735,1518,3003,2355,3134,1764,3948,3329,1888,2424, 1001,1234,1972,3321,3363,1672,1021,1450,1584, 226, 765, 655,2526,3404,3244,2302, 3665, 731, 594,2184, 319,1576, 621, 658,2656,4299,2099,3864,1279,2071,2598,2739, 795,3086,3699,3908,1707,2352,2402,1382,3136,2475,1465,4847,3496,3865,1085,3004, 2591,1084, 213,2287,1963,3565,2250, 822, 793,4574,3187,1772,1789,3050, 595,1484, 1959,2770,1080,2650, 456, 422,2996, 940,3322,4328,4345,3092,2742, 965,2784, 739, 4124, 952,1358,2498,2949,2565, 332,2698,2378, 660,2260,2473,4194,3856,2919, 535, 1260,2651,1208,1428,1300,1949,1303,2942, 433,2455,2450,1251,1946, 614,1269, 641, 1306,1810,2737,3078,2912, 564,2365,1419,1415,1497,4460,2367,2185,1379,3005,1307, 3218,2175,1897,3063, 682,1157,4040,4005,1712,1160,1941,1399, 394, 402,2952,1573, 1151,2986,2404, 862, 299,2033,1489,3006, 346, 171,2886,3401,1726,2932, 168,2533, 47,2507,1030,3735,1145,3370,1395,1318,1579,3609,4560,2857,4116,1457,2529,1965, 504,1036,2690,2988,2405, 745,5871, 849,2397,2056,3081, 863,2359,3857,2096, 99, 1397,1769,2300,4428,1643,3455,1978,1757,3718,1440, 35,4879,3742,1296,4228,2280, 160,5063,1599,2013, 166, 520,3479,1646,3345,3012, 490,1937,1545,1264,2182,2505, 1096,1188,1369,1436,2421,1667,2792,2460,1270,2122, 727,3167,2143, 806,1706,1012, 1800,3037, 960,2218,1882, 805, 139,2456,1139,1521, 851,1052,3093,3089, 342,2039, 744,5097,1468,1502,1585,2087, 223, 939, 326,2140,2577, 892,2481,1623,4077, 982, 3708, 135,2131, 87,2503,3114,2326,1106, 876,1616, 547,2997,2831,2093,3441,4530, 4314, 9,3256,4229,4148, 659,1462,1986,1710,2046,2913,2231,4090,4880,5255,3392, 3274,1368,3689,4645,1477, 705,3384,3635,1068,1529,2941,1458,3782,1509, 100,1656, 2548, 718,2339, 408,1590,2780,3548,1838,4117,3719,1345,3530, 717,3442,2778,3220, 2898,1892,4590,3614,3371,2043,1998,1224,3483, 891, 635, 584,2559,3355, 733,1766, 1729,1172,3789,1891,2307, 781,2982,2271,1957,1580,5773,2633,2005,4195,3097,1535, 3213,1189,1934,5693,3262, 586,3118,1324,1598, 517,1564,2217,1868,1893,4445,3728, 2703,3139,1526,1787,1992,3882,2875,1549,1199,1056,2224,1904,2711,5098,4287, 338, 1993,3129,3489,2689,1809,2815,1997, 957,1855,3898,2550,3275,3057,1105,1319, 627, 1505,1911,1883,3526, 698,3629,3456,1833,1431, 746, 77,1261,2017,2296,1977,1885, 125,1334,1600, 525,1798,1109,2222,1470,1945, 559,2236,1186,3443,2476,1929,1411, 2411,3135,1777,3372,2621,1841,1613,3229, 668,1430,1839,2643,2916, 195,1989,2671, 2358,1387, 629,3205,2293,5256,4439, 123,1310, 888,1879,4300,3021,3605,1003,1162, 3192,2910,2010, 140,2395,2859, 55,1082,2012,2901, 662, 419,2081,1438, 680,2774, 4654,3912,1620,1731,1625,5035,4065,2328, 512,1344, 802,5443,2163,2311,2537, 524, 3399, 98,1155,2103,1918,2606,3925,2816,1393,2465,1504,3773,2177,3963,1478,4346, 180,1113,4655,3461,2028,1698, 833,2696,1235,1322,1594,4408,3623,3013,3225,2040, 3022, 541,2881, 607,3632,2029,1665,1219, 639,1385,1686,1099,2803,3231,1938,3188, 2858, 427, 676,2772,1168,2025, 454,3253,2486,3556, 230,1950, 580, 791,1991,1280, 1086,1974,2034, 630, 257,3338,2788,4903,1017, 86,4790, 966,2789,1995,1696,1131, 259,3095,4188,1308, 179,1463,5257, 289,4107,1248, 42,3413,1725,2288, 896,1947, 774,4474,4254, 604,3430,4264, 392,2514,2588, 452, 237,1408,3018, 988,4531,1970, 3034,3310, 540,2370,1562,1288,2990, 502,4765,1147, 4,1853,2708, 207, 294,2814, 4078,2902,2509, 684, 34,3105,3532,2551, 644, 709,2801,2344, 573,1727,3573,3557, 2021,1081,3100,4315,2100,3681, 199,2263,1837,2385, 146,3484,1195,2776,3949, 997, 1939,3973,1008,1091,1202,1962,1847,1149,4209,5444,1076, 493, 117,5400,2521, 972, 1490,2934,1796,4542,2374,1512,2933,2657, 413,2888,1135,2762,2314,2156,1355,2369, 766,2007,2527,2170,3124,2491,2593,2632,4757,2437, 234,3125,3591,1898,1750,1376, 1942,3468,3138, 570,2127,2145,3276,4131, 962, 132,1445,4196, 19, 941,3624,3480, 3366,1973,1374,4461,3431,2629, 283,2415,2275, 808,2887,3620,2112,2563,1353,3610, 955,1089,3103,1053, 96, 88,4097, 823,3808,1583, 399, 292,4091,3313, 421,1128, 642,4006, 903,2539,1877,2082, 596, 29,4066,1790, 722,2157, 130, 995,1569, 769, 1485, 464, 513,2213, 288,1923,1101,2453,4316, 133, 486,2445, 50, 625, 487,2207, 57, 423, 481,2962, 159,3729,1558, 491, 303, 482, 501, 240,2837, 112,3648,2392, 1783, 362, 8,3433,3422, 610,2793,3277,1390,1284,1654, 21,3823, 734, 367, 623, 193, 287, 374,1009,1483, 816, 476, 313,2255,2340,1262,2150,2899,1146,2581, 782, 2116,1659,2018,1880, 255,3586,3314,1110,2867,2137,2564, 986,2767,5185,2006, 650, 158, 926, 762, 881,3157,2717,2362,3587, 306,3690,3245,1542,3077,2427,1691,2478, 2118,2985,3490,2438, 539,2305, 983, 129,1754, 355,4201,2386, 827,2923, 104,1773, 2838,2771, 411,2905,3919, 376, 767, 122,1114, 828,2422,1817,3506, 266,3460,1007, 1609,4998, 945,2612,4429,2274, 726,1247,1964,2914,2199,2070,4002,4108, 657,3323, 1422, 579, 455,2764,4737,1222,2895,1670, 824,1223,1487,2525, 558, 861,3080, 598, 2659,2515,1967, 752,2583,2376,2214,4180, 977, 704,2464,4999,2622,4109,1210,2961, 819,1541, 142,2284, 44, 418, 457,1126,3730,4347,4626,1644,1876,3671,1864, 302, 1063,5694, 624, 723,1984,3745,1314,1676,2488,1610,1449,3558,3569,2166,2098, 409, 1011,2325,3704,2306, 818,1732,1383,1824,1844,3757, 999,2705,3497,1216,1423,2683, 2426,2954,2501,2726,2229,1475,2554,5064,1971,1794,1666,2014,1343, 783, 724, 191, 2434,1354,2220,5065,1763,2752,2472,4152, 131, 175,2885,3434, 92,1466,4920,2616, 3871,3872,3866, 128,1551,1632, 669,1854,3682,4691,4125,1230, 188,2973,3290,1302, 1213, 560,3266, 917, 763,3909,3249,1760, 868,1958, 764,1782,2097, 145,2277,3774, 4462, 64,1491,3062, 971,2132,3606,2442, 221,1226,1617, 218, 323,1185,3207,3147, 571, 619,1473,1005,1744,2281, 449,1887,2396,3685, 275, 375,3816,1743,3844,3731, 845,1983,2350,4210,1377, 773, 967,3499,3052,3743,2725,4007,1697,1022,3943,1464, 3264,2855,2722,1952,1029,2839,2467, 84,4383,2215, 820,1391,2015,2448,3672, 377, 1948,2168, 797,2545,3536,2578,2645, 94,2874,1678, 405,1259,3071, 771, 546,1315, 470,1243,3083, 895,2468, 981, 969,2037, 846,4181, 653,1276,2928, 14,2594, 557, 3007,2474, 156, 902,1338,1740,2574, 537,2518, 973,2282,2216,2433,1928, 138,2903, 1293,2631,1612, 646,3457, 839,2935, 111, 496,2191,2847, 589,3186, 149,3994,2060, 4031,2641,4067,3145,1870, 37,3597,2136,1025,2051,3009,3383,3549,1121,1016,3261, 1301, 251,2446,2599,2153, 872,3246, 637, 334,3705, 831, 884, 921,3065,3140,4092, 2198,1944, 246,2964, 108,2045,1152,1921,2308,1031, 203,3173,4170,1907,3890, 810, 1401,2003,1690, 506, 647,1242,2828,1761,1649,3208,2249,1589,3709,2931,5156,1708, 498, 666,2613, 834,3817,1231, 184,2851,1124, 883,3197,2261,3710,1765,1553,2658, 1178,2639,2351, 93,1193, 942,2538,2141,4402, 235,1821, 870,1591,2192,1709,1871, 3341,1618,4126,2595,2334, 603, 651, 69, 701, 268,2662,3411,2555,1380,1606, 503, 448, 254,2371,2646, 574,1187,2309,1770, 322,2235,1292,1801, 305, 566,1133, 229, 2067,2057, 706, 167, 483,2002,2672,3295,1820,3561,3067, 316, 378,2746,3452,1112, 136,1981, 507,1651,2917,1117, 285,4591, 182,2580,3522,1304, 335,3303,1835,2504, 1795,1792,2248, 674,1018,2106,2449,1857,2292,2845, 976,3047,1781,2600,2727,1389, 1281, 52,3152, 153, 265,3950, 672,3485,3951,4463, 430,1183, 365, 278,2169, 27, 1407,1336,2304, 209,1340,1730,2202,1852,2403,2883, 979,1737,1062, 631,2829,2542, 3876,2592, 825,2086,2226,3048,3625, 352,1417,3724, 542, 991, 431,1351,3938,1861, 2294, 826,1361,2927,3142,3503,1738, 463,2462,2723, 582,1916,1595,2808, 400,3845, 3891,2868,3621,2254, 58,2492,1123, 910,2160,2614,1372,1603,1196,1072,3385,1700, 3267,1980, 696, 480,2430, 920, 799,1570,2920,1951,2041,4047,2540,1321,4223,2469, 3562,2228,1271,2602, 401,2833,3351,2575,5157, 907,2312,1256, 410, 263,3507,1582, 996, 678,1849,2316,1480, 908,3545,2237, 703,2322, 667,1826,2849,1531,2604,2999, 2407,3146,2151,2630,1786,3711, 469,3542, 497,3899,2409, 858, 837,4446,3393,1274, 786, 620,1845,2001,3311, 484, 308,3367,1204,1815,3691,2332,1532,2557,1842,2020, 2724,1927,2333,4440, 567, 22,1673,2728,4475,1987,1858,1144,1597, 101,1832,3601, 12, 974,3783,4391, 951,1412, 1,3720, 453,4608,4041, 528,1041,1027,3230,2628, 1129, 875,1051,3291,1203,2262,1069,2860,2799,2149,2615,3278, 144,1758,3040, 31, 475,1680, 366,2685,3184, 311,1642,4008,2466,5036,1593,1493,2809, 216,1420,1668, 233, 304,2128,3284, 232,1429,1768,1040,2008,3407,2740,2967,2543, 242,2133, 778, 1565,2022,2620, 505,2189,2756,1098,2273, 372,1614, 708, 553,2846,2094,2278, 169, 3626,2835,4161, 228,2674,3165, 809,1454,1309, 466,1705,1095, 900,3423, 880,2667, 3751,5258,2317,3109,2571,4317,2766,1503,1342, 866,4447,1118, 63,2076, 314,1881, 1348,1061, 172, 978,3515,1747, 532, 511,3970, 6, 601, 905,2699,3300,1751, 276, 1467,3725,2668, 65,4239,2544,2779,2556,1604, 578,2451,1802, 992,2331,2624,1320, 3446, 713,1513,1013, 103,2786,2447,1661, 886,1702, 916, 654,3574,2031,1556, 751, 2178,2821,2179,1498,1538,2176, 271, 914,2251,2080,1325, 638,1953,2937,3877,2432, 2754, 95,3265,1716, 260,1227,4083, 775, 106,1357,3254, 426,1607, 555,2480, 772, 1985, 244,2546, 474, 495,1046,2611,1851,2061, 71,2089,1675,2590, 742,3758,2843, 3222,1433, 267,2180,2576,2826,2233,2092,3913,2435, 956,1745,3075, 856,2113,1116, 451, 3,1988,2896,1398, 993,2463,1878,2049,1341,2718,2721,2870,2108, 712,2904, 4363,2753,2324, 277,2872,2349,2649, 384, 987, 435, 691,3000, 922, 164,3939, 652, 1500,1184,4153,2482,3373,2165,4848,2335,3775,3508,3154,2806,2830,1554,2102,1664, 2530,1434,2408, 893,1547,2623,3447,2832,2242,2532,3169,2856,3223,2078, 49,3770, 3469, 462, 318, 656,2259,3250,3069, 679,1629,2758, 344,1138,1104,3120,1836,1283, 3115,2154,1437,4448, 934, 759,1999, 794,2862,1038, 533,2560,1722,2342, 855,2626, 1197,1663,4476,3127, 85,4240,2528, 25,1111,1181,3673, 407,3470,4561,2679,2713, 768,1925,2841,3986,1544,1165, 932, 373,1240,2146,1930,2673, 721,4766, 354,4333, 391,2963, 187, 61,3364,1442,1102, 330,1940,1767, 341,3809,4118, 393,2496,2062, 2211, 105, 331, 300, 439, 913,1332, 626, 379,3304,1557, 328, 689,3952, 309,1555, 931, 317,2517,3027, 325, 569, 686,2107,3084, 60,1042,1333,2794, 264,3177,4014, 1628, 258,3712, 7,4464,1176,1043,1778, 683, 114,1975, 78,1492, 383,1886, 510, 386, 645,5291,2891,2069,3305,4138,3867,2939,2603,2493,1935,1066,1848,3588,1015, 1282,1289,4609, 697,1453,3044,2666,3611,1856,2412, 54, 719,1330, 568,3778,2459, 1748, 788, 492, 551,1191,1000, 488,3394,3763, 282,1799, 348,2016,1523,3155,2390, 1049, 382,2019,1788,1170, 729,2968,3523, 897,3926,2785,2938,3292, 350,2319,3238, 1718,1717,2655,3453,3143,4465, 161,2889,2980,2009,1421, 56,1908,1640,2387,2232, 1917,1874,2477,4921, 148, 83,3438, 592,4245,2882,1822,1055, 741, 115,1496,1624, 381,1638,4592,1020, 516,3214, 458, 947,4575,1432, 211,1514,2926,1865,2142, 189, 852,1221,1400,1486, 882,2299,4036, 351, 28,1122, 700,6479,6480,6481,6482,6483, # last 512 #Everything below is of no interest for detection purpose 5508,6484,3900,3414,3974,4441,4024,3537,4037,5628,5099,3633,6485,3148,6486,3636, 5509,3257,5510,5973,5445,5872,4941,4403,3174,4627,5873,6276,2286,4230,5446,5874, 5122,6102,6103,4162,5447,5123,5323,4849,6277,3980,3851,5066,4246,5774,5067,6278, 3001,2807,5695,3346,5775,5974,5158,5448,6487,5975,5976,5776,3598,6279,5696,4806, 4211,4154,6280,6488,6489,6490,6281,4212,5037,3374,4171,6491,4562,4807,4722,4827, 5977,6104,4532,4079,5159,5324,5160,4404,3858,5359,5875,3975,4288,4610,3486,4512, 5325,3893,5360,6282,6283,5560,2522,4231,5978,5186,5449,2569,3878,6284,5401,3578, 4415,6285,4656,5124,5979,2506,4247,4449,3219,3417,4334,4969,4329,6492,4576,4828, 4172,4416,4829,5402,6286,3927,3852,5361,4369,4830,4477,4867,5876,4173,6493,6105, 4657,6287,6106,5877,5450,6494,4155,4868,5451,3700,5629,4384,6288,6289,5878,3189, 4881,6107,6290,6495,4513,6496,4692,4515,4723,5100,3356,6497,6291,3810,4080,5561, 3570,4430,5980,6498,4355,5697,6499,4724,6108,6109,3764,4050,5038,5879,4093,3226, 6292,5068,5217,4693,3342,5630,3504,4831,4377,4466,4309,5698,4431,5777,6293,5778, 4272,3706,6110,5326,3752,4676,5327,4273,5403,4767,5631,6500,5699,5880,3475,5039, 6294,5562,5125,4348,4301,4482,4068,5126,4593,5700,3380,3462,5981,5563,3824,5404, 4970,5511,3825,4738,6295,6501,5452,4516,6111,5881,5564,6502,6296,5982,6503,4213, 4163,3454,6504,6112,4009,4450,6113,4658,6297,6114,3035,6505,6115,3995,4904,4739, 4563,4942,4110,5040,3661,3928,5362,3674,6506,5292,3612,4791,5565,4149,5983,5328, 5259,5021,4725,4577,4564,4517,4364,6298,5405,4578,5260,4594,4156,4157,5453,3592, 3491,6507,5127,5512,4709,4922,5984,5701,4726,4289,6508,4015,6116,5128,4628,3424, 4241,5779,6299,4905,6509,6510,5454,5702,5780,6300,4365,4923,3971,6511,5161,3270, 3158,5985,4100, 867,5129,5703,6117,5363,3695,3301,5513,4467,6118,6512,5455,4232, 4242,4629,6513,3959,4478,6514,5514,5329,5986,4850,5162,5566,3846,4694,6119,5456, 4869,5781,3779,6301,5704,5987,5515,4710,6302,5882,6120,4392,5364,5705,6515,6121, 6516,6517,3736,5988,5457,5989,4695,2457,5883,4551,5782,6303,6304,6305,5130,4971, 6122,5163,6123,4870,3263,5365,3150,4871,6518,6306,5783,5069,5706,3513,3498,4409, 5330,5632,5366,5458,5459,3991,5990,4502,3324,5991,5784,3696,4518,5633,4119,6519, 4630,5634,4417,5707,4832,5992,3418,6124,5993,5567,4768,5218,6520,4595,3458,5367, 6125,5635,6126,4202,6521,4740,4924,6307,3981,4069,4385,6308,3883,2675,4051,3834, 4302,4483,5568,5994,4972,4101,5368,6309,5164,5884,3922,6127,6522,6523,5261,5460, 5187,4164,5219,3538,5516,4111,3524,5995,6310,6311,5369,3181,3386,2484,5188,3464, 5569,3627,5708,6524,5406,5165,4677,4492,6312,4872,4851,5885,4468,5996,6313,5709, 5710,6128,2470,5886,6314,5293,4882,5785,3325,5461,5101,6129,5711,5786,6525,4906, 6526,6527,4418,5887,5712,4808,2907,3701,5713,5888,6528,3765,5636,5331,6529,6530, 3593,5889,3637,4943,3692,5714,5787,4925,6315,6130,5462,4405,6131,6132,6316,5262, 6531,6532,5715,3859,5716,5070,4696,5102,3929,5788,3987,4792,5997,6533,6534,3920, 4809,5000,5998,6535,2974,5370,6317,5189,5263,5717,3826,6536,3953,5001,4883,3190, 5463,5890,4973,5999,4741,6133,6134,3607,5570,6000,4711,3362,3630,4552,5041,6318, 6001,2950,2953,5637,4646,5371,4944,6002,2044,4120,3429,6319,6537,5103,4833,6538, 6539,4884,4647,3884,6003,6004,4758,3835,5220,5789,4565,5407,6540,6135,5294,4697, 4852,6320,6321,3206,4907,6541,6322,4945,6542,6136,6543,6323,6005,4631,3519,6544, 5891,6545,5464,3784,5221,6546,5571,4659,6547,6324,6137,5190,6548,3853,6549,4016, 4834,3954,6138,5332,3827,4017,3210,3546,4469,5408,5718,3505,4648,5790,5131,5638, 5791,5465,4727,4318,6325,6326,5792,4553,4010,4698,3439,4974,3638,4335,3085,6006, 5104,5042,5166,5892,5572,6327,4356,4519,5222,5573,5333,5793,5043,6550,5639,5071, 4503,6328,6139,6551,6140,3914,3901,5372,6007,5640,4728,4793,3976,3836,4885,6552, 4127,6553,4451,4102,5002,6554,3686,5105,6555,5191,5072,5295,4611,5794,5296,6556, 5893,5264,5894,4975,5466,5265,4699,4976,4370,4056,3492,5044,4886,6557,5795,4432, 4769,4357,5467,3940,4660,4290,6141,4484,4770,4661,3992,6329,4025,4662,5022,4632, 4835,4070,5297,4663,4596,5574,5132,5409,5895,6142,4504,5192,4664,5796,5896,3885, 5575,5797,5023,4810,5798,3732,5223,4712,5298,4084,5334,5468,6143,4052,4053,4336, 4977,4794,6558,5335,4908,5576,5224,4233,5024,4128,5469,5225,4873,6008,5045,4729, 4742,4633,3675,4597,6559,5897,5133,5577,5003,5641,5719,6330,6560,3017,2382,3854, 4406,4811,6331,4393,3964,4946,6561,2420,3722,6562,4926,4378,3247,1736,4442,6332, 5134,6333,5226,3996,2918,5470,4319,4003,4598,4743,4744,4485,3785,3902,5167,5004, 5373,4394,5898,6144,4874,1793,3997,6334,4085,4214,5106,5642,4909,5799,6009,4419, 4189,3330,5899,4165,4420,5299,5720,5227,3347,6145,4081,6335,2876,3930,6146,3293, 3786,3910,3998,5900,5300,5578,2840,6563,5901,5579,6147,3531,5374,6564,6565,5580, 4759,5375,6566,6148,3559,5643,6336,6010,5517,6337,6338,5721,5902,3873,6011,6339, 6567,5518,3868,3649,5722,6568,4771,4947,6569,6149,4812,6570,2853,5471,6340,6341, 5644,4795,6342,6012,5723,6343,5724,6013,4349,6344,3160,6150,5193,4599,4514,4493, 5168,4320,6345,4927,3666,4745,5169,5903,5005,4928,6346,5725,6014,4730,4203,5046, 4948,3395,5170,6015,4150,6016,5726,5519,6347,5047,3550,6151,6348,4197,4310,5904, 6571,5581,2965,6152,4978,3960,4291,5135,6572,5301,5727,4129,4026,5905,4853,5728, 5472,6153,6349,4533,2700,4505,5336,4678,3583,5073,2994,4486,3043,4554,5520,6350, 6017,5800,4487,6351,3931,4103,5376,6352,4011,4321,4311,4190,5136,6018,3988,3233, 4350,5906,5645,4198,6573,5107,3432,4191,3435,5582,6574,4139,5410,6353,5411,3944, 5583,5074,3198,6575,6354,4358,6576,5302,4600,5584,5194,5412,6577,6578,5585,5413, 5303,4248,5414,3879,4433,6579,4479,5025,4854,5415,6355,4760,4772,3683,2978,4700, 3797,4452,3965,3932,3721,4910,5801,6580,5195,3551,5907,3221,3471,3029,6019,3999, 5908,5909,5266,5267,3444,3023,3828,3170,4796,5646,4979,4259,6356,5647,5337,3694, 6357,5648,5338,4520,4322,5802,3031,3759,4071,6020,5586,4836,4386,5048,6581,3571, 4679,4174,4949,6154,4813,3787,3402,3822,3958,3215,3552,5268,4387,3933,4950,4359, 6021,5910,5075,3579,6358,4234,4566,5521,6359,3613,5049,6022,5911,3375,3702,3178, 4911,5339,4521,6582,6583,4395,3087,3811,5377,6023,6360,6155,4027,5171,5649,4421, 4249,2804,6584,2270,6585,4000,4235,3045,6156,5137,5729,4140,4312,3886,6361,4330, 6157,4215,6158,3500,3676,4929,4331,3713,4930,5912,4265,3776,3368,5587,4470,4855, 3038,4980,3631,6159,6160,4132,4680,6161,6362,3923,4379,5588,4255,6586,4121,6587, 6363,4649,6364,3288,4773,4774,6162,6024,6365,3543,6588,4274,3107,3737,5050,5803, 4797,4522,5589,5051,5730,3714,4887,5378,4001,4523,6163,5026,5522,4701,4175,2791, 3760,6589,5473,4224,4133,3847,4814,4815,4775,3259,5416,6590,2738,6164,6025,5304, 3733,5076,5650,4816,5590,6591,6165,6592,3934,5269,6593,3396,5340,6594,5804,3445, 3602,4042,4488,5731,5732,3525,5591,4601,5196,6166,6026,5172,3642,4612,3202,4506, 4798,6366,3818,5108,4303,5138,5139,4776,3332,4304,2915,3415,4434,5077,5109,4856, 2879,5305,4817,6595,5913,3104,3144,3903,4634,5341,3133,5110,5651,5805,6167,4057, 5592,2945,4371,5593,6596,3474,4182,6367,6597,6168,4507,4279,6598,2822,6599,4777, 4713,5594,3829,6169,3887,5417,6170,3653,5474,6368,4216,2971,5228,3790,4579,6369, 5733,6600,6601,4951,4746,4555,6602,5418,5475,6027,3400,4665,5806,6171,4799,6028, 5052,6172,3343,4800,4747,5006,6370,4556,4217,5476,4396,5229,5379,5477,3839,5914, 5652,5807,4714,3068,4635,5808,6173,5342,4192,5078,5419,5523,5734,6174,4557,6175, 4602,6371,6176,6603,5809,6372,5735,4260,3869,5111,5230,6029,5112,6177,3126,4681, 5524,5915,2706,3563,4748,3130,6178,4018,5525,6604,6605,5478,4012,4837,6606,4534, 4193,5810,4857,3615,5479,6030,4082,3697,3539,4086,5270,3662,4508,4931,5916,4912, 5811,5027,3888,6607,4397,3527,3302,3798,2775,2921,2637,3966,4122,4388,4028,4054, 1633,4858,5079,3024,5007,3982,3412,5736,6608,3426,3236,5595,3030,6179,3427,3336, 3279,3110,6373,3874,3039,5080,5917,5140,4489,3119,6374,5812,3405,4494,6031,4666, 4141,6180,4166,6032,5813,4981,6609,5081,4422,4982,4112,3915,5653,3296,3983,6375, 4266,4410,5654,6610,6181,3436,5082,6611,5380,6033,3819,5596,4535,5231,5306,5113, 6612,4952,5918,4275,3113,6613,6376,6182,6183,5814,3073,4731,4838,5008,3831,6614, 4888,3090,3848,4280,5526,5232,3014,5655,5009,5737,5420,5527,6615,5815,5343,5173, 5381,4818,6616,3151,4953,6617,5738,2796,3204,4360,2989,4281,5739,5174,5421,5197, 3132,5141,3849,5142,5528,5083,3799,3904,4839,5480,2880,4495,3448,6377,6184,5271, 5919,3771,3193,6034,6035,5920,5010,6036,5597,6037,6378,6038,3106,5422,6618,5423, 5424,4142,6619,4889,5084,4890,4313,5740,6620,3437,5175,5307,5816,4199,5198,5529, 5817,5199,5656,4913,5028,5344,3850,6185,2955,5272,5011,5818,4567,4580,5029,5921, 3616,5233,6621,6622,6186,4176,6039,6379,6380,3352,5200,5273,2908,5598,5234,3837, 5308,6623,6624,5819,4496,4323,5309,5201,6625,6626,4983,3194,3838,4167,5530,5922, 5274,6381,6382,3860,3861,5599,3333,4292,4509,6383,3553,5481,5820,5531,4778,6187, 3955,3956,4324,4389,4218,3945,4325,3397,2681,5923,4779,5085,4019,5482,4891,5382, 5383,6040,4682,3425,5275,4094,6627,5310,3015,5483,5657,4398,5924,3168,4819,6628, 5925,6629,5532,4932,4613,6041,6630,4636,6384,4780,4204,5658,4423,5821,3989,4683, 5822,6385,4954,6631,5345,6188,5425,5012,5384,3894,6386,4490,4104,6632,5741,5053, 6633,5823,5926,5659,5660,5927,6634,5235,5742,5824,4840,4933,4820,6387,4859,5928, 4955,6388,4143,3584,5825,5346,5013,6635,5661,6389,5014,5484,5743,4337,5176,5662, 6390,2836,6391,3268,6392,6636,6042,5236,6637,4158,6638,5744,5663,4471,5347,3663, 4123,5143,4293,3895,6639,6640,5311,5929,5826,3800,6189,6393,6190,5664,5348,3554, 3594,4749,4603,6641,5385,4801,6043,5827,4183,6642,5312,5426,4761,6394,5665,6191, 4715,2669,6643,6644,5533,3185,5427,5086,5930,5931,5386,6192,6044,6645,4781,4013, 5745,4282,4435,5534,4390,4267,6045,5746,4984,6046,2743,6193,3501,4087,5485,5932, 5428,4184,4095,5747,4061,5054,3058,3862,5933,5600,6646,5144,3618,6395,3131,5055, 5313,6396,4650,4956,3855,6194,3896,5202,4985,4029,4225,6195,6647,5828,5486,5829, 3589,3002,6648,6397,4782,5276,6649,6196,6650,4105,3803,4043,5237,5830,6398,4096, 3643,6399,3528,6651,4453,3315,4637,6652,3984,6197,5535,3182,3339,6653,3096,2660, 6400,6654,3449,5934,4250,4236,6047,6401,5831,6655,5487,3753,4062,5832,6198,6199, 6656,3766,6657,3403,4667,6048,6658,4338,2897,5833,3880,2797,3780,4326,6659,5748, 5015,6660,5387,4351,5601,4411,6661,3654,4424,5935,4339,4072,5277,4568,5536,6402, 6662,5238,6663,5349,5203,6200,5204,6201,5145,4536,5016,5056,4762,5834,4399,4957, 6202,6403,5666,5749,6664,4340,6665,5936,5177,5667,6666,6667,3459,4668,6404,6668, 6669,4543,6203,6670,4276,6405,4480,5537,6671,4614,5205,5668,6672,3348,2193,4763, 6406,6204,5937,5602,4177,5669,3419,6673,4020,6205,4443,4569,5388,3715,3639,6407, 6049,4058,6206,6674,5938,4544,6050,4185,4294,4841,4651,4615,5488,6207,6408,6051, 5178,3241,3509,5835,6208,4958,5836,4341,5489,5278,6209,2823,5538,5350,5206,5429, 6675,4638,4875,4073,3516,4684,4914,4860,5939,5603,5389,6052,5057,3237,5490,3791, 6676,6409,6677,4821,4915,4106,5351,5058,4243,5539,4244,5604,4842,4916,5239,3028, 3716,5837,5114,5605,5390,5940,5430,6210,4332,6678,5540,4732,3667,3840,6053,4305, 3408,5670,5541,6410,2744,5240,5750,6679,3234,5606,6680,5607,5671,3608,4283,4159, 4400,5352,4783,6681,6411,6682,4491,4802,6211,6412,5941,6413,6414,5542,5751,6683, 4669,3734,5942,6684,6415,5943,5059,3328,4670,4144,4268,6685,6686,6687,6688,4372, 3603,6689,5944,5491,4373,3440,6416,5543,4784,4822,5608,3792,4616,5838,5672,3514, 5391,6417,4892,6690,4639,6691,6054,5673,5839,6055,6692,6056,5392,6212,4038,5544, 5674,4497,6057,6693,5840,4284,5675,4021,4545,5609,6418,4454,6419,6213,4113,4472, 5314,3738,5087,5279,4074,5610,4959,4063,3179,4750,6058,6420,6214,3476,4498,4716, 5431,4960,4685,6215,5241,6694,6421,6216,6695,5841,5945,6422,3748,5946,5179,3905, 5752,5545,5947,4374,6217,4455,6423,4412,6218,4803,5353,6696,3832,5280,6219,4327, 4702,6220,6221,6059,4652,5432,6424,3749,4751,6425,5753,4986,5393,4917,5948,5030, 5754,4861,4733,6426,4703,6697,6222,4671,5949,4546,4961,5180,6223,5031,3316,5281, 6698,4862,4295,4934,5207,3644,6427,5842,5950,6428,6429,4570,5843,5282,6430,6224, 5088,3239,6060,6699,5844,5755,6061,6431,2701,5546,6432,5115,5676,4039,3993,3327, 4752,4425,5315,6433,3941,6434,5677,4617,4604,3074,4581,6225,5433,6435,6226,6062, 4823,5756,5116,6227,3717,5678,4717,5845,6436,5679,5846,6063,5847,6064,3977,3354, 6437,3863,5117,6228,5547,5394,4499,4524,6229,4605,6230,4306,4500,6700,5951,6065, 3693,5952,5089,4366,4918,6701,6231,5548,6232,6702,6438,4704,5434,6703,6704,5953, 4168,6705,5680,3420,6706,5242,4407,6066,3812,5757,5090,5954,4672,4525,3481,5681, 4618,5395,5354,5316,5955,6439,4962,6707,4526,6440,3465,4673,6067,6441,5682,6708, 5435,5492,5758,5683,4619,4571,4674,4804,4893,4686,5493,4753,6233,6068,4269,6442, 6234,5032,4705,5146,5243,5208,5848,6235,6443,4963,5033,4640,4226,6236,5849,3387, 6444,6445,4436,4437,5850,4843,5494,4785,4894,6709,4361,6710,5091,5956,3331,6237, 4987,5549,6069,6711,4342,3517,4473,5317,6070,6712,6071,4706,6446,5017,5355,6713, 6714,4988,5436,6447,4734,5759,6715,4735,4547,4456,4754,6448,5851,6449,6450,3547, 5852,5318,6451,6452,5092,4205,6716,6238,4620,4219,5611,6239,6072,4481,5760,5957, 5958,4059,6240,6453,4227,4537,6241,5761,4030,4186,5244,5209,3761,4457,4876,3337, 5495,5181,6242,5959,5319,5612,5684,5853,3493,5854,6073,4169,5613,5147,4895,6074, 5210,6717,5182,6718,3830,6243,2798,3841,6075,6244,5855,5614,3604,4606,5496,5685, 5118,5356,6719,6454,5960,5357,5961,6720,4145,3935,4621,5119,5962,4261,6721,6455, 4786,5963,4375,4582,6245,6246,6247,6076,5437,4877,5856,3376,4380,6248,4160,6722, 5148,6456,5211,6457,6723,4718,6458,6724,6249,5358,4044,3297,6459,6250,5857,5615, 5497,5245,6460,5498,6725,6251,6252,5550,3793,5499,2959,5396,6461,6462,4572,5093, 5500,5964,3806,4146,6463,4426,5762,5858,6077,6253,4755,3967,4220,5965,6254,4989, 5501,6464,4352,6726,6078,4764,2290,5246,3906,5438,5283,3767,4964,2861,5763,5094, 6255,6256,4622,5616,5859,5860,4707,6727,4285,4708,4824,5617,6257,5551,4787,5212, 4965,4935,4687,6465,6728,6466,5686,6079,3494,4413,2995,5247,5966,5618,6729,5967, 5764,5765,5687,5502,6730,6731,6080,5397,6467,4990,6258,6732,4538,5060,5619,6733, 4719,5688,5439,5018,5149,5284,5503,6734,6081,4607,6259,5120,3645,5861,4583,6260, 4584,4675,5620,4098,5440,6261,4863,2379,3306,4585,5552,5689,4586,5285,6735,4864, 6736,5286,6082,6737,4623,3010,4788,4381,4558,5621,4587,4896,3698,3161,5248,4353, 4045,6262,3754,5183,4588,6738,6263,6739,6740,5622,3936,6741,6468,6742,6264,5095, 6469,4991,5968,6743,4992,6744,6083,4897,6745,4256,5766,4307,3108,3968,4444,5287, 3889,4343,6084,4510,6085,4559,6086,4898,5969,6746,5623,5061,4919,5249,5250,5504, 5441,6265,5320,4878,3242,5862,5251,3428,6087,6747,4237,5624,5442,6266,5553,4539, 6748,2585,3533,5398,4262,6088,5150,4736,4438,6089,6267,5505,4966,6749,6268,6750, 6269,5288,5554,3650,6090,6091,4624,6092,5690,6751,5863,4270,5691,4277,5555,5864, 6752,5692,4720,4865,6470,5151,4688,4825,6753,3094,6754,6471,3235,4653,6755,5213, 5399,6756,3201,4589,5865,4967,6472,5866,6473,5019,3016,6757,5321,4756,3957,4573, 6093,4993,5767,4721,6474,6758,5625,6759,4458,6475,6270,6760,5556,4994,5214,5252, 6271,3875,5768,6094,5034,5506,4376,5769,6761,2120,6476,5253,5770,6762,5771,5970, 3990,5971,5557,5558,5772,6477,6095,2787,4641,5972,5121,6096,6097,6272,6763,3703, 5867,5507,6273,4206,6274,4789,6098,6764,3619,3646,3833,3804,2394,3788,4936,3978, 4866,4899,6099,6100,5559,6478,6765,3599,5868,6101,5869,5870,6275,6766,4527,6767) # flake8: noqa
gpl-3.0
RudoCris/horizon
openstack_dashboard/test/api_tests/lbaas_tests.py
10
16542
# Copyright 2013, Big Switch Networks, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from openstack_dashboard import api from openstack_dashboard.test import helpers as test from neutronclient.v2_0 import client neutronclient = client.Client class LbaasApiTests(test.APITestCase): @test.create_stubs({neutronclient: ('create_vip',)}) def test_vip_create(self): vip1 = self.api_vips.first() form_data = {'address': vip1['address'], 'name': vip1['name'], 'description': vip1['description'], 'subnet_id': vip1['subnet_id'], 'protocol_port': vip1['protocol_port'], 'protocol': vip1['protocol'], 'pool_id': vip1['pool_id'], 'session_persistence': vip1['session_persistence'], 'connection_limit': vip1['connection_limit'], 'admin_state_up': vip1['admin_state_up'] } vip = {'vip': self.api_vips.first()} neutronclient.create_vip({'vip': form_data}).AndReturn(vip) self.mox.ReplayAll() ret_val = api.lbaas.vip_create(self.request, **form_data) self.assertIsInstance(ret_val, api.lbaas.Vip) @test.create_stubs({neutronclient: ('create_vip',)}) def test_vip_create_skip_address_if_empty(self): vip1 = self.api_vips.first() vipform_data = {'name': vip1['name'], 'description': vip1['description'], 'subnet_id': vip1['subnet_id'], 'protocol_port': vip1['protocol_port'], 'protocol': vip1['protocol'], 'pool_id': vip1['pool_id'], 'session_persistence': vip1['session_persistence'], 'connection_limit': vip1['connection_limit'], 'admin_state_up': vip1['admin_state_up'] } neutronclient.create_vip({'vip': vipform_data}).AndReturn( {'vip': vipform_data}) self.mox.ReplayAll() form_data = dict(vipform_data) form_data['address'] = "" ret_val = api.lbaas.vip_create(self.request, **form_data) self.assertIsInstance(ret_val, api.lbaas.Vip) @test.create_stubs({neutronclient: ('list_vips',)}) def test_vip_list(self): vips = {'vips': [{'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'address': '10.0.0.100', 'name': 'vip1name', 'description': 'vip1description', 'subnet_id': '12381d38-c3eb-4fee-9763-12de3338041e', 'protocol_port': '80', 'protocol': 'HTTP', 'pool_id': '8913dde8-4915-4b90-8d3e-b95eeedb0d49', 'connection_limit': '10', 'admin_state_up': True }, ]} neutronclient.list_vips().AndReturn(vips) self.mox.ReplayAll() ret_val = api.lbaas.vip_list(self.request) for v in ret_val: self.assertIsInstance(v, api.lbaas.Vip) self.assertTrue(v.id) @test.create_stubs({neutronclient: ('show_vip', 'show_pool'), api.neutron: ('subnet_get', 'port_get')}) def test_vip_get(self): vip = self.api_vips.first() neutronclient.show_vip(vip['id']).AndReturn({'vip': vip}) api.neutron.subnet_get(self.request, vip['subnet_id'] ).AndReturn(self.subnets.first()) api.neutron.port_get(self.request, vip['port_id'] ).AndReturn(self.ports.first()) neutronclient.show_pool(vip['pool_id'] ).AndReturn({'pool': self.api_pools.first()}) self.mox.ReplayAll() ret_val = api.lbaas.vip_get(self.request, vip['id']) self.assertIsInstance(ret_val, api.lbaas.Vip) self.assertIsInstance(ret_val.subnet, api.neutron.Subnet) self.assertEqual(vip['subnet_id'], ret_val.subnet.id) self.assertIsInstance(ret_val.port, api.neutron.Port) self.assertEqual(vip['port_id'], ret_val.port.id) self.assertIsInstance(ret_val.pool, api.lbaas.Pool) self.assertEqual(self.api_pools.first()['id'], ret_val.pool.id) @test.create_stubs({neutronclient: ('update_vip',)}) def test_vip_update(self): form_data = {'address': '10.0.0.100', 'name': 'vip1name', 'description': 'vip1description', 'subnet_id': '12381d38-c3eb-4fee-9763-12de3338041e', 'protocol_port': '80', 'protocol': 'HTTP', 'pool_id': '8913dde8-4915-4b90-8d3e-b95eeedb0d49', 'connection_limit': '10', 'admin_state_up': True } vip = {'vip': {'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'address': '10.0.0.100', 'name': 'vip1name', 'description': 'vip1description', 'subnet_id': '12381d38-c3eb-4fee-9763-12de3338041e', 'protocol_port': '80', 'protocol': 'HTTP', 'pool_id': '8913dde8-4915-4b90-8d3e-b95eeedb0d49', 'connection_limit': '10', 'admin_state_up': True }} neutronclient.update_vip(vip['vip']['id'], form_data).AndReturn(vip) self.mox.ReplayAll() ret_val = api.lbaas.vip_update(self.request, vip['vip']['id'], **form_data) self.assertIsInstance(ret_val, api.lbaas.Vip) @test.create_stubs({neutronclient: ('create_pool',)}) def test_pool_create(self): form_data = {'name': 'pool1name', 'description': 'pool1description', 'subnet_id': '12381d38-c3eb-4fee-9763-12de3338041e', 'protocol': 'HTTP', 'lb_method': 'ROUND_ROBIN', 'admin_state_up': True, 'provider': 'dummy' } pool = {'pool': {'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'name': 'pool1name', 'description': 'pool1description', 'subnet_id': '12381d38-c3eb-4fee-9763-12de3338041e', 'protocol': 'HTTP', 'lb_method': 'ROUND_ROBIN', 'admin_state_up': True, 'provider': 'dummy' }} neutronclient.create_pool({'pool': form_data}).AndReturn(pool) self.mox.ReplayAll() ret_val = api.lbaas.pool_create(self.request, **form_data) self.assertIsInstance(ret_val, api.lbaas.Pool) @test.create_stubs({neutronclient: ('list_pools', 'list_vips'), api.neutron: ('subnet_list',)}) def test_pool_list(self): pools = {'pools': self.api_pools.list()} subnets = self.subnets.list() vips = {'vips': self.api_vips.list()} neutronclient.list_pools().AndReturn(pools) api.neutron.subnet_list(self.request).AndReturn(subnets) neutronclient.list_vips().AndReturn(vips) self.mox.ReplayAll() ret_val = api.lbaas.pool_list(self.request) for v in ret_val: self.assertIsInstance(v, api.lbaas.Pool) self.assertTrue(v.id) @test.create_stubs({neutronclient: ('show_pool', 'show_vip', 'list_members', 'show_health_monitor',), api.neutron: ('subnet_get',)}) def test_pool_get(self): pool = self.pools.first() subnet = self.subnets.first() pool_dict = {'pool': self.api_pools.first()} vip_dict = {'vip': self.api_vips.first()} neutronclient.show_pool(pool.id).AndReturn(pool_dict) api.neutron.subnet_get(self.request, subnet.id).AndReturn(subnet) neutronclient.show_vip(pool.vip_id).AndReturn(vip_dict) neutronclient.list_members(pool_id=pool.id).AndReturn( {'members': self.api_members.list()}) monitor = self.api_monitors.first() for pool_mon in pool.health_monitors: neutronclient.show_health_monitor(pool_mon).AndReturn( {'health_monitors': [monitor]}) self.mox.ReplayAll() ret_val = api.lbaas.pool_get(self.request, pool.id) self.assertIsInstance(ret_val, api.lbaas.Pool) self.assertIsInstance(ret_val.vip, api.lbaas.Vip) self.assertEqual(ret_val.vip.id, vip_dict['vip']['id']) self.assertIsInstance(ret_val.subnet, api.neutron.Subnet) self.assertEqual(ret_val.subnet.id, subnet.id) self.assertEqual(2, len(ret_val.members)) self.assertIsInstance(ret_val.members[0], api.lbaas.Member) self.assertEqual(len(pool.health_monitors), len(ret_val.health_monitors)) self.assertIsInstance(ret_val.health_monitors[0], api.lbaas.PoolMonitor) @test.create_stubs({neutronclient: ('update_pool',)}) def test_pool_update(self): form_data = {'name': 'pool1name', 'description': 'pool1description', 'subnet_id': '12381d38-c3eb-4fee-9763-12de3338041e', 'protocol': 'HTTPS', 'lb_method': 'LEAST_CONNECTION', 'admin_state_up': True } pool = {'pool': {'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'name': 'pool1name', 'description': 'pool1description', 'subnet_id': '12381d38-c3eb-4fee-9763-12de3338041e', 'protocol': 'HTTPS', 'lb_method': 'LEAST_CONNECTION', 'admin_state_up': True }} neutronclient.update_pool(pool['pool']['id'], form_data).AndReturn(pool) self.mox.ReplayAll() ret_val = api.lbaas.pool_update(self.request, pool['pool']['id'], **form_data) self.assertIsInstance(ret_val, api.lbaas.Pool) @test.create_stubs({neutronclient: ('create_health_monitor',)}) def test_pool_health_monitor_create(self): form_data = {'type': 'PING', 'delay': '10', 'timeout': '10', 'max_retries': '10', 'admin_state_up': True } monitor = {'health_monitor': { 'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'type': 'PING', 'delay': '10', 'timeout': '10', 'max_retries': '10', 'admin_state_up': True}} neutronclient.create_health_monitor({ 'health_monitor': form_data}).AndReturn(monitor) self.mox.ReplayAll() ret_val = api.lbaas.pool_health_monitor_create( self.request, **form_data) self.assertIsInstance(ret_val, api.lbaas.PoolMonitor) @test.create_stubs({neutronclient: ('list_health_monitors',)}) def test_pool_health_monitor_list(self): monitors = {'health_monitors': [ {'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'type': 'PING', 'delay': '10', 'timeout': '10', 'max_retries': '10', 'http_method': 'GET', 'url_path': '/monitor', 'expected_codes': '200', 'admin_state_up': True}, ]} neutronclient.list_health_monitors().AndReturn(monitors) self.mox.ReplayAll() ret_val = api.lbaas.pool_health_monitor_list(self.request) for v in ret_val: self.assertIsInstance(v, api.lbaas.PoolMonitor) self.assertTrue(v.id) @test.create_stubs({neutronclient: ('show_health_monitor', 'list_pools')}) def test_pool_health_monitor_get(self): monitor = self.api_monitors.first() neutronclient.show_health_monitor( monitor['id']).AndReturn({'health_monitor': monitor}) neutronclient.list_pools(id=[p['pool_id'] for p in monitor['pools']] ).AndReturn({'pools': self.api_pools.list()}) self.mox.ReplayAll() ret_val = api.lbaas.pool_health_monitor_get( self.request, monitor['id']) self.assertIsInstance(ret_val, api.lbaas.PoolMonitor) self.assertEqual(2, len(ret_val.pools)) self.assertIsInstance(ret_val.pools[0], api.lbaas.Pool) @test.create_stubs({neutronclient: ('create_member', )}) def test_member_create(self): form_data = {'pool_id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'address': '10.0.1.2', 'protocol_port': '80', 'weight': '10', 'admin_state_up': True } member = {'member': {'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'pool_id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'address': '10.0.1.2', 'protocol_port': '80', 'weight': '10', 'admin_state_up': True}} neutronclient.create_member({'member': form_data}).AndReturn(member) self.mox.ReplayAll() ret_val = api.lbaas.member_create(self.request, **form_data) self.assertIsInstance(ret_val, api.lbaas.Member) @test.create_stubs({neutronclient: ('list_members', 'list_pools')}) def test_member_list(self): members = {'members': self.api_members.list()} pools = {'pools': self.api_pools.list()} neutronclient.list_members().AndReturn(members) neutronclient.list_pools().AndReturn(pools) self.mox.ReplayAll() ret_val = api.lbaas.member_list(self.request) for v in ret_val: self.assertIsInstance(v, api.lbaas.Member) self.assertTrue(v.id) @test.create_stubs({neutronclient: ('show_member', 'show_pool')}) def test_member_get(self): member = self.members.first() member_dict = {'member': self.api_members.first()} pool_dict = {'pool': self.api_pools.first()} neutronclient.show_member(member.id).AndReturn(member_dict) neutronclient.show_pool(member.pool_id).AndReturn(pool_dict) self.mox.ReplayAll() ret_val = api.lbaas.member_get(self.request, member.id) self.assertIsInstance(ret_val, api.lbaas.Member) @test.create_stubs({neutronclient: ('update_member',)}) def test_member_update(self): form_data = {'pool_id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'address': '10.0.1.4', 'protocol_port': '80', 'weight': '10', 'admin_state_up': True } member = {'member': {'id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'pool_id': 'abcdef-c3eb-4fee-9763-12de3338041e', 'address': '10.0.1.2', 'protocol_port': '80', 'weight': '10', 'admin_state_up': True }} neutronclient.update_member(member['member']['id'], form_data).AndReturn(member) self.mox.ReplayAll() ret_val = api.lbaas.member_update(self.request, member['member']['id'], **form_data) self.assertIsInstance(ret_val, api.lbaas.Member)
apache-2.0
superdump/cerbero
cerbero/packages/wix_packager.py
21
11202
# cerbero - a multi-platform build system for Open Source software # Copyright (C) 2012 Andoni Morales Alastruey <ylatuya@gmail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Library General Public # License as published by the Free Software Foundation; either # version 2 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Library General Public License for more details. # # You should have received a copy of the GNU Library General Public # License along with this library; if not, write to the # Free Software Foundation, Inc., 59 Temple Place - Suite 330, # Boston, MA 02111-1307, USA. import os import tempfile import shutil from zipfile import ZipFile from cerbero.errors import EmptyPackageError from cerbero.packages import PackagerBase, PackageType from cerbero.packages.package import Package, App from cerbero.utils import messages as m from cerbero.utils import shell, to_winepath, get_wix_prefix from cerbero.tools import strip from cerbero.packages.wix import MergeModule, VSMergeModule, MSI, WixConfig from cerbero.packages.wix import VSTemplatePackage from cerbero.config import Platform class MergeModulePackager(PackagerBase): def __init__(self, config, package, store): PackagerBase.__init__(self, config, package, store) self._with_wine = config.platform != Platform.WINDOWS self.wix_prefix = get_wix_prefix() def pack(self, output_dir, devel=False, force=False, keep_temp=False): PackagerBase.pack(self, output_dir, devel, force, keep_temp) paths = [] # create runtime package p = self.create_merge_module(output_dir, PackageType.RUNTIME, force, self.package.version, keep_temp) paths.append(p) if devel: p = self.create_merge_module(output_dir, PackageType.DEVEL, force, self.package.version, keep_temp) paths.append(p) return paths def create_merge_module(self, output_dir, package_type, force, version, keep_temp): self.package.set_mode(package_type) files_list = self.files_list(package_type, force) if isinstance(self.package, VSTemplatePackage): mergemodule = VSMergeModule(self.config, files_list, self.package) else: mergemodule = MergeModule(self.config, files_list, self.package) tmpdir = None # For application packages that requires stripping object files, we need # to copy all the files to a new tree and strip them there: if isinstance(self.package, App) and self.package.strip: tmpdir = tempfile.mkdtemp() for f in files_list: src = os.path.join(self.config.prefix, f) dst = os.path.join(tmpdir, f) if not os.path.exists(os.path.dirname(dst)): os.makedirs(os.path.dirname(dst)) shutil.copy(src, dst) s = strip.Strip(self.config, self.package.strip_excludes) for p in self.package.strip_dirs: s.strip_dir(os.path.join(tmpdir, p)) mergemodule = MergeModule(self.config, files_list, self.package) if tmpdir: mergemodule.prefix = tmpdir package_name = self._package_name(version) sources = [os.path.join(output_dir, "%s.wxs" % package_name)] mergemodule.write(sources[0]) wixobjs = [os.path.join(output_dir, "%s.wixobj" % package_name)] for x in ['utils']: wixobjs.append(os.path.join(output_dir, "%s.wixobj" % x)) sources.append(os.path.join(os.path.abspath(self.config.data_dir), 'wix/%s.wxs' % x)) if self._with_wine: wixobjs = [to_winepath(x) for x in wixobjs] sources = [to_winepath(x) for x in sources] candle = Candle(self.wix_prefix, self._with_wine) candle.compile(' '.join(sources), output_dir) light = Light(self.wix_prefix, self._with_wine) path = light.compile(wixobjs, package_name, output_dir, True) # Clean up if not keep_temp: os.remove(sources[0]) for f in wixobjs: os.remove(f) try: os.remove(f.replace('.wixobj', '.wixpdb')) except: pass if tmpdir: shutil.rmtree(tmpdir) return path def _package_name(self, version): return "%s-%s-%s" % (self.package.name, version, self.config.target_arch) class MSIPackager(PackagerBase): UI_EXT = '-ext WixUIExtension' UTIL_EXT = '-ext WixUtilExtension' def __init__(self, config, package, store): PackagerBase.__init__(self, config, package, store) self._with_wine = config.platform != Platform.WINDOWS self.wix_prefix = get_wix_prefix() def pack(self, output_dir, devel=False, force=False, keep_temp=False): self.output_dir = os.path.realpath(output_dir) if not os.path.exists(self.output_dir): os.makedirs(self.output_dir) self.force = force self.keep_temp = keep_temp paths = [] self.merge_modules = {} # create runtime package p = self._create_msi_installer(PackageType.RUNTIME) paths.append(p) # create devel package if devel and not isinstance(self.package, App): p = self._create_msi_installer(PackageType.DEVEL) paths.append(p) # create zip with merge modules self.package.set_mode(PackageType.RUNTIME) zipf = ZipFile(os.path.join(self.output_dir, '%s-merge-modules.zip' % self._package_name()), 'w') for p in self.merge_modules[PackageType.RUNTIME]: zipf.write(p) zipf.close() if not keep_temp: for msms in self.merge_modules.values(): for p in msms: os.remove(p) return paths def _package_name(self): return "%s-%s-%s" % (self.package.name, self.config.target_arch, self.package.version) def _create_msi_installer(self, package_type): self.package.set_mode(package_type) self.packagedeps = self.store.get_package_deps(self.package, True) if isinstance(self.package, App): self.packagedeps = [self.package] self._create_merge_modules(package_type) config_path = self._create_config() return self._create_msi(config_path) def _create_merge_modules(self, package_type): packagedeps = {} for package in self.packagedeps: package.set_mode(package_type) m.action("Creating Merge Module for %s" % package) packager = MergeModulePackager(self.config, package, self.store) try: path = packager.create_merge_module(self.output_dir, package_type, self.force, self.package.version, self.keep_temp) packagedeps[package] = path except EmptyPackageError: m.warning("Package %s is empty" % package) self.packagedeps = packagedeps self.merge_modules[package_type] = packagedeps.values() def _create_config(self): config = WixConfig(self.config, self.package) config_path = config.write(self.output_dir) return config_path def _create_msi(self, config_path): sources = [os.path.join(self.output_dir, "%s.wxs" % self._package_name())] msi = MSI(self.config, self.package, self.packagedeps, config_path, self.store) msi.write(sources[0]) wixobjs = [os.path.join(self.output_dir, "%s.wixobj" % self._package_name())] for x in ['utils']: wixobjs.append(os.path.join(self.output_dir, "%s.wixobj" % x)) sources.append(os.path.join(os.path.abspath(self.config.data_dir), 'wix/%s.wxs' % x)) if self._with_wine: wixobjs = [to_winepath(x) for x in wixobjs] sources = [to_winepath(x) for x in sources] candle = Candle(self.wix_prefix, self._with_wine) candle.compile(' '.join(sources), self.output_dir) light = Light(self.wix_prefix, self._with_wine, "%s %s" % (self.UI_EXT, self.UTIL_EXT)) path = light.compile(wixobjs, self._package_name(), self.output_dir) # Clean up if not self.keep_temp: os.remove(sources[0]) for f in wixobjs: os.remove(f) try: os.remove(f.replace('.wixobj', '.wixpdb')) except: pass os.remove(config_path) return path class Packager(object): def __new__(klass, config, package, store): if isinstance(package, Package): return MergeModulePackager(config, package, store) else: return MSIPackager(config, package, store) class Candle(object): ''' Compile WiX objects with candle ''' cmd = '%(wine)s %(q)s%(prefix)s/candle.exe%(q)s %(source)s' def __init__(self, wix_prefix, with_wine): self.options = {} self.options['prefix'] = wix_prefix if with_wine: self.options['wine'] = 'wine' self.options['q'] = '"' else: self.options['wine'] = '' self.options['q'] = '' def compile(self, source, output_dir): self.options['source'] = source shell.call(self.cmd % self.options, output_dir) return os.path.join(output_dir, source, '.msm') class Light(object): ''' Compile WiX objects with light''' cmd = '%(wine)s %(q)s%(prefix)s/light.exe%(q)s %(objects)s -o '\ '%(msi)s.%(ext)s -sval %(extra)s' def __init__(self, wix_prefix, with_wine, extra=''): self.options = {} self.options['prefix'] = wix_prefix self.options['extra'] = extra if with_wine: self.options['wine'] = 'wine' self.options['q'] = '"' else: self.options['wine'] = '' self.options['q'] = '' def compile(self, objects, msi_file, output_dir, merge_module=False): self.options['objects'] = ' '.join(objects) self.options['msi'] = msi_file if merge_module: self.options['ext'] = 'msm' else: self.options['ext'] = 'msi' shell.call(self.cmd % self.options, output_dir) return os.path.join(output_dir, '%(msi)s.%(ext)s' % self.options) def register(): from cerbero.packages.packager import register_packager from cerbero.config import Distro register_packager(Distro.WINDOWS, Packager)
lgpl-2.1
magicrub/MissionPlanner
Lib/site-packages/scipy/misc/tests/test_doccer.py
61
2281
''' Some tests for the documenting decorator and support functions ''' import numpy as np from numpy.testing import assert_equal, assert_raises from nose.tools import assert_true from scipy.misc import doccer docstring = \ """Docstring %(strtest1)s %(strtest2)s %(strtest3)s """ param_doc1 = \ """Another test with some indent""" param_doc2 = \ """Another test, one line""" param_doc3 = \ """ Another test with some indent""" doc_dict = {'strtest1':param_doc1, 'strtest2':param_doc2, 'strtest3':param_doc3} filled_docstring = \ """Docstring Another test with some indent Another test, one line Another test with some indent """ def test_unindent(): yield assert_equal, doccer.unindent_string(param_doc1), param_doc1 yield assert_equal, doccer.unindent_string(param_doc2), param_doc2 yield assert_equal, doccer.unindent_string(param_doc3), param_doc1 def test_unindent_dict(): d2 = doccer.unindent_dict(doc_dict) yield assert_equal, d2['strtest1'], doc_dict['strtest1'] yield assert_equal, d2['strtest2'], doc_dict['strtest2'] yield assert_equal, d2['strtest3'], doc_dict['strtest1'] def test_docformat(): udd = doccer.unindent_dict(doc_dict) formatted = doccer.docformat(docstring, udd) yield assert_equal, formatted, filled_docstring single_doc = 'Single line doc %(strtest1)s' formatted = doccer.docformat(single_doc, doc_dict) # Note - initial indent of format string does not # affect subsequent indent of inserted parameter yield assert_equal, formatted, """Single line doc Another test with some indent""" def test_decorator(): # with unindentation of parameters decorator = doccer.filldoc(doc_dict, True) @decorator def func(): """ Docstring %(strtest3)s """ yield assert_equal, func.__doc__, """ Docstring Another test with some indent """ # without unindentation of parameters decorator = doccer.filldoc(doc_dict, False) @decorator def func(): """ Docstring %(strtest3)s """ yield assert_equal, func.__doc__, """ Docstring Another test with some indent """
gpl-3.0
ndingwall/scikit-learn
sklearn/metrics/_plot/tests/test_plot_det_curve.py
11
2224
import pytest import numpy as np from numpy.testing import assert_allclose from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression from sklearn.metrics import det_curve from sklearn.metrics import plot_det_curve @pytest.fixture(scope="module") def data(): return load_iris(return_X_y=True) @pytest.fixture(scope="module") def data_binary(data): X, y = data return X[y < 2], y[y < 2] @pytest.mark.parametrize( "response_method", ["predict_proba", "decision_function"] ) @pytest.mark.parametrize("with_sample_weight", [True, False]) @pytest.mark.parametrize("with_strings", [True, False]) def test_plot_det_curve( pyplot, response_method, data_binary, with_sample_weight, with_strings ): X, y = data_binary pos_label = None if with_strings: y = np.array(["c", "b"])[y] pos_label = "c" if with_sample_weight: rng = np.random.RandomState(42) sample_weight = rng.randint(1, 4, size=(X.shape[0])) else: sample_weight = None lr = LogisticRegression() lr.fit(X, y) viz = plot_det_curve( lr, X, y, alpha=0.8, sample_weight=sample_weight, ) y_pred = getattr(lr, response_method)(X) if y_pred.ndim == 2: y_pred = y_pred[:, 1] fpr, fnr, _ = det_curve( y, y_pred, sample_weight=sample_weight, pos_label=pos_label, ) assert_allclose(viz.fpr, fpr) assert_allclose(viz.fnr, fnr) assert viz.estimator_name == "LogisticRegression" # cannot fail thanks to pyplot fixture import matplotlib as mpl # noqal assert isinstance(viz.line_, mpl.lines.Line2D) assert viz.line_.get_alpha() == 0.8 assert isinstance(viz.ax_, mpl.axes.Axes) assert isinstance(viz.figure_, mpl.figure.Figure) assert viz.line_.get_label() == "LogisticRegression" expected_pos_label = 1 if pos_label is None else pos_label expected_ylabel = ( f"False Negative Rate (Positive label: {expected_pos_label})" ) expected_xlabel = ( f"False Positive Rate (Positive label: {expected_pos_label})" ) assert viz.ax_.get_ylabel() == expected_ylabel assert viz.ax_.get_xlabel() == expected_xlabel
bsd-3-clause
acroreiser/LowLatencyKernel
tools/perf/scripts/python/net_dropmonitor.py
1258
1562
# Monitor the system for dropped packets and proudce a report of drop locations and counts 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 * drop_log = {} kallsyms = [] def get_kallsyms_table(): global kallsyms try: f = open("/proc/kallsyms", "r") linecount = 0 for line in f: linecount = linecount+1 f.seek(0) except: return j = 0 for line in f: loc = int(line.split()[0], 16) name = line.split()[2] j = j +1 if ((j % 100) == 0): print "\r" + str(j) + "/" + str(linecount), kallsyms.append({ 'loc': loc, 'name' : name}) print "\r" + str(j) + "/" + str(linecount) kallsyms.sort() return def get_sym(sloc): loc = int(sloc) for i in kallsyms[::-1]: if loc >= i['loc']: return (i['name'], loc - i['loc']) return (None, 0) def print_drop_table(): print "%25s %25s %25s" % ("LOCATION", "OFFSET", "COUNT") for i in drop_log.keys(): (sym, off) = get_sym(i) if sym == None: sym = i print "%25s %25s %25s" % (sym, off, drop_log[i]) def trace_begin(): print "Starting trace (Ctrl-C to dump results)" def trace_end(): print "Gathering kallsyms data" get_kallsyms_table() print_drop_table() # called from perf, when it finds a correspoinding event def skb__kfree_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr, location, protocol): slocation = str(location) try: drop_log[slocation] = drop_log[slocation] + 1 except: drop_log[slocation] = 1
gpl-2.0
Azulinho/ansible
lib/ansible/modules/network/cloudengine/ce_link_status.py
65
22134
#!/usr/bin/python # # 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.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ce_link_status version_added: "2.4" short_description: Get interface link status on HUAWEI CloudEngine switches. description: - Get interface link status on HUAWEI CloudEngine switches. author: - Zhijin Zhou (@CloudEngine-Ansible) notes: - Current physical state shows an interface's physical status. - Current link state shows an interface's link layer protocol status. - Current IPv4 state shows an interface's IPv4 protocol status. - Current IPv6 state shows an interface's IPv6 protocol status. - Inbound octets(bytes) shows the number of bytes that an interface received. - Inbound unicast(pkts) shows the number of unicast packets that an interface received. - Inbound multicast(pkts) shows the number of multicast packets that an interface received. - Inbound broadcast(pkts) shows the number of broadcast packets that an interface received. - Inbound error(pkts) shows the number of error packets that an interface received. - Inbound drop(pkts) shows the total number of packets that were sent to the interface but dropped by an interface. - Inbound rate(byte/sec) shows the rate at which an interface receives bytes within an interval. - Inbound rate(pkts/sec) shows the rate at which an interface receives packets within an interval. - Outbound octets(bytes) shows the number of the bytes that an interface sent. - Outbound unicast(pkts) shows the number of unicast packets that an interface sent. - Outbound multicast(pkts) shows the number of multicast packets that an interface sent. - Outbound broadcast(pkts) shows the number of broadcast packets that an interface sent. - Outbound error(pkts) shows the total number of packets that an interface sent but dropped by the remote interface. - Outbound drop(pkts) shows the number of dropped packets that an interface sent. - Outbound rate(byte/sec) shows the rate at which an interface sends bytes within an interval. - Outbound rate(pkts/sec) shows the rate at which an interface sends packets within an interval. - Speed shows the rate for an Ethernet interface. options: interface: description: - For the interface parameter, you can enter C(all) to display information about all interface, an interface type such as C(40GE) to display information about interfaces of the specified type, or full name of an interface such as C(40GE1/0/22) or C(vlanif10) to display information about the specific interface. required: true ''' EXAMPLES = ''' - name: Link status test hosts: cloudengine connection: local gather_facts: no vars: cli: host: "{{ inventory_hostname }}" port: "{{ ansible_ssh_port }}" username: "{{ username }}" password: "{{ password }}" transport: cli tasks: - name: Get specified interface link status information ce_link_status: interface: 40GE1/0/1 provider: "{{ cli }}" - name: Get specified interface type link status information ce_link_status: interface: 40GE provider: "{{ cli }}" - name: Get all interface link status information ce_link_status: interface: all provider: "{{ cli }}" ''' RETURN = ''' result: description: Interface link status information returned: always type: dict sample: { "40ge2/0/8": { "Current IPv4 state": "down", "Current IPv6 state": "down", "Current link state": "up", "Current physical state": "up", "Inbound broadcast(pkts)": "0", "Inbound drop(pkts)": "0", "Inbound error(pkts)": "0", "Inbound multicast(pkts)": "20151", "Inbound octets(bytes)": "7314813", "Inbound rate(byte/sec)": "11", "Inbound rate(pkts/sec)": "0", "Inbound unicast(pkts)": "0", "Outbound broadcast(pkts)": "1", "Outbound drop(pkts)": "0", "Outbound error(pkts)": "0", "Outbound multicast(pkts)": "20152", "Outbound octets(bytes)": "7235021", "Outbound rate(byte/sec)": "11", "Outbound rate(pkts/sec)": "0", "Outbound unicast(pkts)": "0", "Speed": "40GE" } } ''' from xml.etree import ElementTree from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.cloudengine.ce import ce_argument_spec, get_nc_config CE_NC_GET_PORT_SPEED = """ <filter type="subtree"> <devm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <ports> <port> <position>%s</position> <ethernetPort> <speed></speed> </ethernetPort> </port> </ports> </devm> </filter> """ CE_NC_GET_INT_STATISTICS = """ <filter type="subtree"> <ifm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0"> <interfaces> <interface> <ifName>%s</ifName> <ifDynamicInfo> <ifPhyStatus></ifPhyStatus> <ifLinkStatus></ifLinkStatus> <ifV4State></ifV4State> <ifV6State></ifV6State> </ifDynamicInfo> <ifStatistics> <receiveByte></receiveByte> <sendByte></sendByte> <rcvUniPacket></rcvUniPacket> <rcvMutiPacket></rcvMutiPacket> <rcvBroadPacket></rcvBroadPacket> <sendUniPacket></sendUniPacket> <sendMutiPacket></sendMutiPacket> <sendBroadPacket></sendBroadPacket> <rcvErrorPacket></rcvErrorPacket> <rcvDropPacket></rcvDropPacket> <sendErrorPacket></sendErrorPacket> <sendDropPacket></sendDropPacket> </ifStatistics> <ifClearedStat> <inByteRate></inByteRate> <inPacketRate></inPacketRate> <outByteRate></outByteRate> <outPacketRate></outPacketRate> </ifClearedStat> </interface> </interfaces> </ifm> </filter> """ INTERFACE_ALL = 1 INTERFACE_TYPE = 2 INTERFACE_FULL_NAME = 3 def get_interface_type(interface): """Gets the type of interface, such as 10GE, ETH-TRUNK, VLANIF...""" if interface is None: return None iftype = None if interface.upper().startswith('GE'): iftype = 'ge' elif interface.upper().startswith('10GE'): iftype = '10ge' elif interface.upper().startswith('25GE'): iftype = '25ge' elif interface.upper().startswith('4X10GE'): iftype = '4x10ge' elif interface.upper().startswith('40GE'): iftype = '40ge' elif interface.upper().startswith('100GE'): iftype = '100ge' elif interface.upper().startswith('VLANIF'): iftype = 'vlanif' elif interface.upper().startswith('LOOPBACK'): iftype = 'loopback' elif interface.upper().startswith('METH'): iftype = 'meth' elif interface.upper().startswith('ETH-TRUNK'): iftype = 'eth-trunk' elif interface.upper().startswith('VBDIF'): iftype = 'vbdif' elif interface.upper().startswith('NVE'): iftype = 'nve' elif interface.upper().startswith('TUNNEL'): iftype = 'tunnel' elif interface.upper().startswith('ETHERNET'): iftype = 'ethernet' elif interface.upper().startswith('FCOE-PORT'): iftype = 'fcoe-port' elif interface.upper().startswith('FABRIC-PORT'): iftype = 'fabric-port' elif interface.upper().startswith('STACK-PORT'): iftype = 'stack-Port' elif interface.upper().startswith('NULL'): iftype = 'null' else: return None return iftype.lower() def is_ethernet_port(interface): """Judge whether it is ethernet port""" ethernet_port = ['ge', '10ge', '25ge', '4x10ge', '40ge', '100ge', 'meth'] if_type = get_interface_type(interface) if if_type in ethernet_port: return True return False class LinkStatus(object): """Get interface link status information""" def __init__(self, argument_spec): self.spec = argument_spec self.module = None self.init_module() # interface name self.interface = self.module.params['interface'] self.interface = self.interface.replace(' ', '').lower() self.param_type = None self.if_type = None # state self.results = dict() self.result = dict() def check_params(self): """Check all input params""" if not self.interface: self.module.fail_json(msg='Error: Interface name cannot be empty.') if self.interface and self.interface != 'all': if not self.if_type: self.module.fail_json( msg='Error: Interface name of %s is error.' % self.interface) def init_module(self): """Init module object""" self.module = AnsibleModule( argument_spec=self.spec, supports_check_mode=True) def show_result(self): """Show result""" self.results['result'] = self.result self.module.exit_json(**self.results) def get_intf_dynamic_info(self, dyn_info, intf_name): """Get interface dynamic information""" if not intf_name: return if dyn_info: for eles in dyn_info: if eles.tag in ["ifPhyStatus", "ifV4State", "ifV6State", "ifLinkStatus"]: if eles.tag == "ifPhyStatus": self.result[intf_name][ 'Current physical state'] = eles.text elif eles.tag == "ifLinkStatus": self.result[intf_name][ 'Current link state'] = eles.text elif eles.tag == "ifV4State": self.result[intf_name][ 'Current IPv4 state'] = eles.text elif eles.tag == "ifV6State": self.result[intf_name][ 'Current IPv6 state'] = eles.text def get_intf_statistics_info(self, stat_info, intf_name): """Get interface statistics information""" if not intf_name: return if_type = get_interface_type(intf_name) if if_type == 'fcoe-port' or if_type == 'nve' or if_type == 'tunnel' or \ if_type == 'vbdif' or if_type == 'vlanif': return if stat_info: for eles in stat_info: if eles.tag in ["receiveByte", "sendByte", "rcvUniPacket", "rcvMutiPacket", "rcvBroadPacket", "sendUniPacket", "sendMutiPacket", "sendBroadPacket", "rcvErrorPacket", "rcvDropPacket", "sendErrorPacket", "sendDropPacket"]: if eles.tag == "receiveByte": self.result[intf_name][ 'Inbound octets(bytes)'] = eles.text elif eles.tag == "rcvUniPacket": self.result[intf_name][ 'Inbound unicast(pkts)'] = eles.text elif eles.tag == "rcvMutiPacket": self.result[intf_name][ 'Inbound multicast(pkts)'] = eles.text elif eles.tag == "rcvBroadPacket": self.result[intf_name][ 'Inbound broadcast(pkts)'] = eles.text elif eles.tag == "rcvErrorPacket": self.result[intf_name][ 'Inbound error(pkts)'] = eles.text elif eles.tag == "rcvDropPacket": self.result[intf_name][ 'Inbound drop(pkts)'] = eles.text elif eles.tag == "sendByte": self.result[intf_name][ 'Outbound octets(bytes)'] = eles.text elif eles.tag == "sendUniPacket": self.result[intf_name][ 'Outbound unicast(pkts)'] = eles.text elif eles.tag == "sendMutiPacket": self.result[intf_name][ 'Outbound multicast(pkts)'] = eles.text elif eles.tag == "sendBroadPacket": self.result[intf_name][ 'Outbound broadcast(pkts)'] = eles.text elif eles.tag == "sendErrorPacket": self.result[intf_name][ 'Outbound error(pkts)'] = eles.text elif eles.tag == "sendDropPacket": self.result[intf_name][ 'Outbound drop(pkts)'] = eles.text def get_intf_cleared_stat(self, clr_stat, intf_name): """Get interface cleared state information""" if not intf_name: return if_type = get_interface_type(intf_name) if if_type == 'fcoe-port' or if_type == 'nve' or if_type == 'tunnel' or \ if_type == 'vbdif' or if_type == 'vlanif': return if clr_stat: for eles in clr_stat: if eles.tag in ["inByteRate", "inPacketRate", "outByteRate", "outPacketRate"]: if eles.tag == "inByteRate": self.result[intf_name][ 'Inbound rate(byte/sec)'] = eles.text elif eles.tag == "inPacketRate": self.result[intf_name][ 'Inbound rate(pkts/sec)'] = eles.text elif eles.tag == "outByteRate": self.result[intf_name][ 'Outbound rate(byte/sec)'] = eles.text elif eles.tag == "outPacketRate": self.result[intf_name][ 'Outbound rate(pkts/sec)'] = eles.text def get_all_interface_info(self, intf_type=None): """Get interface information all or by interface type""" xml_str = CE_NC_GET_INT_STATISTICS % '' con_obj = get_nc_config(self.module, xml_str) if "<data/>" in con_obj: return xml_str = con_obj.replace('\r', '').replace('\n', '').\ replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\ replace('xmlns="http://www.huawei.com/netconf/vrp"', "") # get link status information root = ElementTree.fromstring(xml_str) intfs_info = root.find("data/ifm/interfaces") if not intfs_info: return intf_name = '' flag = False for eles in intfs_info: if eles.tag == "interface": for ele in eles: if ele.tag in ["ifName", "ifDynamicInfo", "ifStatistics", "ifClearedStat"]: if ele.tag == "ifName": intf_name = ele.text.lower() if intf_type: if get_interface_type(intf_name) != intf_type.lower(): break else: flag = True self.init_interface_data(intf_name) if is_ethernet_port(intf_name): self.get_port_info(intf_name) if ele.tag == "ifDynamicInfo": self.get_intf_dynamic_info(ele, intf_name) elif ele.tag == "ifStatistics": self.get_intf_statistics_info(ele, intf_name) elif ele.tag == "ifClearedStat": self.get_intf_cleared_stat(ele, intf_name) if intf_type and not flag: self.module.fail_json( msg='Error: %s interface type does not exist.' % intf_type.upper()) def get_interface_info(self): """Get interface information""" xml_str = CE_NC_GET_INT_STATISTICS % self.interface.upper() con_obj = get_nc_config(self.module, xml_str) if "<data/>" in con_obj: self.module.fail_json( msg='Error: %s interface does not exist.' % self.interface.upper()) return xml_str = con_obj.replace('\r', '').replace('\n', '').\ replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\ replace('xmlns="http://www.huawei.com/netconf/vrp"', "") # get link status information root = ElementTree.fromstring(xml_str) intf_info = root.find("data/ifm/interfaces/interface") if intf_info: for eles in intf_info: if eles.tag in ["ifDynamicInfo", "ifStatistics", "ifClearedStat"]: if eles.tag == "ifDynamicInfo": self.get_intf_dynamic_info(eles, self.interface) elif eles.tag == "ifStatistics": self.get_intf_statistics_info(eles, self.interface) elif eles.tag == "ifClearedStat": self.get_intf_cleared_stat(eles, self.interface) def init_interface_data(self, intf_name): """Init interface data""" # init link status data self.result[intf_name] = dict() self.result[intf_name]['Current physical state'] = 'down' self.result[intf_name]['Current link state'] = 'down' self.result[intf_name]['Current IPv4 state'] = 'down' self.result[intf_name]['Current IPv6 state'] = 'down' self.result[intf_name]['Inbound octets(bytes)'] = '--' self.result[intf_name]['Inbound unicast(pkts)'] = '--' self.result[intf_name]['Inbound multicast(pkts)'] = '--' self.result[intf_name]['Inbound broadcast(pkts)'] = '--' self.result[intf_name]['Inbound error(pkts)'] = '--' self.result[intf_name]['Inbound drop(pkts)'] = '--' self.result[intf_name]['Inbound rate(byte/sec)'] = '--' self.result[intf_name]['Inbound rate(pkts/sec)'] = '--' self.result[intf_name]['Outbound octets(bytes)'] = '--' self.result[intf_name]['Outbound unicast(pkts)'] = '--' self.result[intf_name]['Outbound multicast(pkts)'] = '--' self.result[intf_name]['Outbound broadcast(pkts)'] = '--' self.result[intf_name]['Outbound error(pkts)'] = '--' self.result[intf_name]['Outbound drop(pkts)'] = '--' self.result[intf_name]['Outbound rate(byte/sec)'] = '--' self.result[intf_name]['Outbound rate(pkts/sec)'] = '--' self.result[intf_name]['Speed'] = '--' def get_port_info(self, interface): """Get port information""" if_type = get_interface_type(interface) if if_type == 'meth': xml_str = CE_NC_GET_PORT_SPEED % interface.lower().replace('meth', 'MEth') else: xml_str = CE_NC_GET_PORT_SPEED % interface.upper() con_obj = get_nc_config(self.module, xml_str) if "<data/>" in con_obj: return xml_str = con_obj.replace('\r', '').replace('\n', '').\ replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\ replace('xmlns="http://www.huawei.com/netconf/vrp"', "") # get link status information root = ElementTree.fromstring(xml_str) port_info = root.find("data/devm/ports/port") if port_info: for eles in port_info: if eles.tag == "ethernetPort": for ele in eles: if ele.tag == 'speed': self.result[interface]['Speed'] = ele.text def get_link_status(self): """Get link status information""" if self.param_type == INTERFACE_FULL_NAME: self.init_interface_data(self.interface) self.get_interface_info() if is_ethernet_port(self.interface): self.get_port_info(self.interface) elif self.param_type == INTERFACE_TYPE: self.get_all_interface_info(self.interface) else: self.get_all_interface_info() def get_intf_param_type(self): """Get the type of input interface parameter""" if self.interface == 'all': self.param_type = INTERFACE_ALL return if self.if_type == self.interface: self.param_type = INTERFACE_TYPE return self.param_type = INTERFACE_FULL_NAME def work(self): """Worker""" self.if_type = get_interface_type(self.interface) self.check_params() self.get_intf_param_type() self.get_link_status() self.show_result() def main(): """Main function entry""" argument_spec = dict( interface=dict(required=True, type='str'), ) argument_spec.update(ce_argument_spec) linkstatus_obj = LinkStatus(argument_spec) linkstatus_obj.work() if __name__ == '__main__': main()
gpl-3.0
suhe/odoo
addons/payment_ogone/data/ogone.py
107
30329
# -*- coding: utf-8 -*- OGONE_ERROR_MAP = { '0020001001': "Authorization failed, please retry", '0020001002': "Authorization failed, please retry", '0020001003': "Authorization failed, please retry", '0020001004': "Authorization failed, please retry", '0020001005': "Authorization failed, please retry", '0020001006': "Authorization failed, please retry", '0020001007': "Authorization failed, please retry", '0020001008': "Authorization failed, please retry", '0020001009': "Authorization failed, please retry", '0020001010': "Authorization failed, please retry", '0030001999': "Our payment system is currently under maintenance, please try later", '0050001005': "Expiration Date error", '0050001007': "Requested Operation code not allowed", '0050001008': "Invalid delay value", '0050001010': "Input date in invalid format", '0050001013': "Unable to parse socket input stream", '0050001014': "Error in parsing stream content", '0050001015': "Currency error", '0050001016': "Transaction still posted at end of wait", '0050001017': "Sync value not compatible with delay value", '0050001019': "Transaction duplicate of a pre-existing transaction", '0050001020': "Acceptation code empty while required for the transaction", '0050001024': "Maintenance acquirer differs from original transaction acquirer", '0050001025': "Maintenance merchant differs from original transaction merchant", '0050001028': "Maintenance operation not accurate for the original transaction", '0050001031': "Host application unknown for the transaction", '0050001032': "Unable to perform requested operation with requested currency", '0050001033': "Maintenance card number differs from original transaction card number", '0050001034': "Operation code not allowed", '0050001035': "Exception occurred in socket input stream treatment", '0050001036': "Card length does not correspond to an acceptable value for the brand", '0050001036': "Card length does not correspond to an acceptable value for the brand", '0050001068': "A technical problem occurred, please contact helpdesk", '0050001069': "Invalid check for CardID and Brand", '0050001070': "A technical problem occurred, please contact helpdesk", '0050001116': "Unknown origin IP", '0050001117': "No origin IP detected", '0050001118': "Merchant configuration problem, please contact support", '10001001': "Communication failure", '10001002': "Communication failure", '10001003': "Communication failure", '10001004': "Communication failure", '10001005': "Communication failure", '20001001': "We received an unknown status for the transaction. We will contact your acquirer and update the status of the transaction within one working day. Please check the status later.", '20001002': "We received an unknown status for the transaction. We will contact your acquirer and update the status of the transaction within one working day. Please check the status later.", '20001003': "We received an unknown status for the transaction. We will contact your acquirer and update the status of the transaction within one working day. Please check the status later.", '20001004': "We received an unknown status for the transaction. We will contact your acquirer and update the status of the transaction within one working day. Please check the status later.", '20001005': "We received an unknown status for the transaction. We will contact your acquirer and update the status of the transaction within one working day. Please check the status later.", '20001006': "We received an unknown status for the transaction. We will contact your acquirer and update the status of the transaction within one working day. Please check the status later.", '20001007': "We received an unknown status for the transaction. We will contact your acquirer and update the status of the transaction within one working day. Please check the status later.", '20001008': "We received an unknown status for the transaction. We will contact your acquirer and update the status of the transaction within one working day. Please check the status later.", '20001009': "We received an unknown status for the transaction. We will contact your acquirer and update the status of the transaction within one working day. Please check the status later.", '20001010': "We received an unknown status for the transaction. We will contact your acquirer and update the status of the transaction within one working day. Please check the status later.", '20001101': "A technical problem occurred, please contact helpdesk", '20001105': "We received an unknown status for the transaction. We will contact your acquirer and update the status of the transaction within one working day. Please check the status later.", '20001111': "A technical problem occurred, please contact helpdesk", '20002001': "Origin for the response of the bank can not be checked", '20002002': "Beneficiary account number has been modified during processing", '20002003': "Amount has been modified during processing", '20002004': "Currency has been modified during processing", '20002005': "No feedback from the bank server has been detected", '30001001': "Payment refused by the acquirer", '30001002': "Duplicate request", '30001010': "A technical problem occurred, please contact helpdesk", '30001011': "A technical problem occurred, please contact helpdesk", '30001012': "Card black listed - Contact acquirer", '30001015': "Your merchant's acquirer is temporarily unavailable, please try later or choose another payment method.", '30001051': "A technical problem occurred, please contact helpdesk", '30001054': "A technical problem occurred, please contact helpdesk", '30001057': "Your merchant's acquirer is temporarily unavailable, please try later or choose another payment method.", '30001058': "Your merchant's acquirer is temporarily unavailable, please try later or choose another payment method.", '30001060': "Aquirer indicates that a failure occured during payment processing", '30001070': "RATEPAY Invalid Response Type (Failure)", '30001071': "RATEPAY Missing Mandatory status code field (failure)", '30001072': "RATEPAY Missing Mandatory Result code field (failure)", '30001073': "RATEPAY Response parsing Failed", '30001090': "CVC check required by front end and returned invalid by acquirer", '30001091': "ZIP check required by front end and returned invalid by acquirer", '30001092': "Address check required by front end and returned as invalid by acquirer.", '30001100': "Unauthorized buyer's country", '30001101': "IP country <> card country", '30001102': "Number of different countries too high", '30001103': "unauthorized card country", '30001104': "unauthorized ip address country", '30001105': "Anonymous proxy", '30001110': "If the problem persists, please contact Support, or go to paysafecard's card balance page (https://customer.cc.at.paysafecard.com/psccustomer/GetWelcomePanelServlet?language=en) to see when the amount reserved on your card will be available again.", '30001120': "IP address in merchant's black list", '30001130': "BIN in merchant's black list", '30001131': "Wrong BIN for 3xCB", '30001140': "Card in merchant's card blacklist", '30001141': "Email in blacklist", '30001142': "Passenger name in blacklist", '30001143': "Card holder name in blacklist", '30001144': "Passenger name different from owner name", '30001145': "Time to departure too short", '30001149': "Card Configured in Card Supplier Limit for another relation (CSL)", '30001150': "Card not configured in the system for this customer (CSL)", '30001151': "REF1 not allowed for this relationship (Contract number", '30001152': "Card/Supplier Amount limit reached (CSL)", '30001153': "Card not allowed for this supplier (Date out of contract bounds)", '30001154': "You have reached the usage limit allowed", '30001155': "You have reached the usage limit allowed", '30001156': "You have reached the usage limit allowed", '30001157': "Unauthorized IP country for itinerary", '30001158': "email usage limit reached", '30001159': "Unauthorized card country/IP country combination", '30001160': "Postcode in highrisk group", '30001161': "generic blacklist match", '30001162': "Billing Address is a PO Box", '30001180': "maximum scoring reached", '30001997': "Authorization canceled by simulation", '30001998': "A technical problem occurred, please try again.", '30001999': "Your merchant's acquirer is temporarily unavailable, please try later or choose another payment method.", '30002001': "Payment refused by the financial institution", '30002001': "Payment refused by the financial institution", '30021001': "Call acquirer support call number.", '30022001': "Payment must be approved by the acquirer before execution.", '30031001': "Invalid merchant number.", '30041001': "Retain card.", '30051001': "Authorization declined", '30071001': "Retain card - special conditions.", '30121001': "Invalid transaction", '30131001': "Invalid amount", '30131002': "You have reached the total amount allowed", '30141001': "Invalid card number", '30151001': "Unknown acquiring institution.", '30171001': "Payment method cancelled by the buyer", '30171002': "The maximum time allowed is elapsed.", '30191001': "Try again later.", '30201001': "A technical problem occurred, please contact helpdesk", '30301001': "Invalid format", '30311001': "Unknown acquirer ID.", '30331001': "Card expired.", '30341001': "Suspicion of fraud.", '30341002': "Suspicion of fraud (3rdMan)", '30341003': "Suspicion of fraud (Perseuss)", '30341004': "Suspicion of fraud (ETHOCA)", '30381001': "A technical problem occurred, please contact helpdesk", '30401001': "Invalid function.", '30411001': "Lost card.", '30431001': "Stolen card, pick up", '30511001': "Insufficient funds.", '30521001': "No Authorization. Contact the issuer of your card.", '30541001': "Card expired.", '30551001': "Invalid PIN.", '30561001': "Card not in authorizer's database.", '30571001': "Transaction not permitted on card.", '30581001': "Transaction not allowed on this terminal", '30591001': "Suspicion of fraud.", '30601001': "The merchant must contact the acquirer.", '30611001': "Amount exceeds card ceiling.", '30621001': "Restricted card.", '30631001': "Security policy not respected.", '30641001': "Amount changed from ref. trn.", '30681001': "Tardy response.", '30751001': "PIN entered incorrectly too often", '30761001': "Card holder already contesting.", '30771001': "PIN entry required.", '30811001': "Message flow error.", '30821001': "Authorization center unavailable", '30831001': "Authorization center unavailable", '30901001': "Temporary system shutdown.", '30911001': "Acquirer unavailable.", '30921001': "Invalid card type for acquirer.", '30941001': "Duplicate transaction", '30961001': "Processing temporarily not possible", '30971001': "A technical problem occurred, please contact helpdesk", '30981001': "A technical problem occurred, please contact helpdesk", '31011001': "Unknown acceptance code", '31021001': "Invalid currency", '31031001': "Acceptance code missing", '31041001': "Inactive card", '31051001': "Merchant not active", '31061001': "Invalid expiration date", '31071001': "Interrupted host communication", '31081001': "Card refused", '31091001': "Invalid password", '31101001': "Plafond transaction (majoré du bonus) dépassé", '31111001': "Plafond mensuel (majoré du bonus) dépassé", '31121001': "Plafond centre de facturation dépassé", '31131001': "Plafond entreprise dépassé", '31141001': "Code MCC du fournisseur non autorisé pour la carte", '31151001': "Numéro SIRET du fournisseur non autorisé pour la carte", '31161001': "This is not a valid online banking account", '32001004': "A technical problem occurred, please try again.", '34011001': "Bezahlung mit RatePAY nicht möglich.", '39991001': "A technical problem occurred, please contact the helpdesk of your acquirer", '40001001': "A technical problem occurred, please try again.", '40001002': "A technical problem occurred, please try again.", '40001003': "A technical problem occurred, please try again.", '40001004': "A technical problem occurred, please try again.", '40001005': "A technical problem occurred, please try again.", '40001006': "A technical problem occurred, please try again.", '40001007': "A technical problem occurred, please try again.", '40001008': "A technical problem occurred, please try again.", '40001009': "A technical problem occurred, please try again.", '40001010': "A technical problem occurred, please try again.", '40001011': "A technical problem occurred, please contact helpdesk", '40001012': "Your merchant's acquirer is temporarily unavailable, please try later or choose another payment method.", '40001013': "A technical problem occurred, please contact helpdesk", '40001016': "A technical problem occurred, please contact helpdesk", '40001018': "A technical problem occurred, please try again.", '40001019': "Sorry, an error occurred during processing. Please retry the operation (use back button of the browser). If problem persists, contact your merchant's helpdesk.", '40001020': "Sorry, an error occurred during processing. Please retry the operation (use back button of the browser). If problem persists, contact your merchant's helpdesk.", '40001050': "A technical problem occurred, please contact helpdesk", '40001133': "Authentication failed, the signature of your bank access control server is incorrect", '40001134': "Authentication failed, please retry or cancel.", '40001135': "Authentication temporary unavailable, please retry or cancel.", '40001136': "Technical problem with your browser, please retry or cancel", '40001137': "Your bank access control server is temporary unavailable, please retry or cancel", '40001998': "Temporary technical problem. Please retry a little bit later.", '50001001': "Unknown card type", '50001002': "Card number format check failed for given card number.", '50001003': "Merchant data error", '50001004': "Merchant identification missing", '50001005': "Expiration Date error", '50001006': "Amount is not a number", '50001007': "A technical problem occurred, please contact helpdesk", '50001008': "A technical problem occurred, please contact helpdesk", '50001009': "A technical problem occurred, please contact helpdesk", '50001010': "A technical problem occurred, please contact helpdesk", '50001011': "Brand not supported for that merchant", '50001012': "A technical problem occurred, please contact helpdesk", '50001013': "A technical problem occurred, please contact helpdesk", '50001014': "A technical problem occurred, please contact helpdesk", '50001015': "Invalid currency code", '50001016': "A technical problem occurred, please contact helpdesk", '50001017': "A technical problem occurred, please contact helpdesk", '50001018': "A technical problem occurred, please contact helpdesk", '50001019': "A technical problem occurred, please contact helpdesk", '50001020': "A technical problem occurred, please contact helpdesk", '50001021': "A technical problem occurred, please contact helpdesk", '50001022': "A technical problem occurred, please contact helpdesk", '50001023': "A technical problem occurred, please contact helpdesk", '50001024': "A technical problem occurred, please contact helpdesk", '50001025': "A technical problem occurred, please contact helpdesk", '50001026': "A technical problem occurred, please contact helpdesk", '50001027': "A technical problem occurred, please contact helpdesk", '50001028': "A technical problem occurred, please contact helpdesk", '50001029': "A technical problem occurred, please contact helpdesk", '50001030': "A technical problem occurred, please contact helpdesk", '50001031': "A technical problem occurred, please contact helpdesk", '50001032': "A technical problem occurred, please contact helpdesk", '50001033': "A technical problem occurred, please contact helpdesk", '50001034': "A technical problem occurred, please contact helpdesk", '50001035': "A technical problem occurred, please contact helpdesk", '50001036': "Card length does not correspond to an acceptable value for the brand", '50001037': "Purchasing card number for a regular merchant", '50001038': "Non Purchasing card for a Purchasing card merchant", '50001039': "Details sent for a non-Purchasing card merchant, please contact helpdesk", '50001040': "Details not sent for a Purchasing card transaction, please contact helpdesk", '50001041': "Payment detail validation failed", '50001042': "Given transactions amounts (tax,discount,shipping,net,etc…) do not compute correctly together", '50001043': "A technical problem occurred, please contact helpdesk", '50001044': "No acquirer configured for this operation", '50001045': "No UID configured for this operation", '50001046': "Operation not allowed for the merchant", '50001047': "A technical problem occurred, please contact helpdesk", '50001048': "A technical problem occurred, please contact helpdesk", '50001049': "A technical problem occurred, please contact helpdesk", '50001050': "A technical problem occurred, please contact helpdesk", '50001051': "A technical problem occurred, please contact helpdesk", '50001052': "A technical problem occurred, please contact helpdesk", '50001053': "A technical problem occurred, please contact helpdesk", '50001054': "Card number incorrect or incompatible", '50001055': "A technical problem occurred, please contact helpdesk", '50001056': "A technical problem occurred, please contact helpdesk", '50001057': "A technical problem occurred, please contact helpdesk", '50001058': "A technical problem occurred, please contact helpdesk", '50001059': "A technical problem occurred, please contact helpdesk", '50001060': "A technical problem occurred, please contact helpdesk", '50001061': "A technical problem occurred, please contact helpdesk", '50001062': "A technical problem occurred, please contact helpdesk", '50001063': "Card Issue Number does not correspond to range or not present", '50001064': "Start Date not valid or not present", '50001066': "Format of CVC code invalid", '50001067': "The merchant is not enrolled for 3D-Secure", '50001068': "The card number or account number (PAN) is invalid", '50001069': "Invalid check for CardID and Brand", '50001070': "The ECI value given is either not supported, or in conflict with other data in the transaction", '50001071': "Incomplete TRN demat", '50001072': "Incomplete PAY demat", '50001073': "No demat APP", '50001074': "Authorisation too old", '50001075': "VERRes was an error message", '50001076': "DCP amount greater than authorisation amount", '50001077': "Details negative amount", '50001078': "Details negative quantity", '50001079': "Could not decode/decompress received PARes (3D-Secure)", '50001080': "Received PARes was an erereor message from ACS (3D-Secure)", '50001081': "Received PARes format was invalid according to the 3DS specifications (3D-Secure)", '50001082': "PAReq/PARes reconciliation failure (3D-Secure)", '50001084': "Maximum amount reached", '50001087': "The transaction type requires authentication, please check with your bank.", '50001090': "CVC missing at input, but CVC check asked", '50001091': "ZIP missing at input, but ZIP check asked", '50001092': "Address missing at input, but Address check asked", '50001095': "Invalid date of birth", '50001096': "Invalid commodity code", '50001097': "The requested currency and brand are incompatible.", '50001111': "Data validation error", '50001113': "This order has already been processed", '50001114': "Error pre-payment check page access", '50001115': "Request not received in secure mode", '50001116': "Unknown IP address origin", '50001117': "NO IP address origin", '50001118': "Pspid not found or not correct", '50001119': "Password incorrect or disabled due to numbers of errors", '50001120': "Invalid currency", '50001121': "Invalid number of decimals for the currency", '50001122': "Currency not accepted by the merchant", '50001123': "Card type not active", '50001124': "Number of lines don't match with number of payments", '50001125': "Format validation error", '50001126': "Overflow in data capture requests for the original order", '50001127': "The original order is not in a correct status", '50001128': "missing authorization code for unauthorized order", '50001129': "Overflow in refunds requests", '50001130': "Error access to original order", '50001131': "Error access to original history item", '50001132': "The Selected Catalog is empty", '50001133': "Duplicate request", '50001134': "Authentication failed, please retry or cancel.", '50001135': "Authentication temporary unavailable, please retry or cancel.", '50001136': "Technical problem with your browser, please retry or cancel", '50001137': "Your bank access control server is temporary unavailable, please retry or cancel", '50001150': "Fraud Detection, Technical error (IP not valid)", '50001151': "Fraud detection : technical error (IPCTY unknown or error)", '50001152': "Fraud detection : technical error (CCCTY unknown or error)", '50001153': "Overflow in redo-authorisation requests", '50001170': "Dynamic BIN check failed", '50001171': "Dynamic country check failed", '50001172': "Error in Amadeus signature", '50001174': "Card Holder Name is too long", '50001175': "Name contains invalid characters", '50001176': "Card number is too long", '50001177': "Card number contains non-numeric info", '50001178': "Card Number Empty", '50001179': "CVC too long", '50001180': "CVC contains non-numeric info", '50001181': "Expiration date contains non-numeric info", '50001182': "Invalid expiration month", '50001183': "Expiration date must be in the future", '50001184': "SHA Mismatch", '50001205': "Missing mandatory fields for billing address.", '50001206': "Missing mandatory field date of birth.", '50001207': "Missing required shopping basket details.", '50001208': "Missing social security number", '50001209': "Invalid country code", '50001210': "Missing yearly salary", '50001211': "Missing gender", '50001212': "Missing email", '50001213': "Missing IP address", '50001214': "Missing part payment campaign ID", '50001215': "Missing invoice number", '50001216': "The alias must be different than the card number", '60000001': "account number unknown", '60000003': "not credited dd-mm-yy", '60000005': "name/number do not correspond", '60000007': "account number blocked", '60000008': "specific direct debit block", '60000009': "account number WKA", '60000010': "administrative reason", '60000011': "account number expired", '60000012': "no direct debit authorisation given", '60000013': "debit not approved", '60000014': "double payment", '60000018': "name/address/city not entered", '60001001': "no original direct debit for revocation", '60001002': "payer’s account number format error", '60001004': "payer’s account at different bank", '60001005': "payee’s account at different bank", '60001006': "payee’s account number format error", '60001007': "payer’s account number blocked", '60001008': "payer’s account number expired", '60001009': "payee’s account number expired", '60001010': "direct debit not possible", '60001011': "creditor payment not possible", '60001012': "payer’s account number unknown WKA-number", '60001013': "payee’s account number unknown WKA-number", '60001014': "impermissible WKA transaction", '60001015': "period for revocation expired", '60001017': "reason for revocation not correct", '60001018': "original run number not numeric", '60001019': "payment ID incorrect", '60001020': "amount not numeric", '60001021': "amount zero not permitted", '60001022': "negative amount not permitted", '60001023': "payer and payee giro account number", '60001025': "processing code (verwerkingscode) incorrect", '60001028': "revocation not permitted", '60001029': "guaranteed direct debit on giro account number", '60001030': "NBC transaction type incorrect", '60001031': "description too large", '60001032': "book account number not issued", '60001034': "book account number incorrect", '60001035': "payer’s account number not numeric", '60001036': "payer’s account number not eleven-proof", '60001037': "payer’s account number not issued", '60001039': "payer’s account number of DNB/BGC/BLA", '60001040': "payee’s account number not numeric", '60001041': "payee’s account number not eleven-proof", '60001042': "payee’s account number not issued", '60001044': "payee’s account number unknown", '60001050': "payee’s name missing", '60001051': "indicate payee’s bank account number instead of 3102", '60001052': "no direct debit contract", '60001053': "amount beyond bounds", '60001054': "selective direct debit block", '60001055': "original run number unknown", '60001057': "payer’s name missing", '60001058': "payee’s account number missing", '60001059': "restore not permitted", '60001060': "bank’s reference (navraaggegeven) missing", '60001061': "BEC/GBK number incorrect", '60001062': "BEC/GBK code incorrect", '60001087': "book account number not numeric", '60001090': "cancelled on request", '60001091': "cancellation order executed", '60001092': "cancelled instead of bended", '60001093': "book account number is a shortened account number", '60001094': "instructing party account number not identical with payer", '60001095': "payee unknown GBK acceptor", '60001097': "instructing party account number not identical with payee", '60001099': "clearing not permitted", '60001101': "payer’s account number not spaces", '60001102': "PAN length not numeric", '60001103': "PAN length outside limits", '60001104': "track number not numeric", '60001105': "track number not valid", '60001106': "PAN sequence number not numeric", '60001107': "domestic PAN not numeric", '60001108': "domestic PAN not eleven-proof", '60001109': "domestic PAN not issued", '60001110': "foreign PAN not numeric", '60001111': "card valid date not numeric", '60001112': "book period number (boekperiodenr) not numeric", '60001113': "transaction number not numeric", '60001114': "transaction time not numeric", '60001115': "transaction no valid time", '60001116': "transaction date not numeric", '60001117': "transaction no valid date", '60001118': "STAN not numeric", '60001119': "instructing party’s name missing", '60001120': "foreign amount (bedrag-vv) not numeric", '60001122': "rate (verrekenkoers) not numeric", '60001125': "number of decimals (aantaldecimalen) incorrect", '60001126': "tariff (tarifering) not B/O/S", '60001127': "domestic costs (kostenbinnenland) not numeric", '60001128': "domestic costs (kostenbinnenland) not higher than zero", '60001129': "foreign costs (kostenbuitenland) not numeric", '60001130': "foreign costs (kostenbuitenland) not higher than zero", '60001131': "domestic costs (kostenbinnenland) not zero", '60001132': "foreign costs (kostenbuitenland) not zero", '60001134': "Euro record not fully filled in", '60001135': "Client currency incorrect", '60001136': "Amount NLG not numeric", '60001137': "Amount NLG not higher than zero", '60001138': "Amount NLG not equal to Amount", '60001139': "Amount NLG incorrectly converted", '60001140': "Amount EUR not numeric", '60001141': "Amount EUR not greater than zero", '60001142': "Amount EUR not equal to Amount", '60001143': "Amount EUR incorrectly converted", '60001144': "Client currency not NLG", '60001145': "rate euro-vv (Koerseuro-vv) not numeric", '60001146': "comma rate euro-vv (Kommakoerseuro-vv) incorrect", '60001147': "acceptgiro distributor not valid", '60001148': "Original run number and/or BRN are missing", '60001149': "Amount/Account number/ BRN different", '60001150': "Direct debit already revoked/restored", '60001151': "Direct debit already reversed/revoked/restored", '60001153': "Payer’s account number not known", } DATA_VALIDATION_ERROR = '50001111' def retryable(error): return error in [ '0020001001', '0020001002', '0020001003', '0020001004', '0020001005', '0020001006', '0020001007', '0020001008', '0020001009', '0020001010', '30001010', '30001011', '30001015', '30001057', '30001058', '30001998', '30001999', #'30611001', # amount exceeds card limit '30961001', '40001001', '40001002', '40001003', '40001004', '40001005', '40001006', '40001007', '40001008', '40001009', '40001010', '40001012', '40001018', '40001019', '40001020', '40001134', '40001135', '40001136', '40001137', #'50001174', # cardholder name too long ]
gpl-3.0
dnjohnstone/hyperspy
hyperspy/tests/axes/test_axes_manager.py
4
12899
# -*- coding: utf-8 -*- # Copyright 2007-2020 The HyperSpy developers # # This file is part of HyperSpy. # # HyperSpy 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. # # HyperSpy 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 HyperSpy. If not, see <http://www.gnu.org/licenses/>. from unittest import mock from numpy import arange, zeros from hyperspy.axes import AxesManager from hyperspy.defaults_parser import preferences from hyperspy.signals import BaseSignal, Signal1D, Signal2D class TestAxesManager: def setup_method(self, method): axes_list = [ { "name": "a", "navigate": True, "offset": 0.0, "scale": 1.3, "size": 2, "units": "aa", }, { "name": "b", "navigate": False, "offset": 1.0, "scale": 6.0, "size": 3, "units": "bb", }, { "name": "c", "navigate": False, "offset": 2.0, "scale": 100.0, "size": 4, "units": "cc", }, { "name": "d", "navigate": True, "offset": 3.0, "scale": 1000000.0, "size": 5, "units": "dd", }, ] self.am = AxesManager(axes_list) def test_reprs(self): repr(self.am) self.am._repr_html_ def test_update_from(self): am = self.am am2 = self.am.deepcopy() m = mock.Mock() am.events.any_axis_changed.connect(m.changed) am.update_axes_attributes_from(am2._axes) assert not m.changed.called am2[0].scale = 0.5 am2[1].units = "km" am2[2].offset = 50 am2[3].size = 1 am.update_axes_attributes_from(am2._axes, attributes=["units", "scale"]) assert m.changed.called assert am2[0].scale == am[0].scale assert am2[1].units == am[1].units assert am2[2].offset != am[2].offset assert am2[3].size != am[3].size class TestAxesManagerScaleOffset: def test_low_high_value(self): data = arange(11) s = BaseSignal(data) axes = s.axes_manager[0] assert axes.low_value == data[0] assert axes.high_value == data[-1] def test_change_scale(self): data = arange(132) s = BaseSignal(data) axes = s.axes_manager[0] scale_value_list = [0.07, 76, 1] for scale_value in scale_value_list: axes.scale = scale_value assert axes.low_value == data[0] * scale_value assert axes.high_value == data[-1] * scale_value def test_change_offset(self): data = arange(81) s = BaseSignal(data) axes = s.axes_manager[0] offset_value_list = [12, -216, 1, 0] for offset_value in offset_value_list: axes.offset = offset_value assert axes.low_value == (data[0] + offset_value) assert axes.high_value == (data[-1] + offset_value) def test_change_offset_scale(self): data = arange(11) s = BaseSignal(data) axes = s.axes_manager[0] scale, offset = 0.123, -314 axes.offset = offset axes.scale = scale assert axes.low_value == (data[0] * scale + offset) assert axes.high_value == (data[-1] * scale + offset) class TestAxesManagerExtent: def test_1d_basesignal(self): s = BaseSignal(arange(10)) assert len(s.axes_manager.signal_extent) == 2 signal_axis = s.axes_manager.signal_axes[0] signal_extent = (signal_axis.low_value, signal_axis.high_value) assert signal_extent == s.axes_manager.signal_extent assert len(s.axes_manager.navigation_extent) == 0 assert () == s.axes_manager.navigation_extent def test_1d_signal1d(self): s = Signal1D(arange(10)) assert len(s.axes_manager.signal_extent) == 2 signal_axis = s.axes_manager.signal_axes[0] signal_extent = (signal_axis.low_value, signal_axis.high_value) assert signal_extent == s.axes_manager.signal_extent assert len(s.axes_manager.navigation_extent) == 0 assert () == s.axes_manager.navigation_extent def test_2d_signal1d(self): s = Signal1D(arange(100).reshape(10, 10)) assert len(s.axes_manager.signal_extent) == 2 signal_axis = s.axes_manager.signal_axes[0] signal_extent = (signal_axis.low_value, signal_axis.high_value) assert signal_extent == s.axes_manager.signal_extent assert len(s.axes_manager.navigation_extent) == 2 nav_axis = s.axes_manager.navigation_axes[0] nav_extent = (nav_axis.low_value, nav_axis.high_value) assert nav_extent == s.axes_manager.navigation_extent def test_3d_signal1d(self): s = Signal1D(arange(1000).reshape(10, 10, 10)) assert len(s.axes_manager.signal_extent) == 2 signal_axis = s.axes_manager.signal_axes[0] signal_extent = (signal_axis.low_value, signal_axis.high_value) assert signal_extent == s.axes_manager.signal_extent assert len(s.axes_manager.navigation_extent) == 4 nav_axis0 = s.axes_manager.navigation_axes[0] nav_axis1 = s.axes_manager.navigation_axes[1] nav_extent = ( nav_axis0.low_value, nav_axis0.high_value, nav_axis1.low_value, nav_axis1.high_value, ) assert nav_extent == s.axes_manager.navigation_extent def test_2d_signal2d(self): s = Signal2D(arange(100).reshape(10, 10)) assert len(s.axes_manager.signal_extent) == 4 signal_axis0 = s.axes_manager.signal_axes[0] signal_axis1 = s.axes_manager.signal_axes[1] signal_extent = ( signal_axis0.low_value, signal_axis0.high_value, signal_axis1.low_value, signal_axis1.high_value, ) assert signal_extent == s.axes_manager.signal_extent assert len(s.axes_manager.navigation_extent) == 0 assert () == s.axes_manager.navigation_extent def test_3d_signal2d(self): s = Signal2D(arange(1000).reshape(10, 10, 10)) assert len(s.axes_manager.signal_extent) == 4 signal_axis0 = s.axes_manager.signal_axes[0] signal_axis1 = s.axes_manager.signal_axes[1] signal_extent = ( signal_axis0.low_value, signal_axis0.high_value, signal_axis1.low_value, signal_axis1.high_value, ) assert signal_extent == s.axes_manager.signal_extent assert len(s.axes_manager.navigation_extent) == 2 nav_axis = s.axes_manager.navigation_axes[0] nav_extent = (nav_axis.low_value, nav_axis.high_value) assert nav_extent == s.axes_manager.navigation_extent def test_changing_scale_offset(self): s = Signal2D(arange(100).reshape(10, 10)) signal_axis0 = s.axes_manager.signal_axes[0] signal_axis1 = s.axes_manager.signal_axes[1] signal_extent = ( signal_axis0.low_value, signal_axis0.high_value, signal_axis1.low_value, signal_axis1.high_value, ) assert signal_extent == s.axes_manager.signal_extent signal_axis0.scale = 0.2 signal_axis1.scale = 0.7 signal_extent = ( signal_axis0.low_value, signal_axis0.high_value, signal_axis1.low_value, signal_axis1.high_value, ) assert signal_extent == s.axes_manager.signal_extent signal_axis0.offset = -11 signal_axis1.scale = 23 signal_extent = ( signal_axis0.low_value, signal_axis0.high_value, signal_axis1.low_value, signal_axis1.high_value, ) assert signal_extent == s.axes_manager.signal_extent def test_setting_indices_coordinates(): s = Signal1D(arange(1000).reshape(10, 10, 10)) m = mock.Mock() s.axes_manager.events.indices_changed.connect(m, []) # both indices are changed but the event is triggered only once s.axes_manager.indices = (5, 5) assert s.axes_manager.indices == (5, 5) assert m.call_count == 1 # indices not changed, so the event is not triggered s.axes_manager.indices == (5, 5) assert s.axes_manager.indices == (5, 5) assert m.call_count == 1 # both indices changed again, call only once s.axes_manager.indices = (2, 3) assert s.axes_manager.indices == (2, 3) assert m.call_count == 2 # single index changed, call only once s.axes_manager.indices = (2, 2) assert s.axes_manager.indices == (2, 2) assert m.call_count == 3 # both coordinates are changed but the event is triggered only once s.axes_manager.coordinates = (5, 5) assert s.axes_manager.coordinates == (5, 5) assert m.call_count == 4 # coordinates not changed, so the event is not triggered s.axes_manager.indices == (5, 5) assert s.axes_manager.indices == (5, 5) assert m.call_count == 4 # both coordinates changed again, call only once s.axes_manager.coordinates = (2, 3) assert s.axes_manager.coordinates == (2, 3) assert m.call_count == 5 # single coordinate changed, call only once s.axes_manager.indices = (2, 2) assert s.axes_manager.indices == (2, 2) assert m.call_count == 6 class TestAxesHotkeys: def setup_method(self, method): s = Signal1D(zeros(7 * (5,))) self.am = s.axes_manager def test_hotkeys_in_six_dimensions(self): "Step twice increasing and once decreasing all axes" mod01 = preferences.Plot.modifier_dims_01 mod23 = preferences.Plot.modifier_dims_23 mod45 = preferences.Plot.modifier_dims_45 dim0_decrease = mod01 + "+" + preferences.Plot.dims_024_decrease dim0_increase = mod01 + "+" + preferences.Plot.dims_024_increase dim1_decrease = mod01 + "+" + preferences.Plot.dims_135_decrease dim1_increase = mod01 + "+" + preferences.Plot.dims_135_increase dim2_decrease = mod23 + "+" + preferences.Plot.dims_024_decrease dim2_increase = mod23 + "+" + preferences.Plot.dims_024_increase dim3_decrease = mod23 + "+" + preferences.Plot.dims_135_decrease dim3_increase = mod23 + "+" + preferences.Plot.dims_135_increase dim4_decrease = mod45 + "+" + preferences.Plot.dims_024_decrease dim4_increase = mod45 + "+" + preferences.Plot.dims_024_increase dim5_decrease = mod45 + "+" + preferences.Plot.dims_135_decrease dim5_increase = mod45 + "+" + preferences.Plot.dims_135_increase steps = [ dim0_increase, dim0_increase, dim0_decrease, dim1_increase, dim1_increase, dim1_decrease, dim2_increase, dim2_increase, dim2_decrease, dim3_increase, dim3_increase, dim3_decrease, dim4_increase, dim4_increase, dim4_decrease, dim5_increase, dim5_increase, dim5_decrease, ] class fake_key_event: "Fake event handler for plot key press" def __init__(self, key): self.key = key for step in steps: self.am.key_navigator(fake_key_event(step)) assert self.am.indices == (1, 1, 1, 1, 1, 1) class TestIterPathScanPattern: def setup_method(self, method): s = Signal1D(zeros((3, 3, 3, 2))) self.am = s.axes_manager def test_flyback(self): self.am._iterpath = "flyback" for i, index in enumerate(self.am): if i == 3: assert self.am.indices == (0, 1, 0) # Hits a new layer on index 9 if i == 9: assert self.am.indices == (0, 0, 1) break def test_serpentine(self): self.am._iterpath = "serpentine" for i, index in enumerate(self.am): if i == 3: assert self.am.indices == (2, 1, 0) # Hits a new layer on index 9 if i == 9: assert self.am.indices == (2, 2, 1) break
gpl-3.0
TheoRettisch/p2pool-aiden
wstools/XMLSchema.py
289
109858
# Copyright (c) 2003, The Regents of the University of California, # through Lawrence Berkeley National Laboratory (subject to receipt of # any required approvals from the U.S. Dept. of Energy). All rights # reserved. # # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. ident = "$Id$" import types, weakref, sys, warnings from Namespaces import SCHEMA, XMLNS, SOAP, APACHE from Utility import DOM, DOMException, Collection, SplitQName, basejoin from StringIO import StringIO # If we have no threading, this should be a no-op try: from threading import RLock except ImportError: class RLock: def acquire(): pass def release(): pass # # Collections in XMLSchema class # TYPES = 'types' ATTRIBUTE_GROUPS = 'attr_groups' ATTRIBUTES = 'attr_decl' ELEMENTS = 'elements' MODEL_GROUPS = 'model_groups' BUILT_IN_NAMESPACES = [SOAP.ENC,] + SCHEMA.XSD_LIST + [APACHE.AXIS_NS] def GetSchema(component): """convience function for finding the parent XMLSchema instance. """ parent = component while not isinstance(parent, XMLSchema): parent = parent._parent() return parent class SchemaReader: """A SchemaReader creates XMLSchema objects from urls and xml data. """ namespaceToSchema = {} def __init__(self, domReader=None, base_url=None): """domReader -- class must implement DOMAdapterInterface base_url -- base url string """ self.__base_url = base_url self.__readerClass = domReader if not self.__readerClass: self.__readerClass = DOMAdapter self._includes = {} self._imports = {} def __setImports(self, schema): """Add dictionary of imports to schema instance. schema -- XMLSchema instance """ for ns,val in schema.imports.items(): if self._imports.has_key(ns): schema.addImportSchema(self._imports[ns]) def __setIncludes(self, schema): """Add dictionary of includes to schema instance. schema -- XMLSchema instance """ for schemaLocation, val in schema.includes.items(): if self._includes.has_key(schemaLocation): schema.addIncludeSchema(schemaLocation, self._imports[schemaLocation]) def addSchemaByLocation(self, location, schema): """provide reader with schema document for a location. """ self._includes[location] = schema def addSchemaByNamespace(self, schema): """provide reader with schema document for a targetNamespace. """ self._imports[schema.targetNamespace] = schema def loadFromNode(self, parent, element): """element -- DOM node or document parent -- WSDLAdapter instance """ reader = self.__readerClass(element) schema = XMLSchema(parent) #HACK to keep a reference schema.wsdl = parent schema.setBaseUrl(self.__base_url) schema.load(reader) return schema def loadFromStream(self, file, url=None): """Return an XMLSchema instance loaded from a file object. file -- file object url -- base location for resolving imports/includes. """ reader = self.__readerClass() reader.loadDocument(file) schema = XMLSchema() if url is not None: schema.setBaseUrl(url) schema.load(reader) self.__setIncludes(schema) self.__setImports(schema) return schema def loadFromString(self, data): """Return an XMLSchema instance loaded from an XML string. data -- XML string """ return self.loadFromStream(StringIO(data)) def loadFromURL(self, url, schema=None): """Return an XMLSchema instance loaded from the given url. url -- URL to dereference schema -- Optional XMLSchema instance. """ reader = self.__readerClass() if self.__base_url: url = basejoin(self.__base_url,url) reader.loadFromURL(url) schema = schema or XMLSchema() schema.setBaseUrl(url) schema.load(reader) self.__setIncludes(schema) self.__setImports(schema) return schema def loadFromFile(self, filename): """Return an XMLSchema instance loaded from the given file. filename -- name of file to open """ if self.__base_url: filename = basejoin(self.__base_url,filename) file = open(filename, 'rb') try: schema = self.loadFromStream(file, filename) finally: file.close() return schema class SchemaError(Exception): pass class NoSchemaLocationWarning(Exception): pass ########################### # DOM Utility Adapters ########################## class DOMAdapterInterface: def hasattr(self, attr, ns=None): """return true if node has attribute attr -- attribute to check for ns -- namespace of attribute, by default None """ raise NotImplementedError, 'adapter method not implemented' def getContentList(self, *contents): """returns an ordered list of child nodes *contents -- list of node names to return """ raise NotImplementedError, 'adapter method not implemented' def setAttributeDictionary(self, attributes): """set attribute dictionary """ raise NotImplementedError, 'adapter method not implemented' def getAttributeDictionary(self): """returns a dict of node's attributes """ raise NotImplementedError, 'adapter method not implemented' def getNamespace(self, prefix): """returns namespace referenced by prefix. """ raise NotImplementedError, 'adapter method not implemented' def getTagName(self): """returns tagName of node """ raise NotImplementedError, 'adapter method not implemented' def getParentNode(self): """returns parent element in DOMAdapter or None """ raise NotImplementedError, 'adapter method not implemented' def loadDocument(self, file): """load a Document from a file object file -- """ raise NotImplementedError, 'adapter method not implemented' def loadFromURL(self, url): """load a Document from an url url -- URL to dereference """ raise NotImplementedError, 'adapter method not implemented' class DOMAdapter(DOMAdapterInterface): """Adapter for ZSI.Utility.DOM """ def __init__(self, node=None): """Reset all instance variables. element -- DOM document, node, or None """ if hasattr(node, 'documentElement'): self.__node = node.documentElement else: self.__node = node self.__attributes = None def getNode(self): return self.__node def hasattr(self, attr, ns=None): """attr -- attribute ns -- optional namespace, None means unprefixed attribute. """ if not self.__attributes: self.setAttributeDictionary() if ns: return self.__attributes.get(ns,{}).has_key(attr) return self.__attributes.has_key(attr) def getContentList(self, *contents): nodes = [] ELEMENT_NODE = self.__node.ELEMENT_NODE for child in DOM.getElements(self.__node, None): if child.nodeType == ELEMENT_NODE and\ SplitQName(child.tagName)[1] in contents: nodes.append(child) return map(self.__class__, nodes) def setAttributeDictionary(self): self.__attributes = {} for v in self.__node._attrs.values(): self.__attributes[v.nodeName] = v.nodeValue def getAttributeDictionary(self): if not self.__attributes: self.setAttributeDictionary() return self.__attributes def getTagName(self): return self.__node.tagName def getParentNode(self): if self.__node.parentNode.nodeType == self.__node.ELEMENT_NODE: return DOMAdapter(self.__node.parentNode) return None def getNamespace(self, prefix): """prefix -- deference namespace prefix in node's context. Ascends parent nodes until found. """ namespace = None if prefix == 'xmlns': namespace = DOM.findDefaultNS(prefix, self.__node) else: try: namespace = DOM.findNamespaceURI(prefix, self.__node) except DOMException, ex: if prefix != 'xml': raise SchemaError, '%s namespace not declared for %s'\ %(prefix, self.__node._get_tagName()) namespace = XMLNS.XML return namespace def loadDocument(self, file): self.__node = DOM.loadDocument(file) if hasattr(self.__node, 'documentElement'): self.__node = self.__node.documentElement def loadFromURL(self, url): self.__node = DOM.loadFromURL(url) if hasattr(self.__node, 'documentElement'): self.__node = self.__node.documentElement class XMLBase: """ These class variables are for string indentation. """ tag = None __indent = 0 __rlock = RLock() def __str__(self): XMLBase.__rlock.acquire() XMLBase.__indent += 1 tmp = "<" + str(self.__class__) + '>\n' for k,v in self.__dict__.items(): tmp += "%s* %s = %s\n" %(XMLBase.__indent*' ', k, v) XMLBase.__indent -= 1 XMLBase.__rlock.release() return tmp """Marker Interface: can determine something about an instances properties by using the provided convenience functions. """ class DefinitionMarker: """marker for definitions """ pass class DeclarationMarker: """marker for declarations """ pass class AttributeMarker: """marker for attributes """ pass class AttributeGroupMarker: """marker for attribute groups """ pass class WildCardMarker: """marker for wildcards """ pass class ElementMarker: """marker for wildcards """ pass class ReferenceMarker: """marker for references """ pass class ModelGroupMarker: """marker for model groups """ pass class AllMarker(ModelGroupMarker): """marker for all model group """ pass class ChoiceMarker(ModelGroupMarker): """marker for choice model group """ pass class SequenceMarker(ModelGroupMarker): """marker for sequence model group """ pass class ExtensionMarker: """marker for extensions """ pass class RestrictionMarker: """marker for restrictions """ facets = ['enumeration', 'length', 'maxExclusive', 'maxInclusive',\ 'maxLength', 'minExclusive', 'minInclusive', 'minLength',\ 'pattern', 'fractionDigits', 'totalDigits', 'whiteSpace'] class SimpleMarker: """marker for simple type information """ pass class ListMarker: """marker for simple type list """ pass class UnionMarker: """marker for simple type Union """ pass class ComplexMarker: """marker for complex type information """ pass class LocalMarker: """marker for complex type information """ pass class MarkerInterface: def isDefinition(self): return isinstance(self, DefinitionMarker) def isDeclaration(self): return isinstance(self, DeclarationMarker) def isAttribute(self): return isinstance(self, AttributeMarker) def isAttributeGroup(self): return isinstance(self, AttributeGroupMarker) def isElement(self): return isinstance(self, ElementMarker) def isReference(self): return isinstance(self, ReferenceMarker) def isWildCard(self): return isinstance(self, WildCardMarker) def isModelGroup(self): return isinstance(self, ModelGroupMarker) def isAll(self): return isinstance(self, AllMarker) def isChoice(self): return isinstance(self, ChoiceMarker) def isSequence(self): return isinstance(self, SequenceMarker) def isExtension(self): return isinstance(self, ExtensionMarker) def isRestriction(self): return isinstance(self, RestrictionMarker) def isSimple(self): return isinstance(self, SimpleMarker) def isComplex(self): return isinstance(self, ComplexMarker) def isLocal(self): return isinstance(self, LocalMarker) def isList(self): return isinstance(self, ListMarker) def isUnion(self): return isinstance(self, UnionMarker) ########################################################## # Schema Components ######################################################### class XMLSchemaComponent(XMLBase, MarkerInterface): """ class variables: required -- list of required attributes attributes -- dict of default attribute values, including None. Value can be a function for runtime dependencies. contents -- dict of namespace keyed content lists. 'xsd' content of xsd namespace. xmlns_key -- key for declared xmlns namespace. xmlns -- xmlns is special prefix for namespace dictionary xml -- special xml prefix for xml namespace. """ required = [] attributes = {} contents = {} xmlns_key = '' xmlns = 'xmlns' xml = 'xml' def __init__(self, parent=None): """parent -- parent instance instance variables: attributes -- dictionary of node's attributes """ self.attributes = None self._parent = parent if self._parent: self._parent = weakref.ref(parent) if not self.__class__ == XMLSchemaComponent\ and not (type(self.__class__.required) == type(XMLSchemaComponent.required)\ and type(self.__class__.attributes) == type(XMLSchemaComponent.attributes)\ and type(self.__class__.contents) == type(XMLSchemaComponent.contents)): raise RuntimeError, 'Bad type for a class variable in %s' %self.__class__ def getItemTrace(self): """Returns a node trace up to the <schema> item. """ item, path, name, ref = self, [], 'name', 'ref' while not isinstance(item,XMLSchema) and not isinstance(item,WSDLToolsAdapter): attr = item.getAttribute(name) if not attr: attr = item.getAttribute(ref) if not attr: path.append('<%s>' %(item.tag)) else: path.append('<%s ref="%s">' %(item.tag, attr)) else: path.append('<%s name="%s">' %(item.tag,attr)) item = item._parent() try: tns = item.getTargetNamespace() except: tns = '' path.append('<%s targetNamespace="%s">' %(item.tag, tns)) path.reverse() return ''.join(path) def getTargetNamespace(self): """return targetNamespace """ parent = self targetNamespace = 'targetNamespace' tns = self.attributes.get(targetNamespace) while not tns and parent and parent._parent is not None: parent = parent._parent() tns = parent.attributes.get(targetNamespace) return tns or '' def getAttributeDeclaration(self, attribute): """attribute -- attribute with a QName value (eg. type). collection -- check types collection in parent Schema instance """ return self.getQNameAttribute(ATTRIBUTES, attribute) def getAttributeGroup(self, attribute): """attribute -- attribute with a QName value (eg. type). collection -- check types collection in parent Schema instance """ return self.getQNameAttribute(ATTRIBUTE_GROUPS, attribute) def getTypeDefinition(self, attribute): """attribute -- attribute with a QName value (eg. type). collection -- check types collection in parent Schema instance """ return self.getQNameAttribute(TYPES, attribute) def getElementDeclaration(self, attribute): """attribute -- attribute with a QName value (eg. element). collection -- check elements collection in parent Schema instance. """ return self.getQNameAttribute(ELEMENTS, attribute) def getModelGroup(self, attribute): """attribute -- attribute with a QName value (eg. ref). collection -- check model_group collection in parent Schema instance. """ return self.getQNameAttribute(MODEL_GROUPS, attribute) def getQNameAttribute(self, collection, attribute): """returns object instance representing QName --> (namespace,name), or if does not exist return None. attribute -- an information item attribute, with a QName value. collection -- collection in parent Schema instance to search. """ tdc = self.getAttributeQName(attribute) if not tdc: return obj = self.getSchemaItem(collection, tdc.getTargetNamespace(), tdc.getName()) if obj: return obj # raise SchemaError, 'No schema item "%s" in collection %s' %(tdc, collection) return def getSchemaItem(self, collection, namespace, name): """returns object instance representing namespace, name, or if does not exist return None if built-in, else raise SchemaError. namespace -- namespace item defined in. name -- name of item. collection -- collection in parent Schema instance to search. """ parent = GetSchema(self) if parent.targetNamespace == namespace: try: obj = getattr(parent, collection)[name] except KeyError, ex: raise KeyError, 'targetNamespace(%s) collection(%s) has no item(%s)'\ %(namespace, collection, name) return obj if not parent.imports.has_key(namespace): if namespace in BUILT_IN_NAMESPACES: # built-in just return # WARNING: expecting import if "redefine" or add to built-in namespace. return raise SchemaError, 'schema "%s" does not import namespace "%s"' %( parent.targetNamespace, namespace) # Lazy Eval schema = parent.imports[namespace] if not isinstance(schema, XMLSchema): schema = schema.getSchema() if schema is not None: parent.imports[namespace] = schema if schema is None: if namespace in BUILT_IN_NAMESPACES: # built-in just return return raise SchemaError, 'no schema instance for imported namespace (%s).'\ %(namespace) if not isinstance(schema, XMLSchema): raise TypeError, 'expecting XMLSchema instance not "%r"' %schema try: obj = getattr(schema, collection)[name] except KeyError, ex: raise KeyError, 'targetNamespace(%s) collection(%s) has no item(%s)'\ %(namespace, collection, name) return obj def getXMLNS(self, prefix=None): """deference prefix or by default xmlns, returns namespace. """ if prefix == XMLSchemaComponent.xml: return XMLNS.XML parent = self ns = self.attributes[XMLSchemaComponent.xmlns].get(prefix or\ XMLSchemaComponent.xmlns_key) while not ns: parent = parent._parent() ns = parent.attributes[XMLSchemaComponent.xmlns].get(prefix or\ XMLSchemaComponent.xmlns_key) if not ns and isinstance(parent, WSDLToolsAdapter): if prefix is None: return '' raise SchemaError, 'unknown prefix %s' %prefix return ns def getAttribute(self, attribute): """return requested attribute value or None """ if type(attribute) in (list, tuple): if len(attribute) != 2: raise LookupError, 'To access attributes must use name or (namespace,name)' ns_dict = self.attributes.get(attribute[0]) if ns_dict is None: return None return ns_dict.get(attribute[1]) return self.attributes.get(attribute) def getAttributeQName(self, attribute): """return requested attribute value as (namespace,name) or None """ qname = self.getAttribute(attribute) if isinstance(qname, TypeDescriptionComponent) is True: return qname if qname is None: return None prefix,ncname = SplitQName(qname) namespace = self.getXMLNS(prefix) return TypeDescriptionComponent((namespace,ncname)) def getAttributeName(self): """return attribute name or None """ return self.getAttribute('name') def setAttributes(self, node): """Sets up attribute dictionary, checks for required attributes and sets default attribute values. attr is for default attribute values determined at runtime. structure of attributes dictionary ['xmlns'][xmlns_key] -- xmlns namespace ['xmlns'][prefix] -- declared namespace prefix [namespace][prefix] -- attributes declared in a namespace [attribute] -- attributes w/o prefix, default namespaces do not directly apply to attributes, ie Name can't collide with QName. """ self.attributes = {XMLSchemaComponent.xmlns:{}} for k,v in node.getAttributeDictionary().items(): prefix,value = SplitQName(k) if value == XMLSchemaComponent.xmlns: self.attributes[value][prefix or XMLSchemaComponent.xmlns_key] = v elif prefix: ns = node.getNamespace(prefix) if not ns: raise SchemaError, 'no namespace for attribute prefix %s'\ %prefix if not self.attributes.has_key(ns): self.attributes[ns] = {} elif self.attributes[ns].has_key(value): raise SchemaError, 'attribute %s declared multiple times in %s'\ %(value, ns) self.attributes[ns][value] = v elif not self.attributes.has_key(value): self.attributes[value] = v else: raise SchemaError, 'attribute %s declared multiple times' %value if not isinstance(self, WSDLToolsAdapter): self.__checkAttributes() self.__setAttributeDefaults() #set QNames for k in ['type', 'element', 'base', 'ref', 'substitutionGroup', 'itemType']: if self.attributes.has_key(k): prefix, value = SplitQName(self.attributes.get(k)) self.attributes[k] = \ TypeDescriptionComponent((self.getXMLNS(prefix), value)) #Union, memberTypes is a whitespace separated list of QNames for k in ['memberTypes']: if self.attributes.has_key(k): qnames = self.attributes[k] self.attributes[k] = [] for qname in qnames.split(): prefix, value = SplitQName(qname) self.attributes['memberTypes'].append(\ TypeDescriptionComponent(\ (self.getXMLNS(prefix), value))) def getContents(self, node): """retrieve xsd contents """ return node.getContentList(*self.__class__.contents['xsd']) def __setAttributeDefaults(self): """Looks for default values for unset attributes. If class variable representing attribute is None, then it must be defined as an instance variable. """ for k,v in self.__class__.attributes.items(): if v is not None and self.attributes.has_key(k) is False: if isinstance(v, types.FunctionType): self.attributes[k] = v(self) else: self.attributes[k] = v def __checkAttributes(self): """Checks that required attributes have been defined, attributes w/default cannot be required. Checks all defined attributes are legal, attribute references are not subject to this test. """ for a in self.__class__.required: if not self.attributes.has_key(a): raise SchemaError,\ 'class instance %s, missing required attribute %s'\ %(self.__class__, a) for a,v in self.attributes.items(): # attribute #other, ie. not in empty namespace if type(v) is dict: continue # predefined prefixes xmlns, xml if a in (XMLSchemaComponent.xmlns, XMLNS.XML): continue if (a not in self.__class__.attributes.keys()) and not\ (self.isAttribute() and self.isReference()): raise SchemaError, '%s, unknown attribute(%s,%s)' \ %(self.getItemTrace(), a, self.attributes[a]) class WSDLToolsAdapter(XMLSchemaComponent): """WSDL Adapter to grab the attributes from the wsdl document node. """ attributes = {'name':None, 'targetNamespace':None} tag = 'definitions' def __init__(self, wsdl): XMLSchemaComponent.__init__(self, parent=wsdl) self.setAttributes(DOMAdapter(wsdl.document)) def getImportSchemas(self): """returns WSDLTools.WSDL types Collection """ return self._parent().types class Notation(XMLSchemaComponent): """<notation> parent: schema attributes: id -- ID name -- NCName, Required public -- token, Required system -- anyURI contents: annotation? """ required = ['name', 'public'] attributes = {'id':None, 'name':None, 'public':None, 'system':None} contents = {'xsd':('annotation')} tag = 'notation' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) for i in contents: component = SplitQName(i.getTagName())[1] if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) class Annotation(XMLSchemaComponent): """<annotation> parent: all,any,anyAttribute,attribute,attributeGroup,choice,complexContent, complexType,element,extension,field,group,import,include,key,keyref, list,notation,redefine,restriction,schema,selector,simpleContent, simpleType,union,unique attributes: id -- ID contents: (documentation | appinfo)* """ attributes = {'id':None} contents = {'xsd':('documentation', 'appinfo')} tag = 'annotation' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.content = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) content = [] for i in contents: component = SplitQName(i.getTagName())[1] if component == 'documentation': #print_debug('class %s, documentation skipped' %self.__class__, 5) continue elif component == 'appinfo': #print_debug('class %s, appinfo skipped' %self.__class__, 5) continue else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) self.content = tuple(content) class Documentation(XMLSchemaComponent): """<documentation> parent: annotation attributes: source, anyURI xml:lang, language contents: mixed, any """ attributes = {'source':None, 'xml:lang':None} contents = {'xsd':('mixed', 'any')} tag = 'documentation' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.content = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) content = [] for i in contents: component = SplitQName(i.getTagName())[1] if component == 'mixed': #print_debug('class %s, mixed skipped' %self.__class__, 5) continue elif component == 'any': #print_debug('class %s, any skipped' %self.__class__, 5) continue else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) self.content = tuple(content) class Appinfo(XMLSchemaComponent): """<appinfo> parent: annotation attributes: source, anyURI contents: mixed, any """ attributes = {'source':None, 'anyURI':None} contents = {'xsd':('mixed', 'any')} tag = 'appinfo' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.content = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) content = [] for i in contents: component = SplitQName(i.getTagName())[1] if component == 'mixed': #print_debug('class %s, mixed skipped' %self.__class__, 5) continue elif component == 'any': #print_debug('class %s, any skipped' %self.__class__, 5) continue else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) self.content = tuple(content) class XMLSchemaFake: # This is temporary, for the benefit of WSDL until the real thing works. def __init__(self, element): self.targetNamespace = DOM.getAttr(element, 'targetNamespace') self.element = element class XMLSchema(XMLSchemaComponent): """A schema is a collection of schema components derived from one or more schema documents, that is, one or more <schema> element information items. It represents the abstract notion of a schema rather than a single schema document (or other representation). <schema> parent: ROOT attributes: id -- ID version -- token xml:lang -- language targetNamespace -- anyURI attributeFormDefault -- 'qualified' | 'unqualified', 'unqualified' elementFormDefault -- 'qualified' | 'unqualified', 'unqualified' blockDefault -- '#all' | list of ('substitution | 'extension' | 'restriction') finalDefault -- '#all' | list of ('extension' | 'restriction' | 'list' | 'union') contents: ((include | import | redefine | annotation)*, (attribute, attributeGroup, complexType, element, group, notation, simpleType)*, annotation*)* attributes -- schema attributes imports -- import statements includes -- include statements redefines -- types -- global simpleType, complexType definitions elements -- global element declarations attr_decl -- global attribute declarations attr_groups -- attribute Groups model_groups -- model Groups notations -- global notations """ attributes = {'id':None, 'version':None, 'xml:lang':None, 'targetNamespace':None, 'attributeFormDefault':'unqualified', 'elementFormDefault':'unqualified', 'blockDefault':None, 'finalDefault':None} contents = {'xsd':('include', 'import', 'redefine', 'annotation', 'attribute', 'attributeGroup', 'complexType', 'element', 'group', 'notation', 'simpleType', 'annotation')} empty_namespace = '' tag = 'schema' def __init__(self, parent=None): """parent -- instance variables: targetNamespace -- schema's declared targetNamespace, or empty string. _imported_schemas -- namespace keyed dict of schema dependencies, if a schema is provided instance will not resolve import statement. _included_schemas -- schemaLocation keyed dict of component schemas, if schema is provided instance will not resolve include statement. _base_url -- needed for relative URLs support, only works with URLs relative to initial document. includes -- collection of include statements imports -- collection of import statements elements -- collection of global element declarations types -- collection of global type definitions attr_decl -- collection of global attribute declarations attr_groups -- collection of global attribute group definitions model_groups -- collection of model group definitions notations -- collection of notations """ self.__node = None self.targetNamespace = None XMLSchemaComponent.__init__(self, parent) f = lambda k: k.attributes['name'] ns = lambda k: k.attributes['namespace'] sl = lambda k: k.attributes['schemaLocation'] self.includes = Collection(self, key=sl) self.imports = Collection(self, key=ns) self.elements = Collection(self, key=f) self.types = Collection(self, key=f) self.attr_decl = Collection(self, key=f) self.attr_groups = Collection(self, key=f) self.model_groups = Collection(self, key=f) self.notations = Collection(self, key=f) self._imported_schemas = {} self._included_schemas = {} self._base_url = None def getNode(self): """ Interacting with the underlying DOM tree. """ return self.__node def addImportSchema(self, schema): """for resolving import statements in Schema instance schema -- schema instance _imported_schemas """ if not isinstance(schema, XMLSchema): raise TypeError, 'expecting a Schema instance' if schema.targetNamespace != self.targetNamespace: self._imported_schemas[schema.targetNamespace] = schema else: raise SchemaError, 'import schema bad targetNamespace' def addIncludeSchema(self, schemaLocation, schema): """for resolving include statements in Schema instance schemaLocation -- schema location schema -- schema instance _included_schemas """ if not isinstance(schema, XMLSchema): raise TypeError, 'expecting a Schema instance' if not schema.targetNamespace or\ schema.targetNamespace == self.targetNamespace: self._included_schemas[schemaLocation] = schema else: raise SchemaError, 'include schema bad targetNamespace' def setImportSchemas(self, schema_dict): """set the import schema dictionary, which is used to reference depedent schemas. """ self._imported_schemas = schema_dict def getImportSchemas(self): """get the import schema dictionary, which is used to reference depedent schemas. """ return self._imported_schemas def getSchemaNamespacesToImport(self): """returns tuple of namespaces the schema instance has declared itself to be depedent upon. """ return tuple(self.includes.keys()) def setIncludeSchemas(self, schema_dict): """set the include schema dictionary, which is keyed with schemaLocation (uri). This is a means of providing schemas to the current schema for content inclusion. """ self._included_schemas = schema_dict def getIncludeSchemas(self): """get the include schema dictionary, which is keyed with schemaLocation (uri). """ return self._included_schemas def getBaseUrl(self): """get base url, used for normalizing all relative uri's """ return self._base_url def setBaseUrl(self, url): """set base url, used for normalizing all relative uri's """ self._base_url = url def getElementFormDefault(self): """return elementFormDefault attribute """ return self.attributes.get('elementFormDefault') def isElementFormDefaultQualified(self): return self.attributes.get('elementFormDefault') == 'qualified' def getAttributeFormDefault(self): """return attributeFormDefault attribute """ return self.attributes.get('attributeFormDefault') def getBlockDefault(self): """return blockDefault attribute """ return self.attributes.get('blockDefault') def getFinalDefault(self): """return finalDefault attribute """ return self.attributes.get('finalDefault') def load(self, node, location=None): self.__node = node pnode = node.getParentNode() if pnode: pname = SplitQName(pnode.getTagName())[1] if pname == 'types': attributes = {} self.setAttributes(pnode) attributes.update(self.attributes) self.setAttributes(node) for k,v in attributes['xmlns'].items(): if not self.attributes['xmlns'].has_key(k): self.attributes['xmlns'][k] = v else: self.setAttributes(node) else: self.setAttributes(node) self.targetNamespace = self.getTargetNamespace() for childNode in self.getContents(node): component = SplitQName(childNode.getTagName())[1] if component == 'include': tp = self.__class__.Include(self) tp.fromDom(childNode) sl = tp.attributes['schemaLocation'] schema = tp.getSchema() if not self.getIncludeSchemas().has_key(sl): self.addIncludeSchema(sl, schema) self.includes[sl] = tp pn = childNode.getParentNode().getNode() pn.removeChild(childNode.getNode()) for child in schema.getNode().getNode().childNodes: pn.appendChild(child.cloneNode(1)) for collection in ['imports','elements','types', 'attr_decl','attr_groups','model_groups', 'notations']: for k,v in getattr(schema,collection).items(): if not getattr(self,collection).has_key(k): v._parent = weakref.ref(self) getattr(self,collection)[k] = v else: warnings.warn("Not keeping schema component.") elif component == 'import': slocd = SchemaReader.namespaceToSchema tp = self.__class__.Import(self) tp.fromDom(childNode) import_ns = tp.getAttribute('namespace') or\ self.__class__.empty_namespace schema = slocd.get(import_ns) if schema is None: schema = XMLSchema() slocd[import_ns] = schema try: tp.loadSchema(schema) except NoSchemaLocationWarning, ex: # Dependency declaration, hopefully implementation # is aware of this namespace (eg. SOAP,WSDL,?) print "IMPORT: ", import_ns print ex del slocd[import_ns] continue except SchemaError, ex: #warnings.warn(\ # '<import namespace="%s" schemaLocation=?>, %s'\ # %(import_ns, 'failed to load schema instance') #) print ex del slocd[import_ns] class _LazyEvalImport(str): '''Lazy evaluation of import, replace entry in self.imports.''' #attributes = dict(namespace=import_ns) def getSchema(namespace): schema = slocd.get(namespace) if schema is None: parent = self._parent() wstypes = parent if isinstance(parent, WSDLToolsAdapter): wstypes = parent.getImportSchemas() schema = wstypes.get(namespace) if isinstance(schema, XMLSchema): self.imports[namespace] = schema return schema return None self.imports[import_ns] = _LazyEvalImport(import_ns) continue else: tp._schema = schema if self.getImportSchemas().has_key(import_ns): warnings.warn(\ 'Detected multiple imports of the namespace "%s" '\ %import_ns) self.addImportSchema(schema) # spec says can have multiple imports of same namespace # but purpose of import is just dependency declaration. self.imports[import_ns] = tp elif component == 'redefine': warnings.warn('redefine is ignored') elif component == 'annotation': warnings.warn('annotation is ignored') elif component == 'attribute': tp = AttributeDeclaration(self) tp.fromDom(childNode) self.attr_decl[tp.getAttribute('name')] = tp elif component == 'attributeGroup': tp = AttributeGroupDefinition(self) tp.fromDom(childNode) self.attr_groups[tp.getAttribute('name')] = tp elif component == 'element': tp = ElementDeclaration(self) tp.fromDom(childNode) self.elements[tp.getAttribute('name')] = tp elif component == 'group': tp = ModelGroupDefinition(self) tp.fromDom(childNode) self.model_groups[tp.getAttribute('name')] = tp elif component == 'notation': tp = Notation(self) tp.fromDom(childNode) self.notations[tp.getAttribute('name')] = tp elif component == 'complexType': tp = ComplexType(self) tp.fromDom(childNode) self.types[tp.getAttribute('name')] = tp elif component == 'simpleType': tp = SimpleType(self) tp.fromDom(childNode) self.types[tp.getAttribute('name')] = tp else: break class Import(XMLSchemaComponent): """<import> parent: schema attributes: id -- ID namespace -- anyURI schemaLocation -- anyURI contents: annotation? """ attributes = {'id':None, 'namespace':None, 'schemaLocation':None} contents = {'xsd':['annotation']} tag = 'import' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self._schema = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) if self.attributes['namespace'] == self.getTargetNamespace(): raise SchemaError, 'namespace of schema and import match' for i in contents: component = SplitQName(i.getTagName())[1] if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) def getSchema(self): """if schema is not defined, first look for a Schema class instance in parent Schema. Else if not defined resolve schemaLocation and create a new Schema class instance, and keep a hard reference. """ if not self._schema: ns = self.attributes['namespace'] schema = self._parent().getImportSchemas().get(ns) if not schema and self._parent()._parent: schema = self._parent()._parent().getImportSchemas().get(ns) if not schema: url = self.attributes.get('schemaLocation') if not url: raise SchemaError, 'namespace(%s) is unknown' %ns base_url = self._parent().getBaseUrl() reader = SchemaReader(base_url=base_url) reader._imports = self._parent().getImportSchemas() reader._includes = self._parent().getIncludeSchemas() self._schema = reader.loadFromURL(url) return self._schema or schema def loadSchema(self, schema): """ """ base_url = self._parent().getBaseUrl() reader = SchemaReader(base_url=base_url) reader._imports = self._parent().getImportSchemas() reader._includes = self._parent().getIncludeSchemas() self._schema = schema if not self.attributes.has_key('schemaLocation'): raise NoSchemaLocationWarning('no schemaLocation attribute in import') reader.loadFromURL(self.attributes.get('schemaLocation'), schema) class Include(XMLSchemaComponent): """<include schemaLocation> parent: schema attributes: id -- ID schemaLocation -- anyURI, required contents: annotation? """ required = ['schemaLocation'] attributes = {'id':None, 'schemaLocation':None} contents = {'xsd':['annotation']} tag = 'include' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self._schema = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) for i in contents: component = SplitQName(i.getTagName())[1] if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) def getSchema(self): """if schema is not defined, first look for a Schema class instance in parent Schema. Else if not defined resolve schemaLocation and create a new Schema class instance. """ if not self._schema: schema = self._parent() self._schema = schema.getIncludeSchemas().get(\ self.attributes['schemaLocation'] ) if not self._schema: url = self.attributes['schemaLocation'] reader = SchemaReader(base_url=schema.getBaseUrl()) reader._imports = schema.getImportSchemas() reader._includes = schema.getIncludeSchemas() # create schema before loading so chameleon include # will evalute targetNamespace correctly. self._schema = XMLSchema(schema) reader.loadFromURL(url, self._schema) return self._schema class AttributeDeclaration(XMLSchemaComponent,\ AttributeMarker,\ DeclarationMarker): """<attribute name> parent: schema attributes: id -- ID name -- NCName, required type -- QName default -- string fixed -- string contents: annotation?, simpleType? """ required = ['name'] attributes = {'id':None, 'name':None, 'type':None, 'default':None, 'fixed':None} contents = {'xsd':['annotation','simpleType']} tag = 'attribute' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self.content = None def fromDom(self, node): """ No list or union support """ self.setAttributes(node) contents = self.getContents(node) for i in contents: component = SplitQName(i.getTagName())[1] if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) elif component == 'simpleType': self.content = AnonymousSimpleType(self) self.content.fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) class LocalAttributeDeclaration(AttributeDeclaration,\ AttributeMarker,\ LocalMarker,\ DeclarationMarker): """<attribute name> parent: complexType, restriction, extension, attributeGroup attributes: id -- ID name -- NCName, required type -- QName form -- ('qualified' | 'unqualified'), schema.attributeFormDefault use -- ('optional' | 'prohibited' | 'required'), optional default -- string fixed -- string contents: annotation?, simpleType? """ required = ['name'] attributes = {'id':None, 'name':None, 'type':None, 'form':lambda self: GetSchema(self).getAttributeFormDefault(), 'use':'optional', 'default':None, 'fixed':None} contents = {'xsd':['annotation','simpleType']} def __init__(self, parent): AttributeDeclaration.__init__(self, parent) self.annotation = None self.content = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) for i in contents: component = SplitQName(i.getTagName())[1] if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) elif component == 'simpleType': self.content = AnonymousSimpleType(self) self.content.fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) class AttributeWildCard(XMLSchemaComponent,\ AttributeMarker,\ DeclarationMarker,\ WildCardMarker): """<anyAttribute> parents: complexType, restriction, extension, attributeGroup attributes: id -- ID namespace -- '##any' | '##other' | (anyURI* | '##targetNamespace' | '##local'), ##any processContents -- 'lax' | 'skip' | 'strict', strict contents: annotation? """ attributes = {'id':None, 'namespace':'##any', 'processContents':'strict'} contents = {'xsd':['annotation']} tag = 'anyAttribute' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) for i in contents: component = SplitQName(i.getTagName())[1] if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) class AttributeReference(XMLSchemaComponent,\ AttributeMarker,\ ReferenceMarker): """<attribute ref> parents: complexType, restriction, extension, attributeGroup attributes: id -- ID ref -- QName, required use -- ('optional' | 'prohibited' | 'required'), optional default -- string fixed -- string contents: annotation? """ required = ['ref'] attributes = {'id':None, 'ref':None, 'use':'optional', 'default':None, 'fixed':None} contents = {'xsd':['annotation']} tag = 'attribute' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None def getAttributeDeclaration(self, attribute='ref'): return XMLSchemaComponent.getAttributeDeclaration(self, attribute) def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) for i in contents: component = SplitQName(i.getTagName())[1] if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) class AttributeGroupDefinition(XMLSchemaComponent,\ AttributeGroupMarker,\ DefinitionMarker): """<attributeGroup name> parents: schema, redefine attributes: id -- ID name -- NCName, required contents: annotation?, (attribute | attributeGroup)*, anyAttribute? """ required = ['name'] attributes = {'id':None, 'name':None} contents = {'xsd':['annotation', 'attribute', 'attributeGroup', 'anyAttribute']} tag = 'attributeGroup' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self.attr_content = None def getAttributeContent(self): return self.attr_content def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) content = [] for indx in range(len(contents)): component = SplitQName(contents[indx].getTagName())[1] if (component == 'annotation') and (not indx): self.annotation = Annotation(self) self.annotation.fromDom(contents[indx]) elif component == 'attribute': if contents[indx].hasattr('name'): content.append(LocalAttributeDeclaration(self)) elif contents[indx].hasattr('ref'): content.append(AttributeReference(self)) else: raise SchemaError, 'Unknown attribute type' content[-1].fromDom(contents[indx]) elif component == 'attributeGroup': content.append(AttributeGroupReference(self)) content[-1].fromDom(contents[indx]) elif component == 'anyAttribute': if len(contents) != indx+1: raise SchemaError, 'anyAttribute is out of order in %s' %self.getItemTrace() content.append(AttributeWildCard(self)) content[-1].fromDom(contents[indx]) else: raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName()) self.attr_content = tuple(content) class AttributeGroupReference(XMLSchemaComponent,\ AttributeGroupMarker,\ ReferenceMarker): """<attributeGroup ref> parents: complexType, restriction, extension, attributeGroup attributes: id -- ID ref -- QName, required contents: annotation? """ required = ['ref'] attributes = {'id':None, 'ref':None} contents = {'xsd':['annotation']} tag = 'attributeGroup' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None def getAttributeGroup(self, attribute='ref'): """attribute -- attribute with a QName value (eg. type). collection -- check types collection in parent Schema instance """ return XMLSchemaComponent.getAttributeGroup(self, attribute) def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) for i in contents: component = SplitQName(i.getTagName())[1] if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) ###################################################### # Elements ##################################################### class IdentityConstrants(XMLSchemaComponent): """Allow one to uniquely identify nodes in a document and ensure the integrity of references between them. attributes -- dictionary of attributes selector -- XPath to selected nodes fields -- list of XPath to key field """ def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.selector = None self.fields = None self.annotation = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) fields = [] for i in contents: component = SplitQName(i.getTagName())[1] if component in self.__class__.contents['xsd']: if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) elif component == 'selector': self.selector = self.Selector(self) self.selector.fromDom(i) continue elif component == 'field': fields.append(self.Field(self)) fields[-1].fromDom(i) continue else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) self.fields = tuple(fields) class Constraint(XMLSchemaComponent): def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) for i in contents: component = SplitQName(i.getTagName())[1] if component in self.__class__.contents['xsd']: if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) class Selector(Constraint): """<selector xpath> parent: unique, key, keyref attributes: id -- ID xpath -- XPath subset, required contents: annotation? """ required = ['xpath'] attributes = {'id':None, 'xpath':None} contents = {'xsd':['annotation']} tag = 'selector' class Field(Constraint): """<field xpath> parent: unique, key, keyref attributes: id -- ID xpath -- XPath subset, required contents: annotation? """ required = ['xpath'] attributes = {'id':None, 'xpath':None} contents = {'xsd':['annotation']} tag = 'field' class Unique(IdentityConstrants): """<unique name> Enforce fields are unique w/i a specified scope. parent: element attributes: id -- ID name -- NCName, required contents: annotation?, selector, field+ """ required = ['name'] attributes = {'id':None, 'name':None} contents = {'xsd':['annotation', 'selector', 'field']} tag = 'unique' class Key(IdentityConstrants): """<key name> Enforce fields are unique w/i a specified scope, and all field values are present w/i document. Fields cannot be nillable. parent: element attributes: id -- ID name -- NCName, required contents: annotation?, selector, field+ """ required = ['name'] attributes = {'id':None, 'name':None} contents = {'xsd':['annotation', 'selector', 'field']} tag = 'key' class KeyRef(IdentityConstrants): """<keyref name refer> Ensure a match between two sets of values in an instance. parent: element attributes: id -- ID name -- NCName, required refer -- QName, required contents: annotation?, selector, field+ """ required = ['name', 'refer'] attributes = {'id':None, 'name':None, 'refer':None} contents = {'xsd':['annotation', 'selector', 'field']} tag = 'keyref' class ElementDeclaration(XMLSchemaComponent,\ ElementMarker,\ DeclarationMarker): """<element name> parents: schema attributes: id -- ID name -- NCName, required type -- QName default -- string fixed -- string nillable -- boolean, false abstract -- boolean, false substitutionGroup -- QName block -- ('#all' | ('substition' | 'extension' | 'restriction')*), schema.blockDefault final -- ('#all' | ('extension' | 'restriction')*), schema.finalDefault contents: annotation?, (simpleType,complexType)?, (key | keyref | unique)* """ required = ['name'] attributes = {'id':None, 'name':None, 'type':None, 'default':None, 'fixed':None, 'nillable':0, 'abstract':0, 'substitutionGroup':None, 'block':lambda self: self._parent().getBlockDefault(), 'final':lambda self: self._parent().getFinalDefault()} contents = {'xsd':['annotation', 'simpleType', 'complexType', 'key',\ 'keyref', 'unique']} tag = 'element' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self.content = None self.constraints = () def isQualified(self): """Global elements are always qualified. """ return True def getAttribute(self, attribute): """return attribute. If attribute is type and it's None, and no simple or complex content, return the default type "xsd:anyType" """ value = XMLSchemaComponent.getAttribute(self, attribute) if attribute != 'type' or value is not None: return value if self.content is not None: return None parent = self while 1: nsdict = parent.attributes[XMLSchemaComponent.xmlns] for k,v in nsdict.items(): if v not in SCHEMA.XSD_LIST: continue return TypeDescriptionComponent((v, 'anyType')) if isinstance(parent, WSDLToolsAdapter)\ or not hasattr(parent, '_parent'): break parent = parent._parent() raise SchemaError, 'failed to locate the XSD namespace' def getElementDeclaration(self, attribute): raise Warning, 'invalid operation for <%s>' %self.tag def getTypeDefinition(self, attribute=None): """If attribute is None, "type" is assumed, return the corresponding representation of the global type definition (TypeDefinition), or the local definition if don't find "type". To maintain backwards compat, if attribute is provided call base class method. """ if attribute: return XMLSchemaComponent.getTypeDefinition(self, attribute) gt = XMLSchemaComponent.getTypeDefinition(self, 'type') if gt: return gt return self.content def getConstraints(self): return self._constraints def setConstraints(self, constraints): self._constraints = tuple(constraints) constraints = property(getConstraints, setConstraints, None, "tuple of key, keyref, unique constraints") def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) constraints = [] for i in contents: component = SplitQName(i.getTagName())[1] if component in self.__class__.contents['xsd']: if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) elif component == 'simpleType' and not self.content: self.content = AnonymousSimpleType(self) self.content.fromDom(i) elif component == 'complexType' and not self.content: self.content = LocalComplexType(self) self.content.fromDom(i) elif component == 'key': constraints.append(Key(self)) constraints[-1].fromDom(i) elif component == 'keyref': constraints.append(KeyRef(self)) constraints[-1].fromDom(i) elif component == 'unique': constraints.append(Unique(self)) constraints[-1].fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) self.constraints = constraints class LocalElementDeclaration(ElementDeclaration,\ LocalMarker): """<element> parents: all, choice, sequence attributes: id -- ID name -- NCName, required form -- ('qualified' | 'unqualified'), schema.elementFormDefault type -- QName minOccurs -- Whole Number, 1 maxOccurs -- (Whole Number | 'unbounded'), 1 default -- string fixed -- string nillable -- boolean, false block -- ('#all' | ('extension' | 'restriction')*), schema.blockDefault contents: annotation?, (simpleType,complexType)?, (key | keyref | unique)* """ required = ['name'] attributes = {'id':None, 'name':None, 'form':lambda self: GetSchema(self).getElementFormDefault(), 'type':None, 'minOccurs':'1', 'maxOccurs':'1', 'default':None, 'fixed':None, 'nillable':0, 'abstract':0, 'block':lambda self: GetSchema(self).getBlockDefault()} contents = {'xsd':['annotation', 'simpleType', 'complexType', 'key',\ 'keyref', 'unique']} def isQualified(self): """ Local elements can be qualified or unqualifed according to the attribute form, or the elementFormDefault. By default local elements are unqualified. """ form = self.getAttribute('form') if form == 'qualified': return True if form == 'unqualified': return False raise SchemaError, 'Bad form (%s) for element: %s' %(form, self.getItemTrace()) class ElementReference(XMLSchemaComponent,\ ElementMarker,\ ReferenceMarker): """<element ref> parents: all, choice, sequence attributes: id -- ID ref -- QName, required minOccurs -- Whole Number, 1 maxOccurs -- (Whole Number | 'unbounded'), 1 contents: annotation? """ required = ['ref'] attributes = {'id':None, 'ref':None, 'minOccurs':'1', 'maxOccurs':'1'} contents = {'xsd':['annotation']} tag = 'element' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None def getElementDeclaration(self, attribute=None): """If attribute is None, "ref" is assumed, return the corresponding representation of the global element declaration (ElementDeclaration), To maintain backwards compat, if attribute is provided call base class method. """ if attribute: return XMLSchemaComponent.getElementDeclaration(self, attribute) return XMLSchemaComponent.getElementDeclaration(self, 'ref') def fromDom(self, node): self.annotation = None self.setAttributes(node) for i in self.getContents(node): component = SplitQName(i.getTagName())[1] if component in self.__class__.contents['xsd']: if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) class ElementWildCard(LocalElementDeclaration, WildCardMarker): """<any> parents: choice, sequence attributes: id -- ID minOccurs -- Whole Number, 1 maxOccurs -- (Whole Number | 'unbounded'), 1 namespace -- '##any' | '##other' | (anyURI* | '##targetNamespace' | '##local'), ##any processContents -- 'lax' | 'skip' | 'strict', strict contents: annotation? """ required = [] attributes = {'id':None, 'minOccurs':'1', 'maxOccurs':'1', 'namespace':'##any', 'processContents':'strict'} contents = {'xsd':['annotation']} tag = 'any' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None def isQualified(self): """ Global elements are always qualified, but if processContents are not strict could have dynamically generated local elements. """ return GetSchema(self).isElementFormDefaultQualified() def getAttribute(self, attribute): """return attribute. """ return XMLSchemaComponent.getAttribute(self, attribute) def getTypeDefinition(self, attribute): raise Warning, 'invalid operation for <%s>' % self.tag def fromDom(self, node): self.annotation = None self.setAttributes(node) for i in self.getContents(node): component = SplitQName(i.getTagName())[1] if component in self.__class__.contents['xsd']: if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) ###################################################### # Model Groups ##################################################### class Sequence(XMLSchemaComponent,\ SequenceMarker): """<sequence> parents: complexType, extension, restriction, group, choice, sequence attributes: id -- ID minOccurs -- Whole Number, 1 maxOccurs -- (Whole Number | 'unbounded'), 1 contents: annotation?, (element | group | choice | sequence | any)* """ attributes = {'id':None, 'minOccurs':'1', 'maxOccurs':'1'} contents = {'xsd':['annotation', 'element', 'group', 'choice', 'sequence',\ 'any']} tag = 'sequence' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self.content = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) content = [] for i in contents: component = SplitQName(i.getTagName())[1] if component in self.__class__.contents['xsd']: if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) continue elif component == 'element': if i.hasattr('ref'): content.append(ElementReference(self)) else: content.append(LocalElementDeclaration(self)) elif component == 'group': content.append(ModelGroupReference(self)) elif component == 'choice': content.append(Choice(self)) elif component == 'sequence': content.append(Sequence(self)) elif component == 'any': content.append(ElementWildCard(self)) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) content[-1].fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) self.content = tuple(content) class All(XMLSchemaComponent,\ AllMarker): """<all> parents: complexType, extension, restriction, group attributes: id -- ID minOccurs -- '0' | '1', 1 maxOccurs -- '1', 1 contents: annotation?, element* """ attributes = {'id':None, 'minOccurs':'1', 'maxOccurs':'1'} contents = {'xsd':['annotation', 'element']} tag = 'all' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self.content = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) content = [] for i in contents: component = SplitQName(i.getTagName())[1] if component in self.__class__.contents['xsd']: if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) continue elif component == 'element': if i.hasattr('ref'): content.append(ElementReference(self)) else: content.append(LocalElementDeclaration(self)) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) content[-1].fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) self.content = tuple(content) class Choice(XMLSchemaComponent,\ ChoiceMarker): """<choice> parents: complexType, extension, restriction, group, choice, sequence attributes: id -- ID minOccurs -- Whole Number, 1 maxOccurs -- (Whole Number | 'unbounded'), 1 contents: annotation?, (element | group | choice | sequence | any)* """ attributes = {'id':None, 'minOccurs':'1', 'maxOccurs':'1'} contents = {'xsd':['annotation', 'element', 'group', 'choice', 'sequence',\ 'any']} tag = 'choice' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self.content = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) content = [] for i in contents: component = SplitQName(i.getTagName())[1] if component in self.__class__.contents['xsd']: if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) continue elif component == 'element': if i.hasattr('ref'): content.append(ElementReference(self)) else: content.append(LocalElementDeclaration(self)) elif component == 'group': content.append(ModelGroupReference(self)) elif component == 'choice': content.append(Choice(self)) elif component == 'sequence': content.append(Sequence(self)) elif component == 'any': content.append(ElementWildCard(self)) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) content[-1].fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) self.content = tuple(content) class ModelGroupDefinition(XMLSchemaComponent,\ ModelGroupMarker,\ DefinitionMarker): """<group name> parents: redefine, schema attributes: id -- ID name -- NCName, required contents: annotation?, (all | choice | sequence)? """ required = ['name'] attributes = {'id':None, 'name':None} contents = {'xsd':['annotation', 'all', 'choice', 'sequence']} tag = 'group' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self.content = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) for i in contents: component = SplitQName(i.getTagName())[1] if component in self.__class__.contents['xsd']: if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) continue elif component == 'all' and not self.content: self.content = All(self) elif component == 'choice' and not self.content: self.content = Choice(self) elif component == 'sequence' and not self.content: self.content = Sequence(self) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) self.content.fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) class ModelGroupReference(XMLSchemaComponent,\ ModelGroupMarker,\ ReferenceMarker): """<group ref> parents: choice, complexType, extension, restriction, sequence attributes: id -- ID ref -- NCName, required minOccurs -- Whole Number, 1 maxOccurs -- (Whole Number | 'unbounded'), 1 contents: annotation? """ required = ['ref'] attributes = {'id':None, 'ref':None, 'minOccurs':'1', 'maxOccurs':'1'} contents = {'xsd':['annotation']} tag = 'group' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None def getModelGroupReference(self): return self.getModelGroup('ref') def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) for i in contents: component = SplitQName(i.getTagName())[1] if component in self.__class__.contents['xsd']: if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) class ComplexType(XMLSchemaComponent,\ DefinitionMarker,\ ComplexMarker): """<complexType name> parents: redefine, schema attributes: id -- ID name -- NCName, required mixed -- boolean, false abstract -- boolean, false block -- ('#all' | ('extension' | 'restriction')*), schema.blockDefault final -- ('#all' | ('extension' | 'restriction')*), schema.finalDefault contents: annotation?, (simpleContent | complexContent | ((group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute?)) """ required = ['name'] attributes = {'id':None, 'name':None, 'mixed':0, 'abstract':0, 'block':lambda self: self._parent().getBlockDefault(), 'final':lambda self: self._parent().getFinalDefault()} contents = {'xsd':['annotation', 'simpleContent', 'complexContent',\ 'group', 'all', 'choice', 'sequence', 'attribute', 'attributeGroup',\ 'anyAttribute', 'any']} tag = 'complexType' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self.content = None self.attr_content = None def isMixed(self): m = self.getAttribute('mixed') if m == 0 or m == False: return False if isinstance(m, basestring) is True: if m in ('false', '0'): return False if m in ('true', '1'): return True raise SchemaError, 'invalid value for attribute mixed(%s): %s'\ %(m, self.getItemTrace()) def getAttributeContent(self): return self.attr_content def getElementDeclaration(self, attribute): raise Warning, 'invalid operation for <%s>' %self.tag def getTypeDefinition(self, attribute): raise Warning, 'invalid operation for <%s>' %self.tag def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) indx = 0 num = len(contents) if not num: return component = SplitQName(contents[indx].getTagName())[1] if component == 'annotation': self.annotation = Annotation(self) self.annotation.fromDom(contents[indx]) indx += 1 if indx < num: component = SplitQName(contents[indx].getTagName())[1] self.content = None if component == 'simpleContent': self.content = self.__class__.SimpleContent(self) self.content.fromDom(contents[indx]) elif component == 'complexContent': self.content = self.__class__.ComplexContent(self) self.content.fromDom(contents[indx]) else: if component == 'all': self.content = All(self) elif component == 'choice': self.content = Choice(self) elif component == 'sequence': self.content = Sequence(self) elif component == 'group': self.content = ModelGroupReference(self) if self.content: self.content.fromDom(contents[indx]) indx += 1 self.attr_content = [] while indx < num: component = SplitQName(contents[indx].getTagName())[1] if component == 'attribute': if contents[indx].hasattr('ref'): self.attr_content.append(AttributeReference(self)) else: self.attr_content.append(LocalAttributeDeclaration(self)) elif component == 'attributeGroup': self.attr_content.append(AttributeGroupReference(self)) elif component == 'anyAttribute': self.attr_content.append(AttributeWildCard(self)) else: raise SchemaError, 'Unknown component (%s): %s' \ %(contents[indx].getTagName(),self.getItemTrace()) self.attr_content[-1].fromDom(contents[indx]) indx += 1 class _DerivedType(XMLSchemaComponent): def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None # XXX remove attribute derivation, inconsistent self.derivation = None self.content = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) for i in contents: component = SplitQName(i.getTagName())[1] if component in self.__class__.contents['xsd']: if component == 'annotation' and not self.annotation: self.annotation = Annotation(self) self.annotation.fromDom(i) continue elif component == 'restriction' and not self.derivation: self.derivation = self.__class__.Restriction(self) elif component == 'extension' and not self.derivation: self.derivation = self.__class__.Extension(self) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) self.derivation.fromDom(i) self.content = self.derivation class ComplexContent(_DerivedType,\ ComplexMarker): """<complexContent> parents: complexType attributes: id -- ID mixed -- boolean, false contents: annotation?, (restriction | extension) """ attributes = {'id':None, 'mixed':0} contents = {'xsd':['annotation', 'restriction', 'extension']} tag = 'complexContent' def isMixed(self): m = self.getAttribute('mixed') if m == 0 or m == False: return False if isinstance(m, basestring) is True: if m in ('false', '0'): return False if m in ('true', '1'): return True raise SchemaError, 'invalid value for attribute mixed(%s): %s'\ %(m, self.getItemTrace()) class _DerivationBase(XMLSchemaComponent): """<extension>,<restriction> parents: complexContent attributes: id -- ID base -- QName, required contents: annotation?, (group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute? """ required = ['base'] attributes = {'id':None, 'base':None } contents = {'xsd':['annotation', 'group', 'all', 'choice',\ 'sequence', 'attribute', 'attributeGroup', 'anyAttribute']} def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self.content = None self.attr_content = None def getAttributeContent(self): return self.attr_content def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) indx = 0 num = len(contents) #XXX ugly if not num: return component = SplitQName(contents[indx].getTagName())[1] if component == 'annotation': self.annotation = Annotation(self) self.annotation.fromDom(contents[indx]) indx += 1 component = SplitQName(contents[indx].getTagName())[1] if component == 'all': self.content = All(self) self.content.fromDom(contents[indx]) indx += 1 elif component == 'choice': self.content = Choice(self) self.content.fromDom(contents[indx]) indx += 1 elif component == 'sequence': self.content = Sequence(self) self.content.fromDom(contents[indx]) indx += 1 elif component == 'group': self.content = ModelGroupReference(self) self.content.fromDom(contents[indx]) indx += 1 else: self.content = None self.attr_content = [] while indx < num: component = SplitQName(contents[indx].getTagName())[1] if component == 'attribute': if contents[indx].hasattr('ref'): self.attr_content.append(AttributeReference(self)) else: self.attr_content.append(LocalAttributeDeclaration(self)) elif component == 'attributeGroup': if contents[indx].hasattr('ref'): self.attr_content.append(AttributeGroupReference(self)) else: self.attr_content.append(AttributeGroupDefinition(self)) elif component == 'anyAttribute': self.attr_content.append(AttributeWildCard(self)) else: raise SchemaError, 'Unknown component (%s)' %(contents[indx].getTagName()) self.attr_content[-1].fromDom(contents[indx]) indx += 1 class Extension(_DerivationBase, ExtensionMarker): """<extension base> parents: complexContent attributes: id -- ID base -- QName, required contents: annotation?, (group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute? """ tag = 'extension' class Restriction(_DerivationBase,\ RestrictionMarker): """<restriction base> parents: complexContent attributes: id -- ID base -- QName, required contents: annotation?, (group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute? """ tag = 'restriction' class SimpleContent(_DerivedType,\ SimpleMarker): """<simpleContent> parents: complexType attributes: id -- ID contents: annotation?, (restriction | extension) """ attributes = {'id':None} contents = {'xsd':['annotation', 'restriction', 'extension']} tag = 'simpleContent' class Extension(XMLSchemaComponent,\ ExtensionMarker): """<extension base> parents: simpleContent attributes: id -- ID base -- QName, required contents: annotation?, (attribute | attributeGroup)*, anyAttribute? """ required = ['base'] attributes = {'id':None, 'base':None } contents = {'xsd':['annotation', 'attribute', 'attributeGroup', 'anyAttribute']} tag = 'extension' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self.attr_content = None def getAttributeContent(self): return self.attr_content def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) indx = 0 num = len(contents) if num: component = SplitQName(contents[indx].getTagName())[1] if component == 'annotation': self.annotation = Annotation(self) self.annotation.fromDom(contents[indx]) indx += 1 component = SplitQName(contents[indx].getTagName())[1] content = [] while indx < num: component = SplitQName(contents[indx].getTagName())[1] if component == 'attribute': if contents[indx].hasattr('ref'): content.append(AttributeReference(self)) else: content.append(LocalAttributeDeclaration(self)) elif component == 'attributeGroup': content.append(AttributeGroupReference(self)) elif component == 'anyAttribute': content.append(AttributeWildCard(self)) else: raise SchemaError, 'Unknown component (%s)'\ %(contents[indx].getTagName()) content[-1].fromDom(contents[indx]) indx += 1 self.attr_content = tuple(content) class Restriction(XMLSchemaComponent,\ RestrictionMarker): """<restriction base> parents: simpleContent attributes: id -- ID base -- QName, required contents: annotation?, simpleType?, (enumeration | length | maxExclusive | maxInclusive | maxLength | minExclusive | minInclusive | minLength | pattern | fractionDigits | totalDigits | whiteSpace)*, (attribute | attributeGroup)*, anyAttribute? """ required = ['base'] attributes = {'id':None, 'base':None } contents = {'xsd':['annotation', 'simpleType', 'attribute',\ 'attributeGroup', 'anyAttribute'] + RestrictionMarker.facets} tag = 'restriction' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self.content = None self.attr_content = None def getAttributeContent(self): return self.attr_content def fromDom(self, node): self.content = [] self.setAttributes(node) contents = self.getContents(node) indx = 0 num = len(contents) component = SplitQName(contents[indx].getTagName())[1] if component == 'annotation': self.annotation = Annotation(self) self.annotation.fromDom(contents[indx]) indx += 1 component = SplitQName(contents[indx].getTagName())[1] content = [] while indx < num: component = SplitQName(contents[indx].getTagName())[1] if component == 'attribute': if contents[indx].hasattr('ref'): content.append(AttributeReference(self)) else: content.append(LocalAttributeDeclaration(self)) elif component == 'attributeGroup': content.append(AttributeGroupReference(self)) elif component == 'anyAttribute': content.append(AttributeWildCard(self)) elif component == 'simpleType': self.content.append(AnonymousSimpleType(self)) self.content[-1].fromDom(contents[indx]) else: raise SchemaError, 'Unknown component (%s)'\ %(contents[indx].getTagName()) content[-1].fromDom(contents[indx]) indx += 1 self.attr_content = tuple(content) class LocalComplexType(ComplexType,\ LocalMarker): """<complexType> parents: element attributes: id -- ID mixed -- boolean, false contents: annotation?, (simpleContent | complexContent | ((group | all | choice | sequence)?, (attribute | attributeGroup)*, anyAttribute?)) """ required = [] attributes = {'id':None, 'mixed':0} tag = 'complexType' class SimpleType(XMLSchemaComponent,\ DefinitionMarker,\ SimpleMarker): """<simpleType name> parents: redefine, schema attributes: id -- ID name -- NCName, required final -- ('#all' | ('extension' | 'restriction' | 'list' | 'union')*), schema.finalDefault contents: annotation?, (restriction | list | union) """ required = ['name'] attributes = {'id':None, 'name':None, 'final':lambda self: self._parent().getFinalDefault()} contents = {'xsd':['annotation', 'restriction', 'list', 'union']} tag = 'simpleType' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self.content = None def getElementDeclaration(self, attribute): raise Warning, 'invalid operation for <%s>' %self.tag def getTypeDefinition(self, attribute): raise Warning, 'invalid operation for <%s>' %self.tag def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) for child in contents: component = SplitQName(child.getTagName())[1] if component == 'annotation': self.annotation = Annotation(self) self.annotation.fromDom(child) continue break else: return if component == 'restriction': self.content = self.__class__.Restriction(self) elif component == 'list': self.content = self.__class__.List(self) elif component == 'union': self.content = self.__class__.Union(self) else: raise SchemaError, 'Unknown component (%s)' %(component) self.content.fromDom(child) class Restriction(XMLSchemaComponent,\ RestrictionMarker): """<restriction base> parents: simpleType attributes: id -- ID base -- QName, required or simpleType child contents: annotation?, simpleType?, (enumeration | length | maxExclusive | maxInclusive | maxLength | minExclusive | minInclusive | minLength | pattern | fractionDigits | totalDigits | whiteSpace)* """ attributes = {'id':None, 'base':None } contents = {'xsd':['annotation', 'simpleType']+RestrictionMarker.facets} tag = 'restriction' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self.content = None self.facets = None def getAttributeBase(self): return XMLSchemaComponent.getAttribute(self, 'base') def getTypeDefinition(self, attribute='base'): return XMLSchemaComponent.getTypeDefinition(self, attribute) def getSimpleTypeContent(self): for el in self.content: if el.isSimple(): return el return None def fromDom(self, node): self.facets = [] self.setAttributes(node) contents = self.getContents(node) content = [] for indx in range(len(contents)): component = SplitQName(contents[indx].getTagName())[1] if (component == 'annotation') and (not indx): self.annotation = Annotation(self) self.annotation.fromDom(contents[indx]) continue elif (component == 'simpleType') and (not indx or indx == 1): content.append(AnonymousSimpleType(self)) content[-1].fromDom(contents[indx]) elif component in RestrictionMarker.facets: self.facets.append(contents[indx]) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) self.content = tuple(content) class Union(XMLSchemaComponent, UnionMarker): """<union> parents: simpleType attributes: id -- ID memberTypes -- list of QNames, required or simpleType child. contents: annotation?, simpleType* """ attributes = {'id':None, 'memberTypes':None } contents = {'xsd':['annotation', 'simpleType']} tag = 'union' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self.content = None def fromDom(self, node): self.setAttributes(node) contents = self.getContents(node) content = [] for indx in range(len(contents)): component = SplitQName(contents[indx].getTagName())[1] if (component == 'annotation') and (not indx): self.annotation = Annotation(self) self.annotation.fromDom(contents[indx]) elif (component == 'simpleType'): content.append(AnonymousSimpleType(self)) content[-1].fromDom(contents[indx]) else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) self.content = tuple(content) class List(XMLSchemaComponent, ListMarker): """<list> parents: simpleType attributes: id -- ID itemType -- QName, required or simpleType child. contents: annotation?, simpleType? """ attributes = {'id':None, 'itemType':None } contents = {'xsd':['annotation', 'simpleType']} tag = 'list' def __init__(self, parent): XMLSchemaComponent.__init__(self, parent) self.annotation = None self.content = None def getItemType(self): return self.attributes.get('itemType') def getTypeDefinition(self, attribute='itemType'): """ return the type refered to by itemType attribute or the simpleType content. If returns None, then the type refered to by itemType is primitive. """ tp = XMLSchemaComponent.getTypeDefinition(self, attribute) return tp or self.content def fromDom(self, node): self.annotation = None self.content = None self.setAttributes(node) contents = self.getContents(node) for indx in range(len(contents)): component = SplitQName(contents[indx].getTagName())[1] if (component == 'annotation') and (not indx): self.annotation = Annotation(self) self.annotation.fromDom(contents[indx]) elif (component == 'simpleType'): self.content = AnonymousSimpleType(self) self.content.fromDom(contents[indx]) break else: raise SchemaError, 'Unknown component (%s)' %(i.getTagName()) class AnonymousSimpleType(SimpleType,\ SimpleMarker,\ LocalMarker): """<simpleType> parents: attribute, element, list, restriction, union attributes: id -- ID contents: annotation?, (restriction | list | union) """ required = [] attributes = {'id':None} tag = 'simpleType' class Redefine: """<redefine> parents: attributes: contents: """ tag = 'redefine' ########################### ########################### if sys.version_info[:2] >= (2, 2): tupleClass = tuple else: import UserTuple tupleClass = UserTuple.UserTuple class TypeDescriptionComponent(tupleClass): """Tuple of length 2, consisting of a namespace and unprefixed name. """ def __init__(self, args): """args -- (namespace, name) Remove the name's prefix, irrelevant. """ if len(args) != 2: raise TypeError, 'expecting tuple (namespace, name), got %s' %args elif args[1].find(':') >= 0: args = (args[0], SplitQName(args[1])[1]) tuple.__init__(self, args) return def getTargetNamespace(self): return self[0] def getName(self): return self[1]
gpl-3.0
peheje/baselines
baselines/ddpg/ddpg.py
5
17098
from copy import copy from functools import reduce import numpy as np import tensorflow as tf import tensorflow.contrib as tc from baselines import logger from baselines.common.mpi_adam import MpiAdam import baselines.common.tf_util as U from baselines.common.mpi_running_mean_std import RunningMeanStd from baselines.ddpg.util import reduce_std, mpi_mean def normalize(x, stats): if stats is None: return x return (x - stats.mean) / stats.std def denormalize(x, stats): if stats is None: return x return x * stats.std + stats.mean def get_target_updates(vars, target_vars, tau): logger.info('setting up target updates ...') soft_updates = [] init_updates = [] assert len(vars) == len(target_vars) for var, target_var in zip(vars, target_vars): logger.info(' {} <- {}'.format(target_var.name, var.name)) init_updates.append(tf.assign(target_var, var)) soft_updates.append(tf.assign(target_var, (1. - tau) * target_var + tau * var)) assert len(init_updates) == len(vars) assert len(soft_updates) == len(vars) return tf.group(*init_updates), tf.group(*soft_updates) def get_perturbed_actor_updates(actor, perturbed_actor, param_noise_stddev): assert len(actor.vars) == len(perturbed_actor.vars) assert len(actor.perturbable_vars) == len(perturbed_actor.perturbable_vars) updates = [] for var, perturbed_var in zip(actor.vars, perturbed_actor.vars): if var in actor.perturbable_vars: logger.info(' {} <- {} + noise'.format(perturbed_var.name, var.name)) updates.append(tf.assign(perturbed_var, var + tf.random_normal(tf.shape(var), mean=0., stddev=param_noise_stddev))) else: logger.info(' {} <- {}'.format(perturbed_var.name, var.name)) updates.append(tf.assign(perturbed_var, var)) assert len(updates) == len(actor.vars) return tf.group(*updates) class DDPG(object): def __init__(self, actor, critic, memory, observation_shape, action_shape, param_noise=None, action_noise=None, gamma=0.99, tau=0.001, normalize_returns=False, enable_popart=False, normalize_observations=True, batch_size=128, observation_range=(-5., 5.), action_range=(-1., 1.), return_range=(-np.inf, np.inf), adaptive_param_noise=True, adaptive_param_noise_policy_threshold=.1, critic_l2_reg=0., actor_lr=1e-4, critic_lr=1e-3, clip_norm=None, reward_scale=1.): # Inputs. self.obs0 = tf.placeholder(tf.float32, shape=(None,) + observation_shape, name='obs0') self.obs1 = tf.placeholder(tf.float32, shape=(None,) + observation_shape, name='obs1') self.terminals1 = tf.placeholder(tf.float32, shape=(None, 1), name='terminals1') self.rewards = tf.placeholder(tf.float32, shape=(None, 1), name='rewards') self.actions = tf.placeholder(tf.float32, shape=(None,) + action_shape, name='actions') self.critic_target = tf.placeholder(tf.float32, shape=(None, 1), name='critic_target') self.param_noise_stddev = tf.placeholder(tf.float32, shape=(), name='param_noise_stddev') # Parameters. self.gamma = gamma self.tau = tau self.memory = memory self.normalize_observations = normalize_observations self.normalize_returns = normalize_returns self.action_noise = action_noise self.param_noise = param_noise self.action_range = action_range self.return_range = return_range self.observation_range = observation_range self.critic = critic self.actor = actor self.actor_lr = actor_lr self.critic_lr = critic_lr self.clip_norm = clip_norm self.enable_popart = enable_popart self.reward_scale = reward_scale self.batch_size = batch_size self.stats_sample = None self.critic_l2_reg = critic_l2_reg # Observation normalization. if self.normalize_observations: with tf.variable_scope('obs_rms'): self.obs_rms = RunningMeanStd(shape=observation_shape) else: self.obs_rms = None normalized_obs0 = tf.clip_by_value(normalize(self.obs0, self.obs_rms), self.observation_range[0], self.observation_range[1]) normalized_obs1 = tf.clip_by_value(normalize(self.obs1, self.obs_rms), self.observation_range[0], self.observation_range[1]) # Return normalization. if self.normalize_returns: with tf.variable_scope('ret_rms'): self.ret_rms = RunningMeanStd() else: self.ret_rms = None # Create target networks. target_actor = copy(actor) target_actor.name = 'target_actor' self.target_actor = target_actor target_critic = copy(critic) target_critic.name = 'target_critic' self.target_critic = target_critic # Create networks and core TF parts that are shared across setup parts. self.actor_tf = actor(normalized_obs0) self.normalized_critic_tf = critic(normalized_obs0, self.actions) self.critic_tf = denormalize(tf.clip_by_value(self.normalized_critic_tf, self.return_range[0], self.return_range[1]), self.ret_rms) self.normalized_critic_with_actor_tf = critic(normalized_obs0, self.actor_tf, reuse=True) self.critic_with_actor_tf = denormalize(tf.clip_by_value(self.normalized_critic_with_actor_tf, self.return_range[0], self.return_range[1]), self.ret_rms) Q_obs1 = denormalize(target_critic(normalized_obs1, target_actor(normalized_obs1)), self.ret_rms) self.target_Q = self.rewards + (1. - self.terminals1) * gamma * Q_obs1 # Set up parts. if self.param_noise is not None: self.setup_param_noise(normalized_obs0) self.setup_actor_optimizer() self.setup_critic_optimizer() if self.normalize_returns and self.enable_popart: self.setup_popart() self.setup_stats() self.setup_target_network_updates() def setup_target_network_updates(self): actor_init_updates, actor_soft_updates = get_target_updates(self.actor.vars, self.target_actor.vars, self.tau) critic_init_updates, critic_soft_updates = get_target_updates(self.critic.vars, self.target_critic.vars, self.tau) self.target_init_updates = [actor_init_updates, critic_init_updates] self.target_soft_updates = [actor_soft_updates, critic_soft_updates] def setup_param_noise(self, normalized_obs0): assert self.param_noise is not None # Configure perturbed actor. param_noise_actor = copy(self.actor) param_noise_actor.name = 'param_noise_actor' self.perturbed_actor_tf = param_noise_actor(normalized_obs0) logger.info('setting up param noise') self.perturb_policy_ops = get_perturbed_actor_updates(self.actor, param_noise_actor, self.param_noise_stddev) # Configure separate copy for stddev adoption. adaptive_param_noise_actor = copy(self.actor) adaptive_param_noise_actor.name = 'adaptive_param_noise_actor' adaptive_actor_tf = adaptive_param_noise_actor(normalized_obs0) self.perturb_adaptive_policy_ops = get_perturbed_actor_updates(self.actor, adaptive_param_noise_actor, self.param_noise_stddev) self.adaptive_policy_distance = tf.sqrt(tf.reduce_mean(tf.square(self.actor_tf - adaptive_actor_tf))) def setup_actor_optimizer(self): logger.info('setting up actor optimizer') self.actor_loss = -tf.reduce_mean(self.critic_with_actor_tf) actor_shapes = [var.get_shape().as_list() for var in self.actor.trainable_vars] actor_nb_params = sum([reduce(lambda x, y: x * y, shape) for shape in actor_shapes]) logger.info(' actor shapes: {}'.format(actor_shapes)) logger.info(' actor params: {}'.format(actor_nb_params)) self.actor_grads = U.flatgrad(self.actor_loss, self.actor.trainable_vars, clip_norm=self.clip_norm) self.actor_optimizer = MpiAdam(var_list=self.actor.trainable_vars, beta1=0.9, beta2=0.999, epsilon=1e-08) def setup_critic_optimizer(self): logger.info('setting up critic optimizer') normalized_critic_target_tf = tf.clip_by_value(normalize(self.critic_target, self.ret_rms), self.return_range[0], self.return_range[1]) self.critic_loss = tf.reduce_mean(tf.square(self.normalized_critic_tf - normalized_critic_target_tf)) if self.critic_l2_reg > 0.: critic_reg_vars = [var for var in self.critic.trainable_vars if 'kernel' in var.name and 'output' not in var.name] for var in critic_reg_vars: logger.info(' regularizing: {}'.format(var.name)) logger.info(' applying l2 regularization with {}'.format(self.critic_l2_reg)) critic_reg = tc.layers.apply_regularization( tc.layers.l2_regularizer(self.critic_l2_reg), weights_list=critic_reg_vars ) self.critic_loss += critic_reg critic_shapes = [var.get_shape().as_list() for var in self.critic.trainable_vars] critic_nb_params = sum([reduce(lambda x, y: x * y, shape) for shape in critic_shapes]) logger.info(' critic shapes: {}'.format(critic_shapes)) logger.info(' critic params: {}'.format(critic_nb_params)) self.critic_grads = U.flatgrad(self.critic_loss, self.critic.trainable_vars, clip_norm=self.clip_norm) self.critic_optimizer = MpiAdam(var_list=self.critic.trainable_vars, beta1=0.9, beta2=0.999, epsilon=1e-08) def setup_popart(self): # See https://arxiv.org/pdf/1602.07714.pdf for details. self.old_std = tf.placeholder(tf.float32, shape=[1], name='old_std') new_std = self.ret_rms.std self.old_mean = tf.placeholder(tf.float32, shape=[1], name='old_mean') new_mean = self.ret_rms.mean self.renormalize_Q_outputs_op = [] for vs in [self.critic.output_vars, self.target_critic.output_vars]: assert len(vs) == 2 M, b = vs assert 'kernel' in M.name assert 'bias' in b.name assert M.get_shape()[-1] == 1 assert b.get_shape()[-1] == 1 self.renormalize_Q_outputs_op += [M.assign(M * self.old_std / new_std)] self.renormalize_Q_outputs_op += [b.assign((b * self.old_std + self.old_mean - new_mean) / new_std)] def setup_stats(self): ops = [] names = [] if self.normalize_returns: ops += [self.ret_rms.mean, self.ret_rms.std] names += ['ret_rms_mean', 'ret_rms_std'] if self.normalize_observations: ops += [tf.reduce_mean(self.obs_rms.mean), tf.reduce_mean(self.obs_rms.std)] names += ['obs_rms_mean', 'obs_rms_std'] ops += [tf.reduce_mean(self.critic_tf)] names += ['reference_Q_mean'] ops += [reduce_std(self.critic_tf)] names += ['reference_Q_std'] ops += [tf.reduce_mean(self.critic_with_actor_tf)] names += ['reference_actor_Q_mean'] ops += [reduce_std(self.critic_with_actor_tf)] names += ['reference_actor_Q_std'] ops += [tf.reduce_mean(self.actor_tf)] names += ['reference_action_mean'] ops += [reduce_std(self.actor_tf)] names += ['reference_action_std'] if self.param_noise: ops += [tf.reduce_mean(self.perturbed_actor_tf)] names += ['reference_perturbed_action_mean'] ops += [reduce_std(self.perturbed_actor_tf)] names += ['reference_perturbed_action_std'] self.stats_ops = ops self.stats_names = names def pi(self, obs, apply_noise=True, compute_Q=True): if self.param_noise is not None and apply_noise: actor_tf = self.perturbed_actor_tf else: actor_tf = self.actor_tf feed_dict = {self.obs0: [obs]} if compute_Q: action, q = self.sess.run([actor_tf, self.critic_with_actor_tf], feed_dict=feed_dict) else: action = self.sess.run(actor_tf, feed_dict=feed_dict) q = None action = action.flatten() if self.action_noise is not None and apply_noise: noise = self.action_noise() assert noise.shape == action.shape action += noise action = np.clip(action, self.action_range[0], self.action_range[1]) return action, q def store_transition(self, obs0, action, reward, obs1, terminal1): reward *= self.reward_scale self.memory.append(obs0, action, reward, obs1, terminal1) if self.normalize_observations: self.obs_rms.update(np.array([obs0])) def train(self): # Get a batch. batch = self.memory.sample(batch_size=self.batch_size) if self.normalize_returns and self.enable_popart: old_mean, old_std, target_Q = self.sess.run([self.ret_rms.mean, self.ret_rms.std, self.target_Q], feed_dict={ self.obs1: batch['obs1'], self.rewards: batch['rewards'], self.terminals1: batch['terminals1'].astype('float32'), }) self.ret_rms.update(target_Q.flatten()) self.sess.run(self.renormalize_Q_outputs_op, feed_dict={ self.old_std : np.array([old_std]), self.old_mean : np.array([old_mean]), }) # Run sanity check. Disabled by default since it slows down things considerably. # print('running sanity check') # target_Q_new, new_mean, new_std = self.sess.run([self.target_Q, self.ret_rms.mean, self.ret_rms.std], feed_dict={ # self.obs1: batch['obs1'], # self.rewards: batch['rewards'], # self.terminals1: batch['terminals1'].astype('float32'), # }) # print(target_Q_new, target_Q, new_mean, new_std) # assert (np.abs(target_Q - target_Q_new) < 1e-3).all() else: target_Q = self.sess.run(self.target_Q, feed_dict={ self.obs1: batch['obs1'], self.rewards: batch['rewards'], self.terminals1: batch['terminals1'].astype('float32'), }) # Get all gradients and perform a synced update. ops = [self.actor_grads, self.actor_loss, self.critic_grads, self.critic_loss] actor_grads, actor_loss, critic_grads, critic_loss = self.sess.run(ops, feed_dict={ self.obs0: batch['obs0'], self.actions: batch['actions'], self.critic_target: target_Q, }) self.actor_optimizer.update(actor_grads, stepsize=self.actor_lr) self.critic_optimizer.update(critic_grads, stepsize=self.critic_lr) return critic_loss, actor_loss def initialize(self, sess): self.sess = sess self.sess.run(tf.global_variables_initializer()) self.actor_optimizer.sync() self.critic_optimizer.sync() self.sess.run(self.target_init_updates) def update_target_net(self): self.sess.run(self.target_soft_updates) def get_stats(self): if self.stats_sample is None: # Get a sample and keep that fixed for all further computations. # This allows us to estimate the change in value for the same set of inputs. self.stats_sample = self.memory.sample(batch_size=self.batch_size) values = self.sess.run(self.stats_ops, feed_dict={ self.obs0: self.stats_sample['obs0'], self.actions: self.stats_sample['actions'], }) names = self.stats_names[:] assert len(names) == len(values) stats = dict(zip(names, values)) if self.param_noise is not None: stats = {**stats, **self.param_noise.get_stats()} return stats def adapt_param_noise(self): if self.param_noise is None: return 0. # Perturb a separate copy of the policy to adjust the scale for the next "real" perturbation. batch = self.memory.sample(batch_size=self.batch_size) self.sess.run(self.perturb_adaptive_policy_ops, feed_dict={ self.param_noise_stddev: self.param_noise.current_stddev, }) distance = self.sess.run(self.adaptive_policy_distance, feed_dict={ self.obs0: batch['obs0'], self.param_noise_stddev: self.param_noise.current_stddev, }) mean_distance = mpi_mean(distance) self.param_noise.adapt(mean_distance) return mean_distance def reset(self): # Reset internal state after an episode is complete. if self.action_noise is not None: self.action_noise.reset() if self.param_noise is not None: self.sess.run(self.perturb_policy_ops, feed_dict={ self.param_noise_stddev: self.param_noise.current_stddev, })
mit
JasonGross/mozjs
testing/mozbase/mozprofile/mozprofile/profile.py
2
17306
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. __all__ = ['Profile', 'FirefoxProfile', 'MetroFirefoxProfile', 'ThunderbirdProfile'] import json import os import time import tempfile import types import uuid from addons import AddonManager import mozfile from permissions import Permissions from prefs import Preferences from shutil import copytree from webapps import WebappCollection class Profile(object): """Handles all operations regarding profile. Creating new profiles, installing add-ons, setting preferences and handling cleanup. """ def __init__(self, profile=None, addons=None, addon_manifests=None, apps=None, preferences=None, locations=None, proxy=None, restore=True): """ :param profile: Path to the profile :param addons: String of one or list of addons to install :param addon_manifests: Manifest for addons (see http://bit.ly/17jQ7i6) :param apps: Dictionary or class of webapps to install :param preferences: Dictionary or class of preferences :param locations: ServerLocations object :param proxy: Setup a proxy :param restore: Flag for removing all custom settings during cleanup """ self._addons = addons self._addon_manifests = addon_manifests self._apps = apps self._locations = locations self._proxy = proxy # Prepare additional preferences if preferences: if isinstance(preferences, dict): # unordered preferences = preferences.items() # sanity check assert not [i for i in preferences if len(i) != 2] else: preferences = [] self._preferences = preferences # Handle profile creation self.create_new = not profile if profile: # Ensure we have a full path to the profile self.profile = os.path.abspath(os.path.expanduser(profile)) else: self.profile = tempfile.mkdtemp(suffix='.mozrunner') self.restore = restore # Initialize all class members self._internal_init() def _internal_init(self): """Internal: Initialize all class members to their default value""" if not os.path.exists(self.profile): os.makedirs(self.profile) # Preferences files written to self.written_prefs = set() # Our magic markers nonce = '%s %s' % (str(time.time()), uuid.uuid4()) self.delimeters = ('#MozRunner Prefs Start %s' % nonce, '#MozRunner Prefs End %s' % nonce) # If sub-classes want to set default preferences if hasattr(self.__class__, 'preferences'): self.set_preferences(self.__class__.preferences) # Set additional preferences self.set_preferences(self._preferences) self.permissions = Permissions(self.profile, self._locations) prefs_js, user_js = self.permissions.network_prefs(self._proxy) self.set_preferences(prefs_js, 'prefs.js') self.set_preferences(user_js) # handle add-on installation self.addon_manager = AddonManager(self.profile, restore=self.restore) self.addon_manager.install_addons(self._addons, self._addon_manifests) # handle webapps self.webapps = WebappCollection(profile=self.profile, apps=self._apps) self.webapps.update_manifests() def __del__(self): self.cleanup() ### cleanup def cleanup(self): """Cleanup operations for the profile.""" if self.restore: # If copies of those class instances exist ensure we correctly # reset them all (see bug 934484) self.clean_preferences() if getattr(self, 'addon_manager', None) is not None: self.addon_manager.clean() if getattr(self, 'permissions', None) is not None: self.permissions.clean_db() if getattr(self, 'webapps', None) is not None: self.webapps.clean() # If it's a temporary profile we have to remove it if self.create_new: mozfile.remove(self.profile) def reset(self): """ reset the profile to the beginning state """ self.cleanup() self._internal_init() def clean_preferences(self): """Removed preferences added by mozrunner.""" for filename in self.written_prefs: if not os.path.exists(os.path.join(self.profile, filename)): # file has been deleted break while True: if not self.pop_preferences(filename): break @classmethod def clone(cls, path_from, path_to=None, **kwargs): """Instantiate a temporary profile via cloning - path: path of the basis to clone - kwargs: arguments to the profile constructor """ if not path_to: tempdir = tempfile.mkdtemp() # need an unused temp dir name mozfile.remove(tempdir) # copytree requires that dest does not exist path_to = tempdir copytree(path_from, path_to) def cleanup_clone(fn): """Deletes a cloned profile when restore is True""" def wrapped(self): fn(self) if self.restore and os.path.exists(self.profile): mozfile.remove(self.profile) return wrapped c = cls(path_to, **kwargs) c.__del__ = c.cleanup = types.MethodType(cleanup_clone(cls.cleanup), c) return c def exists(self): """returns whether the profile exists or not""" return os.path.exists(self.profile) ### methods for preferences def set_preferences(self, preferences, filename='user.js'): """Adds preferences dict to profile preferences""" # append to the file prefs_file = os.path.join(self.profile, filename) f = open(prefs_file, 'a') if preferences: # note what files we've touched self.written_prefs.add(filename) # opening delimeter f.write('\n%s\n' % self.delimeters[0]) # write the preferences Preferences.write(f, preferences) # closing delimeter f.write('%s\n' % self.delimeters[1]) f.close() def pop_preferences(self, filename): """ pop the last set of preferences added returns True if popped """ path = os.path.join(self.profile, filename) with file(path) as f: lines = f.read().splitlines() def last_index(_list, value): """ returns the last index of an item; this should actually be part of python code but it isn't """ for index in reversed(range(len(_list))): if _list[index] == value: return index s = last_index(lines, self.delimeters[0]) e = last_index(lines, self.delimeters[1]) # ensure both markers are found if s is None: assert e is None, '%s found without %s' % (self.delimeters[1], self.delimeters[0]) return False # no preferences found elif e is None: assert s is None, '%s found without %s' % (self.delimeters[0], self.delimeters[1]) # ensure the markers are in the proper order assert e > s, '%s found at %s, while %s found at %s' % (self.delimeters[1], e, self.delimeters[0], s) # write the prefs cleaned_prefs = '\n'.join(lines[:s] + lines[e+1:]) with file(path, 'w') as f: f.write(cleaned_prefs) return True ### methods for introspection def summary(self, return_parts=False): """ returns string summarizing profile information. if return_parts is true, return the (Part_name, value) list of tuples instead of the assembled string """ parts = [('Path', self.profile)] # profile path # directory tree parts.append(('Files', '\n%s' % mozfile.tree(self.profile))) # preferences for prefs_file in ('user.js', 'prefs.js'): path = os.path.join(self.profile, prefs_file) if os.path.exists(path): # prefs that get their own section # This is currently only 'network.proxy.autoconfig_url' # but could be expanded to include others section_prefs = ['network.proxy.autoconfig_url'] line_length = 80 line_length_buffer = 10 # buffer for 80 character display: length = 80 - len(key) - len(': ') - line_length_buffer line_length_buffer += len(': ') def format_value(key, value): if key not in section_prefs: return value max_length = line_length - len(key) - line_length_buffer if len(value) > max_length: value = '%s...' % value[:max_length] return value prefs = Preferences.read_prefs(path) if prefs: prefs = dict(prefs) parts.append((prefs_file, '\n%s' %('\n'.join(['%s: %s' % (key, format_value(key, prefs[key])) for key in sorted(prefs.keys()) ])))) # Currently hardcorded to 'network.proxy.autoconfig_url' # but could be generalized, possibly with a generalized (simple) # JS-parser network_proxy_autoconfig = prefs.get('network.proxy.autoconfig_url') if network_proxy_autoconfig and network_proxy_autoconfig.strip(): network_proxy_autoconfig = network_proxy_autoconfig.strip() lines = network_proxy_autoconfig.replace(';', ';\n').splitlines() lines = [line.strip() for line in lines] origins_string = 'var origins = [' origins_end = '];' if origins_string in lines[0]: start = lines[0].find(origins_string) end = lines[0].find(origins_end, start); splitline = [lines[0][:start], lines[0][start:start+len(origins_string)-1], ] splitline.extend(lines[0][start+len(origins_string):end].replace(',', ',\n').splitlines()) splitline.append(lines[0][end:]) lines[0:1] = [i.strip() for i in splitline] parts.append(('Network Proxy Autoconfig, %s' % (prefs_file), '\n%s' % '\n'.join(lines))) if return_parts: return parts retval = '%s\n' % ('\n\n'.join(['[%s]: %s' % (key, value) for key, value in parts])) return retval __str__ = summary class FirefoxProfile(Profile): """Specialized Profile subclass for Firefox""" preferences = {# Don't automatically update the application 'app.update.enabled' : False, # Don't restore the last open set of tabs if the browser has crashed 'browser.sessionstore.resume_from_crash': False, # Don't check for the default web browser during startup 'browser.shell.checkDefaultBrowser' : False, # Don't warn on exit when multiple tabs are open 'browser.tabs.warnOnClose' : False, # Don't warn when exiting the browser 'browser.warnOnQuit': False, # Don't send Firefox health reports to the production server 'datareporting.healthreport.documentServerURI' : 'http://%(server)s/healthreport/', # Only install add-ons from the profile and the application scope # Also ensure that those are not getting disabled. # see: https://developer.mozilla.org/en/Installing_extensions 'extensions.enabledScopes' : 5, 'extensions.autoDisableScopes' : 10, # Don't send the list of installed addons to AMO 'extensions.getAddons.cache.enabled' : False, # Don't install distribution add-ons from the app folder 'extensions.installDistroAddons' : False, # Dont' run the add-on compatibility check during start-up 'extensions.showMismatchUI' : False, # Don't automatically update add-ons 'extensions.update.enabled' : False, # Don't open a dialog to show available add-on updates 'extensions.update.notifyUser' : False, # Enable test mode to run multiple tests in parallel 'focusmanager.testmode' : True, # Enable test mode to not raise an OS level dialog for location sharing 'geo.provider.testing' : True, # Suppress delay for main action in popup notifications 'security.notification_enable_delay' : 0, # Suppress automatic safe mode after crashes 'toolkit.startup.max_resumed_crashes' : -1, # Don't report telemetry information 'toolkit.telemetry.enabled' : False, } class MetroFirefoxProfile(Profile): """Specialized Profile subclass for Firefox Metro""" preferences = {# Don't automatically update the application for desktop and metro build 'app.update.enabled' : False, 'app.update.metro.enabled' : False, # Dismiss first run content overlay 'browser.firstrun-content.dismissed' : True, # Don't restore the last open set of tabs if the browser has crashed 'browser.sessionstore.resume_from_crash': False, # Don't check for the default web browser during startup 'browser.shell.checkDefaultBrowser' : False, # Don't send Firefox health reports to the production server 'datareporting.healthreport.documentServerURI' : 'http://%(server)s/healthreport/', # Enable extensions 'extensions.defaultProviders.enabled' : True, # Only install add-ons from the profile and the application scope # Also ensure that those are not getting disabled. # see: https://developer.mozilla.org/en/Installing_extensions 'extensions.enabledScopes' : 5, 'extensions.autoDisableScopes' : 10, # Don't send the list of installed addons to AMO 'extensions.getAddons.cache.enabled' : False, # Don't install distribution add-ons from the app folder 'extensions.installDistroAddons' : False, # Dont' run the add-on compatibility check during start-up 'extensions.showMismatchUI' : False, # Disable strict compatibility checks to allow add-ons enabled by default 'extensions.strictCompatibility' : False, # Don't automatically update add-ons 'extensions.update.enabled' : False, # Don't open a dialog to show available add-on updates 'extensions.update.notifyUser' : False, # Enable test mode to run multiple tests in parallel 'focusmanager.testmode' : True, # Suppress delay for main action in popup notifications 'security.notification_enable_delay' : 0, # Suppress automatic safe mode after crashes 'toolkit.startup.max_resumed_crashes' : -1, # Don't report telemetry information 'toolkit.telemetry.enabled' : False, } class ThunderbirdProfile(Profile): """Specialized Profile subclass for Thunderbird""" preferences = {'extensions.update.enabled' : False, 'extensions.update.notifyUser' : False, 'browser.shell.checkDefaultBrowser' : False, 'browser.tabs.warnOnClose' : False, 'browser.warnOnQuit': False, 'browser.sessionstore.resume_from_crash': False, # prevents the 'new e-mail address' wizard on new profile 'mail.provider.enabled': False, }
mpl-2.0
FCP-INDI/C-PAC
CPAC/utils/tests/test_datasource.py
1
2537
import os import json from CPAC.pipeline import nipype_pipeline_engine as pe import nipype.interfaces.utility as util from CPAC.utils.test_resources import setup_test_wf from CPAC.utils.datasource import match_epi_fmaps def test_match_epi_fmaps(): # good data to use s3_prefix = "s3://fcp-indi/data/Projects/HBN/MRI/Site-CBIC/sub-NDARAB708LM5" s3_paths = [ "func/sub-NDARAB708LM5_task-rest_run-1_bold.json", "fmap/sub-NDARAB708LM5_dir-PA_acq-fMRI_epi.nii.gz", "fmap/sub-NDARAB708LM5_dir-PA_acq-fMRI_epi.json", "fmap/sub-NDARAB708LM5_dir-AP_acq-fMRI_epi.nii.gz", "fmap/sub-NDARAB708LM5_dir-AP_acq-fMRI_epi.json" ] wf, ds, local_paths = setup_test_wf(s3_prefix, s3_paths, "test_match_epi_fmaps") opposite_pe_json = local_paths["fmap/sub-NDARAB708LM5_dir-PA_acq-fMRI_epi.json"] same_pe_json = local_paths["fmap/sub-NDARAB708LM5_dir-AP_acq-fMRI_epi.json"] func_json = local_paths["func/sub-NDARAB708LM5_task-rest_run-1_bold.json"] with open(opposite_pe_json, "r") as f: opposite_pe_params = json.load(f) with open(same_pe_json, "r") as f: same_pe_params = json.load(f) with open(func_json, "r") as f: func_params = json.load(f) bold_pedir = func_params["PhaseEncodingDirection"] fmap_paths_dct = {"epi_PA": {"scan": local_paths["fmap/sub-NDARAB708LM5_dir-PA_acq-fMRI_epi.nii.gz"], "scan_parameters": opposite_pe_params}, "epi_AP": {"scan": local_paths["fmap/sub-NDARAB708LM5_dir-AP_acq-fMRI_epi.nii.gz"], "scan_parameters": same_pe_params} } match_fmaps = \ pe.Node(util.Function(input_names=['fmap_dct', 'bold_pedir'], output_names=['opposite_pe_epi', 'same_pe_epi'], function=match_epi_fmaps, as_module=True), name='match_epi_fmaps') match_fmaps.inputs.fmap_dct = fmap_paths_dct match_fmaps.inputs.bold_pedir = bold_pedir ds.inputs.func_json = func_json ds.inputs.opposite_pe_json = opposite_pe_json ds.inputs.same_pe_json = same_pe_json wf.connect(match_fmaps, 'opposite_pe_epi', ds, 'should_be_dir-PA') wf.connect(match_fmaps, 'same_pe_epi', ds, 'should_be_dir-AP') wf.run()
bsd-3-clause
ojengwa/oh-mainline
vendor/packages/docutils/test/test_parsers/test_rst/test_directives/test_topics.py
18
5059
#! /usr/bin/env python # $Id: test_topics.py 7062 2011-06-30 22:14:29Z milde $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Tests for the "topic" directive. """ from __init__ import DocutilsTestSupport def suite(): s = DocutilsTestSupport.ParserTestSuite() s.generateTests(totest) return s totest = {} totest['topics'] = [ ["""\ .. topic:: """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "topic" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> .. topic:: """], ["""\ .. topic:: Title """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Content block expected for the "topic" directive; none found. <literal_block xml:space="preserve"> .. topic:: Title """], ["""\ .. topic:: Title Body. """, """\ <document source="test data"> <topic> <title> Title <paragraph> Body. """], ["""\ .. topic:: With Options :class: custom :name: my point Body. """, """\ <document source="test data"> <topic classes="custom" ids="my-point" names="my\ point"> <title> With Options <paragraph> Body. """], ["""\ .. topic:: Title Body. """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "topic" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> .. topic:: \n\ Title \n\ Body. """], ["""\ .. topic:: Title Body. """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Content block expected for the "topic" directive; none found. <literal_block xml:space="preserve"> .. topic:: Title Body. """], ["""\ .. topic:: Title Body. """, """\ <document source="test data"> <system_message level="3" line="1" source="test data" type="ERROR"> <paragraph> Error in "topic" directive: 1 argument(s) required, 0 supplied. <literal_block xml:space="preserve"> .. topic:: \n\ Title Body. """], ["""\ .. topic:: Title .. topic:: Nested Body. """, """\ <document source="test data"> <topic> <title> Title <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> The "topic" directive may not be used within topics or body elements. <literal_block xml:space="preserve"> .. topic:: Nested \n\ Body. """], ["""\ .. topic:: Title .. topic:: Nested Body. More. """, """\ <document source="test data"> <topic> <title> Title <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> The "topic" directive may not be used within topics or body elements. <literal_block xml:space="preserve"> .. topic:: Nested \n\ Body. <system_message level="2" line="6" source="test data" type="WARNING"> <paragraph> Explicit markup ends without a blank line; unexpected unindent. <paragraph> More. """], ["""\ .. topic:: Title .. topic:: Nested Body. More. More. """, """\ <document source="test data"> <topic> <title> Title <system_message level="3" line="3" source="test data" type="ERROR"> <paragraph> The "topic" directive may not be used within topics or body elements. <literal_block xml:space="preserve"> .. topic:: Nested \n\ Body. <paragraph> More. <paragraph> More. """], ["""\ .. topic:: First Body .. topic:: Second Body. """, """\ <document source="test data"> <topic> <title> First <paragraph> Body <topic> <title> Second <paragraph> Body. """], ["""\ .. sidebar:: Title :subtitle: Outer .. topic:: Nested Body. More. More. """, """\ <document source="test data"> <sidebar> <title> Title <subtitle> Outer <topic> <title> Nested <paragraph> Body. <paragraph> More. <paragraph> More. """], ] if __name__ == '__main__': import unittest unittest.main(defaultTest='suite')
agpl-3.0
OpenTrons/opentrons-api
api/src/opentrons/system/camera.py
3
1170
import asyncio import os from pathlib import Path from opentrons.config import IS_OSX class CameraException(Exception): pass async def take_picture(filename: Path, loop: asyncio.AbstractEventLoop = None): """ Take a picture and save it to filename :param filename: Name of file to save picture to :param loop: optional loop to use :return: None :raises: CameraException """ try: os.remove(filename) except OSError: pass cmd = 'ffmpeg -f video4linux2 -s 640x480 -i /dev/video0 -ss 0:0:1 -frames 1' # NOQA if IS_OSX: # Purely for development on macos cmd = 'ffmpeg -f avfoundation -framerate 1 -s 640x480 -i "0" -ss 0:0:1 -frames 1' # NOQA proc = await asyncio.create_subprocess_shell( f'{cmd} {filename}', stderr=asyncio.subprocess.PIPE, loop=loop or asyncio.get_event_loop()) res = await proc.stderr.read() # type: ignore res = res.decode().strip() await proc.wait() if proc.returncode != 0: raise CameraException(res) if not filename.exists(): raise CameraException('picture not saved')
apache-2.0
mmllr/MMFlowView
scripts/objc_dep.py
3
6277
#!/usr/bin/python # Nicolas Seriot # 2011-01-06 -> 2011-12-16 # https://github.com/nst/objc_dep/ """ Input: path of an Objective-C project Output: import dependencies Graphviz format Typical usage: $ python objc_dep.py /path/to/project [-x regex] [-i subfolder [subfolder ...]] > graph.dot The .dot file can be opened with Graphviz or OmniGraffle. - red arrows: .pch imports - blue arrows: two ways imports """ import sys import os from sets import Set import re from os.path import basename import argparse regex_import = re.compile("^#(import|include) \"(?P<filename>\S*)\.h") def gen_filenames_imported_in_file(path, regex_exclude): for line in open(path): results = re.search(regex_import, line) if results: filename = results.group('filename') if regex_exclude is not None and regex_exclude.search(filename): continue yield filename def dependencies_in_project(path, ext, exclude, ignore): d = {} regex_exclude = None if exclude: regex_exclude = re.compile(exclude) for root, dirs, files in os.walk(path): if ignore: for subfolder in ignore: if subfolder in dirs: dirs.remove(subfolder) objc_files = (f for f in files if f.endswith(ext)) for f in objc_files: filename = os.path.splitext(f)[0] if regex_exclude is not None and regex_exclude.search(filename): continue if filename not in d: d[filename] = Set() path = os.path.join(root, f) for imported_filename in gen_filenames_imported_in_file(path, regex_exclude): if imported_filename != filename and '+' not in imported_filename and '+' not in filename: d[filename].add(imported_filename) return d def dependencies_in_project_with_file_extensions(path, exts, exclude, ignore): d = {} for ext in exts: d2 = dependencies_in_project(path, ext, exclude, ignore) for (k, v) in d2.iteritems(): if not k in d: d[k] = Set() d[k] = d[k].union(v) return d def two_ways_dependencies(d): two_ways = Set() # d is {'a1':[b1, b2], 'a2':[b1, b3, b4], ...} for a, l in d.iteritems(): for b in l: if b in d and a in d[b]: if (a, b) in two_ways or (b, a) in two_ways: continue if a != b: two_ways.add((a, b)) return two_ways def untraversed_files(d): dead_ends = Set() for file_a, file_a_dependencies in d.iteritems(): for file_b in file_a_dependencies: if not file_b in dead_ends and not file_b in d: dead_ends.add(file_b) return dead_ends def category_files(d): d2 = {} l = [] for k, v in d.iteritems(): if not v and '+' in k: l.append(k) else: d2[k] = v return l, d2 def referenced_classes_from_dict(d): d2 = {} for k, deps in d.iteritems(): for x in deps: d2.setdefault(x, Set()) d2[x].add(k) return d2 def print_frequencies_chart(d): lengths = map(lambda x:len(x), d.itervalues()) if not lengths: return max_length = max(lengths) for i in range(0, max_length+1): s = "%2d | %s\n" % (i, '*'*lengths.count(i)) sys.stderr.write(s) sys.stderr.write("\n") l = [Set() for i in range(max_length+1)] for k, v in d.iteritems(): l[len(v)].add(k) for i in range(0, max_length+1): s = "%2d | %s\n" % (i, ", ".join(sorted(list(l[i])))) sys.stderr.write(s) def dependencies_in_dot_format(path, exclude, ignore): d = dependencies_in_project_with_file_extensions(path, ['.h', '.hpp', '.m', '.mm', '.c', '.cc', '.cpp'], exclude, ignore) two_ways_set = two_ways_dependencies(d) untraversed_set = untraversed_files(d) category_list, d = category_files(d) pch_set = dependencies_in_project(path, '.pch', exclude, ignore) # sys.stderr.write("# number of imports\n\n") print_frequencies_chart(d) sys.stderr.write("\n# times the class is imported\n\n") d2 = referenced_classes_from_dict(d) print_frequencies_chart(d2) # l = [] l.append("digraph G {") l.append("\tnode [shape=box];") for k, deps in d.iteritems(): if deps: deps.discard(k) if len(deps) == 0: l.append("\t\"%s\" -> {};" % (k)) for k2 in deps: if not ((k, k2) in two_ways_set or (k2, k) in two_ways_set): l.append("\t\"%s\" -> \"%s\";" % (k, k2)) l.append("\t") for (k, v) in pch_set.iteritems(): l.append("\t\"%s\" [color=red];" % k) for x in v: l.append("\t\"%s\" -> \"%s\" [color=red];" % (k, x)) l.append("\t") l.append("\tedge [color=blue, dir=both];") for (k, k2) in two_ways_set: l.append("\t\"%s\" -> \"%s\";" % (k, k2)) for k in untraversed_set: l.append("\t\"%s\" [color=gray, style=dashed, fontcolor=gray]" % k) if category_list: l.append("\t") l.append("\tedge [color=black];") l.append("\tnode [shape=plaintext];") l.append("\t\"Categories\" [label=\"%s\"];" % "\\n".join(category_list)) if ignore: l.append("\t") l.append("\tnode [shape=box, color=blue];") l.append("\t\"Ignored\" [label=\"%s\"];" % "\\n".join(ignore)) l.append("}\n") return '\n'.join(l) def main(): parser = argparse.ArgumentParser() parser.add_argument("project_path", help="path to folder hierarchy containing Objective-C files") parser.add_argument("-x", "--exclude", nargs='?', default='' ,help="regular expression of substrings to exclude from module names") parser.add_argument("-i", "--ignore", nargs='*', help="list of subfolder names to ignore") args= parser.parse_args() print dependencies_in_dot_format(args.project_path, args.exclude, args.ignore) if __name__=='__main__': main()
mit
igemsoftware/SYSU-Software2013
project/Python27/Lib/site-packages/flask/views.py
140
5610
# -*- coding: utf-8 -*- """ flask.views ~~~~~~~~~~~ This module provides class-based views inspired by the ones in Django. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from .globals import request http_method_funcs = frozenset(['get', 'post', 'head', 'options', 'delete', 'put', 'trace', 'patch']) class View(object): """Alternative way to use view functions. A subclass has to implement :meth:`dispatch_request` which is called with the view arguments from the URL routing system. If :attr:`methods` is provided the methods do not have to be passed to the :meth:`~flask.Flask.add_url_rule` method explicitly:: class MyView(View): methods = ['GET'] def dispatch_request(self, name): return 'Hello %s!' % name app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview')) When you want to decorate a pluggable view you will have to either do that when the view function is created (by wrapping the return value of :meth:`as_view`) or you can use the :attr:`decorators` attribute:: class SecretView(View): methods = ['GET'] decorators = [superuser_required] def dispatch_request(self): ... The decorators stored in the decorators list are applied one after another when the view function is created. Note that you can *not* use the class based decorators since those would decorate the view class and not the generated view function! """ #: A for which methods this pluggable view can handle. methods = None #: The canonical way to decorate class-based views is to decorate the #: return value of as_view(). However since this moves parts of the #: logic from the class declaration to the place where it's hooked #: into the routing system. #: #: You can place one or more decorators in this list and whenever the #: view function is created the result is automatically decorated. #: #: .. versionadded:: 0.8 decorators = [] def dispatch_request(self): """Subclasses have to override this method to implement the actual view function code. This method is called with all the arguments from the URL rule. """ raise NotImplementedError() @classmethod def as_view(cls, name, *class_args, **class_kwargs): """Converts the class into an actual view function that can be used with the routing system. Internally this generates a function on the fly which will instantiate the :class:`View` on each request and call the :meth:`dispatch_request` method on it. The arguments passed to :meth:`as_view` are forwarded to the constructor of the class. """ def view(*args, **kwargs): self = view.view_class(*class_args, **class_kwargs) return self.dispatch_request(*args, **kwargs) if cls.decorators: view.__name__ = name view.__module__ = cls.__module__ for decorator in cls.decorators: view = decorator(view) # we attach the view class to the view function for two reasons: # first of all it allows us to easily figure out what class-based # view this thing came from, secondly it's also used for instantiating # the view class so you can actually replace it with something else # for testing purposes and debugging. view.view_class = cls view.__name__ = name view.__doc__ = cls.__doc__ view.__module__ = cls.__module__ view.methods = cls.methods return view class MethodViewType(type): def __new__(cls, name, bases, d): rv = type.__new__(cls, name, bases, d) if 'methods' not in d: methods = set(rv.methods or []) for key in d: if key in http_method_funcs: methods.add(key.upper()) # if we have no method at all in there we don't want to # add a method list. (This is for instance the case for # the baseclass or another subclass of a base method view # that does not introduce new methods). if methods: rv.methods = sorted(methods) return rv class MethodView(View): """Like a regular class-based view but that dispatches requests to particular methods. For instance if you implement a method called :meth:`get` it means you will response to ``'GET'`` requests and the :meth:`dispatch_request` implementation will automatically forward your request to that. Also :attr:`options` is set for you automatically:: class CounterAPI(MethodView): def get(self): return session.get('counter', 0) def post(self): session['counter'] = session.get('counter', 0) + 1 return 'OK' app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter')) """ __metaclass__ = MethodViewType def dispatch_request(self, *args, **kwargs): meth = getattr(self, request.method.lower(), None) # if the request method is HEAD and we don't have a handler for it # retry with GET if meth is None and request.method == 'HEAD': meth = getattr(self, 'get', None) assert meth is not None, 'Unimplemented method %r' % request.method return meth(*args, **kwargs)
mit
HelloAWorld/NoahGameFrame
Dependencies/protobuf-2.5.0/python/google/protobuf/text_format.py
61
22180
# Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # http://code.google.com/p/protobuf/ # # 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. """Contains routines for printing protocol messages in text format.""" __author__ = 'kenton@google.com (Kenton Varda)' import cStringIO import re from collections import deque from google.protobuf.internal import type_checkers from google.protobuf import descriptor __all__ = [ 'MessageToString', 'PrintMessage', 'PrintField', 'PrintFieldValue', 'Merge' ] _INTEGER_CHECKERS = (type_checkers.Uint32ValueChecker(), type_checkers.Int32ValueChecker(), type_checkers.Uint64ValueChecker(), type_checkers.Int64ValueChecker()) _FLOAT_INFINITY = re.compile('-?inf(?:inity)?f?', re.IGNORECASE) _FLOAT_NAN = re.compile('nanf?', re.IGNORECASE) class ParseError(Exception): """Thrown in case of ASCII parsing error.""" def MessageToString(message, as_utf8=False, as_one_line=False): out = cStringIO.StringIO() PrintMessage(message, out, as_utf8=as_utf8, as_one_line=as_one_line) result = out.getvalue() out.close() if as_one_line: return result.rstrip() return result def PrintMessage(message, out, indent=0, as_utf8=False, as_one_line=False): for field, value in message.ListFields(): if field.label == descriptor.FieldDescriptor.LABEL_REPEATED: for element in value: PrintField(field, element, out, indent, as_utf8, as_one_line) else: PrintField(field, value, out, indent, as_utf8, as_one_line) def PrintField(field, value, out, indent=0, as_utf8=False, as_one_line=False): """Print a single field name/value pair. For repeated fields, the value should be a single element.""" out.write(' ' * indent); if field.is_extension: out.write('[') if (field.containing_type.GetOptions().message_set_wire_format and field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and field.message_type == field.extension_scope and field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL): out.write(field.message_type.full_name) else: out.write(field.full_name) out.write(']') elif field.type == descriptor.FieldDescriptor.TYPE_GROUP: # For groups, use the capitalized name. out.write(field.message_type.name) else: out.write(field.name) if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE: # The colon is optional in this case, but our cross-language golden files # don't include it. out.write(': ') PrintFieldValue(field, value, out, indent, as_utf8, as_one_line) if as_one_line: out.write(' ') else: out.write('\n') def PrintFieldValue(field, value, out, indent=0, as_utf8=False, as_one_line=False): """Print a single field value (not including name). For repeated fields, the value should be a single element.""" if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: if as_one_line: out.write(' { ') PrintMessage(value, out, indent, as_utf8, as_one_line) out.write('}') else: out.write(' {\n') PrintMessage(value, out, indent + 2, as_utf8, as_one_line) out.write(' ' * indent + '}') elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM: enum_value = field.enum_type.values_by_number.get(value, None) if enum_value is not None: out.write(enum_value.name) else: out.write(str(value)) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING: out.write('\"') if type(value) is unicode: out.write(_CEscape(value.encode('utf-8'), as_utf8)) else: out.write(_CEscape(value, as_utf8)) out.write('\"') elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL: if value: out.write("true") else: out.write("false") else: out.write(str(value)) def Merge(text, message): """Merges an ASCII representation of a protocol message into a message. Args: text: Message ASCII representation. message: A protocol buffer message to merge into. Raises: ParseError: On ASCII parsing problems. """ tokenizer = _Tokenizer(text) while not tokenizer.AtEnd(): _MergeField(tokenizer, message) def _MergeField(tokenizer, message): """Merges a single protocol message field into a message. Args: tokenizer: A tokenizer to parse the field name and values. message: A protocol message to record the data. Raises: ParseError: In case of ASCII parsing problems. """ message_descriptor = message.DESCRIPTOR if tokenizer.TryConsume('['): name = [tokenizer.ConsumeIdentifier()] while tokenizer.TryConsume('.'): name.append(tokenizer.ConsumeIdentifier()) name = '.'.join(name) if not message_descriptor.is_extendable: raise tokenizer.ParseErrorPreviousToken( 'Message type "%s" does not have extensions.' % message_descriptor.full_name) field = message.Extensions._FindExtensionByName(name) if not field: raise tokenizer.ParseErrorPreviousToken( 'Extension "%s" not registered.' % name) elif message_descriptor != field.containing_type: raise tokenizer.ParseErrorPreviousToken( 'Extension "%s" does not extend message type "%s".' % ( name, message_descriptor.full_name)) tokenizer.Consume(']') else: name = tokenizer.ConsumeIdentifier() field = message_descriptor.fields_by_name.get(name, None) # Group names are expected to be capitalized as they appear in the # .proto file, which actually matches their type names, not their field # names. if not field: field = message_descriptor.fields_by_name.get(name.lower(), None) if field and field.type != descriptor.FieldDescriptor.TYPE_GROUP: field = None if (field and field.type == descriptor.FieldDescriptor.TYPE_GROUP and field.message_type.name != name): field = None if not field: raise tokenizer.ParseErrorPreviousToken( 'Message type "%s" has no field named "%s".' % ( message_descriptor.full_name, name)) if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: tokenizer.TryConsume(':') if tokenizer.TryConsume('<'): end_token = '>' else: tokenizer.Consume('{') end_token = '}' if field.label == descriptor.FieldDescriptor.LABEL_REPEATED: if field.is_extension: sub_message = message.Extensions[field].add() else: sub_message = getattr(message, field.name).add() else: if field.is_extension: sub_message = message.Extensions[field] else: sub_message = getattr(message, field.name) sub_message.SetInParent() while not tokenizer.TryConsume(end_token): if tokenizer.AtEnd(): raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % (end_token)) _MergeField(tokenizer, sub_message) else: _MergeScalarField(tokenizer, message, field) def _MergeScalarField(tokenizer, message, field): """Merges a single protocol message scalar field into a message. Args: tokenizer: A tokenizer to parse the field value. message: A protocol message to record the data. field: The descriptor of the field to be merged. Raises: ParseError: In case of ASCII parsing problems. RuntimeError: On runtime errors. """ tokenizer.Consume(':') value = None if field.type in (descriptor.FieldDescriptor.TYPE_INT32, descriptor.FieldDescriptor.TYPE_SINT32, descriptor.FieldDescriptor.TYPE_SFIXED32): value = tokenizer.ConsumeInt32() elif field.type in (descriptor.FieldDescriptor.TYPE_INT64, descriptor.FieldDescriptor.TYPE_SINT64, descriptor.FieldDescriptor.TYPE_SFIXED64): value = tokenizer.ConsumeInt64() elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32, descriptor.FieldDescriptor.TYPE_FIXED32): value = tokenizer.ConsumeUint32() elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64, descriptor.FieldDescriptor.TYPE_FIXED64): value = tokenizer.ConsumeUint64() elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT, descriptor.FieldDescriptor.TYPE_DOUBLE): value = tokenizer.ConsumeFloat() elif field.type == descriptor.FieldDescriptor.TYPE_BOOL: value = tokenizer.ConsumeBool() elif field.type == descriptor.FieldDescriptor.TYPE_STRING: value = tokenizer.ConsumeString() elif field.type == descriptor.FieldDescriptor.TYPE_BYTES: value = tokenizer.ConsumeByteString() elif field.type == descriptor.FieldDescriptor.TYPE_ENUM: value = tokenizer.ConsumeEnum(field) else: raise RuntimeError('Unknown field type %d' % field.type) if field.label == descriptor.FieldDescriptor.LABEL_REPEATED: if field.is_extension: message.Extensions[field].append(value) else: getattr(message, field.name).append(value) else: if field.is_extension: message.Extensions[field] = value else: setattr(message, field.name, value) class _Tokenizer(object): """Protocol buffer ASCII representation tokenizer. This class handles the lower level string parsing by splitting it into meaningful tokens. It was directly ported from the Java protocol buffer API. """ _WHITESPACE = re.compile('(\\s|(#.*$))+', re.MULTILINE) _TOKEN = re.compile( '[a-zA-Z_][0-9a-zA-Z_+-]*|' # an identifier '[0-9+-][0-9a-zA-Z_.+-]*|' # a number '\"([^\"\n\\\\]|\\\\.)*(\"|\\\\?$)|' # a double-quoted string '\'([^\'\n\\\\]|\\\\.)*(\'|\\\\?$)') # a single-quoted string _IDENTIFIER = re.compile('\w+') def __init__(self, text_message): self._text_message = text_message self._position = 0 self._line = -1 self._column = 0 self._token_start = None self.token = '' self._lines = deque(text_message.split('\n')) self._current_line = '' self._previous_line = 0 self._previous_column = 0 self._SkipWhitespace() self.NextToken() def AtEnd(self): """Checks the end of the text was reached. Returns: True iff the end was reached. """ return self.token == '' def _PopLine(self): while len(self._current_line) <= self._column: if not self._lines: self._current_line = '' return self._line += 1 self._column = 0 self._current_line = self._lines.popleft() def _SkipWhitespace(self): while True: self._PopLine() match = self._WHITESPACE.match(self._current_line, self._column) if not match: break length = len(match.group(0)) self._column += length def TryConsume(self, token): """Tries to consume a given piece of text. Args: token: Text to consume. Returns: True iff the text was consumed. """ if self.token == token: self.NextToken() return True return False def Consume(self, token): """Consumes a piece of text. Args: token: Text to consume. Raises: ParseError: If the text couldn't be consumed. """ if not self.TryConsume(token): raise self._ParseError('Expected "%s".' % token) def ConsumeIdentifier(self): """Consumes protocol message field identifier. Returns: Identifier string. Raises: ParseError: If an identifier couldn't be consumed. """ result = self.token if not self._IDENTIFIER.match(result): raise self._ParseError('Expected identifier.') self.NextToken() return result def ConsumeInt32(self): """Consumes a signed 32bit integer number. Returns: The integer parsed. Raises: ParseError: If a signed 32bit integer couldn't be consumed. """ try: result = ParseInteger(self.token, is_signed=True, is_long=False) except ValueError, e: raise self._ParseError(str(e)) self.NextToken() return result def ConsumeUint32(self): """Consumes an unsigned 32bit integer number. Returns: The integer parsed. Raises: ParseError: If an unsigned 32bit integer couldn't be consumed. """ try: result = ParseInteger(self.token, is_signed=False, is_long=False) except ValueError, e: raise self._ParseError(str(e)) self.NextToken() return result def ConsumeInt64(self): """Consumes a signed 64bit integer number. Returns: The integer parsed. Raises: ParseError: If a signed 64bit integer couldn't be consumed. """ try: result = ParseInteger(self.token, is_signed=True, is_long=True) except ValueError, e: raise self._ParseError(str(e)) self.NextToken() return result def ConsumeUint64(self): """Consumes an unsigned 64bit integer number. Returns: The integer parsed. Raises: ParseError: If an unsigned 64bit integer couldn't be consumed. """ try: result = ParseInteger(self.token, is_signed=False, is_long=True) except ValueError, e: raise self._ParseError(str(e)) self.NextToken() return result def ConsumeFloat(self): """Consumes an floating point number. Returns: The number parsed. Raises: ParseError: If a floating point number couldn't be consumed. """ try: result = ParseFloat(self.token) except ValueError, e: raise self._ParseError(str(e)) self.NextToken() return result def ConsumeBool(self): """Consumes a boolean value. Returns: The bool parsed. Raises: ParseError: If a boolean value couldn't be consumed. """ try: result = ParseBool(self.token) except ValueError, e: raise self._ParseError(str(e)) self.NextToken() return result def ConsumeString(self): """Consumes a string value. Returns: The string parsed. Raises: ParseError: If a string value couldn't be consumed. """ bytes = self.ConsumeByteString() try: return unicode(bytes, 'utf-8') except UnicodeDecodeError, e: raise self._StringParseError(e) def ConsumeByteString(self): """Consumes a byte array value. Returns: The array parsed (as a string). Raises: ParseError: If a byte array value couldn't be consumed. """ list = [self._ConsumeSingleByteString()] while len(self.token) > 0 and self.token[0] in ('\'', '"'): list.append(self._ConsumeSingleByteString()) return "".join(list) def _ConsumeSingleByteString(self): """Consume one token of a string literal. String literals (whether bytes or text) can come in multiple adjacent tokens which are automatically concatenated, like in C or Python. This method only consumes one token. """ text = self.token if len(text) < 1 or text[0] not in ('\'', '"'): raise self._ParseError('Expected string.') if len(text) < 2 or text[-1] != text[0]: raise self._ParseError('String missing ending quote.') try: result = _CUnescape(text[1:-1]) except ValueError, e: raise self._ParseError(str(e)) self.NextToken() return result def ConsumeEnum(self, field): try: result = ParseEnum(field, self.token) except ValueError, e: raise self._ParseError(str(e)) self.NextToken() return result def ParseErrorPreviousToken(self, message): """Creates and *returns* a ParseError for the previously read token. Args: message: A message to set for the exception. Returns: A ParseError instance. """ return ParseError('%d:%d : %s' % ( self._previous_line + 1, self._previous_column + 1, message)) def _ParseError(self, message): """Creates and *returns* a ParseError for the current token.""" return ParseError('%d:%d : %s' % ( self._line + 1, self._column + 1, message)) def _StringParseError(self, e): return self._ParseError('Couldn\'t parse string: ' + str(e)) def NextToken(self): """Reads the next meaningful token.""" self._previous_line = self._line self._previous_column = self._column self._column += len(self.token) self._SkipWhitespace() if not self._lines and len(self._current_line) <= self._column: self.token = '' return match = self._TOKEN.match(self._current_line, self._column) if match: token = match.group(0) self.token = token else: self.token = self._current_line[self._column] # text.encode('string_escape') does not seem to satisfy our needs as it # encodes unprintable characters using two-digit hex escapes whereas our # C++ unescaping function allows hex escapes to be any length. So, # "\0011".encode('string_escape') ends up being "\\x011", which will be # decoded in C++ as a single-character string with char code 0x11. def _CEscape(text, as_utf8): def escape(c): o = ord(c) if o == 10: return r"\n" # optional escape if o == 13: return r"\r" # optional escape if o == 9: return r"\t" # optional escape if o == 39: return r"\'" # optional escape if o == 34: return r'\"' # necessary escape if o == 92: return r"\\" # necessary escape # necessary escapes if not as_utf8 and (o >= 127 or o < 32): return "\\%03o" % o return c return "".join([escape(c) for c in text]) _CUNESCAPE_HEX = re.compile(r'(\\+)x([0-9a-fA-F])(?![0-9a-fA-F])') def _CUnescape(text): def ReplaceHex(m): # Only replace the match if the number of leading back slashes is odd. i.e. # the slash itself is not escaped. if len(m.group(1)) & 1: return m.group(1) + 'x0' + m.group(2) return m.group(0) # This is required because the 'string_escape' encoding doesn't # allow single-digit hex escapes (like '\xf'). result = _CUNESCAPE_HEX.sub(ReplaceHex, text) return result.decode('string_escape') def ParseInteger(text, is_signed=False, is_long=False): """Parses an integer. Args: text: The text to parse. is_signed: True if a signed integer must be parsed. is_long: True if a long integer must be parsed. Returns: The integer value. Raises: ValueError: Thrown Iff the text is not a valid integer. """ # Do the actual parsing. Exception handling is propagated to caller. try: result = int(text, 0) except ValueError: raise ValueError('Couldn\'t parse integer: %s' % text) # Check if the integer is sane. Exceptions handled by callers. checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)] checker.CheckValue(result) return result def ParseFloat(text): """Parse a floating point number. Args: text: Text to parse. Returns: The number parsed. Raises: ValueError: If a floating point number couldn't be parsed. """ try: # Assume Python compatible syntax. return float(text) except ValueError: # Check alternative spellings. if _FLOAT_INFINITY.match(text): if text[0] == '-': return float('-inf') else: return float('inf') elif _FLOAT_NAN.match(text): return float('nan') else: # assume '1.0f' format try: return float(text.rstrip('f')) except ValueError: raise ValueError('Couldn\'t parse float: %s' % text) def ParseBool(text): """Parse a boolean value. Args: text: Text to parse. Returns: Boolean values parsed Raises: ValueError: If text is not a valid boolean. """ if text in ('true', 't', '1'): return True elif text in ('false', 'f', '0'): return False else: raise ValueError('Expected "true" or "false".') def ParseEnum(field, value): """Parse an enum value. The value can be specified by a number (the enum value), or by a string literal (the enum name). Args: field: Enum field descriptor. value: String value. Returns: Enum value number. Raises: ValueError: If the enum value could not be parsed. """ enum_descriptor = field.enum_type try: number = int(value, 0) except ValueError: # Identifier. enum_value = enum_descriptor.values_by_name.get(value, None) if enum_value is None: raise ValueError( 'Enum type "%s" has no value named %s.' % ( enum_descriptor.full_name, value)) else: # Numeric value. enum_value = enum_descriptor.values_by_number.get(number, None) if enum_value is None: raise ValueError( 'Enum type "%s" has no value with number %d.' % ( enum_descriptor.full_name, number)) return enum_value.number
apache-2.0
stackforge/networking-mlnx
doc/source/conf.py
2
2469
# -*- coding: utf-8 -*- # 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 sys sys.path.insert(0, os.path.abspath('../..')) # -- General configuration ---------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', #'sphinx.ext.intersphinx', 'oslosphinx' ] # autodoc generation is a bit aggressive and a nuisance when doing heavy # text edit cycles. # execute "export SPHINX_DEBUG=1" in your terminal to disable # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General information about the project. project = u'networking-mlnx' copyright = u'2015, Mellanox Technologies, Ltd' # 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 # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # -- Options for HTML output -------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. # html_theme_path = ["."] # html_theme = '_theme' # html_static_path = ['static'] # Output file base name for HTML help builder. htmlhelp_basename = '%sdoc' % project # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [ ('index', '%s.tex' % project, u'%s Documentation' % project, u'OpenStack Foundation', 'manual'), ] # Example configuration for intersphinx: refer to the Python standard library. #intersphinx_mapping = {'http://docs.python.org/': None}
apache-2.0
cyberark-bizdev/ansible
test/units/module_utils/basic/test_no_log.py
53
6160
# -*- coding: utf-8 -*- # (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com> # (c) 2017, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type from ansible.compat.tests import unittest from ansible.module_utils.basic import return_values, remove_values class TestReturnValues(unittest.TestCase): dataset = ( ('string', frozenset(['string'])), ('', frozenset()), (1, frozenset(['1'])), (1.0, frozenset(['1.0'])), (False, frozenset()), (['1', '2', '3'], frozenset(['1', '2', '3'])), (('1', '2', '3'), frozenset(['1', '2', '3'])), ({'one': 1, 'two': 'dos'}, frozenset(['1', 'dos'])), ( { 'one': 1, 'two': 'dos', 'three': [ 'amigos', 'musketeers', None, { 'ping': 'pong', 'base': ( 'balls', 'raquets' ) } ] }, frozenset(['1', 'dos', 'amigos', 'musketeers', 'pong', 'balls', 'raquets']) ), (u'Toshio くらとみ', frozenset(['Toshio くらとみ'])), ('Toshio くらとみ', frozenset(['Toshio くらとみ'])), ) def test_return_values(self): for data, expected in self.dataset: self.assertEquals(frozenset(return_values(data)), expected) def test_unknown_type(self): self.assertRaises(TypeError, frozenset, return_values(object())) class TestRemoveValues(unittest.TestCase): OMIT = 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER' dataset_no_remove = ( ('string', frozenset(['nope'])), (1234, frozenset(['4321'])), (False, frozenset(['4321'])), (1.0, frozenset(['4321'])), (['string', 'strang', 'strung'], frozenset(['nope'])), ({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['nope'])), ( { 'one': 1, 'two': 'dos', 'three': [ 'amigos', 'musketeers', None, { 'ping': 'pong', 'base': ['balls', 'raquets'] } ] }, frozenset(['nope']) ), (u'Toshio くら'.encode('utf-8'), frozenset([u'とみ'.encode('utf-8')])), (u'Toshio くら', frozenset([u'とみ'])), ) dataset_remove = ( ('string', frozenset(['string']), OMIT), (1234, frozenset(['1234']), OMIT), (1234, frozenset(['23']), OMIT), (1.0, frozenset(['1.0']), OMIT), (['string', 'strang', 'strung'], frozenset(['strang']), ['string', OMIT, 'strung']), (['string', 'strang', 'strung'], frozenset(['strang', 'string', 'strung']), [OMIT, OMIT, OMIT]), (('string', 'strang', 'strung'), frozenset(['string', 'strung']), [OMIT, 'strang', OMIT]), ((1234567890, 345678, 987654321), frozenset(['1234567890']), [OMIT, 345678, 987654321]), ((1234567890, 345678, 987654321), frozenset(['345678']), [OMIT, OMIT, 987654321]), ({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['key']), {'one': 1, 'two': 'dos', 'secret': OMIT}), ({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['key', 'dos', '1']), {'one': OMIT, 'two': OMIT, 'secret': OMIT}), ({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['key', 'dos', '1']), {'one': OMIT, 'two': OMIT, 'secret': OMIT}), ( { 'one': 1, 'two': 'dos', 'three': [ 'amigos', 'musketeers', None, { 'ping': 'pong', 'base': [ 'balls', 'raquets' ] } ] }, frozenset(['balls', 'base', 'pong', 'amigos']), { 'one': 1, 'two': 'dos', 'three': [ OMIT, 'musketeers', None, { 'ping': OMIT, 'base': [ OMIT, 'raquets' ] } ] } ), ( 'This sentence has an enigma wrapped in a mystery inside of a secret. - mr mystery', frozenset(['enigma', 'mystery', 'secret']), 'This sentence has an ******** wrapped in a ******** inside of a ********. - mr ********' ), (u'Toshio くらとみ'.encode('utf-8'), frozenset([u'くらとみ'.encode('utf-8')]), u'Toshio ********'.encode('utf-8')), (u'Toshio くらとみ', frozenset([u'くらとみ']), u'Toshio ********'), ) def test_no_removal(self): for value, no_log_strings in self.dataset_no_remove: self.assertEquals(remove_values(value, no_log_strings), value) def test_strings_to_remove(self): for value, no_log_strings, expected in self.dataset_remove: self.assertEquals(remove_values(value, no_log_strings), expected) def test_unknown_type(self): self.assertRaises(TypeError, remove_values, object(), frozenset()) def test_hit_recursion_limit(self): """ Check that we do not hit a recursion limit""" data_list = [] inner_list = data_list for i in range(0, 10000): new_list = [] inner_list.append(new_list) inner_list = new_list inner_list.append('secret') # Check that this does not hit a recursion limit actual_data_list = remove_values(data_list, frozenset(('secret',))) levels = 0 inner_list = actual_data_list while inner_list: if isinstance(inner_list, list): self.assertEquals(len(inner_list), 1) else: levels -= 1 break inner_list = inner_list[0] levels += 1 self.assertEquals(inner_list, self.OMIT) self.assertEquals(levels, 10000)
gpl-3.0
luiscberrocal/django_quiz_factory
django_quiz_factory/quiz/models.py
2
18611
from __future__ import unicode_literals import re import json from django.db import models from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator from django.utils.translation import ugettext as _ from django.utils.timezone import now from django.utils.encoding import python_2_unicode_compatible from django.conf import settings from model_utils.managers import InheritanceManager class CategoryManager(models.Manager): def new_category(self, category): new_category = self.create(category=re.sub('\s+', '-', category) .lower()) new_category.save() return new_category @python_2_unicode_compatible class Category(models.Model): category = models.CharField( verbose_name=_("Category"), max_length=250, blank=True, unique=True, null=True) objects = CategoryManager() class Meta: verbose_name = _("Category") verbose_name_plural = _("Categories") def __str__(self): return self.category @python_2_unicode_compatible class SubCategory(models.Model): sub_category = models.CharField( verbose_name=_("Sub-Category"), max_length=250, blank=True, null=True) category = models.ForeignKey( Category, null=True, blank=True, verbose_name=_("Category")) objects = CategoryManager() class Meta: verbose_name = _("Sub-Category") verbose_name_plural = _("Sub-Categories") def __str__(self): return self.sub_category + " (" + self.category.category + ")" @python_2_unicode_compatible class Quiz(models.Model): title = models.CharField( verbose_name=_("Title"), max_length=60, blank=False) description = models.TextField( verbose_name=_("Description"), blank=True, help_text=_("a description of the quiz")) url = models.SlugField( max_length=60, blank=False, help_text=_("a user friendly url"), verbose_name=_("user friendly url")) category = models.ForeignKey( Category, null=True, blank=True, verbose_name=_("Category")) random_order = models.BooleanField( blank=False, default=False, verbose_name=_("Random Order"), help_text=_("Display the questions in " "a random order or as they " "are set?")) max_questions = models.PositiveIntegerField( blank=True, null=True, verbose_name=_("Max Questions"), help_text=_("Number of questions to be answered on each attempt.")) answers_at_end = models.BooleanField( blank=False, default=False, help_text=_("Correct answer is NOT shown after question." " Answers displayed at the end."), verbose_name=_("Answers at end")) exam_paper = models.BooleanField( blank=False, default=False, help_text=_("If yes, the result of each" " attempt by a user will be" " stored. Necessary for marking."), verbose_name=_("Exam Paper")) single_attempt = models.BooleanField( blank=False, default=False, help_text=_("If yes, only one attempt by" " a user will be permitted." " Non users cannot sit this exam."), verbose_name=_("Single Attempt")) pass_mark = models.SmallIntegerField( blank=True, default=0, help_text=_("Percentage required to pass exam."), validators=[MaxValueValidator(100)]) success_text = models.TextField( blank=True, help_text=_("Displayed if user passes."), verbose_name=_("Success Text")) fail_text = models.TextField( verbose_name=_("Fail Text"), blank=True, help_text=_("Displayed if user fails.")) draft = models.BooleanField( blank=True, default=False, verbose_name=_("Draft"), help_text=_("If yes, the quiz is not displayed" " in the quiz list and can only be" " taken by users who can edit" " quizzes.")) def save(self, force_insert=False, force_update=False, *args, **kwargs): self.url = re.sub('\s+', '-', self.url).lower() self.url = ''.join(letter for letter in self.url if letter.isalnum() or letter == '-') if self.single_attempt is True: self.exam_paper = True if self.pass_mark > 100: raise ValidationError('%s is above 100' % self.pass_mark) super(Quiz, self).save(force_insert, force_update, *args, **kwargs) class Meta: verbose_name = _("Quiz") verbose_name_plural = _("Quizzes") def __str__(self): return self.title def get_questions(self): return self.question_set.all().select_subclasses() @property def get_max_score(self): return self.get_questions().count() def anon_score_id(self): return str(self.id) + "_score" def anon_q_list(self): return str(self.id) + "_q_list" def anon_q_data(self): return str(self.id) + "_data" class ProgressManager(models.Manager): def new_progress(self, user): new_progress = self.create(user=user, score="") new_progress.save() return new_progress class Progress(models.Model): """ Progress is used to track an individual signed in users score on different quiz's and categories Data stored in csv using the format: category, score, possible, category, score, possible, ... """ user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_("User")) score = models.CommaSeparatedIntegerField(max_length=1024, verbose_name=_("Score")) objects = ProgressManager() class Meta: verbose_name = _("User Progress") verbose_name_plural = _("User progress records") @property def list_all_cat_scores(self): """ Returns a dict in which the key is the category name and the item is a list of three integers. The first is the number of questions correct, the second is the possible best score, the third is the percentage correct. The dict will have one key for every category that you have defined """ score_before = self.score output = {} for cat in Category.objects.all(): to_find = re.escape(cat.category) + r",(\d+),(\d+)," # group 1 is score, group 2 is highest possible match = re.search(to_find, self.score, re.IGNORECASE) if match: score = int(match.group(1)) possible = int(match.group(2)) try: percent = int(round((float(score) / float(possible)) * 100)) except: percent = 0 output[cat.category] = [score, possible, percent] else: # if category has not been added yet, add it. self.score += cat.category + ",0,0," output[cat.category] = [0, 0] if len(self.score) > len(score_before): # If a new category has been added, save changes. self.save() return output def update_score(self, question, score_to_add=0, possible_to_add=0): """ Pass in question object, amount to increase score and max possible. Does not return anything. """ category_test = Category.objects.filter(category=question.category)\ .exists() if any([item is False for item in [category_test, score_to_add, possible_to_add, isinstance(score_to_add, int), isinstance(possible_to_add, int)]]): return _("error"), _("category does not exist or invalid score") to_find = re.escape(str(question.category)) +\ r",(?P<score>\d+),(?P<possible>\d+)," match = re.search(to_find, self.score, re.IGNORECASE) if match: updated_score = int(match.group('score')) + abs(score_to_add) updated_possible = int(match.group('possible')) +\ abs(possible_to_add) new_score = ",".join( [ str(question.category), str(updated_score), str(updated_possible), "" ]) # swap old score for the new one self.score = self.score.replace(match.group(), new_score) self.save() else: # if not present but existing, add with the points passed in self.score += ",".join( [ str(question.category), str(score_to_add), str(possible_to_add), "" ]) self.save() def show_exams(self): """ Finds the previous quizzes marked as 'exam papers'. Returns a queryset of complete exams. """ return Sitting.objects.filter(user=self.user, complete=True) class SittingManager(models.Manager): def new_sitting(self, user, quiz): if quiz.random_order is True: question_set = quiz.question_set.all() \ .select_subclasses() \ .order_by('?') else: question_set = quiz.question_set.all() \ .select_subclasses() question_set = question_set.values_list('id', flat=True) if quiz.max_questions and quiz.max_questions < len(question_set): question_set = question_set[:quiz.max_questions] questions = ",".join(map(str, question_set)) + "," new_sitting = self.create(user=user, quiz=quiz, question_order=questions, question_list=questions, incorrect_questions="", current_score=0, complete=False, user_answers='{}') return new_sitting def user_sitting(self, user, quiz): if quiz.single_attempt is True and self.filter(user=user, quiz=quiz, complete=True)\ .exists(): return False try: sitting = self.get(user=user, quiz=quiz, complete=False) except Sitting.DoesNotExist: sitting = self.new_sitting(user, quiz) except Sitting.MultipleObjectsReturned: sitting = self.filter(user=user, quiz=quiz, complete=False)[0] return sitting class Sitting(models.Model): """ Used to store the progress of logged in users sitting a quiz. Replaces the session system used by anon users. Question_order is a list of integer pks of all the questions in the quiz, in order. Question_list is a list of integers which represent id's of the unanswered questions in csv format. Incorrect_questions is a list in the same format. Sitting deleted when quiz finished unless quiz.exam_paper is true. User_answers is a json object in which the question PK is stored with the answer the user gave. """ user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_("User")) quiz = models.ForeignKey(Quiz, verbose_name=_("Quiz")) question_order = models.CommaSeparatedIntegerField( max_length=1024, verbose_name=_("Question Order")) question_list = models.CommaSeparatedIntegerField( max_length=1024, verbose_name=_("Question List")) incorrect_questions = models.CommaSeparatedIntegerField( max_length=1024, blank=True, verbose_name=_("Incorrect questions")) current_score = models.IntegerField(verbose_name=_("Current Score")) complete = models.BooleanField(default=False, blank=False, verbose_name=_("Complete")) user_answers = models.TextField(blank=True, default='{}', verbose_name=_("User Answers")) start = models.DateTimeField(auto_now_add=True, verbose_name=_("Start")) end = models.DateTimeField(null=True, blank=True, verbose_name=_("End")) objects = SittingManager() class Meta: permissions = (("view_sittings", _("Can see completed exams.")),) def get_first_question(self): """ Returns the next question. If no question is found, returns False Does NOT remove the question from the front of the list. """ if not self.question_list: return False first, _ = self.question_list.split(',', 1) question_id = int(first) return Question.objects.get_subclass(id=question_id) def remove_first_question(self): if not self.question_list: return _, others = self.question_list.split(',', 1) self.question_list = others self.save() def add_to_score(self, points): self.current_score += int(points) self.save() @property def get_current_score(self): return self.current_score def _question_ids(self): return [int(n) for n in self.question_order.split(',') if n] @property def get_percent_correct(self): dividend = float(self.current_score) divisor = len(self._question_ids()) if divisor < 1: return 0 # prevent divide by zero error if dividend > divisor: return 100 correct = int(round((dividend / divisor) * 100)) if correct >= 1: return correct else: return 0 def mark_quiz_complete(self): self.complete = True self.end = now() self.save() def add_incorrect_question(self, question): """ Adds uid of incorrect question to the list. The question object must be passed in. """ if len(self.incorrect_questions) > 0: self.incorrect_questions += ',' self.incorrect_questions += str(question.id) + "," if self.complete: self.add_to_score(-1) self.save() @property def get_incorrect_questions(self): """ Returns a list of non empty integers, representing the pk of questions """ return [int(q) for q in self.incorrect_questions.split(',') if q] def remove_incorrect_question(self, question): current = self.get_incorrect_questions current.remove(question.id) self.incorrect_questions = ','.join(map(str, current)) self.add_to_score(1) self.save() @property def check_if_passed(self): return self.get_percent_correct >= self.quiz.pass_mark @property def result_message(self): if self.check_if_passed: return self.quiz.success_text else: return self.quiz.fail_text def add_user_answer(self, question, guess): current = json.loads(self.user_answers) current[question.id] = guess self.user_answers = json.dumps(current) self.save() def get_questions(self, with_answers=False): question_ids = self._question_ids() questions = sorted( self.quiz.question_set.filter(id__in=question_ids) .select_subclasses(), key=lambda q: question_ids.index(q.id)) if with_answers: user_answers = json.loads(self.user_answers) for question in questions: question.user_answer = user_answers[str(question.id)] return questions @property def questions_with_user_answers(self): return { q: q.user_answer for q in self.get_questions(with_answers=True) } @property def get_max_score(self): return len(self._question_ids()) def progress(self): """ Returns the number of questions answered so far and the total number of questions. """ answered = len(json.loads(self.user_answers)) total = self.get_max_score return answered, total @python_2_unicode_compatible class Question(models.Model): """ Base class for all question types. Shared properties placed here. """ quiz = models.ManyToManyField(Quiz, verbose_name=_("Quiz"), blank=True) category = models.ForeignKey(Category, verbose_name=_("Category"), blank=True, null=True) sub_category = models.ForeignKey(SubCategory, verbose_name=_("Sub-Category"), blank=True, null=True) figure = models.ImageField(upload_to='uploads/%Y/%m/%d', blank=True, null=True, verbose_name=_("Figure")) content = models.CharField(max_length=1000, blank=False, help_text=_("Enter the question text that " "you want displayed"), verbose_name=_('Question')) explanation = models.TextField(max_length=2000, blank=True, help_text=_("Explanation to be shown " "after the question has " "been answered."), verbose_name=_('Explanation')) objects = InheritanceManager() class Meta: verbose_name = _("Question") verbose_name_plural = _("Questions") ordering = ['category'] def __str__(self): return self.content
mit
lahosken/pants
src/python/pants/init/options_initializer.py
5
6563
# coding=utf-8 # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import logging import sys import pkg_resources from pants.base.build_environment import pants_version from pants.base.exceptions import BuildConfigurationError from pants.goal.goal import Goal from pants.init.extension_loader import load_backends_and_plugins from pants.init.plugin_resolver import PluginResolver from pants.logging.setup import setup_logging from pants.option.global_options import GlobalOptionsRegistrar from pants.subsystem.subsystem import Subsystem logger = logging.getLogger(__name__) class OptionsInitializer(object): """Initializes backends/plugins, global options and logging. This class uses a class-level cache for the internally generated `BuildConfiguration` object, which permits multiple invocations in the same runtime context without re-incurring backend & plugin loading, which can be expensive and cause issues (double task registration, etc). """ # Class-level cache for the `BuildConfiguration` object. _build_configuration = None def __init__(self, options_bootstrapper, working_set=None, exiter=sys.exit): """ :param OptionsBootStrapper options_bootstrapper: An options bootstrapper instance. :param pkg_resources.WorkingSet working_set: The working set of the current run as returned by PluginResolver.resolve(). :param func exiter: A function that accepts an exit code value and exits (for tests). """ self._options_bootstrapper = options_bootstrapper self._working_set = working_set or PluginResolver(self._options_bootstrapper).resolve() self._exiter = exiter @classmethod def _has_build_configuration(cls): return cls._build_configuration is not None @classmethod def _get_build_configuration(cls): return cls._build_configuration @classmethod def _set_build_configuration(cls, build_configuration): cls._build_configuration = build_configuration @classmethod def reset(cls): cls._set_build_configuration(None) def _setup_logging(self, quiet, level, log_dir): """Initializes logging.""" # N.B. quiet help says 'Squelches all console output apart from errors'. level = 'ERROR' if quiet else level.upper() setup_logging(level, console_stream=sys.stderr, log_dir=log_dir) def _load_plugins(self, working_set, python_paths, plugins, backend_packages): """Load backends and plugins. :returns: A `BuildConfiguration` object constructed during backend/plugin loading. """ # Add any extra paths to python path (e.g., for loading extra source backends). for path in python_paths: if path not in sys.path: sys.path.append(path) pkg_resources.fixup_namespace_packages(path) # Load plugins and backends. return load_backends_and_plugins(plugins, working_set, backend_packages) def _register_options(self, subsystems, options): """Registers global options.""" # Standalone global options. GlobalOptionsRegistrar.register_options_on_scope(options) # Options for subsystems. for subsystem in subsystems: subsystem.register_options_on_scope(options) # TODO(benjy): Should Goals or the entire goal-running mechanism be a Subsystem? for goal in Goal.all(): # Register task options. goal.register_options(options) def _install_options(self, options_bootstrapper, build_configuration): """Parse and register options. :returns: An Options object representing the full set of runtime options. """ # TODO: This inline import is currently necessary to resolve a ~legitimate cycle between # `GoalRunner`->`EngineInitializer`->`OptionsInitializer`->`GoalRunner`. from pants.bin.goal_runner import GoalRunner # Now that plugins and backends are loaded, we can gather the known scopes. known_scope_infos = [GlobalOptionsRegistrar.get_scope_info()] # Add scopes for all needed subsystems via a union of all known subsystem sets. subsystems = Subsystem.closure( GoalRunner.subsystems() | Goal.subsystems() | build_configuration.subsystems() ) for subsystem in subsystems: known_scope_infos.append(subsystem.get_scope_info()) # Add scopes for all tasks in all goals. for goal in Goal.all(): known_scope_infos.extend(filter(None, goal.known_scope_infos())) # Now that we have the known scopes we can get the full options. options = options_bootstrapper.get_full_options(known_scope_infos) self._register_options(subsystems, options) # Make the options values available to all subsystems. Subsystem.set_options(options) return options def setup(self, init_logging=True): """Initializes logging, loads backends/plugins and parses options. :param bool init_logging: Whether or not to initialize logging as part of setup. :returns: A tuple of (options, build_configuration). """ global_bootstrap_options = self._options_bootstrapper.get_bootstrap_options().for_global_scope() if global_bootstrap_options.pants_version != pants_version(): raise BuildConfigurationError( 'Version mismatch: Requested version was {}, our version is {}.' .format(global_bootstrap_options.pants_version, pants_version()) ) # Get logging setup prior to loading backends so that they can log as needed. if init_logging: self._setup_logging(global_bootstrap_options.quiet, global_bootstrap_options.level, global_bootstrap_options.logdir) # Conditionally load backends/plugins and materialize a `BuildConfiguration` object. if not self._has_build_configuration(): build_configuration = self._load_plugins(self._working_set, global_bootstrap_options.pythonpath, global_bootstrap_options.plugins, global_bootstrap_options.backend_packages) self._set_build_configuration(build_configuration) else: build_configuration = self._get_build_configuration() # Parse and register options. options = self._install_options(self._options_bootstrapper, build_configuration) return options, build_configuration
apache-2.0
jjffryan/pymtl
accel/mvmult/MatrixVecLaneRTL_test.py
7
10181
#============================================================================== # MatrixVecLaneBL_test #============================================================================== import pytest from pymtl import * from pclib.ifcs import mem_msgs from pclib.test import TestSource, TestMemory from MatrixVecLaneRTL import MatrixVecLaneRTL from LaneManager import LaneManager #------------------------------------------------------------------------------ # TestHarness #------------------------------------------------------------------------------ class TestHarness( Model ): def __init__( s, lane_id, nmul_stages, mem_delay, test_verilog ): memreq_params = mem_msgs.MemReqParams( 32, 32 ) memresp_params = mem_msgs.MemRespParams( 32 ) s.mem = TestMemory( memreq_params, memresp_params, 1, mem_delay ) s.lane = MatrixVecLaneRTL( lane_id, nmul_stages, memreq_params, memresp_params ) if test_verilog: s.lane = TranslationTool( s.lane ) def elaborate_logic( s ): s.connect( s.lane.req , s.mem.reqs [0] ) s.connect( s.lane.resp, s.mem.resps[0] ) def done( s ): return s.lane.done def line_trace( s ): return "{} -> {}".format( s.lane.line_trace(), s.mem.line_trace() ) #------------------------------------------------------------------------------ # run_mvmult_test #------------------------------------------------------------------------------ def run_mvmult_test( dump_vcd, model, lane_id, src_matrix, src_vector, dest_vector ): model.vcd_file = dump_vcd model.elaborate() sim = SimulationTool( model ) # Load the memory model.mem.load_memory( src_matrix ) model.mem.load_memory( src_vector ) # Run the simulation sim.reset() # Set the inputs model.lane.m_baseaddr.value = src_matrix [0] model.lane.v_baseaddr.value = src_vector [0] model.lane.d_baseaddr.value = dest_vector[0] model.lane.size .value = len(src_vector[1]) / 4 sim.cycle() model.lane.go.value = True print while not model.done() and sim.ncycles < 80: sim.print_line_trace() sim.cycle() model.lane.go.value = False assert model.done() dest_addr = dest_vector[0] dest_value = dest_vector[1][0] assert model.mem.mem.mem[ dest_addr+(lane_id*4) ] == dest_value # Add a couple extra ticks so that the VCD dump is nicer sim.cycle() sim.cycle() sim.cycle() #------------------------------------------------------------------------------ # mem_array_32bit #------------------------------------------------------------------------------ # Utility function for creating arrays formatted for memory loading. from itertools import chain def mem_array_32bit( base_addr, data ): return [base_addr, list( chain.from_iterable([ [x,0,0,0] for x in data ] )) ] #------------------------------------------------------------------------------ # test_mvmult #------------------------------------------------------------------------------ # 5 1 3 1 16 # 1 1 1 . 2 = 6 # 1 2 1 3 8 # @pytest.mark.parametrize( ('mem_delay','nmul_stages'), [(0,1),(0,4),(5,1),(5,4)] ) def test_mvmult_lane0_row0( dump_vcd, test_verilog, mem_delay, nmul_stages ): lane = 0 run_mvmult_test( dump_vcd, TestHarness( lane, nmul_stages, mem_delay, test_verilog ), lane, # NOTE: C++ has dummy data between rows when you have array**! mem_array_32bit( 0, [ 5, 1 ,3, 99, 1, 1 ,1, 99, 1, 2 ,1] ), mem_array_32bit( 80, [ 1, 2, 3 ]), mem_array_32bit(160, [16, 6, 8 ]), ) @pytest.mark.parametrize( ('mem_delay','nmul_stages'), [(0,1),(0,4),(5,1),(5,4)] ) def test_mvmult_lane0_row2( dump_vcd, test_verilog, mem_delay, nmul_stages ): lane = 0 run_mvmult_test( dump_vcd, TestHarness( lane, nmul_stages, mem_delay, test_verilog ), lane, mem_array_32bit( 0, [ 1, 2, 1] ), mem_array_32bit( 12, [ 1, 2, 3] ), mem_array_32bit( 24, [ 8 ]), ) @pytest.mark.parametrize( ('mem_delay','nmul_stages'), [(0,1),(0,4),(5,1),(5,4)] ) def test_mvmult_lane2_row0( dump_vcd, test_verilog, mem_delay, nmul_stages ): lane = 2 run_mvmult_test( dump_vcd, TestHarness( lane, nmul_stages, mem_delay, test_verilog ), lane, # NOTE: C++ has dummy data between rows when you have array**! mem_array_32bit( 0, [ 5, 1 ,3, 99, 1, 1 ,1, 99, 1, 2 ,1] ), mem_array_32bit( 80, [ 1, 2, 3 ]), mem_array_32bit(160, [ 8 ]), ) @pytest.mark.parametrize( ('mem_delay','nmul_stages'), [(0,1),(0,4),(5,1),(5,4)] ) def test_mvmult_lane1_row0( dump_vcd, test_verilog, mem_delay, nmul_stages ): lane = 1 run_mvmult_test( dump_vcd, TestHarness( lane, nmul_stages, mem_delay, test_verilog ), lane, mem_array_32bit( 0, [ 5, 1 ,3, 99, 1, 1 ,1, 99, 1, 2 ,1] ), mem_array_32bit( 80, [ 1, 2, 3 ]), mem_array_32bit(160, [ 6 ]), ) #------------------------------------------------------------------------------ # LaneManagerHarness #------------------------------------------------------------------------------ class LaneManagerHarness( Model ): def __init__( s, nlanes, nmul_stages, mem_delay, src_delay, config_msgs, test_verilog ): memreq_params = mem_msgs.MemReqParams( 32, 32 ) memresp_params = mem_msgs.MemRespParams( 32 ) s.src = TestSource( 5 + 32, config_msgs, src_delay ) s.mgr = LaneManager( nlanes ) s.lane = [ MatrixVecLaneRTL( x, nmul_stages, memreq_params, memresp_params ) for x in range( nlanes ) ] s.mem = TestMemory( memreq_params, memresp_params, nlanes, mem_delay ) if test_verilog: s.mgr = TranslationTool( s.mgr ) s.lane = [ TranslationTool(x) for x in s.lane ] assert nlanes > 0 s.nlanes = nlanes def elaborate_logic( s ): s.connect( s.src.out, s.mgr.from_cpu ) for i in range( s.nlanes ): s.connect( s.mgr.size, s.lane[i].size ) s.connect( s.mgr.r_baddr, s.lane[i].m_baseaddr ) s.connect( s.mgr.v_baddr, s.lane[i].v_baseaddr ) s.connect( s.mgr.d_baddr, s.lane[i].d_baseaddr ) s.connect( s.mgr.go, s.lane[i].go ) s.connect( s.mgr.done[i], s.lane[i].done ) s.connect( s.lane[i].req , s.mem.reqs [i] ) s.connect( s.lane[i].resp, s.mem.resps[i] ) def done( s ): return s.src.done and s.mgr.from_cpu.rdy def line_trace( s ): #return "{} -> {}".format( s.accel.line_trace(), s.mem.line_trace() ) return "{} () {}".format( s.mgr.line_trace(), s.mem.line_trace() ) #------------------------------------------------------------------------------ # run_lane_managed_test #------------------------------------------------------------------------------ def run_lane_managed_test( dump_vcd, model, src_matrix, src_vector, dest_vector ): model.vcd_file = dump_vcd model.elaborate() sim = SimulationTool( model ) # Load the memory model.mem.load_memory( src_matrix ) model.mem.load_memory( src_vector ) #model.mem.load_memory( dest_vector ) # Run the simulation sim.reset() print while not model.done() and sim.ncycles < 80: sim.print_line_trace() sim.cycle() assert model.done() dest_addr = dest_vector[0] for i, dest_value in enumerate( dest_vector[1] ): assert model.mem.mem.mem[ dest_addr+i ] == dest_value # Add a couple extra ticks so that the VCD dump is nicer sim.cycle() sim.cycle() sim.cycle() #------------------------------------------------------------------------------ # config_msg #------------------------------------------------------------------------------ # Utility method for creating config messages def config_msg( addr, value ): return concat( Bits(3, addr), Bits(32, value) ) @pytest.mark.parametrize( ('mem_delay','nmul_stages'), [(0,1),(0,4),(5,1),(5,4)] ) def test_managed_1lane( dump_vcd, test_verilog, mem_delay, nmul_stages ): run_lane_managed_test( dump_vcd, LaneManagerHarness( 1, nmul_stages, mem_delay, 0, [ config_msg( 1, 3), # size config_msg( 2, 0), # r_addr config_msg( 3, 80), # v_addr config_msg( 4, 160), # d_addr config_msg( 0, 1), # go ], test_verilog ), mem_array_32bit( 0, [ 5, 1 ,3, 99, 1, 1 ,1, 99, 1, 2 ,1] ), mem_array_32bit( 80, [ 1, 2, 3 ]), mem_array_32bit(160, [16]), ) @pytest.mark.parametrize( ('mem_delay','nmul_stages'), [(0,1),(0,4),(5,1),(5,4)] ) def test_managed_3lane( dump_vcd, test_verilog, mem_delay, nmul_stages ): run_lane_managed_test( dump_vcd, LaneManagerHarness( 3, nmul_stages, mem_delay, 0, [ config_msg( 1, 3), # size config_msg( 2, 0), # r_addr config_msg( 3, 80), # v_addr config_msg( 4, 160), # d_addr config_msg( 0, 1), # go ], test_verilog ), mem_array_32bit( 0, [ 5, 1 ,3, 99, 1, 1 ,1, 99, 1, 2 ,1] ), mem_array_32bit( 80, [ 1, 2, 3 ]), mem_array_32bit(160, [16, 6, 8 ]), )
bsd-3-clause
styxit/CouchPotatoServer
libs/html5lib/treebuilders/etree.py
721
12609
from __future__ import absolute_import, division, unicode_literals from six import text_type import re from . import _base from .. import ihatexml from .. import constants from ..constants import namespaces from ..utils import moduleFactoryFactory tag_regexp = re.compile("{([^}]*)}(.*)") def getETreeBuilder(ElementTreeImplementation, fullTree=False): ElementTree = ElementTreeImplementation ElementTreeCommentType = ElementTree.Comment("asd").tag class Element(_base.Node): def __init__(self, name, namespace=None): self._name = name self._namespace = namespace self._element = ElementTree.Element(self._getETreeTag(name, namespace)) if namespace is None: self.nameTuple = namespaces["html"], self._name else: self.nameTuple = self._namespace, self._name self.parent = None self._childNodes = [] self._flags = [] def _getETreeTag(self, name, namespace): if namespace is None: etree_tag = name else: etree_tag = "{%s}%s" % (namespace, name) return etree_tag def _setName(self, name): self._name = name self._element.tag = self._getETreeTag(self._name, self._namespace) def _getName(self): return self._name name = property(_getName, _setName) def _setNamespace(self, namespace): self._namespace = namespace self._element.tag = self._getETreeTag(self._name, self._namespace) def _getNamespace(self): return self._namespace namespace = property(_getNamespace, _setNamespace) def _getAttributes(self): return self._element.attrib def _setAttributes(self, attributes): # Delete existing attributes first # XXX - there may be a better way to do this... for key in list(self._element.attrib.keys()): del self._element.attrib[key] for key, value in attributes.items(): if isinstance(key, tuple): name = "{%s}%s" % (key[2], key[1]) else: name = key self._element.set(name, value) attributes = property(_getAttributes, _setAttributes) def _getChildNodes(self): return self._childNodes def _setChildNodes(self, value): del self._element[:] self._childNodes = [] for element in value: self.insertChild(element) childNodes = property(_getChildNodes, _setChildNodes) def hasContent(self): """Return true if the node has children or text""" return bool(self._element.text or len(self._element)) def appendChild(self, node): self._childNodes.append(node) self._element.append(node._element) node.parent = self def insertBefore(self, node, refNode): index = list(self._element).index(refNode._element) self._element.insert(index, node._element) node.parent = self def removeChild(self, node): self._element.remove(node._element) node.parent = None def insertText(self, data, insertBefore=None): if not(len(self._element)): if not self._element.text: self._element.text = "" self._element.text += data elif insertBefore is None: # Insert the text as the tail of the last child element if not self._element[-1].tail: self._element[-1].tail = "" self._element[-1].tail += data else: # Insert the text before the specified node children = list(self._element) index = children.index(insertBefore._element) if index > 0: if not self._element[index - 1].tail: self._element[index - 1].tail = "" self._element[index - 1].tail += data else: if not self._element.text: self._element.text = "" self._element.text += data def cloneNode(self): element = type(self)(self.name, self.namespace) for name, value in self.attributes.items(): element.attributes[name] = value return element def reparentChildren(self, newParent): if newParent.childNodes: newParent.childNodes[-1]._element.tail += self._element.text else: if not newParent._element.text: newParent._element.text = "" if self._element.text is not None: newParent._element.text += self._element.text self._element.text = "" _base.Node.reparentChildren(self, newParent) class Comment(Element): def __init__(self, data): # Use the superclass constructor to set all properties on the # wrapper element self._element = ElementTree.Comment(data) self.parent = None self._childNodes = [] self._flags = [] def _getData(self): return self._element.text def _setData(self, value): self._element.text = value data = property(_getData, _setData) class DocumentType(Element): def __init__(self, name, publicId, systemId): Element.__init__(self, "<!DOCTYPE>") self._element.text = name self.publicId = publicId self.systemId = systemId def _getPublicId(self): return self._element.get("publicId", "") def _setPublicId(self, value): if value is not None: self._element.set("publicId", value) publicId = property(_getPublicId, _setPublicId) def _getSystemId(self): return self._element.get("systemId", "") def _setSystemId(self, value): if value is not None: self._element.set("systemId", value) systemId = property(_getSystemId, _setSystemId) class Document(Element): def __init__(self): Element.__init__(self, "DOCUMENT_ROOT") class DocumentFragment(Element): def __init__(self): Element.__init__(self, "DOCUMENT_FRAGMENT") def testSerializer(element): rv = [] def serializeElement(element, indent=0): if not(hasattr(element, "tag")): element = element.getroot() if element.tag == "<!DOCTYPE>": if element.get("publicId") or element.get("systemId"): publicId = element.get("publicId") or "" systemId = element.get("systemId") or "" rv.append("""<!DOCTYPE %s "%s" "%s">""" % (element.text, publicId, systemId)) else: rv.append("<!DOCTYPE %s>" % (element.text,)) elif element.tag == "DOCUMENT_ROOT": rv.append("#document") if element.text is not None: rv.append("|%s\"%s\"" % (' ' * (indent + 2), element.text)) if element.tail is not None: raise TypeError("Document node cannot have tail") if hasattr(element, "attrib") and len(element.attrib): raise TypeError("Document node cannot have attributes") elif element.tag == ElementTreeCommentType: rv.append("|%s<!-- %s -->" % (' ' * indent, element.text)) else: assert isinstance(element.tag, text_type), \ "Expected unicode, got %s, %s" % (type(element.tag), element.tag) nsmatch = tag_regexp.match(element.tag) if nsmatch is None: name = element.tag else: ns, name = nsmatch.groups() prefix = constants.prefixes[ns] name = "%s %s" % (prefix, name) rv.append("|%s<%s>" % (' ' * indent, name)) if hasattr(element, "attrib"): attributes = [] for name, value in element.attrib.items(): nsmatch = tag_regexp.match(name) if nsmatch is not None: ns, name = nsmatch.groups() prefix = constants.prefixes[ns] attr_string = "%s %s" % (prefix, name) else: attr_string = name attributes.append((attr_string, value)) for name, value in sorted(attributes): rv.append('|%s%s="%s"' % (' ' * (indent + 2), name, value)) if element.text: rv.append("|%s\"%s\"" % (' ' * (indent + 2), element.text)) indent += 2 for child in element: serializeElement(child, indent) if element.tail: rv.append("|%s\"%s\"" % (' ' * (indent - 2), element.tail)) serializeElement(element, 0) return "\n".join(rv) def tostring(element): """Serialize an element and its child nodes to a string""" rv = [] filter = ihatexml.InfosetFilter() def serializeElement(element): if isinstance(element, ElementTree.ElementTree): element = element.getroot() if element.tag == "<!DOCTYPE>": if element.get("publicId") or element.get("systemId"): publicId = element.get("publicId") or "" systemId = element.get("systemId") or "" rv.append("""<!DOCTYPE %s PUBLIC "%s" "%s">""" % (element.text, publicId, systemId)) else: rv.append("<!DOCTYPE %s>" % (element.text,)) elif element.tag == "DOCUMENT_ROOT": if element.text is not None: rv.append(element.text) if element.tail is not None: raise TypeError("Document node cannot have tail") if hasattr(element, "attrib") and len(element.attrib): raise TypeError("Document node cannot have attributes") for child in element: serializeElement(child) elif element.tag == ElementTreeCommentType: rv.append("<!--%s-->" % (element.text,)) else: # This is assumed to be an ordinary element if not element.attrib: rv.append("<%s>" % (filter.fromXmlName(element.tag),)) else: attr = " ".join(["%s=\"%s\"" % ( filter.fromXmlName(name), value) for name, value in element.attrib.items()]) rv.append("<%s %s>" % (element.tag, attr)) if element.text: rv.append(element.text) for child in element: serializeElement(child) rv.append("</%s>" % (element.tag,)) if element.tail: rv.append(element.tail) serializeElement(element) return "".join(rv) class TreeBuilder(_base.TreeBuilder): documentClass = Document doctypeClass = DocumentType elementClass = Element commentClass = Comment fragmentClass = DocumentFragment implementation = ElementTreeImplementation def testSerializer(self, element): return testSerializer(element) def getDocument(self): if fullTree: return self.document._element else: if self.defaultNamespace is not None: return self.document._element.find( "{%s}html" % self.defaultNamespace) else: return self.document._element.find("html") def getFragment(self): return _base.TreeBuilder.getFragment(self)._element return locals() getETreeModule = moduleFactoryFactory(getETreeBuilder)
gpl-3.0
gnuhub/intellij-community
python/lib/Lib/site-packages/django/contrib/gis/tests/layermap/tests.py
78
12254
import os from decimal import Decimal from django.utils.copycompat import copy from django.utils.unittest import TestCase from django.contrib.gis.gdal import DataSource from django.contrib.gis.tests.utils import mysql from django.contrib.gis.utils.layermapping import LayerMapping, LayerMapError, InvalidDecimal, MissingForeignKey from models import City, County, CountyFeat, Interstate, ICity1, ICity2, State, city_mapping, co_mapping, cofeat_mapping, inter_mapping shp_path = os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'data')) city_shp = os.path.join(shp_path, 'cities', 'cities.shp') co_shp = os.path.join(shp_path, 'counties', 'counties.shp') inter_shp = os.path.join(shp_path, 'interstates', 'interstates.shp') # Dictionaries to hold what's expected in the county shapefile. NAMES = ['Bexar', 'Galveston', 'Harris', 'Honolulu', 'Pueblo'] NUMS = [1, 2, 1, 19, 1] # Number of polygons for each. STATES = ['Texas', 'Texas', 'Texas', 'Hawaii', 'Colorado'] class LayerMapTest(TestCase): def test01_init(self): "Testing LayerMapping initialization." # Model field that does not exist. bad1 = copy(city_mapping) bad1['foobar'] = 'FooField' # Shapefile field that does not exist. bad2 = copy(city_mapping) bad2['name'] = 'Nombre' # Nonexistent geographic field type. bad3 = copy(city_mapping) bad3['point'] = 'CURVE' # Incrementing through the bad mapping dictionaries and # ensuring that a LayerMapError is raised. for bad_map in (bad1, bad2, bad3): try: lm = LayerMapping(City, city_shp, bad_map) except LayerMapError: pass else: self.fail('Expected a LayerMapError.') # A LookupError should be thrown for bogus encodings. try: lm = LayerMapping(City, city_shp, city_mapping, encoding='foobar') except LookupError: pass else: self.fail('Expected a LookupError') def test02_simple_layermap(self): "Test LayerMapping import of a simple point shapefile." # Setting up for the LayerMapping. lm = LayerMapping(City, city_shp, city_mapping) lm.save() # There should be three cities in the shape file. self.assertEqual(3, City.objects.count()) # Opening up the shapefile, and verifying the values in each # of the features made it to the model. ds = DataSource(city_shp) layer = ds[0] for feat in layer: city = City.objects.get(name=feat['Name'].value) self.assertEqual(feat['Population'].value, city.population) self.assertEqual(Decimal(str(feat['Density'])), city.density) self.assertEqual(feat['Created'].value, city.dt) # Comparing the geometries. pnt1, pnt2 = feat.geom, city.point self.assertAlmostEqual(pnt1.x, pnt2.x, 6) self.assertAlmostEqual(pnt1.y, pnt2.y, 6) def test03_layermap_strict(self): "Testing the `strict` keyword, and import of a LineString shapefile." # When the `strict` keyword is set an error encountered will force # the importation to stop. try: lm = LayerMapping(Interstate, inter_shp, inter_mapping) lm.save(silent=True, strict=True) except InvalidDecimal: # No transactions for geoms on MySQL; delete added features. if mysql: Interstate.objects.all().delete() else: self.fail('Should have failed on strict import with invalid decimal values.') # This LayerMapping should work b/c `strict` is not set. lm = LayerMapping(Interstate, inter_shp, inter_mapping) lm.save(silent=True) # Two interstate should have imported correctly. self.assertEqual(2, Interstate.objects.count()) # Verifying the values in the layer w/the model. ds = DataSource(inter_shp) # Only the first two features of this shapefile are valid. valid_feats = ds[0][:2] for feat in valid_feats: istate = Interstate.objects.get(name=feat['Name'].value) if feat.fid == 0: self.assertEqual(Decimal(str(feat['Length'])), istate.length) elif feat.fid == 1: # Everything but the first two decimal digits were truncated, # because the Interstate model's `length` field has decimal_places=2. self.assertAlmostEqual(feat.get('Length'), float(istate.length), 2) for p1, p2 in zip(feat.geom, istate.path): self.assertAlmostEqual(p1[0], p2[0], 6) self.assertAlmostEqual(p1[1], p2[1], 6) def county_helper(self, county_feat=True): "Helper function for ensuring the integrity of the mapped County models." for name, n, st in zip(NAMES, NUMS, STATES): # Should only be one record b/c of `unique` keyword. c = County.objects.get(name=name) self.assertEqual(n, len(c.mpoly)) self.assertEqual(st, c.state.name) # Checking ForeignKey mapping. # Multiple records because `unique` was not set. if county_feat: qs = CountyFeat.objects.filter(name=name) self.assertEqual(n, qs.count()) def test04_layermap_unique_multigeometry_fk(self): "Testing the `unique`, and `transform`, geometry collection conversion, and ForeignKey mappings." # All the following should work. try: # Telling LayerMapping that we want no transformations performed on the data. lm = LayerMapping(County, co_shp, co_mapping, transform=False) # Specifying the source spatial reference system via the `source_srs` keyword. lm = LayerMapping(County, co_shp, co_mapping, source_srs=4269) lm = LayerMapping(County, co_shp, co_mapping, source_srs='NAD83') # Unique may take tuple or string parameters. for arg in ('name', ('name', 'mpoly')): lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique=arg) except: self.fail('No exception should be raised for proper use of keywords.') # Testing invalid params for the `unique` keyword. for e, arg in ((TypeError, 5.0), (ValueError, 'foobar'), (ValueError, ('name', 'mpolygon'))): self.assertRaises(e, LayerMapping, County, co_shp, co_mapping, transform=False, unique=arg) # No source reference system defined in the shapefile, should raise an error. if not mysql: self.assertRaises(LayerMapError, LayerMapping, County, co_shp, co_mapping) # Passing in invalid ForeignKey mapping parameters -- must be a dictionary # mapping for the model the ForeignKey points to. bad_fk_map1 = copy(co_mapping); bad_fk_map1['state'] = 'name' bad_fk_map2 = copy(co_mapping); bad_fk_map2['state'] = {'nombre' : 'State'} self.assertRaises(TypeError, LayerMapping, County, co_shp, bad_fk_map1, transform=False) self.assertRaises(LayerMapError, LayerMapping, County, co_shp, bad_fk_map2, transform=False) # There exist no State models for the ForeignKey mapping to work -- should raise # a MissingForeignKey exception (this error would be ignored if the `strict` # keyword is not set). lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name') self.assertRaises(MissingForeignKey, lm.save, silent=True, strict=True) # Now creating the state models so the ForeignKey mapping may work. co, hi, tx = State(name='Colorado'), State(name='Hawaii'), State(name='Texas') co.save(), hi.save(), tx.save() # If a mapping is specified as a collection, all OGR fields that # are not collections will be converted into them. For example, # a Point column would be converted to MultiPoint. Other things being done # w/the keyword args: # `transform=False`: Specifies that no transform is to be done; this # has the effect of ignoring the spatial reference check (because the # county shapefile does not have implicit spatial reference info). # # `unique='name'`: Creates models on the condition that they have # unique county names; geometries from each feature however will be # appended to the geometry collection of the unique model. Thus, # all of the various islands in Honolulu county will be in in one # database record with a MULTIPOLYGON type. lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name') lm.save(silent=True, strict=True) # A reference that doesn't use the unique keyword; a new database record will # created for each polygon. lm = LayerMapping(CountyFeat, co_shp, cofeat_mapping, transform=False) lm.save(silent=True, strict=True) # The county helper is called to ensure integrity of County models. self.county_helper() def test05_test_fid_range_step(self): "Tests the `fid_range` keyword and the `step` keyword of .save()." # Function for clearing out all the counties before testing. def clear_counties(): County.objects.all().delete() # Initializing the LayerMapping object to use in these tests. lm = LayerMapping(County, co_shp, co_mapping, transform=False, unique='name') # Bad feature id ranges should raise a type error. clear_counties() bad_ranges = (5.0, 'foo', co_shp) for bad in bad_ranges: self.assertRaises(TypeError, lm.save, fid_range=bad) # Step keyword should not be allowed w/`fid_range`. fr = (3, 5) # layer[3:5] self.assertRaises(LayerMapError, lm.save, fid_range=fr, step=10) lm.save(fid_range=fr) # Features IDs 3 & 4 are for Galveston County, Texas -- only # one model is returned because the `unique` keyword was set. qs = County.objects.all() self.assertEqual(1, qs.count()) self.assertEqual('Galveston', qs[0].name) # Features IDs 5 and beyond for Honolulu County, Hawaii, and # FID 0 is for Pueblo County, Colorado. clear_counties() lm.save(fid_range=slice(5, None), silent=True, strict=True) # layer[5:] lm.save(fid_range=slice(None, 1), silent=True, strict=True) # layer[:1] # Only Pueblo & Honolulu counties should be present because of # the `unique` keyword. Have to set `order_by` on this QuerySet # or else MySQL will return a different ordering than the other dbs. qs = County.objects.order_by('name') self.assertEqual(2, qs.count()) hi, co = tuple(qs) hi_idx, co_idx = tuple(map(NAMES.index, ('Honolulu', 'Pueblo'))) self.assertEqual('Pueblo', co.name); self.assertEqual(NUMS[co_idx], len(co.mpoly)) self.assertEqual('Honolulu', hi.name); self.assertEqual(NUMS[hi_idx], len(hi.mpoly)) # Testing the `step` keyword -- should get the same counties # regardless of we use a step that divides equally, that is odd, # or that is larger than the dataset. for st in (4,7,1000): clear_counties() lm.save(step=st, strict=True) self.county_helper(county_feat=False) def test06_model_inheritance(self): "Tests LayerMapping on inherited models. See #12093." icity_mapping = {'name' : 'Name', 'population' : 'Population', 'density' : 'Density', 'point' : 'POINT', 'dt' : 'Created', } # Parent model has geometry field. lm1 = LayerMapping(ICity1, city_shp, icity_mapping) lm1.save() # Grandparent has geometry field. lm2 = LayerMapping(ICity2, city_shp, icity_mapping) lm2.save() self.assertEqual(6, ICity1.objects.count()) self.assertEqual(3, ICity2.objects.count())
apache-2.0
bowang/tensorflow
tensorflow/contrib/data/__init__.py
3
2402
# Copyright 2017 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. # ============================================================================== """`tf.contrib.data.Dataset` API for input pipelines. @@Dataset @@Iterator @@TFRecordDataset @@FixedLengthRecordDataset @@TextLineDataset @@batch_and_drop_remainder @@dense_to_sparse_batch @@enumerate_dataset @@group_by_window @@ignore_errors @@read_batch_features @@unbatch @@rejection_resample @@sloppy_interleave """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # pylint: disable=unused-import from tensorflow.contrib.data.python.ops.dataset_ops import batch_and_drop_remainder from tensorflow.contrib.data.python.ops.dataset_ops import Dataset from tensorflow.contrib.data.python.ops.dataset_ops import dense_to_sparse_batch from tensorflow.contrib.data.python.ops.dataset_ops import enumerate_dataset from tensorflow.contrib.data.python.ops.dataset_ops import FixedLengthRecordDataset from tensorflow.contrib.data.python.ops.dataset_ops import group_by_window from tensorflow.contrib.data.python.ops.dataset_ops import ignore_errors from tensorflow.contrib.data.python.ops.dataset_ops import read_batch_features from tensorflow.contrib.data.python.ops.dataset_ops import rejection_resample from tensorflow.contrib.data.python.ops.dataset_ops import SqlDataset from tensorflow.contrib.data.python.ops.dataset_ops import TextLineDataset from tensorflow.contrib.data.python.ops.dataset_ops import TFRecordDataset from tensorflow.contrib.data.python.ops.dataset_ops import unbatch from tensorflow.contrib.data.python.ops.sloppy_ops import sloppy_interleave from tensorflow.python.data.ops.dataset_ops import Iterator # pylint: enable=unused-import from tensorflow.python.util.all_util import remove_undocumented remove_undocumented(__name__)
apache-2.0
jeffreymingyue/ansible
v1/ansible/cache/memcached.py
132
5890
# (c) 2014, Brian Coca, Josh Drake, et al # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. import collections import os import sys import time import threading from itertools import chain from ansible import constants as C from ansible.cache.base import BaseCacheModule try: import memcache except ImportError: print 'python-memcached is required for the memcached fact cache' sys.exit(1) class ProxyClientPool(object): """ Memcached connection pooling for thread/fork safety. Inspired by py-redis connection pool. Available connections are maintained in a deque and released in a FIFO manner. """ def __init__(self, *args, **kwargs): self.max_connections = kwargs.pop('max_connections', 1024) self.connection_args = args self.connection_kwargs = kwargs self.reset() def reset(self): self.pid = os.getpid() self._num_connections = 0 self._available_connections = collections.deque(maxlen=self.max_connections) self._locked_connections = set() self._lock = threading.Lock() def _check_safe(self): if self.pid != os.getpid(): with self._lock: if self.pid == os.getpid(): # bail out - another thread already acquired the lock return self.disconnect_all() self.reset() def get_connection(self): self._check_safe() try: connection = self._available_connections.popleft() except IndexError: connection = self.create_connection() self._locked_connections.add(connection) return connection def create_connection(self): if self._num_connections >= self.max_connections: raise RuntimeError("Too many memcached connections") self._num_connections += 1 return memcache.Client(*self.connection_args, **self.connection_kwargs) def release_connection(self, connection): self._check_safe() self._locked_connections.remove(connection) self._available_connections.append(connection) def disconnect_all(self): for conn in chain(self._available_connections, self._locked_connections): conn.disconnect_all() def __getattr__(self, name): def wrapped(*args, **kwargs): return self._proxy_client(name, *args, **kwargs) return wrapped def _proxy_client(self, name, *args, **kwargs): conn = self.get_connection() try: return getattr(conn, name)(*args, **kwargs) finally: self.release_connection(conn) class CacheModuleKeys(collections.MutableSet): """ A set subclass that keeps track of insertion time and persists the set in memcached. """ PREFIX = 'ansible_cache_keys' def __init__(self, cache, *args, **kwargs): self._cache = cache self._keyset = dict(*args, **kwargs) def __contains__(self, key): return key in self._keyset def __iter__(self): return iter(self._keyset) def __len__(self): return len(self._keyset) def add(self, key): self._keyset[key] = time.time() self._cache.set(self.PREFIX, self._keyset) def discard(self, key): del self._keyset[key] self._cache.set(self.PREFIX, self._keyset) def remove_by_timerange(self, s_min, s_max): for k in self._keyset.keys(): t = self._keyset[k] if s_min < t < s_max: del self._keyset[k] self._cache.set(self.PREFIX, self._keyset) class CacheModule(BaseCacheModule): def __init__(self, *args, **kwargs): if C.CACHE_PLUGIN_CONNECTION: connection = C.CACHE_PLUGIN_CONNECTION.split(',') else: connection = ['127.0.0.1:11211'] self._timeout = C.CACHE_PLUGIN_TIMEOUT self._prefix = C.CACHE_PLUGIN_PREFIX self._cache = ProxyClientPool(connection, debug=0) self._keys = CacheModuleKeys(self._cache, self._cache.get(CacheModuleKeys.PREFIX) or []) def _make_key(self, key): return "{0}{1}".format(self._prefix, key) def _expire_keys(self): if self._timeout > 0: expiry_age = time.time() - self._timeout self._keys.remove_by_timerange(0, expiry_age) def get(self, key): value = self._cache.get(self._make_key(key)) # guard against the key not being removed from the keyset; # this could happen in cases where the timeout value is changed # between invocations if value is None: self.delete(key) raise KeyError return value def set(self, key, value): self._cache.set(self._make_key(key), value, time=self._timeout, min_compress_len=1) self._keys.add(key) def keys(self): self._expire_keys() return list(iter(self._keys)) def contains(self, key): self._expire_keys() return key in self._keys def delete(self, key): self._cache.delete(self._make_key(key)) self._keys.discard(key) def flush(self): for key in self.keys(): self.delete(key) def copy(self): return self._keys.copy()
gpl-3.0
wreckJ/intellij-community
python/lib/Lib/site-packages/django/utils/importlib.py
445
1229
# Taken from Python 2.7 with permission from/by the original author. import sys def _resolve_name(name, package, level): """Return the absolute name of the module to be imported.""" if not hasattr(package, 'rindex'): raise ValueError("'package' not set to a string") dot = len(package) for x in xrange(level, 1, -1): try: dot = package.rindex('.', 0, dot) except ValueError: raise ValueError("attempted relative import beyond top-level " "package") return "%s.%s" % (package[:dot], name) def import_module(name, package=None): """Import a module. The 'package' argument is required when performing a relative import. It specifies the package to use as the anchor point from which to resolve the relative import to an absolute import. """ if name.startswith('.'): if not package: raise TypeError("relative imports require the 'package' argument") level = 0 for character in name: if character != '.': break level += 1 name = _resolve_name(name[level:], package, level) __import__(name) return sys.modules[name]
apache-2.0
Kubuxu/cjdns
node_build/dependencies/libuv/build/gyp/pylib/gyp/generator/eclipse.py
1825
17014
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """GYP backend that generates Eclipse CDT settings files. This backend DOES NOT generate Eclipse CDT projects. Instead, it generates XML files that can be imported into an Eclipse CDT project. The XML file contains a list of include paths and symbols (i.e. defines). Because a full .cproject definition is not created by this generator, it's not possible to properly define the include dirs and symbols for each file individually. Instead, one set of includes/symbols is generated for the entire project. This works fairly well (and is a vast improvement in general), but may still result in a few indexer issues here and there. This generator has no automated tests, so expect it to be broken. """ from xml.sax.saxutils import escape import os.path import subprocess import gyp import gyp.common import gyp.msvs_emulation import shlex import xml.etree.cElementTree as ET generator_wants_static_library_dependencies_adjusted = False generator_default_variables = { } for dirname in ['INTERMEDIATE_DIR', 'PRODUCT_DIR', 'LIB_DIR', 'SHARED_LIB_DIR']: # Some gyp steps fail if these are empty(!), so we convert them to variables generator_default_variables[dirname] = '$' + dirname for unused in ['RULE_INPUT_PATH', 'RULE_INPUT_ROOT', 'RULE_INPUT_NAME', 'RULE_INPUT_DIRNAME', 'RULE_INPUT_EXT', 'EXECUTABLE_PREFIX', 'EXECUTABLE_SUFFIX', 'STATIC_LIB_PREFIX', 'STATIC_LIB_SUFFIX', 'SHARED_LIB_PREFIX', 'SHARED_LIB_SUFFIX', 'CONFIGURATION_NAME']: generator_default_variables[unused] = '' # Include dirs will occasionally use the SHARED_INTERMEDIATE_DIR variable as # part of the path when dealing with generated headers. This value will be # replaced dynamically for each configuration. generator_default_variables['SHARED_INTERMEDIATE_DIR'] = \ '$SHARED_INTERMEDIATE_DIR' def CalculateVariables(default_variables, params): generator_flags = params.get('generator_flags', {}) for key, val in generator_flags.items(): default_variables.setdefault(key, val) flavor = gyp.common.GetFlavor(params) default_variables.setdefault('OS', flavor) if flavor == 'win': # Copy additional generator configuration data from VS, which is shared # by the Eclipse generator. import gyp.generator.msvs as msvs_generator generator_additional_non_configuration_keys = getattr(msvs_generator, 'generator_additional_non_configuration_keys', []) generator_additional_path_sections = getattr(msvs_generator, 'generator_additional_path_sections', []) gyp.msvs_emulation.CalculateCommonVariables(default_variables, params) def CalculateGeneratorInputInfo(params): """Calculate the generator specific info that gets fed to input (called by gyp).""" generator_flags = params.get('generator_flags', {}) if generator_flags.get('adjust_static_libraries', False): global generator_wants_static_library_dependencies_adjusted generator_wants_static_library_dependencies_adjusted = True def GetAllIncludeDirectories(target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path): """Calculate the set of include directories to be used. Returns: A list including all the include_dir's specified for every target followed by any include directories that were added as cflag compiler options. """ gyp_includes_set = set() compiler_includes_list = [] # Find compiler's default include dirs. if compiler_path: command = shlex.split(compiler_path) command.extend(['-E', '-xc++', '-v', '-']) proc = subprocess.Popen(args=command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output = proc.communicate()[1] # Extract the list of include dirs from the output, which has this format: # ... # #include "..." search starts here: # #include <...> search starts here: # /usr/include/c++/4.6 # /usr/local/include # End of search list. # ... in_include_list = False for line in output.splitlines(): if line.startswith('#include'): in_include_list = True continue if line.startswith('End of search list.'): break if in_include_list: include_dir = line.strip() if include_dir not in compiler_includes_list: compiler_includes_list.append(include_dir) flavor = gyp.common.GetFlavor(params) if flavor == 'win': generator_flags = params.get('generator_flags', {}) for target_name in target_list: target = target_dicts[target_name] if config_name in target['configurations']: config = target['configurations'][config_name] # Look for any include dirs that were explicitly added via cflags. This # may be done in gyp files to force certain includes to come at the end. # TODO(jgreenwald): Change the gyp files to not abuse cflags for this, and # remove this. if flavor == 'win': msvs_settings = gyp.msvs_emulation.MsvsSettings(target, generator_flags) cflags = msvs_settings.GetCflags(config_name) else: cflags = config['cflags'] for cflag in cflags: if cflag.startswith('-I'): include_dir = cflag[2:] if include_dir not in compiler_includes_list: compiler_includes_list.append(include_dir) # Find standard gyp include dirs. if config.has_key('include_dirs'): include_dirs = config['include_dirs'] for shared_intermediate_dir in shared_intermediate_dirs: for include_dir in include_dirs: include_dir = include_dir.replace('$SHARED_INTERMEDIATE_DIR', shared_intermediate_dir) if not os.path.isabs(include_dir): base_dir = os.path.dirname(target_name) include_dir = base_dir + '/' + include_dir include_dir = os.path.abspath(include_dir) gyp_includes_set.add(include_dir) # Generate a list that has all the include dirs. all_includes_list = list(gyp_includes_set) all_includes_list.sort() for compiler_include in compiler_includes_list: if not compiler_include in gyp_includes_set: all_includes_list.append(compiler_include) # All done. return all_includes_list def GetCompilerPath(target_list, data, options): """Determine a command that can be used to invoke the compiler. Returns: If this is a gyp project that has explicit make settings, try to determine the compiler from that. Otherwise, see if a compiler was specified via the CC_target environment variable. """ # First, see if the compiler is configured in make's settings. build_file, _, _ = gyp.common.ParseQualifiedTarget(target_list[0]) make_global_settings_dict = data[build_file].get('make_global_settings', {}) for key, value in make_global_settings_dict: if key in ['CC', 'CXX']: return os.path.join(options.toplevel_dir, value) # Check to see if the compiler was specified as an environment variable. for key in ['CC_target', 'CC', 'CXX']: compiler = os.environ.get(key) if compiler: return compiler return 'gcc' def GetAllDefines(target_list, target_dicts, data, config_name, params, compiler_path): """Calculate the defines for a project. Returns: A dict that includes explict defines declared in gyp files along with all of the default defines that the compiler uses. """ # Get defines declared in the gyp files. all_defines = {} flavor = gyp.common.GetFlavor(params) if flavor == 'win': generator_flags = params.get('generator_flags', {}) for target_name in target_list: target = target_dicts[target_name] if flavor == 'win': msvs_settings = gyp.msvs_emulation.MsvsSettings(target, generator_flags) extra_defines = msvs_settings.GetComputedDefines(config_name) else: extra_defines = [] if config_name in target['configurations']: config = target['configurations'][config_name] target_defines = config['defines'] else: target_defines = [] for define in target_defines + extra_defines: split_define = define.split('=', 1) if len(split_define) == 1: split_define.append('1') if split_define[0].strip() in all_defines: # Already defined continue all_defines[split_define[0].strip()] = split_define[1].strip() # Get default compiler defines (if possible). if flavor == 'win': return all_defines # Default defines already processed in the loop above. if compiler_path: command = shlex.split(compiler_path) command.extend(['-E', '-dM', '-']) cpp_proc = subprocess.Popen(args=command, cwd='.', stdin=subprocess.PIPE, stdout=subprocess.PIPE) cpp_output = cpp_proc.communicate()[0] cpp_lines = cpp_output.split('\n') for cpp_line in cpp_lines: if not cpp_line.strip(): continue cpp_line_parts = cpp_line.split(' ', 2) key = cpp_line_parts[1] if len(cpp_line_parts) >= 3: val = cpp_line_parts[2] else: val = '1' all_defines[key] = val return all_defines def WriteIncludePaths(out, eclipse_langs, include_dirs): """Write the includes section of a CDT settings export file.""" out.write(' <section name="org.eclipse.cdt.internal.ui.wizards.' \ 'settingswizards.IncludePaths">\n') out.write(' <language name="holder for library settings"></language>\n') for lang in eclipse_langs: out.write(' <language name="%s">\n' % lang) for include_dir in include_dirs: out.write(' <includepath workspace_path="false">%s</includepath>\n' % include_dir) out.write(' </language>\n') out.write(' </section>\n') def WriteMacros(out, eclipse_langs, defines): """Write the macros section of a CDT settings export file.""" out.write(' <section name="org.eclipse.cdt.internal.ui.wizards.' \ 'settingswizards.Macros">\n') out.write(' <language name="holder for library settings"></language>\n') for lang in eclipse_langs: out.write(' <language name="%s">\n' % lang) for key in sorted(defines.iterkeys()): out.write(' <macro><name>%s</name><value>%s</value></macro>\n' % (escape(key), escape(defines[key]))) out.write(' </language>\n') out.write(' </section>\n') def GenerateOutputForConfig(target_list, target_dicts, data, params, config_name): options = params['options'] generator_flags = params.get('generator_flags', {}) # build_dir: relative path from source root to our output files. # e.g. "out/Debug" build_dir = os.path.join(generator_flags.get('output_dir', 'out'), config_name) toplevel_build = os.path.join(options.toplevel_dir, build_dir) # Ninja uses out/Debug/gen while make uses out/Debug/obj/gen as the # SHARED_INTERMEDIATE_DIR. Include both possible locations. shared_intermediate_dirs = [os.path.join(toplevel_build, 'obj', 'gen'), os.path.join(toplevel_build, 'gen')] GenerateCdtSettingsFile(target_list, target_dicts, data, params, config_name, os.path.join(toplevel_build, 'eclipse-cdt-settings.xml'), options, shared_intermediate_dirs) GenerateClasspathFile(target_list, target_dicts, options.toplevel_dir, toplevel_build, os.path.join(toplevel_build, 'eclipse-classpath.xml')) def GenerateCdtSettingsFile(target_list, target_dicts, data, params, config_name, out_name, options, shared_intermediate_dirs): gyp.common.EnsureDirExists(out_name) with open(out_name, 'w') as out: out.write('<?xml version="1.0" encoding="UTF-8"?>\n') out.write('<cdtprojectproperties>\n') eclipse_langs = ['C++ Source File', 'C Source File', 'Assembly Source File', 'GNU C++', 'GNU C', 'Assembly'] compiler_path = GetCompilerPath(target_list, data, options) include_dirs = GetAllIncludeDirectories(target_list, target_dicts, shared_intermediate_dirs, config_name, params, compiler_path) WriteIncludePaths(out, eclipse_langs, include_dirs) defines = GetAllDefines(target_list, target_dicts, data, config_name, params, compiler_path) WriteMacros(out, eclipse_langs, defines) out.write('</cdtprojectproperties>\n') def GenerateClasspathFile(target_list, target_dicts, toplevel_dir, toplevel_build, out_name): '''Generates a classpath file suitable for symbol navigation and code completion of Java code (such as in Android projects) by finding all .java and .jar files used as action inputs.''' gyp.common.EnsureDirExists(out_name) result = ET.Element('classpath') def AddElements(kind, paths): # First, we need to normalize the paths so they are all relative to the # toplevel dir. rel_paths = set() for path in paths: if os.path.isabs(path): rel_paths.add(os.path.relpath(path, toplevel_dir)) else: rel_paths.add(path) for path in sorted(rel_paths): entry_element = ET.SubElement(result, 'classpathentry') entry_element.set('kind', kind) entry_element.set('path', path) AddElements('lib', GetJavaJars(target_list, target_dicts, toplevel_dir)) AddElements('src', GetJavaSourceDirs(target_list, target_dicts, toplevel_dir)) # Include the standard JRE container and a dummy out folder AddElements('con', ['org.eclipse.jdt.launching.JRE_CONTAINER']) # Include a dummy out folder so that Eclipse doesn't use the default /bin # folder in the root of the project. AddElements('output', [os.path.join(toplevel_build, '.eclipse-java-build')]) ET.ElementTree(result).write(out_name) def GetJavaJars(target_list, target_dicts, toplevel_dir): '''Generates a sequence of all .jars used as inputs.''' for target_name in target_list: target = target_dicts[target_name] for action in target.get('actions', []): for input_ in action['inputs']: if os.path.splitext(input_)[1] == '.jar' and not input_.startswith('$'): if os.path.isabs(input_): yield input_ else: yield os.path.join(os.path.dirname(target_name), input_) def GetJavaSourceDirs(target_list, target_dicts, toplevel_dir): '''Generates a sequence of all likely java package root directories.''' for target_name in target_list: target = target_dicts[target_name] for action in target.get('actions', []): for input_ in action['inputs']: if (os.path.splitext(input_)[1] == '.java' and not input_.startswith('$')): dir_ = os.path.dirname(os.path.join(os.path.dirname(target_name), input_)) # If there is a parent 'src' or 'java' folder, navigate up to it - # these are canonical package root names in Chromium. This will # break if 'src' or 'java' exists in the package structure. This # could be further improved by inspecting the java file for the # package name if this proves to be too fragile in practice. parent_search = dir_ while os.path.basename(parent_search) not in ['src', 'java']: parent_search, _ = os.path.split(parent_search) if not parent_search or parent_search == toplevel_dir: # Didn't find a known root, just return the original path yield dir_ break else: yield parent_search def GenerateOutput(target_list, target_dicts, data, params): """Generate an XML settings file that can be imported into a CDT project.""" if params['options'].generator_output: raise NotImplementedError("--generator_output not implemented for eclipse") user_config = params.get('generator_flags', {}).get('config', None) if user_config: GenerateOutputForConfig(target_list, target_dicts, data, params, user_config) else: config_names = target_dicts[target_list[0]]['configurations'].keys() for config_name in config_names: GenerateOutputForConfig(target_list, target_dicts, data, params, config_name)
gpl-3.0
zhaochao/fuel-main
fuelweb_test/tests/test_services.py
4
36313
# Copyright 2013 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import division from devops.helpers.helpers import wait from proboscis import asserts from proboscis import SkipTest from proboscis import test from proboscis.asserts import assert_equal from fuelweb_test.helpers import checkers from fuelweb_test.helpers.common import Common from fuelweb_test.helpers.decorators import log_snapshot_on_error from fuelweb_test.helpers import os_actions from fuelweb_test import settings from fuelweb_test import logger as LOGGER from fuelweb_test.tests.base_test_case import SetupEnvironment from fuelweb_test.tests.base_test_case import TestBasic @test(groups=["services", "services.sahara", "services_ha_one_controller"]) class SaharaHAOneController(TestBasic): """Sahara ha with 1 controller tests. Don't recommend to start tests without kvm Put Sahara image before start """ @test(depends_on=[SetupEnvironment.prepare_slaves_3], groups=["deploy_sahara_ha_one_controller_gre"]) @log_snapshot_on_error def deploy_sahara_ha_one_controller_gre(self): """Deploy cluster in ha mode with 1 controller Sahara and Neutron GRE Scenario: 1. Create a Fuel cluster. Set the option for Sahara installation 2. Add 1 node with "controller" role 3. Add 1 node with "compute" role 4. Deploy the Fuel cluster 5. Verify Sahara service on controller 6. Run all sanity and smoke tests 7. Register Vanilla2 image for Sahara 8. Run platform Vanilla2 test for Sahara Duration 65m Snapshot: deploy_sahara_ha_one_controller_gre """ if settings.OPENSTACK_RELEASE == settings.OPENSTACK_RELEASE_REDHAT: raise SkipTest() LOGGER.debug('Check MD5 sum of Vanilla2 image') check_image = checkers.check_image( settings.SERVTEST_SAHARA_VANILLA_2_IMAGE, settings.SERVTEST_SAHARA_VANILLA_2_IMAGE_MD5, settings.SERVTEST_LOCAL_PATH) asserts.assert_true(check_image) self.env.revert_snapshot("ready_with_3_slaves") LOGGER.debug('Create Fuel cluster for Sahara tests') data = { 'sahara': True, 'net_provider': 'neutron', 'net_segment_type': 'gre', 'tenant': 'saharaSimple', 'user': 'saharaSimple', 'password': 'saharaSimple' } cluster_id = self.fuel_web.create_cluster( name=self.__class__.__name__, mode=settings.DEPLOYMENT_MODE, settings=data ) self.fuel_web.update_nodes( cluster_id, { 'slave-01': ['controller'], 'slave-02': ['compute'] } ) self.fuel_web.deploy_cluster_wait(cluster_id) os_conn = os_actions.OpenStackActions( self.fuel_web.get_public_vip(cluster_id), data['user'], data['password'], data['tenant']) self.fuel_web.assert_cluster_ready( os_conn, smiles_count=5, networks_count=2, timeout=300) LOGGER.debug('Verify Sahara service on controller') checkers.verify_service( self.env.get_ssh_to_remote_by_name("slave-01"), service_name='sahara-all') LOGGER.debug('Run all sanity and smoke tests') path_to_tests = 'fuel_health.tests.sanity.test_sanity_sahara.' test_names = ['VanillaTwoTemplatesTest.test_vanilla_two_templates', 'HDPTwoTemplatesTest.test_hdp_two_templates'] self.fuel_web.run_ostf( cluster_id=self.fuel_web.get_last_created_cluster(), tests_must_be_passed=[path_to_tests + test_name for test_name in test_names] ) LOGGER.debug('Import Vanilla2 image for Sahara') common_func = Common( self.fuel_web.get_public_vip(cluster_id), data['user'], data['password'], data['tenant']) common_func.image_import( settings.SERVTEST_LOCAL_PATH, settings.SERVTEST_SAHARA_VANILLA_2_IMAGE, settings.SERVTEST_SAHARA_VANILLA_2_IMAGE_NAME, settings.SERVTEST_SAHARA_VANILLA_2_IMAGE_META) path_to_tests = 'fuel_health.tests.platform_tests.test_sahara.' test_names = ['VanillaTwoClusterTest.test_vanilla_two_cluster'] for test_name in test_names: LOGGER.debug('Run platform test {0} for Sahara'.format(test_name)) self.fuel_web.run_single_ostf_test( cluster_id=cluster_id, test_sets=['platform_tests'], test_name=path_to_tests + test_name, timeout=60 * 200) self.env.make_snapshot("deploy_sahara_ha_one_controller_gre") @test(groups=["services", "services.sahara", "services_ha"]) class SaharaHA(TestBasic): """Sahara HA tests. Don't recommend to start tests without kvm Put Sahara image before start """ @test(depends_on=[SetupEnvironment.prepare_slaves_5], groups=["deploy_sahara_ha_gre"]) @log_snapshot_on_error def deploy_sahara_ha_gre(self): """Deploy cluster in HA mode with Sahara and Neutron GRE Scenario: 1. Create a Fuel cluster. Set the option for Sahara installation 2. Add 3 node with "controller" role 3. Add 1 node with "compute" role 4. Deploy the Fuel cluster 5. Verify Sahara service on all controllers 6. Run all sanity and smoke tests 7. Register Vanilla2 image for Sahara 8. Run platform Vanilla2 test for Sahara Duration 130m Snapshot: deploy_sahara_ha_gre """ if settings.OPENSTACK_RELEASE == settings.OPENSTACK_RELEASE_REDHAT: raise SkipTest() LOGGER.debug('Check MD5 sum of Vanilla2 image') check_image = checkers.check_image( settings.SERVTEST_SAHARA_VANILLA_2_IMAGE, settings.SERVTEST_SAHARA_VANILLA_2_IMAGE_MD5, settings.SERVTEST_LOCAL_PATH) asserts.assert_true(check_image) self.env.revert_snapshot("ready_with_5_slaves") LOGGER.debug('Create Fuel cluster for Sahara tests') data = { 'sahara': True, 'net_provider': 'neutron', 'net_segment_type': 'gre', 'tenant': 'saharaHA', 'user': 'saharaHA', 'password': 'saharaHA' } cluster_id = self.fuel_web.create_cluster( name=self.__class__.__name__, mode=settings.DEPLOYMENT_MODE, settings=data ) self.fuel_web.update_nodes( cluster_id, { 'slave-01': ['controller'], 'slave-02': ['controller'], 'slave-03': ['controller'], 'slave-04': ['compute'] } ) self.fuel_web.deploy_cluster_wait(cluster_id) cluster_vip = self.fuel_web.get_public_vip(cluster_id) os_conn = os_actions.OpenStackActions( cluster_vip, data['user'], data['password'], data['tenant']) self.fuel_web.assert_cluster_ready( os_conn, smiles_count=13, networks_count=2, timeout=300) LOGGER.debug('Verify Sahara service on all controllers') for slave in ["slave-01", "slave-02", "slave-03"]: checkers.verify_service( self.env.get_ssh_to_remote_by_name(slave), service_name='sahara-all') LOGGER.debug('Run all sanity and smoke tests') path_to_tests = 'fuel_health.tests.sanity.test_sanity_sahara.' test_names = ['VanillaTwoTemplatesTest.test_vanilla_two_templates', 'HDPTwoTemplatesTest.test_hdp_two_templates'] self.fuel_web.run_ostf( cluster_id=self.fuel_web.get_last_created_cluster(), tests_must_be_passed=[path_to_tests + test_name for test_name in test_names] ) LOGGER.debug('Import Vanilla2 image for Sahara') common_func = Common(cluster_vip, data['user'], data['password'], data['tenant']) common_func.image_import( settings.SERVTEST_LOCAL_PATH, settings.SERVTEST_SAHARA_VANILLA_2_IMAGE, settings.SERVTEST_SAHARA_VANILLA_2_IMAGE_NAME, settings.SERVTEST_SAHARA_VANILLA_2_IMAGE_META) path_to_tests = 'fuel_health.tests.platform_tests.test_sahara.' test_names = ['VanillaTwoClusterTest.test_vanilla_two_cluster'] for test_name in test_names: LOGGER.debug('Run platform test {0} for Sahara'.format(test_name)) self.fuel_web.run_single_ostf_test( cluster_id=cluster_id, test_sets=['platform_tests'], test_name=path_to_tests + test_name, timeout=60 * 200) self.env.make_snapshot("deploy_sahara_ha_gre") @test(groups=["services", "services.murano", "services_ha_one_controller"]) class MuranoHAOneController(TestBasic): """Murano HA with 1 controller tests. Don't recommend to start tests without kvm Put Murano image before start Murano OSTF platform tests without Internet connection will be failed """ @test(depends_on=[SetupEnvironment.prepare_slaves_3], groups=["deploy_murano_ha_one_controller_gre"]) @log_snapshot_on_error def deploy_murano_ha_one_controller_gre(self): """Deploy cluster in HA mode with Murano and Neutron GRE Scenario: 1. Create cluster. Set install Murano option 2. Add 1 node with controller role 3. Add 1 nodes with compute role 4. Deploy the cluster 5. Verify Murano services 6. Run OSTF 7. Register Murano image 8. Run OSTF Murano platform tests Duration 40m Snapshot: deploy_murano_ha_one_controller_gre """ if settings.OPENSTACK_RELEASE == settings.OPENSTACK_RELEASE_REDHAT: raise SkipTest() self.env.revert_snapshot("ready_with_3_slaves") LOGGER.debug('Check MD5 of image') check_image = checkers.check_image( settings.SERVTEST_MURANO_IMAGE, settings.SERVTEST_MURANO_IMAGE_MD5, settings.SERVTEST_LOCAL_PATH) asserts.assert_true(check_image, "Image verification failed") data = { 'murano': True, 'net_provider': 'neutron', 'net_segment_type': 'gre', 'tenant': 'muranoSimple', 'user': 'muranoSimple', 'password': 'muranoSimple' } cluster_id = self.fuel_web.create_cluster( name=self.__class__.__name__, mode=settings.DEPLOYMENT_MODE, settings=data) self.fuel_web.update_nodes( cluster_id, { 'slave-01': ['controller'], 'slave-02': ['compute'] } ) self.fuel_web.deploy_cluster_wait(cluster_id) os_conn = os_actions.OpenStackActions( self.fuel_web.get_public_vip(cluster_id), data['user'], data['password'], data['tenant']) self.fuel_web.assert_cluster_ready( os_conn, smiles_count=5, networks_count=2, timeout=300) checkers.verify_service( self.env.get_ssh_to_remote_by_name("slave-01"), service_name='murano-api') common_func = Common(self.fuel_web.get_public_vip(cluster_id), data['user'], data['password'], data['tenant']) LOGGER.debug('Run sanity and functional Murano OSTF tests') self.fuel_web.run_single_ostf_test( cluster_id=self.fuel_web.get_last_created_cluster(), test_sets=['sanity'], test_name=('fuel_health.tests.sanity.test_sanity_murano.' 'MuranoSanityTests.test_create_and_delete_service') ) LOGGER.debug('Import Murano image') common_func.image_import( settings.SERVTEST_LOCAL_PATH, settings.SERVTEST_MURANO_IMAGE, settings.SERVTEST_MURANO_IMAGE_NAME, settings.SERVTEST_MURANO_IMAGE_META) LOGGER.debug('Boot instance with Murano image') image_name = settings.SERVTEST_MURANO_IMAGE_NAME srv = common_func.create_instance(flavor_name='test_murano_flavor', ram=2048, vcpus=1, disk=20, server_name='murano_instance', image_name=image_name, neutron_network=True) wait(lambda: common_func.get_instance_detail(srv).status == 'ACTIVE', timeout=60 * 60) common_func.delete_instance(srv) LOGGER.debug('Run OSTF platform tests') test_class_main = ('fuel_health.tests.platform_tests' '.test_murano_linux.MuranoDeployLinuxServicesTests') tests_names = ['test_deploy_apache_service', ] test_classes = [] for test_name in tests_names: test_classes.append('{0}.{1}'.format(test_class_main, test_name)) for test_name in test_classes: self.fuel_web.run_single_ostf_test( cluster_id=cluster_id, test_sets=['platform_tests'], test_name=test_name, timeout=60 * 36) self.env.make_snapshot("deploy_murano_ha_one_controller_gre") @test(groups=["services", "services.murano", "services_ha"]) class MuranoHA(TestBasic): """Murano HA tests. Don't recommend to start tests without kvm Put Murano image before start Murano OSTF platform tests without Internet connection will be failed """ @test(depends_on=[SetupEnvironment.prepare_slaves_5], groups=["deploy_murano_ha_with_gre"]) @log_snapshot_on_error def deploy_murano_ha_with_gre(self): """Deploy cluster in ha mode with Murano and Neutron GRE Scenario: 1. Create cluster. Set install Murano option 2. Add 3 node with controller role 3. Add 1 nodes with compute role 4. Deploy the cluster 5. Verify Murano services 6. Run OSTF 7. Register Murano image 8. Run OSTF Murano platform tests Duration 100m Snapshot: deploy_murano_ha_with_gre """ self.env.revert_snapshot("ready_with_5_slaves") LOGGER.debug('Check MD5 of image') check_image = checkers.check_image( settings.SERVTEST_MURANO_IMAGE, settings.SERVTEST_MURANO_IMAGE_MD5, settings.SERVTEST_LOCAL_PATH) asserts.assert_true(check_image, "Image verification failed") data = { 'murano': True, 'net_provider': 'neutron', 'net_segment_type': 'gre', 'tenant': 'muranoHA', 'user': 'muranoHA', 'password': 'muranoHA' } cluster_id = self.fuel_web.create_cluster( name=self.__class__.__name__, mode=settings.DEPLOYMENT_MODE, settings=data) self.fuel_web.update_nodes( cluster_id, { 'slave-01': ['controller'], 'slave-02': ['controller'], 'slave-03': ['controller'], 'slave-04': ['compute'] } ) self.fuel_web.deploy_cluster_wait(cluster_id) cluster_vip = self.fuel_web.get_public_vip(cluster_id) os_conn = os_actions.OpenStackActions( cluster_vip, data['user'], data['password'], data['tenant']) self.fuel_web.assert_cluster_ready( os_conn, smiles_count=13, networks_count=2, timeout=300) for slave in ["slave-01", "slave-02", "slave-03"]: checkers.verify_service( self.env.get_ssh_to_remote_by_name(slave), service_name='murano-api') common_func = Common(cluster_vip, data['user'], data['password'], data['tenant']) LOGGER.debug('Run sanity and functional Murano OSTF tests') self.fuel_web.run_single_ostf_test( cluster_id=self.fuel_web.get_last_created_cluster(), test_sets=['sanity'], test_name=('fuel_health.tests.sanity.test_sanity_murano.' 'MuranoSanityTests.test_create_and_delete_service') ) LOGGER.debug('Import Murano image') common_func.image_import( settings.SERVTEST_LOCAL_PATH, settings.SERVTEST_MURANO_IMAGE, settings.SERVTEST_MURANO_IMAGE_NAME, settings.SERVTEST_MURANO_IMAGE_META) LOGGER.debug('Boot instance with Murano image') image_name = settings.SERVTEST_MURANO_IMAGE_NAME srv = common_func.create_instance(flavor_name='test_murano_flavor', ram=2048, vcpus=1, disk=20, server_name='murano_instance', image_name=image_name, neutron_network=True) wait(lambda: common_func.get_instance_detail(srv).status == 'ACTIVE', timeout=60 * 60) common_func.delete_instance(srv) LOGGER.debug('Run OSTF platform tests') test_class_main = ('fuel_health.tests.platform_tests' '.test_murano_linux.MuranoDeployLinuxServicesTests') tests_names = ['test_deploy_apache_service', ] test_classes = [] for test_name in tests_names: test_classes.append('{0}.{1}'.format(test_class_main, test_name)) for test_name in test_classes: self.fuel_web.run_single_ostf_test( cluster_id=cluster_id, test_sets=['platform_tests'], test_name=test_name, timeout=60 * 36) self.env.make_snapshot("deploy_murano_ha_with_gre") class CeilometerOSTFTestsRun(TestBasic): def run_tests(self, cluster_id): """Method run smoke, sanity and platform Ceilometer tests.""" LOGGER.debug('Run sanity and smoke tests') self.fuel_web.run_ostf( cluster_id=cluster_id, test_sets=['smoke', 'sanity'], timeout=60 * 10 ) LOGGER.debug('Run platform OSTF Ceilometer tests') test_class_main = ('fuel_health.tests.platform_tests.' 'test_ceilometer.' 'CeilometerApiPlatformTests') tests_names = ['test_check_alarm_state', 'test_create_sample'] test_classes = [] for test_name in tests_names: test_classes.append('{0}.{1}'.format(test_class_main, test_name)) for test_name in test_classes: self.fuel_web.run_single_ostf_test( cluster_id=cluster_id, test_sets=['platform_tests'], test_name=test_name, timeout=60 * 20) @test(groups=["services", "services.ceilometer", "services_ha_one_controller"]) class CeilometerHAOneControllerMongo(CeilometerOSTFTestsRun): @test(depends_on=[SetupEnvironment.prepare_slaves_3], groups=["deploy_ceilometer_ha_one_controller_with_mongo"]) @log_snapshot_on_error def deploy_ceilometer_ha_one_controller_with_mongo(self): """Deploy cluster in HA mode with Ceilometer Scenario: 1. Create cluster. Set install Ceilometer option 2. Add 1 node with controller role 3. Add 1 nodes with compute role 4. Add 1 node with cinder role 5. Add 1 node with mongo role 6. Deploy the cluster 7. Verify ceilometer api is running 8. Run OSTF Duration 45m Snapshot: deploy_ceilometer_ha_one_controller_with_mongo """ self.env.revert_snapshot("ready_with_3_slaves") cluster_id = self.fuel_web.create_cluster( name=self.__class__.__name__, mode=settings.DEPLOYMENT_MODE, settings={ 'ceilometer': True, 'tenant': 'ceilometerSimple', 'user': 'ceilometerSimple', 'password': 'ceilometerSimple' } ) self.fuel_web.update_nodes( cluster_id, { 'slave-01': ['controller'], 'slave-02': ['compute', 'cinder'], 'slave-03': ['mongo'] } ) nailgun_nodes = self.fuel_web.client.list_cluster_nodes(cluster_id) disk_mb = 0 for node in nailgun_nodes: if node.get('pending_roles') == ['mongo']: disk_mb = self.fuel_web.get_node_disk_size(node.get('id'), "vda") LOGGER.debug('disk size is {0}'.format(disk_mb)) mongo_disk_mb = 11116 os_disk_mb = disk_mb - mongo_disk_mb mongo_disk_gb = ("{0}G".format(round(mongo_disk_mb / 1024, 1))) disk_part = { "vda": { "os": os_disk_mb, "mongo": mongo_disk_mb } } for node in nailgun_nodes: if node.get('pending_roles') == ['mongo']: self.fuel_web.update_node_disk(node.get('id'), disk_part) self.fuel_web.deploy_cluster_wait(cluster_id) checkers.verify_service( self.env.get_ssh_to_remote_by_name("slave-01"), service_name='ceilometer-api') partitions = checkers.get_mongo_partitions( self.env.get_ssh_to_remote_by_name("slave-03"), "vda5") assert_equal(partitions[0].rstrip(), mongo_disk_gb, 'Mongo size {0} before deployment is not equal' ' to size after {1}'.format(mongo_disk_gb, partitions)) self.run_tests(cluster_id) self.env.make_snapshot( "deploy_ceilometer_ha_one_controller_with_mongo") @test(depends_on=[SetupEnvironment.prepare_slaves_3], groups=["deploy_ceilometer_ha_one_controller_multirole"]) @log_snapshot_on_error def deploy_ceilometer_ha_one_controller_multirole(self): """Deploy cluster in ha multirole mode with Ceilometer Scenario: 1. Create cluster. Set install Ceilometer option 2. Add 1 node with controller role 3. Add 1 nodes with compute role 4. Add 2 nodes with cinder and mongo roles 5. Deploy the cluster 6. Verify ceilometer api is running 7. Run OSTF Duration 35m Snapshot: deploy_ceilometer_ha_one_controller_multirole """ self.env.revert_snapshot("ready_with_3_slaves") cluster_id = self.fuel_web.create_cluster( name=self.__class__.__name__, mode=settings.DEPLOYMENT_MODE, settings={ 'ceilometer': True } ) self.fuel_web.update_nodes( cluster_id, { 'slave-01': ['controller'], 'slave-02': ['compute'], 'slave-03': ['cinder', 'mongo'] } ) self.fuel_web.deploy_cluster_wait(cluster_id) checkers.verify_service( self.env.get_ssh_to_remote_by_name("slave-01"), service_name='ceilometer-api') self.run_tests(cluster_id) self.env.make_snapshot("deploy_ceilometer_ha_one_controller_mulirole") @test(groups=["services", "services.ceilometer", "services_ha"]) class CeilometerHAMongo(CeilometerOSTFTestsRun): @test(depends_on=[SetupEnvironment.prepare_slaves_5], groups=["deploy_ceilometer_ha_with_mongo"]) @log_snapshot_on_error def deploy_ceilometer_ha_with_mongo(self): """Deploy cluster in ha mode with Ceilometer Scenario: 1. Create cluster. Set install Ceilometer option 2. Add 3 node with controller role 3. Add 1 nodes with compute role 4. Add 1 node with mongo role 5. Deploy the cluster 6. Verify ceilometer api is running 7. Run OSTF Duration 65m Snapshot: deploy_ceilometer_ha_with_mongo """ self.env.revert_snapshot("ready_with_5_slaves") cluster_id = self.fuel_web.create_cluster( name=self.__class__.__name__, mode=settings.DEPLOYMENT_MODE, settings={ 'ceilometer': True, 'tenant': 'ceilometerHA', 'user': 'ceilometerHA', 'password': 'ceilometerHA' } ) self.fuel_web.update_nodes( cluster_id, { 'slave-01': ['controller'], 'slave-02': ['controller'], 'slave-03': ['controller'], 'slave-04': ['compute'], 'slave-05': ['mongo'] } ) self.fuel_web.deploy_cluster_wait(cluster_id) checkers.verify_service( self.env.get_ssh_to_remote_by_name("slave-01"), service_name='ceilometer-api') self.run_tests(cluster_id) self.env.make_snapshot("deploy_ceilometer_ha_with_mongo") @test(depends_on=[SetupEnvironment.prepare_slaves_5], groups=["deploy_ceilometer_ha_multirole"]) @log_snapshot_on_error def deploy_ceilometer_ha_multirole(self): """Deploy cluster in ha multirole mode with Ceilometer Scenario: 1. Create cluster. Set install Ceilometer option 2. Add 3 node with controller and mongo roles 3. Add 1 nodes with compute role 4. Add 1 nodes with cinder 5. Deploy the cluster 6. Verify ceilometer api is running 7. Run OSTF Duration 80m Snapshot: deploy_ceilometer_ha_multirole """ self.env.revert_snapshot("ready_with_5_slaves") cluster_id = self.fuel_web.create_cluster( name=self.__class__.__name__, mode=settings.DEPLOYMENT_MODE, settings={ 'ceilometer': True } ) self.fuel_web.update_nodes( cluster_id, { 'slave-01': ['controller', 'mongo'], 'slave-02': ['controller', 'mongo'], 'slave-03': ['controller', 'mongo'], 'slave-04': ['compute'], 'slave-05': ['cinder'] } ) self.fuel_web.deploy_cluster_wait(cluster_id) checkers.verify_service( self.env.get_ssh_to_remote_by_name("slave-01"), service_name='ceilometer-api') self.run_tests(cluster_id) self.env.make_snapshot("deploy_ceilometer_ha_mulirole") @test(groups=["services", "services.heat", "services_ha_one_controller"]) class HeatHAOneController(TestBasic): """Heat HA one controller test. Don't recommend to start tests without kvm """ @test(depends_on=[SetupEnvironment.prepare_slaves_3], groups=["deploy_heat_ha_one_controller_neutron"]) @log_snapshot_on_error def deploy_heat_ha_one_controller_neutron(self): """Deploy Heat cluster in HA mode with Neutron GRE Scenario: 1. Create cluster 2. Add 1 node with controller role and mongo 3. Add 1 nodes with compute role 4. Set install Ceilometer option 5. Deploy the cluster 6. Verify Heat, Ceilometer services 7. Run OSTF platform tests Duration 40m Snapshot: deploy_heat_ha_one_controller_neutron """ self.env.revert_snapshot("ready_with_3_slaves") data = { 'ceilometer': True, 'net_provider': 'neutron', 'net_segment_type': 'gre', 'tenant': 'heatSimple', 'user': 'heatSimple', 'password': 'heatSimple' } cluster_id = self.fuel_web.create_cluster( name=self.__class__.__name__, mode=settings.DEPLOYMENT_MODE, settings=data) self.fuel_web.update_nodes( cluster_id, { 'slave-01': ['controller', 'mongo'], 'slave-02': ['compute'] } ) self.fuel_web.deploy_cluster_wait(cluster_id) os_conn = os_actions.OpenStackActions( self.fuel_web.get_public_vip(cluster_id), data['user'], data['password'], data['tenant']) self.fuel_web.assert_cluster_ready( os_conn, smiles_count=5, networks_count=2, timeout=300) checkers.verify_service( self.env.get_ssh_to_remote_by_name("slave-01"), service_name='heat-api', count=3) checkers.verify_service( self.env.get_ssh_to_remote_by_name("slave-01"), service_name='ceilometer-api') LOGGER.debug('Run Heat OSTF platform tests') test_class_main = ('fuel_health.tests.platform_tests.' 'test_heat.' 'HeatSmokeTests') tests_names = ['test_actions', 'test_autoscaling', 'test_rollback', 'test_update'] test_classes = [] for test_name in tests_names: test_classes.append('{0}.{1}'.format(test_class_main, test_name)) for test_name in test_classes: self.fuel_web.run_single_ostf_test( cluster_id=cluster_id, test_sets=['platform_tests'], test_name=test_name, timeout=60 * 60) self.env.make_snapshot("deploy_heat_ha_one_controller_neutron") @test(depends_on=[SetupEnvironment.prepare_slaves_3], groups=["deploy_heat_ha_one_controller_nova"]) @log_snapshot_on_error def deploy_heat_ha_one_controller_nova(self): """Deploy Heat cluster in ha mode with Nova Network Scenario: 1. Create cluster 2. Add 1 node with controller role and mongo 3. Add 1 nodes with compute role 4. Set Ceilometer install option 4. Deploy the cluster 5. Verify Heat, Ceilometer services 6. Run OSTF platform tests Duration 40m Snapshot: deploy_heat_ha_one_controller_nova """ self.env.revert_snapshot("ready_with_3_slaves") data = { 'ceilometer': True, 'tenant': 'heatSimple', 'user': 'heatSimple', 'password': 'heatSimple' } cluster_id = self.fuel_web.create_cluster( name=self.__class__.__name__, mode=settings.DEPLOYMENT_MODE, settings=data) self.fuel_web.update_nodes( cluster_id, { 'slave-01': ['controller', 'mongo'], 'slave-02': ['compute'] } ) self.fuel_web.deploy_cluster_wait(cluster_id) os_conn = os_actions.OpenStackActions( self.fuel_web.get_public_vip(cluster_id), data['user'], data['password'], data['tenant']) self.fuel_web.assert_cluster_ready( os_conn, smiles_count=6, networks_count=1, timeout=300) checkers.verify_service( self.env.get_ssh_to_remote_by_name("slave-01"), service_name='heat-api', count=3) checkers.verify_service( self.env.get_ssh_to_remote_by_name("slave-01"), service_name='ceilometer-api') LOGGER.debug('Run Heat OSTF platform tests') test_class_main = ('fuel_health.tests.platform_tests.' 'test_heat.' 'HeatSmokeTests') tests_names = ['test_actions', 'test_autoscaling', 'test_rollback', 'test_update'] test_classes = [] for test_name in tests_names: test_classes.append('{0}.{1}'.format(test_class_main, test_name)) for test_name in test_classes: self.fuel_web.run_single_ostf_test( cluster_id=cluster_id, test_sets=['platform_tests'], test_name=test_name, timeout=60 * 60) self.env.make_snapshot("deploy_heat_ha_one_controller_nova") @test(groups=["services", "services.heat", "services_ha"]) class HeatHA(TestBasic): """Heat HA test. Don't recommend to start tests without kvm """ @test(depends_on=[SetupEnvironment.prepare_slaves_5], groups=["deploy_heat_ha"]) @log_snapshot_on_error def deploy_heat_ha(self): """Deploy Heat cluster in HA mode Scenario: 1. Create cluster 2. Add 3 node with controller role and mongo 3. Add 1 nodes with compute role 4. Set Ceilometer install option 4. Deploy the cluster 5. Verify Heat and Ceilometer services 6. Run OSTF platform tests Duration 70m Snapshot: deploy_heat_ha """ self.env.revert_snapshot("ready_with_5_slaves") data = { 'ceilometer': True, 'net_provider': 'neutron', 'net_segment_type': 'gre', 'tenant': 'heatHA', 'user': 'heatHA', 'password': 'heatHA' } cluster_id = self.fuel_web.create_cluster( name=self.__class__.__name__, mode=settings.DEPLOYMENT_MODE, settings=data) self.fuel_web.update_nodes( cluster_id, { 'slave-01': ['controller', 'mongo'], 'slave-02': ['controller', 'mongo'], 'slave-03': ['controller', 'mongo'], 'slave-04': ['compute'] } ) self.fuel_web.deploy_cluster_wait(cluster_id) cluster_vip = self.fuel_web.get_public_vip(cluster_id) os_conn = os_actions.OpenStackActions( cluster_vip, data['user'], data['password'], data['tenant']) self.fuel_web.assert_cluster_ready( os_conn, smiles_count=13, networks_count=2, timeout=300) for slave in ["slave-01", "slave-02", "slave-03"]: checkers.verify_service( self.env.get_ssh_to_remote_by_name(slave), service_name='heat-api', count=3) checkers.verify_service( self.env.get_ssh_to_remote_by_name(slave), service_name='ceilometer-api') LOGGER.debug('Run Heat OSTF platform tests') test_class_main = ('fuel_health.tests.platform_tests.' 'test_heat.' 'HeatSmokeTests') tests_names = ['test_actions', 'test_rollback'] test_classes = [] for test_name in tests_names: test_classes.append('{0}.{1}'.format(test_class_main, test_name)) for test_name in test_classes: self.fuel_web.run_single_ostf_test( cluster_id=cluster_id, test_sets=['platform_tests'], test_name=test_name, timeout=60 * 60) self.env.make_snapshot("deploy_heat_ha")
apache-2.0
elishowk/flaskexperiment
commonecouteserver/data/__init__.py
1
6483
# -*- coding: utf-8 -*- # Copyright (c) 2011 CommOnEcoute http://commonecoute.com # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation. # # 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/agpl.html> from flask import abort import riak import uuid from datetime import datetime import os DB_HOST = os.environ.get('COESERVER_DB_HOST') or '127.0.0.1' DB_PORT = os.environ.get('COESERVER_DB_PORT') or 8087 DB_PORT = int(DB_PORT) import logging logger = logging.getLogger('coeserver') class ObjectExistsException(Exception): pass class GenericBucket(object): def __init__(self, bucketname, port=DB_PORT, host=DB_HOST): """ initiate a riak bucket """ self.bucketname = bucketname self._connect(bucketname, port, host) def _connect(self, bucketname, port, host): """ Connects to a particular bucket on the defaut port of riak protobuf interface """ #print "connecting to %s on port %d"%(host, port) self.client = riak.RiakClient(host=host, port=port, transport_class=riak.RiakPbcTransport) #self.client.set_r(1) #self.client.set_w(1) self.bucket = self.client.bucket(bucketname) def _encode(self, data): """ on the fly encoding """ encodeddata = {} for (key, value) in data.iteritems(): if isinstance(value, unicode): encodeddata[key] = value.encode('utf-8', 'replace') else: encodeddata[key] = value return encodeddata def _addLinks(self, object, links): """ add links to an object given a list of identifiers """ for linked_key in links: linked_object = self.bucket.get(linked_key) object.add_link(linked_object) linked_object.add_link(object) def _genID(self, data): return "%s:::%s"%(datetime.utcnow().isoformat(), uuid.uuid4()) def _getNewObject(self, data): if self.bucket.get(data['id_txt']).exists(): raise(ObjectExistsException()) else: encodeddata = self._encode(data) return self.bucket.new(encodeddata['id_txt'], encodeddata) def create(self, data, links=[]): """ Supply a key to store data under The 'data' can be any data Python's 'json' encoder can handle (except unicode values with protobuf) Returns the json object created """ if not self.client.is_alive(): return {'response': {"error": "database is dead"}, 'statuscode': 500} try: if 'id_txt' not in data: data['id_txt'] = self._genID(data) new_object = self._getNewObject(data) # eventually links to other objects self._addLinks(new_object, links) # Save the object to Riak. return {'response':new_object.store().get_data()} #return new_object.get_key() except ObjectExistsException, existsexc: return {'response': {"error": "record already exists"}, 'statuscode': 400} def read(self, key): """ Returns json object for a given key """ if isinstance(key, unicode): key = key.encode('utf-8', 'replace') response = self.bucket.get(key).get_data() if response is None: abort(404) return {'response': response } def update(self, key, update_data, links=[]): """ Gets an updates an item for database Returns the updated json object """ if isinstance(key, unicode): key = key.encode('utf-8', 'replace') update_object = self.bucket.get(key) if not update_object.exists(): abort(404) data = update_object.get_data() data.update(update_data) update_object.set_data(self._encode(data)) # eventually links to other objects self._addLinks(update_object, links) return {'response': update_object.get_data()} or {'response': {"error": "could not update record"}, 'statuscode': 404} def delete(self, key): """ Deletes a record """ if isinstance(key, unicode): key = key.encode('utf-8', 'replace') response = self.bucket.get(key) if not response.exists(): abort(404) else: response.delete() def readallkeys(self): return {'response': self.bucket.get_keys()} class Track(GenericBucket): def __init__(self, *args, **kwargs): GenericBucket.__init__(self, "track", *args, **kwargs) def _genID(self, data): return "%s:::%s:::%s"%(data['start_date'], data['end_date'], uuid.uuid4()) class Event(GenericBucket): def __init__(self, *args, **kwargs): GenericBucket.__init__(self, "event", *args, **kwargs) def _genID(self, data): return "%s:::%s:::%s"%(data['start_date'], data['end_date'], uuid.uuid4()) class User(GenericBucket): def __init__(self, *args, **kwargs): GenericBucket.__init__(self, "user", *args, **kwargs) def _genID(self, data): return data['email_txt'] class Post(GenericBucket): def __init__(self, *args, **kwargs): GenericBucket.__init__(self, "post", *args, **kwargs) class Product(GenericBucket): def __init__(self, *args, **kwargs): GenericBucket.__init__(self, "product", *args, **kwargs) def _genID(self, data): return "%s"%uuid.uuid4() class Genre(GenericBucket): def __init__(self, *args, **kwargs): GenericBucket.__init__(self, "genre", *args, **kwargs) def _genID(self, data): return "%s"%uuid.uuid4() class Artist(GenericBucket): def __init__(self, *args, **kwargs): GenericBucket.__init__(self, "artist", *args, **kwargs) def _genID(self, data): return "%s"%uuid.uuid4()
agpl-3.0
sonnyhu/scipy
scipy/weave/swigptr.py
103
12378
# swigptr.py from __future__ import absolute_import, print_function swigptr_code = """ /*********************************************************************** * $Header$ * swig_lib/python/python.cfg * * Contains variable linking and pointer type-checking code. ************************************************************************/ #include <string.h> #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif #include "Python.h" /* Definitions for Windows/Unix exporting */ #if defined(_WIN32) || defined(__WIN32__) # if defined(_MSC_VER) # define SWIGEXPORT(a) __declspec(dllexport) a # else # if defined(__BORLANDC__) # define SWIGEXPORT(a) a _export # else # define SWIGEXPORT(a) a # endif # endif #else # define SWIGEXPORT(a) a #endif #ifdef SWIG_GLOBAL #define SWIGSTATICRUNTIME(a) SWIGEXPORT(a) #else #define SWIGSTATICRUNTIME(a) static a #endif typedef struct { char *name; PyObject *(*get_attr)(void); int (*set_attr)(PyObject *); } swig_globalvar; typedef struct swig_varlinkobject { PyObject_HEAD swig_globalvar **vars; int nvars; int maxvars; } swig_varlinkobject; /* ---------------------------------------------------------------------- swig_varlink_repr() Function for python repr method ---------------------------------------------------------------------- */ static PyObject * swig_varlink_repr(swig_varlinkobject *v) { v = v; return PyString_FromString("<Global variables>"); } /* --------------------------------------------------------------------- swig_varlink_print() Print out all of the global variable names --------------------------------------------------------------------- */ static int swig_varlink_print(swig_varlinkobject *v, FILE *fp, int flags) { int i = 0; flags = flags; fprintf(fp,"Global variables { "); while (v->vars[i]) { fprintf(fp,"%s", v->vars[i]->name); i++; if (v->vars[i]) fprintf(fp,", "); } fprintf(fp," }\\n"); return 0; } /* -------------------------------------------------------------------- swig_varlink_getattr This function gets the value of a variable and returns it as a PyObject. In our case, we'll be looking at the datatype and converting into a number or string -------------------------------------------------------------------- */ static PyObject * swig_varlink_getattr(swig_varlinkobject *v, char *n) { int i = 0; char temp[128]; while (v->vars[i]) { if (strcmp(v->vars[i]->name,n) == 0) { return (*v->vars[i]->get_attr)(); } i++; } sprintf(temp,"C global variable %s not found.", n); PyErr_SetString(PyExc_NameError,temp); return NULL; } /* ------------------------------------------------------------------- swig_varlink_setattr() This function sets the value of a variable. ------------------------------------------------------------------- */ static int swig_varlink_setattr(swig_varlinkobject *v, char *n, PyObject *p) { char temp[128]; int i = 0; while (v->vars[i]) { if (strcmp(v->vars[i]->name,n) == 0) { return (*v->vars[i]->set_attr)(p); } i++; } sprintf(temp,"C global variable %s not found.", n); PyErr_SetString(PyExc_NameError,temp); return 1; } statichere PyTypeObject varlinktype = { /* PyObject_HEAD_INIT(&PyType_Type) Note : This doesn't work on some machines */ PyObject_HEAD_INIT(0) 0, "varlink", /* Type name */ sizeof(swig_varlinkobject), /* Basic size */ 0, /* Itemsize */ 0, /* Deallocator */ (printfunc) swig_varlink_print, /* Print */ (getattrfunc) swig_varlink_getattr, /* get attr */ (setattrfunc) swig_varlink_setattr, /* Set attr */ 0, /* tp_compare */ (reprfunc) swig_varlink_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_mapping*/ 0, /* tp_hash */ }; /* Create a variable linking object for use later */ SWIGSTATICRUNTIME(PyObject *) SWIG_newvarlink(void) { swig_varlinkobject *result = 0; result = PyMem_NEW(swig_varlinkobject,1); varlinktype.ob_type = &PyType_Type; /* Patch varlinktype into a PyType */ result->ob_type = &varlinktype; /* _Py_NewReference(result); Does not seem to be necessary */ result->nvars = 0; result->maxvars = 64; result->vars = (swig_globalvar **) malloc(64*sizeof(swig_globalvar *)); result->vars[0] = 0; result->ob_refcnt = 0; Py_XINCREF((PyObject *) result); return ((PyObject*) result); } SWIGSTATICRUNTIME(void) SWIG_addvarlink(PyObject *p, char *name, PyObject *(*get_attr)(void), int (*set_attr)(PyObject *p)) { swig_varlinkobject *v; v= (swig_varlinkobject *) p; if (v->nvars >= v->maxvars -1) { v->maxvars = 2*v->maxvars; v->vars = (swig_globalvar **) realloc(v->vars,v->maxvars*sizeof(swig_globalvar *)); if (v->vars == NULL) { fprintf(stderr,"SWIG : Fatal error in initializing Python module.\\n"); exit(1); } } v->vars[v->nvars] = (swig_globalvar *) malloc(sizeof(swig_globalvar)); v->vars[v->nvars]->name = (char *) malloc(strlen(name)+1); strcpy(v->vars[v->nvars]->name,name); v->vars[v->nvars]->get_attr = get_attr; v->vars[v->nvars]->set_attr = set_attr; v->nvars++; v->vars[v->nvars] = 0; } /* ----------------------------------------------------------------------------- * Pointer type-checking * ----------------------------------------------------------------------------- */ /* SWIG pointer structure */ typedef struct SwigPtrType { char *name; /* Datatype name */ int len; /* Length (used for optimization) */ void *(*cast)(void *); /* Pointer casting function */ struct SwigPtrType *next; /* Linked list pointer */ } SwigPtrType; /* Pointer cache structure */ typedef struct { int stat; /* Status (valid) bit */ SwigPtrType *tp; /* Pointer to type structure */ char name[256]; /* Given datatype name */ char mapped[256]; /* Equivalent name */ } SwigCacheType; static int SwigPtrMax = 64; /* Max entries that can be currently held */ static int SwigPtrN = 0; /* Current number of entries */ static int SwigPtrSort = 0; /* Status flag indicating sort */ static int SwigStart[256]; /* Starting positions of types */ static SwigPtrType *SwigPtrTable = 0; /* Table containing pointer equivalences */ /* Cached values */ #define SWIG_CACHESIZE 8 #define SWIG_CACHEMASK 0x7 static SwigCacheType SwigCache[SWIG_CACHESIZE]; static int SwigCacheIndex = 0; static int SwigLastCache = 0; /* Sort comparison function */ static int swigsort(const void *data1, const void *data2) { SwigPtrType *d1 = (SwigPtrType *) data1; SwigPtrType *d2 = (SwigPtrType *) data2; return strcmp(d1->name,d2->name); } /* Register a new datatype with the type-checker */ SWIGSTATICRUNTIME(void) SWIG_RegisterMapping(char *origtype, char *newtype, void *(*cast)(void *)) { int i; SwigPtrType *t = 0,*t1; /* Allocate the pointer table if necessary */ if (!SwigPtrTable) { SwigPtrTable = (SwigPtrType *) malloc(SwigPtrMax*sizeof(SwigPtrType)); } /* Grow the table */ if (SwigPtrN >= SwigPtrMax) { SwigPtrMax = 2*SwigPtrMax; SwigPtrTable = (SwigPtrType *) realloc((char *) SwigPtrTable,SwigPtrMax*sizeof(SwigPtrType)); } for (i = 0; i < SwigPtrN; i++) { if (strcmp(SwigPtrTable[i].name,origtype) == 0) { t = &SwigPtrTable[i]; break; } } if (!t) { t = &SwigPtrTable[SwigPtrN++]; t->name = origtype; t->len = strlen(t->name); t->cast = 0; t->next = 0; } /* Check for existing entries */ while (t->next) { if ((strcmp(t->name,newtype) == 0)) { if (cast) t->cast = cast; return; } t = t->next; } t1 = (SwigPtrType *) malloc(sizeof(SwigPtrType)); t1->name = newtype; t1->len = strlen(t1->name); t1->cast = cast; t1->next = 0; t->next = t1; SwigPtrSort = 0; } /* Make a pointer value string */ SWIGSTATICRUNTIME(void) SWIG_MakePtr(char *c, const void *ptr, char *type) { static char hex[17] = "0123456789abcdef"; unsigned long p, s; char result[24], *r; r = result; p = (unsigned long) ptr; if (p > 0) { while (p > 0) { s = p & 0xf; *(r++) = hex[s]; p = p >> 4; } *r = '_'; while (r >= result) *(c++) = *(r--); strcpy (c, type); } else { strcpy (c, "NULL"); } } /* Function for getting a pointer value */ SWIGSTATICRUNTIME(char *) SWIG_GetPtr(char *c, void **ptr, char *t) { //std::cout << t << " " << c << std::endl; unsigned long p; char temp_type[256], *name; int i, len, start, end; SwigPtrType *sp,*tp; SwigCacheType *cache; register int d; p = 0; /* Pointer values must start with leading underscore */ if (*c != '_') { *ptr = (void *) 0; if (strcmp(c,"NULL") == 0) return (char *) 0; else c; } c++; /* Extract hex value from pointer */ while (d = *c) { if ((d >= '0') && (d <= '9')) p = (p << 4) + (d - '0'); else if ((d >= 'a') && (d <= 'f')) p = (p << 4) + (d - ('a'-10)); else break; c++; } *ptr = (void *) p; //std::cout << t << " " << c << std::endl; if ((!t) || (strcmp(t,c)==0)) return (char *) 0; else { // added ej -- if type check fails, its always an error. return (char*) 1; } if (!SwigPtrSort) { qsort((void *) SwigPtrTable, SwigPtrN, sizeof(SwigPtrType), swigsort); for (i = 0; i < 256; i++) SwigStart[i] = SwigPtrN; for (i = SwigPtrN-1; i >= 0; i--) SwigStart[(int) (SwigPtrTable[i].name[1])] = i; for (i = 255; i >= 1; i--) { if (SwigStart[i-1] > SwigStart[i]) SwigStart[i-1] = SwigStart[i]; } SwigPtrSort = 1; for (i = 0; i < SWIG_CACHESIZE; i++) SwigCache[i].stat = 0; } /* First check cache for matches. Uses last cache value as starting point */ cache = &SwigCache[SwigLastCache]; for (i = 0; i < SWIG_CACHESIZE; i++) { if (cache->stat && (strcmp(t,cache->name) == 0) && (strcmp(c,cache->mapped) == 0)) { cache->stat++; if (cache->tp->cast) *ptr = (*(cache->tp->cast))(*ptr); return (char *) 0; } SwigLastCache = (SwigLastCache+1) & SWIG_CACHEMASK; if (!SwigLastCache) cache = SwigCache; else cache++; } /* Type mismatch. Look through type-mapping table */ start = SwigStart[(int) t[1]]; end = SwigStart[(int) t[1]+1]; sp = &SwigPtrTable[start]; /* Try to find a match */ while (start <= end) { if (strncmp(t,sp->name,sp->len) == 0) { name = sp->name; len = sp->len; tp = sp->next; /* Try to find entry for our given datatype */ while(tp) { if (tp->len >= 255) { return c; } strcpy(temp_type,tp->name); strncat(temp_type,t+len,255-tp->len); if (strcmp(c,temp_type) == 0) { strcpy(SwigCache[SwigCacheIndex].mapped,c); strcpy(SwigCache[SwigCacheIndex].name,t); SwigCache[SwigCacheIndex].stat = 1; SwigCache[SwigCacheIndex].tp = tp; SwigCacheIndex = SwigCacheIndex & SWIG_CACHEMASK; /* Get pointer value */ *ptr = (void *) p; if (tp->cast) *ptr = (*(tp->cast))(*ptr); return (char *) 0; } tp = tp->next; } } sp++; start++; } return c; } /* New object-based GetPointer function. This uses the Python abstract * object interface to automatically dereference the 'this' attribute * of shadow objects. */ SWIGSTATICRUNTIME(char *) SWIG_GetPtrObj(PyObject *obj, void **ptr, char *type) { PyObject *sobj = obj; char *str; if (!PyString_Check(obj)) { sobj = PyObject_GetAttrString(obj,"this"); if (!sobj) return ""; } str = PyString_AsString(sobj); //printf("str: %s\\n", str); return SWIG_GetPtr(str,ptr,type); } #ifdef __cplusplus } #endif """
bsd-3-clause
MalloyPower/parsing-python
front-end/testsuite-python-lib/Python-2.7/Lib/sqlite3/test/userfunctions.py
16
13208
#-*- coding: ISO-8859-1 -*- # pysqlite2/test/userfunctions.py: tests for user-defined functions and # aggregates. # # Copyright (C) 2005-2007 Gerhard Häring <gh@ghaering.de> # # This file is part of pysqlite. # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from the use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # freely, subject to the following restrictions: # # 1. The origin of this software must not be misrepresented; you must not # claim that you wrote the original software. If you use this software # in a product, an acknowledgment in the product documentation would be # appreciated but is not required. # 2. Altered source versions must be plainly marked as such, and must not be # misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. import unittest import sqlite3 as sqlite def func_returntext(): return "foo" def func_returnunicode(): return u"bar" def func_returnint(): return 42 def func_returnfloat(): return 3.14 def func_returnnull(): return None def func_returnblob(): return buffer("blob") def func_raiseexception(): 5 // 0 def func_isstring(v): return type(v) is unicode def func_isint(v): return type(v) is int def func_isfloat(v): return type(v) is float def func_isnone(v): return type(v) is type(None) def func_isblob(v): return type(v) is buffer class AggrNoStep: def __init__(self): pass def finalize(self): return 1 class AggrNoFinalize: def __init__(self): pass def step(self, x): pass class AggrExceptionInInit: def __init__(self): 5 // 0 def step(self, x): pass def finalize(self): pass class AggrExceptionInStep: def __init__(self): pass def step(self, x): 5 // 0 def finalize(self): return 42 class AggrExceptionInFinalize: def __init__(self): pass def step(self, x): pass def finalize(self): 5 // 0 class AggrCheckType: def __init__(self): self.val = None def step(self, whichType, val): theType = {"str": unicode, "int": int, "float": float, "None": type(None), "blob": buffer} self.val = int(theType[whichType] is type(val)) def finalize(self): return self.val class AggrSum: def __init__(self): self.val = 0.0 def step(self, val): self.val += val def finalize(self): return self.val class FunctionTests(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:") self.con.create_function("returntext", 0, func_returntext) self.con.create_function("returnunicode", 0, func_returnunicode) self.con.create_function("returnint", 0, func_returnint) self.con.create_function("returnfloat", 0, func_returnfloat) self.con.create_function("returnnull", 0, func_returnnull) self.con.create_function("returnblob", 0, func_returnblob) self.con.create_function("raiseexception", 0, func_raiseexception) self.con.create_function("isstring", 1, func_isstring) self.con.create_function("isint", 1, func_isint) self.con.create_function("isfloat", 1, func_isfloat) self.con.create_function("isnone", 1, func_isnone) self.con.create_function("isblob", 1, func_isblob) def tearDown(self): self.con.close() def CheckFuncErrorOnCreate(self): try: self.con.create_function("bla", -100, lambda x: 2*x) self.fail("should have raised an OperationalError") except sqlite.OperationalError: pass def CheckFuncRefCount(self): def getfunc(): def f(): return 1 return f f = getfunc() globals()["foo"] = f # self.con.create_function("reftest", 0, getfunc()) self.con.create_function("reftest", 0, f) cur = self.con.cursor() cur.execute("select reftest()") def CheckFuncReturnText(self): cur = self.con.cursor() cur.execute("select returntext()") val = cur.fetchone()[0] self.assertEqual(type(val), unicode) self.assertEqual(val, "foo") def CheckFuncReturnUnicode(self): cur = self.con.cursor() cur.execute("select returnunicode()") val = cur.fetchone()[0] self.assertEqual(type(val), unicode) self.assertEqual(val, u"bar") def CheckFuncReturnInt(self): cur = self.con.cursor() cur.execute("select returnint()") val = cur.fetchone()[0] self.assertEqual(type(val), int) self.assertEqual(val, 42) def CheckFuncReturnFloat(self): cur = self.con.cursor() cur.execute("select returnfloat()") val = cur.fetchone()[0] self.assertEqual(type(val), float) if val < 3.139 or val > 3.141: self.fail("wrong value") def CheckFuncReturnNull(self): cur = self.con.cursor() cur.execute("select returnnull()") val = cur.fetchone()[0] self.assertEqual(type(val), type(None)) self.assertEqual(val, None) def CheckFuncReturnBlob(self): cur = self.con.cursor() cur.execute("select returnblob()") val = cur.fetchone()[0] self.assertEqual(type(val), buffer) self.assertEqual(val, buffer("blob")) def CheckFuncException(self): cur = self.con.cursor() try: cur.execute("select raiseexception()") cur.fetchone() self.fail("should have raised OperationalError") except sqlite.OperationalError, e: self.assertEqual(e.args[0], 'user-defined function raised exception') def CheckParamString(self): cur = self.con.cursor() cur.execute("select isstring(?)", ("foo",)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckParamInt(self): cur = self.con.cursor() cur.execute("select isint(?)", (42,)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckParamFloat(self): cur = self.con.cursor() cur.execute("select isfloat(?)", (3.14,)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckParamNone(self): cur = self.con.cursor() cur.execute("select isnone(?)", (None,)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckParamBlob(self): cur = self.con.cursor() cur.execute("select isblob(?)", (buffer("blob"),)) val = cur.fetchone()[0] self.assertEqual(val, 1) class AggregateTests(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:") cur = self.con.cursor() cur.execute(""" create table test( t text, i integer, f float, n, b blob ) """) cur.execute("insert into test(t, i, f, n, b) values (?, ?, ?, ?, ?)", ("foo", 5, 3.14, None, buffer("blob"),)) self.con.create_aggregate("nostep", 1, AggrNoStep) self.con.create_aggregate("nofinalize", 1, AggrNoFinalize) self.con.create_aggregate("excInit", 1, AggrExceptionInInit) self.con.create_aggregate("excStep", 1, AggrExceptionInStep) self.con.create_aggregate("excFinalize", 1, AggrExceptionInFinalize) self.con.create_aggregate("checkType", 2, AggrCheckType) self.con.create_aggregate("mysum", 1, AggrSum) def tearDown(self): #self.cur.close() #self.con.close() pass def CheckAggrErrorOnCreate(self): try: self.con.create_function("bla", -100, AggrSum) self.fail("should have raised an OperationalError") except sqlite.OperationalError: pass def CheckAggrNoStep(self): cur = self.con.cursor() try: cur.execute("select nostep(t) from test") self.fail("should have raised an AttributeError") except AttributeError, e: self.assertEqual(e.args[0], "AggrNoStep instance has no attribute 'step'") def CheckAggrNoFinalize(self): cur = self.con.cursor() try: cur.execute("select nofinalize(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError, e: self.assertEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error") def CheckAggrExceptionInInit(self): cur = self.con.cursor() try: cur.execute("select excInit(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError, e: self.assertEqual(e.args[0], "user-defined aggregate's '__init__' method raised error") def CheckAggrExceptionInStep(self): cur = self.con.cursor() try: cur.execute("select excStep(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError, e: self.assertEqual(e.args[0], "user-defined aggregate's 'step' method raised error") def CheckAggrExceptionInFinalize(self): cur = self.con.cursor() try: cur.execute("select excFinalize(t) from test") val = cur.fetchone()[0] self.fail("should have raised an OperationalError") except sqlite.OperationalError, e: self.assertEqual(e.args[0], "user-defined aggregate's 'finalize' method raised error") def CheckAggrCheckParamStr(self): cur = self.con.cursor() cur.execute("select checkType('str', ?)", ("foo",)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckAggrCheckParamInt(self): cur = self.con.cursor() cur.execute("select checkType('int', ?)", (42,)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckAggrCheckParamFloat(self): cur = self.con.cursor() cur.execute("select checkType('float', ?)", (3.14,)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckAggrCheckParamNone(self): cur = self.con.cursor() cur.execute("select checkType('None', ?)", (None,)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckAggrCheckParamBlob(self): cur = self.con.cursor() cur.execute("select checkType('blob', ?)", (buffer("blob"),)) val = cur.fetchone()[0] self.assertEqual(val, 1) def CheckAggrCheckAggrSum(self): cur = self.con.cursor() cur.execute("delete from test") cur.executemany("insert into test(i) values (?)", [(10,), (20,), (30,)]) cur.execute("select mysum(i) from test") val = cur.fetchone()[0] self.assertEqual(val, 60) def authorizer_cb(action, arg1, arg2, dbname, source): if action != sqlite.SQLITE_SELECT: return sqlite.SQLITE_DENY if arg2 == 'c2' or arg1 == 't2': return sqlite.SQLITE_DENY return sqlite.SQLITE_OK class AuthorizerTests(unittest.TestCase): def setUp(self): self.con = sqlite.connect(":memory:") self.con.executescript(""" create table t1 (c1, c2); create table t2 (c1, c2); insert into t1 (c1, c2) values (1, 2); insert into t2 (c1, c2) values (4, 5); """) # For our security test: self.con.execute("select c2 from t2") self.con.set_authorizer(authorizer_cb) def tearDown(self): pass def CheckTableAccess(self): try: self.con.execute("select * from t2") except sqlite.DatabaseError, e: if not e.args[0].endswith("prohibited"): self.fail("wrong exception text: %s" % e.args[0]) return self.fail("should have raised an exception due to missing privileges") def CheckColumnAccess(self): try: self.con.execute("select c2 from t1") except sqlite.DatabaseError, e: if not e.args[0].endswith("prohibited"): self.fail("wrong exception text: %s" % e.args[0]) return self.fail("should have raised an exception due to missing privileges") def suite(): function_suite = unittest.makeSuite(FunctionTests, "Check") aggregate_suite = unittest.makeSuite(AggregateTests, "Check") authorizer_suite = unittest.makeSuite(AuthorizerTests, "Check") return unittest.TestSuite((function_suite, aggregate_suite, authorizer_suite)) def test(): runner = unittest.TextTestRunner() runner.run(suite()) if __name__ == "__main__": test()
mit
Timus1712/boto
tests/integration/ec2/test_cert_verification.py
3
1502
# Copyright (c) 2012 Mitch Garnaat http://garnaat.org/ # Copyright (c) 2012 Amazon.com, Inc. or its affiliates. # All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL- # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. """ Check that all of the certs on all service endpoints validate. """ import unittest import boto.ec2 class CertVerificationTest(unittest.TestCase): ec2 = True ssl = True def test_certs(self): for region in boto.ec2.regions(): c = region.connect() c.get_all_reservations()
mit
ivanhorvath/openshift-tools
ansible/roles/lib_openshift_3.2/library/oc_serviceaccount.py
6
40250
#!/usr/bin/env python # pylint: disable=too-many-lines # ___ ___ _ _ ___ ___ _ _____ ___ ___ # / __| __| \| | __| _ \ /_\_ _| __| \ # | (_ | _|| .` | _|| / / _ \| | | _|| |) | # \___|___|_|\_|___|_|_\/_/_\_\_|_|___|___/_ _____ # | \ / _ \ | \| |/ _ \_ _| | __| \_ _|_ _| # | |) | (_) | | .` | (_) || | | _|| |) | | | | # |___/ \___/ |_|\_|\___/ |_| |___|___/___| |_| ''' OpenShiftCLI class that wraps the oc commands in a subprocess ''' # pylint: disable=too-many-lines import atexit import json import os import re import shutil import subprocess import ruamel.yaml as yaml #import yaml # ## This is here because of a bug that causes yaml ## to incorrectly handle timezone info on timestamps #def timestamp_constructor(_, node): # '''return timestamps as strings''' # return str(node.value) #yaml.add_constructor(u'tag:yaml.org,2002:timestamp', timestamp_constructor) class OpenShiftCLIError(Exception): '''Exception class for openshiftcli''' pass # pylint: disable=too-few-public-methods class OpenShiftCLI(object): ''' Class to wrap the command line tools ''' def __init__(self, namespace, kubeconfig='/etc/origin/master/admin.kubeconfig', verbose=False, all_namespaces=False): ''' Constructor for OpenshiftCLI ''' self.namespace = namespace self.verbose = verbose self.kubeconfig = kubeconfig self.all_namespaces = all_namespaces # Pylint allows only 5 arguments to be passed. # pylint: disable=too-many-arguments def _replace_content(self, resource, rname, content, force=False, sep='.'): ''' replace the current object with the content ''' res = self._get(resource, rname) if not res['results']: return res fname = '/tmp/%s' % rname yed = Yedit(fname, res['results'][0], separator=sep) changes = [] for key, value in content.items(): changes.append(yed.put(key, value)) if any([change[0] for change in changes]): yed.write() atexit.register(Utils.cleanup, [fname]) return self._replace(fname, force) return {'returncode': 0, 'updated': False} def _replace(self, fname, force=False): '''return all pods ''' cmd = ['-n', self.namespace, 'replace', '-f', fname] if force: cmd.append('--force') return self.openshift_cmd(cmd) def _create_from_content(self, rname, content): '''return all pods ''' fname = '/tmp/%s' % rname yed = Yedit(fname, content=content) yed.write() atexit.register(Utils.cleanup, [fname]) return self._create(fname) def _create(self, fname): '''return all pods ''' return self.openshift_cmd(['create', '-f', fname, '-n', self.namespace]) def _delete(self, resource, rname, selector=None): '''return all pods ''' cmd = ['delete', resource, rname, '-n', self.namespace] if selector: cmd.append('--selector=%s' % selector) return self.openshift_cmd(cmd) def _process(self, template_name, create=False, params=None, template_data=None): '''return all pods ''' cmd = ['process', '-n', self.namespace] if template_data: cmd.extend(['-f', '-']) else: cmd.append(template_name) if params: param_str = ["%s=%s" % (key, value) for key, value in params.items()] cmd.append('-v') cmd.extend(param_str) results = self.openshift_cmd(cmd, output=True, input_data=template_data) if results['returncode'] != 0 or not create: return results fname = '/tmp/%s' % template_name yed = Yedit(fname, results['results']) yed.write() atexit.register(Utils.cleanup, [fname]) return self.openshift_cmd(['-n', self.namespace, 'create', '-f', fname]) def _get(self, resource, rname=None, selector=None): '''return a resource by name ''' cmd = ['get', resource] if selector: cmd.append('--selector=%s' % selector) if self.all_namespaces: cmd.extend(['--all-namespaces']) elif self.namespace: cmd.extend(['-n', self.namespace]) cmd.extend(['-o', 'json']) if rname: cmd.append(rname) rval = self.openshift_cmd(cmd, output=True) # Ensure results are retuned in an array if rval.has_key('items'): rval['results'] = rval['items'] elif not isinstance(rval['results'], list): rval['results'] = [rval['results']] return rval def _schedulable(self, node=None, selector=None, schedulable=True): ''' perform oadm manage-node scheduable ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector=%s' % selector) cmd.append('--schedulable=%s' % schedulable) return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') def _list_pods(self, node=None, selector=None, pod_selector=None): ''' perform oadm manage-node evacuate ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector=%s' % selector) if pod_selector: cmd.append('--pod-selector=%s' % pod_selector) cmd.extend(['--list-pods', '-o', 'json']) return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') #pylint: disable=too-many-arguments def _evacuate(self, node=None, selector=None, pod_selector=None, dry_run=False, grace_period=None, force=False): ''' perform oadm manage-node evacuate ''' cmd = ['manage-node'] if node: cmd.extend(node) else: cmd.append('--selector=%s' % selector) if dry_run: cmd.append('--dry-run') if pod_selector: cmd.append('--pod-selector=%s' % pod_selector) if grace_period: cmd.append('--grace-period=%s' % int(grace_period)) if force: cmd.append('--force') cmd.append('--evacuate') return self.openshift_cmd(cmd, oadm=True, output=True, output_type='raw') def _import_image(self, url=None, name=None, tag=None): ''' perform image import ''' cmd = ['import-image'] image = '{0}'.format(name) if tag: image += ':{0}'.format(tag) cmd.append(image) if url: cmd.append('--from={0}/{1}'.format(url, image)) cmd.append('-n{0}'.format(self.namespace)) cmd.append('--confirm') return self.openshift_cmd(cmd) #pylint: disable=too-many-arguments def openshift_cmd(self, cmd, oadm=False, output=False, output_type='json', input_data=None): '''Base command for oc ''' cmds = [] if oadm: cmds = ['/usr/bin/oc', 'adm'] else: cmds = ['/usr/bin/oc'] cmds.extend(cmd) rval = {} results = '' err = None if self.verbose: print ' '.join(cmds) proc = subprocess.Popen(cmds, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env={'KUBECONFIG': self.kubeconfig}) stdout, stderr = proc.communicate(input_data) rval = {"returncode": proc.returncode, "results": results, "cmd": ' '.join(cmds), } if proc.returncode == 0: if output: if output_type == 'json': try: rval['results'] = json.loads(stdout) except ValueError as err: if "No JSON object could be decoded" in err.message: err = err.message elif output_type == 'raw': rval['results'] = stdout if self.verbose: print stdout print stderr if err: rval.update({"err": err, "stderr": stderr, "stdout": stdout, "cmd": cmds }) else: rval.update({"stderr": stderr, "stdout": stdout, "results": {}, }) return rval class Utils(object): ''' utilities for openshiftcli modules ''' @staticmethod def create_file(rname, data, ftype='yaml'): ''' create a file in tmp with name and contents''' path = os.path.join('/tmp', rname) with open(path, 'w') as fds: if ftype == 'yaml': fds.write(yaml.dump(data, Dumper=yaml.RoundTripDumper)) elif ftype == 'json': fds.write(json.dumps(data)) else: fds.write(data) # Register cleanup when module is done atexit.register(Utils.cleanup, [path]) return path @staticmethod def create_files_from_contents(content, content_type=None): '''Turn an array of dict: filename, content into a files array''' if not isinstance(content, list): content = [content] files = [] for item in content: path = Utils.create_file(item['path'], item['data'], ftype=content_type) files.append({'name': os.path.basename(path), 'path': path}) return files @staticmethod def cleanup(files): '''Clean up on exit ''' for sfile in files: if os.path.exists(sfile): if os.path.isdir(sfile): shutil.rmtree(sfile) elif os.path.isfile(sfile): os.remove(sfile) @staticmethod def exists(results, _name): ''' Check to see if the results include the name ''' if not results: return False if Utils.find_result(results, _name): return True return False @staticmethod def find_result(results, _name): ''' Find the specified result by name''' rval = None for result in results: if result.has_key('metadata') and result['metadata']['name'] == _name: rval = result break return rval @staticmethod def get_resource_file(sfile, sfile_type='yaml'): ''' return the service file ''' contents = None with open(sfile) as sfd: contents = sfd.read() if sfile_type == 'yaml': contents = yaml.load(contents, yaml.RoundTripLoader) elif sfile_type == 'json': contents = json.loads(contents) return contents # Disabling too-many-branches. This is a yaml dictionary comparison function # pylint: disable=too-many-branches,too-many-return-statements,too-many-statements @staticmethod def check_def_equal(user_def, result_def, skip_keys=None, debug=False): ''' Given a user defined definition, compare it with the results given back by our query. ''' # Currently these values are autogenerated and we do not need to check them skip = ['metadata', 'status'] if skip_keys: skip.extend(skip_keys) for key, value in result_def.items(): if key in skip: continue # Both are lists if isinstance(value, list): if not user_def.has_key(key): if debug: print 'User data does not have key [%s]' % key print 'User data: %s' % user_def return False if not isinstance(user_def[key], list): if debug: print 'user_def[key] is not a list key=[%s] user_def[key]=%s' % (key, user_def[key]) return False if len(user_def[key]) != len(value): if debug: print "List lengths are not equal." print "key=[%s]: user_def[%s] != value[%s]" % (key, len(user_def[key]), len(value)) print "user_def: %s" % user_def[key] print "value: %s" % value return False for values in zip(user_def[key], value): if isinstance(values[0], dict) and isinstance(values[1], dict): if debug: print 'sending list - list' print type(values[0]) print type(values[1]) result = Utils.check_def_equal(values[0], values[1], skip_keys=skip_keys, debug=debug) if not result: print 'list compare returned false' return False elif value != user_def[key]: if debug: print 'value should be identical' print value print user_def[key] return False # recurse on a dictionary elif isinstance(value, dict): if not user_def.has_key(key): if debug: print "user_def does not have key [%s]" % key return False if not isinstance(user_def[key], dict): if debug: print "dict returned false: not instance of dict" return False # before passing ensure keys match api_values = set(value.keys()) - set(skip) user_values = set(user_def[key].keys()) - set(skip) if api_values != user_values: if debug: print "keys are not equal in dict" print api_values print user_values return False result = Utils.check_def_equal(user_def[key], value, skip_keys=skip_keys, debug=debug) if not result: if debug: print "dict returned false" print result return False # Verify each key, value pair is the same else: if not user_def.has_key(key) or value != user_def[key]: if debug: print "value not equal; user_def does not have key" print key print value if user_def.has_key(key): print user_def[key] return False if debug: print 'returning true' return True class OpenShiftCLIConfig(object): '''Generic Config''' def __init__(self, rname, namespace, kubeconfig, options): self.kubeconfig = kubeconfig self.name = rname self.namespace = namespace self._options = options @property def config_options(self): ''' return config options ''' return self._options def to_option_list(self): '''return all options as a string''' return self.stringify() def stringify(self): ''' return the options hash as cli params in a string ''' rval = [] for key, data in self.config_options.items(): if data['include'] \ and (data['value'] or isinstance(data['value'], int)): rval.append('--%s=%s' % (key.replace('_', '-'), data['value'])) return rval class YeditException(Exception): ''' Exception class for Yedit ''' pass class Yedit(object): ''' Class to modify yaml files ''' re_valid_key = r"(((\[-?\d+\])|([0-9a-zA-Z%s/_-]+)).?)+$" re_key = r"(?:\[(-?\d+)\])|([0-9a-zA-Z%s/_-]+)" com_sep = set(['.', '#', '|', ':']) # pylint: disable=too-many-arguments def __init__(self, filename=None, content=None, content_type='yaml', separator='.', backup=False): self.content = content self._separator = separator self.filename = filename self.__yaml_dict = content self.content_type = content_type self.backup = backup self.load(content_type=self.content_type) if self.__yaml_dict == None: self.__yaml_dict = {} @property def separator(self): ''' getter method for yaml_dict ''' return self._separator @separator.setter def separator(self): ''' getter method for yaml_dict ''' return self._separator @property def yaml_dict(self): ''' getter method for yaml_dict ''' return self.__yaml_dict @yaml_dict.setter def yaml_dict(self, value): ''' setter method for yaml_dict ''' self.__yaml_dict = value @staticmethod def parse_key(key, sep='.'): '''parse the key allowing the appropriate separator''' common_separators = list(Yedit.com_sep - set([sep])) return re.findall(Yedit.re_key % ''.join(common_separators), key) @staticmethod def valid_key(key, sep='.'): '''validate the incoming key''' common_separators = list(Yedit.com_sep - set([sep])) if not re.match(Yedit.re_valid_key % ''.join(common_separators), key): return False return True @staticmethod def remove_entry(data, key, sep='.'): ''' remove data at location key ''' if key == '' and isinstance(data, dict): data.clear() return True elif key == '' and isinstance(data, list): del data[:] return True if not (key and Yedit.valid_key(key, sep)) and isinstance(data, (list, dict)): return None key_indexes = Yedit.parse_key(key, sep) for arr_ind, dict_key in key_indexes[:-1]: if dict_key and isinstance(data, dict): data = data.get(dict_key, None) elif arr_ind and isinstance(data, list) and int(arr_ind) <= len(data) - 1: data = data[int(arr_ind)] else: return None # process last index for remove # expected list entry if key_indexes[-1][0]: if isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: del data[int(key_indexes[-1][0])] return True # expected dict entry elif key_indexes[-1][1]: if isinstance(data, dict): del data[key_indexes[-1][1]] return True @staticmethod def add_entry(data, key, item=None, sep='.'): ''' Get an item from a dictionary with key notation a.b.c d = {'a': {'b': 'c'}}} key = a#b return c ''' if key == '': pass elif not (key and Yedit.valid_key(key, sep)) and isinstance(data, (list, dict)): return None key_indexes = Yedit.parse_key(key, sep) for arr_ind, dict_key in key_indexes[:-1]: if dict_key: if isinstance(data, dict) and data.has_key(dict_key) and data[dict_key]: data = data[dict_key] continue elif data and not isinstance(data, dict): raise YeditException("Unexpected item type found while going through key " + "path: {} (at key: {})".format(key, dict_key)) data[dict_key] = {} data = data[dict_key] elif arr_ind and isinstance(data, list) and int(arr_ind) <= len(data) - 1: data = data[int(arr_ind)] else: raise YeditException("Unexpected item type found while going through key path: {}".format(key)) if key == '': data = item # process last index for add # expected list entry elif key_indexes[-1][0] and isinstance(data, list) and int(key_indexes[-1][0]) <= len(data) - 1: data[int(key_indexes[-1][0])] = item # expected dict entry elif key_indexes[-1][1] and isinstance(data, dict): data[key_indexes[-1][1]] = item # didn't add/update to an existing list, nor add/update key to a dict # so we must have been provided some syntax like a.b.c[<int>] = "data" for a # non-existent array else: raise YeditException("Error adding data to object at path: {}".format(key)) return data @staticmethod def get_entry(data, key, sep='.'): ''' Get an item from a dictionary with key notation a.b.c d = {'a': {'b': 'c'}}} key = a.b return c ''' if key == '': pass elif not (key and Yedit.valid_key(key, sep)) and isinstance(data, (list, dict)): return None key_indexes = Yedit.parse_key(key, sep) for arr_ind, dict_key in key_indexes: if dict_key and isinstance(data, dict): data = data.get(dict_key, None) elif arr_ind and isinstance(data, list) and int(arr_ind) <= len(data) - 1: data = data[int(arr_ind)] else: return None return data def write(self): ''' write to file ''' if not self.filename: raise YeditException('Please specify a filename.') if self.backup and self.file_exists(): shutil.copy(self.filename, self.filename + '.orig') tmp_filename = self.filename + '.yedit' try: with open(tmp_filename, 'w') as yfd: # pylint: disable=no-member,maybe-no-member if hasattr(self.yaml_dict, 'fa'): self.yaml_dict.fa.set_block_style() yfd.write(yaml.dump(self.yaml_dict, Dumper=yaml.RoundTripDumper)) except Exception as err: raise YeditException(err.message) os.rename(tmp_filename, self.filename) return (True, self.yaml_dict) def read(self): ''' read from file ''' # check if it exists if self.filename == None or not self.file_exists(): return None contents = None with open(self.filename) as yfd: contents = yfd.read() return contents def file_exists(self): ''' return whether file exists ''' if os.path.exists(self.filename): return True return False def load(self, content_type='yaml'): ''' return yaml file ''' contents = self.read() if not contents and not self.content: return None if self.content: if isinstance(self.content, dict): self.yaml_dict = self.content return self.yaml_dict elif isinstance(self.content, str): contents = self.content # check if it is yaml try: if content_type == 'yaml' and contents: self.yaml_dict = yaml.load(contents, yaml.RoundTripLoader) # pylint: disable=no-member,maybe-no-member if hasattr(self.yaml_dict, 'fa'): self.yaml_dict.fa.set_block_style() elif content_type == 'json' and contents: self.yaml_dict = json.loads(contents) except yaml.YAMLError as err: # Error loading yaml or json raise YeditException('Problem with loading yaml file. %s' % err) return self.yaml_dict def get(self, key): ''' get a specified key''' try: entry = Yedit.get_entry(self.yaml_dict, key, self.separator) except KeyError as _: entry = None return entry def pop(self, path, key_or_item): ''' remove a key, value pair from a dict or an item for a list''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError as _: entry = None if entry == None: return (False, self.yaml_dict) if isinstance(entry, dict): # pylint: disable=no-member,maybe-no-member if entry.has_key(key_or_item): entry.pop(key_or_item) return (True, self.yaml_dict) return (False, self.yaml_dict) elif isinstance(entry, list): # pylint: disable=no-member,maybe-no-member ind = None try: ind = entry.index(key_or_item) except ValueError: return (False, self.yaml_dict) entry.pop(ind) return (True, self.yaml_dict) return (False, self.yaml_dict) def delete(self, path): ''' remove path from a dict''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError as _: entry = None if entry == None: return (False, self.yaml_dict) result = Yedit.remove_entry(self.yaml_dict, path, self.separator) if not result: return (False, self.yaml_dict) return (True, self.yaml_dict) def exists(self, path, value): ''' check if value exists at path''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError as _: entry = None if isinstance(entry, list): if value in entry: return True return False elif isinstance(entry, dict): if isinstance(value, dict): rval = False for key, val in value.items(): if entry[key] != val: rval = False break else: rval = True return rval return value in entry return entry == value def append(self, path, value): '''append value to a list''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError as _: entry = None if entry is None: self.put(path, []) entry = Yedit.get_entry(self.yaml_dict, path, self.separator) if not isinstance(entry, list): return (False, self.yaml_dict) # pylint: disable=no-member,maybe-no-member entry.append(value) return (True, self.yaml_dict) # pylint: disable=too-many-arguments def update(self, path, value, index=None, curr_value=None): ''' put path, value into a dict ''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError as _: entry = None if isinstance(entry, dict): # pylint: disable=no-member,maybe-no-member if not isinstance(value, dict): raise YeditException('Cannot replace key, value entry in dict with non-dict type.' \ ' value=[%s] [%s]' % (value, type(value))) entry.update(value) return (True, self.yaml_dict) elif isinstance(entry, list): # pylint: disable=no-member,maybe-no-member ind = None if curr_value: try: ind = entry.index(curr_value) except ValueError: return (False, self.yaml_dict) elif index != None: ind = index if ind != None and entry[ind] != value: entry[ind] = value return (True, self.yaml_dict) # see if it exists in the list try: ind = entry.index(value) except ValueError: # doesn't exist, append it entry.append(value) return (True, self.yaml_dict) #already exists, return if ind != None: return (False, self.yaml_dict) return (False, self.yaml_dict) def put(self, path, value): ''' put path, value into a dict ''' try: entry = Yedit.get_entry(self.yaml_dict, path, self.separator) except KeyError as _: entry = None if entry == value: return (False, self.yaml_dict) # deepcopy didn't work tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), yaml.RoundTripLoader) # pylint: disable=no-member if hasattr(self.yaml_dict, 'fa'): tmp_copy.fa.set_block_style() result = Yedit.add_entry(tmp_copy, path, value, self.separator) if not result: return (False, self.yaml_dict) self.yaml_dict = tmp_copy return (True, self.yaml_dict) def create(self, path, value): ''' create a yaml file ''' if not self.file_exists(): # deepcopy didn't work tmp_copy = yaml.load(yaml.round_trip_dump(self.yaml_dict, default_flow_style=False), yaml.RoundTripLoader) # pylint: disable=no-member if hasattr(self.yaml_dict, 'fa'): tmp_copy.fa.set_block_style() result = Yedit.add_entry(tmp_copy, path, value, self.separator) if result: self.yaml_dict = tmp_copy return (True, self.yaml_dict) return (False, self.yaml_dict) class ServiceAccountConfig(object): '''Service account config class This class stores the options and returns a default service account ''' # pylint: disable=too-many-arguments def __init__(self, sname, namespace, kubeconfig, secrets=None, image_pull_secrets=None): self.name = sname self.kubeconfig = kubeconfig self.namespace = namespace self.secrets = secrets or [] self.image_pull_secrets = image_pull_secrets or [] self.data = {} self.create_dict() def create_dict(self): ''' return a properly structured volume ''' self.data['apiVersion'] = 'v1' self.data['kind'] = 'ServiceAccount' self.data['metadata'] = {} self.data['metadata']['name'] = self.name self.data['metadata']['namespace'] = self.namespace self.data['secrets'] = [] if self.secrets: for sec in self.secrets: self.data['secrets'].append({"name": sec}) self.data['imagePullSecrets'] = [] if self.image_pull_secrets: for sec in self.image_pull_secrets: self.data['imagePullSecrets'].append({"name": sec}) # pylint: disable=too-many-public-methods class ServiceAccount(Yedit): ''' Class to wrap the oc command line tools ''' image_pull_secrets_path = "imagePullSecrets" secrets_path = "secrets" def __init__(self, content): '''ServiceAccount constructor''' super(ServiceAccount, self).__init__(content=content) self._secrets = None self._image_pull_secrets = None @property def image_pull_secrets(self): ''' property for image_pull_secrets ''' if self._image_pull_secrets == None: self._image_pull_secrets = self.get(ServiceAccount.image_pull_secrets_path) or [] return self._image_pull_secrets @image_pull_secrets.setter def image_pull_secrets(self, secrets): ''' property for secrets ''' self._image_pull_secrets = secrets @property def secrets(self): ''' property for secrets ''' print "Getting secrets property" if not self._secrets: self._secrets = self.get(ServiceAccount.secrets_path) or [] return self._secrets @secrets.setter def secrets(self, secrets): ''' property for secrets ''' self._secrets = secrets def delete_secret(self, inc_secret): ''' remove a secret ''' remove_idx = None for idx, sec in enumerate(self.secrets): if sec['name'] == inc_secret: remove_idx = idx break if remove_idx: del self.secrets[remove_idx] return True return False def delete_image_pull_secret(self, inc_secret): ''' remove a image_pull_secret ''' remove_idx = None for idx, sec in enumerate(self.image_pull_secrets): if sec['name'] == inc_secret: remove_idx = idx break if remove_idx: del self.image_pull_secrets[remove_idx] return True return False def find_secret(self, inc_secret): '''find secret''' for secret in self.secrets: if secret['name'] == inc_secret: return secret return None def find_image_pull_secret(self, inc_secret): '''find secret''' for secret in self.image_pull_secrets: if secret['name'] == inc_secret: return secret return None def add_secret(self, inc_secret): '''add secret''' if self.secrets: self.secrets.append({"name": inc_secret}) else: self.put(ServiceAccount.secrets_path, [{"name": inc_secret}]) def add_image_pull_secret(self, inc_secret): '''add image_pull_secret''' if self.image_pull_secrets: self.image_pull_secrets.append({"name": inc_secret}) else: self.put(ServiceAccount.image_pull_secrets_path, [{"name": inc_secret}]) # pylint: disable=too-many-instance-attributes class OCServiceAccount(OpenShiftCLI): ''' Class to wrap the oc command line tools ''' kind = 'sa' # pylint allows 5 # pylint: disable=too-many-arguments def __init__(self, config, verbose=False): ''' Constructor for OCVolume ''' super(OCServiceAccount, self).__init__(config.namespace, config.kubeconfig) self.config = config self.namespace = config.namespace self._service_account = None @property def service_account(self): ''' property function service''' if not self._service_account: self.get() return self._service_account @service_account.setter def service_account(self, data): ''' setter function for yedit var ''' self._service_account = data def exists(self): ''' return whether a volume exists ''' if self.service_account: return True return False def get(self): '''return volume information ''' result = self._get(self.kind, self.config.name) if result['returncode'] == 0: self.service_account = ServiceAccount(content=result['results'][0]) elif '\"%s\" not found' % self.config.name in result['stderr']: result['returncode'] = 0 result['results'] = [{}] return result def delete(self): '''delete the object''' return self._delete(self.kind, self.config.name) def create(self): '''create the object''' return self._create_from_content(self.config.name, self.config.data) def update(self): '''update the object''' # need to update the tls information and the service name for secret in self.config.secrets: result = self.service_account.find_secret(secret) if not result: self.service_account.add_secret(secret) for secret in self.config.image_pull_secrets: result = self.service_account.find_image_pull_secret(secret) if not result: self.service_account.add_image_pull_secret(secret) return self._replace_content(self.kind, self.config.name, self.config.data) def needs_update(self): ''' verify an update is needed ''' # since creating an service account generates secrets and imagepullsecrets # check_def_equal will not work # Instead, verify all secrets passed are in the list for secret in self.config.secrets: result = self.service_account.find_secret(secret) if not result: return True for secret in self.config.image_pull_secrets: result = self.service_account.find_image_pull_secret(secret) if not result: return True return False def main(): ''' ansible oc module for route ''' module = AnsibleModule( argument_spec=dict( kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'), state=dict(default='present', type='str', choices=['present', 'absent', 'list']), debug=dict(default=False, type='bool'), name=dict(default=None, required=True, type='str'), namespace=dict(default=None, required=True, type='str'), secrets=dict(default=None, type='list'), image_pull_secrets=dict(default=None, type='list'), ), supports_check_mode=True, ) rconfig = ServiceAccountConfig(module.params['name'], module.params['namespace'], module.params['kubeconfig'], module.params['secrets'], module.params['image_pull_secrets'], ) oc_sa = OCServiceAccount(rconfig, verbose=module.params['debug']) state = module.params['state'] api_rval = oc_sa.get() ##### # Get ##### if state == 'list': module.exit_json(changed=False, results=api_rval['results'], state="list") ######## # Delete ######## if state == 'absent': if oc_sa.exists(): if module.check_mode: module.exit_json(changed=False, msg='Would have performed a delete.') api_rval = oc_sa.delete() module.exit_json(changed=True, results=api_rval, state="absent") module.exit_json(changed=False, state="absent") if state == 'present': ######## # Create ######## if not oc_sa.exists(): if module.check_mode: module.exit_json(changed=False, msg='Would have performed a create.') # Create it here api_rval = oc_sa.create() if api_rval['returncode'] != 0: module.fail_json(msg=api_rval) # return the created object api_rval = oc_sa.get() if api_rval['returncode'] != 0: module.fail_json(msg=api_rval) module.exit_json(changed=True, results=api_rval, state="present") ######## # Update ######## if oc_sa.needs_update(): api_rval = oc_sa.update() if api_rval['returncode'] != 0: module.fail_json(msg=api_rval) # return the created object api_rval = oc_sa.get() if api_rval['returncode'] != 0: module.fail_json(msg=api_rval) module.exit_json(changed=True, results=api_rval, state="present") module.exit_json(changed=False, results=api_rval, state="present") module.exit_json(failed=True, changed=False, results='Unknown state passed. %s' % state, state="unknown") # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled # import module snippets. This are required from ansible.module_utils.basic import * main()
apache-2.0
petebachant/scipy
scipy/fftpack/basic.py
56
20010
""" Discrete Fourier Transforms - basic.py """ # Created by Pearu Peterson, August,September 2002 from __future__ import division, print_function, absolute_import __all__ = ['fft','ifft','fftn','ifftn','rfft','irfft', 'fft2','ifft2'] from numpy import zeros, swapaxes import numpy from . import _fftpack import atexit atexit.register(_fftpack.destroy_zfft_cache) atexit.register(_fftpack.destroy_zfftnd_cache) atexit.register(_fftpack.destroy_drfft_cache) atexit.register(_fftpack.destroy_cfft_cache) atexit.register(_fftpack.destroy_cfftnd_cache) atexit.register(_fftpack.destroy_rfft_cache) del atexit def istype(arr, typeclass): return issubclass(arr.dtype.type, typeclass) def _datacopied(arr, original): """ Strict check for `arr` not sharing any data with `original`, under the assumption that arr = asarray(original) """ if arr is original: return False if not isinstance(original, numpy.ndarray) and hasattr(original, '__array__'): return False return arr.base is None # XXX: single precision FFTs partially disabled due to accuracy issues # for large prime-sized inputs. # # See http://permalink.gmane.org/gmane.comp.python.scientific.devel/13834 # ("fftpack test failures for 0.8.0b1", Ralf Gommers, 17 Jun 2010, # @ scipy-dev) # # These should be re-enabled once the problems are resolved def _is_safe_size(n): """ Is the size of FFT such that FFTPACK can handle it in single precision with sufficient accuracy? Composite numbers of 2, 3, and 5 are accepted, as FFTPACK has those """ n = int(n) if n == 0: return True # Divide by 3 until you can't, then by 5 until you can't for c in (3, 5): while n % c == 0: n //= c # Return True if the remainder is a power of 2 return not n & (n-1) def _fake_crfft(x, n, *a, **kw): if _is_safe_size(n): return _fftpack.crfft(x, n, *a, **kw) else: return _fftpack.zrfft(x, n, *a, **kw).astype(numpy.complex64) def _fake_cfft(x, n, *a, **kw): if _is_safe_size(n): return _fftpack.cfft(x, n, *a, **kw) else: return _fftpack.zfft(x, n, *a, **kw).astype(numpy.complex64) def _fake_rfft(x, n, *a, **kw): if _is_safe_size(n): return _fftpack.rfft(x, n, *a, **kw) else: return _fftpack.drfft(x, n, *a, **kw).astype(numpy.float32) def _fake_cfftnd(x, shape, *a, **kw): if numpy.all(list(map(_is_safe_size, shape))): return _fftpack.cfftnd(x, shape, *a, **kw) else: return _fftpack.zfftnd(x, shape, *a, **kw).astype(numpy.complex64) _DTYPE_TO_FFT = { # numpy.dtype(numpy.float32): _fftpack.crfft, numpy.dtype(numpy.float32): _fake_crfft, numpy.dtype(numpy.float64): _fftpack.zrfft, # numpy.dtype(numpy.complex64): _fftpack.cfft, numpy.dtype(numpy.complex64): _fake_cfft, numpy.dtype(numpy.complex128): _fftpack.zfft, } _DTYPE_TO_RFFT = { # numpy.dtype(numpy.float32): _fftpack.rfft, numpy.dtype(numpy.float32): _fake_rfft, numpy.dtype(numpy.float64): _fftpack.drfft, } _DTYPE_TO_FFTN = { # numpy.dtype(numpy.complex64): _fftpack.cfftnd, numpy.dtype(numpy.complex64): _fake_cfftnd, numpy.dtype(numpy.complex128): _fftpack.zfftnd, # numpy.dtype(numpy.float32): _fftpack.cfftnd, numpy.dtype(numpy.float32): _fake_cfftnd, numpy.dtype(numpy.float64): _fftpack.zfftnd, } def _asfarray(x): """Like numpy asfarray, except that it does not modify x dtype if x is already an array with a float dtype, and do not cast complex types to real.""" if hasattr(x, "dtype") and x.dtype.char in numpy.typecodes["AllFloat"]: return x else: # We cannot use asfarray directly because it converts sequences of # complex to sequence of real ret = numpy.asarray(x) if ret.dtype.char not in numpy.typecodes["AllFloat"]: return numpy.asfarray(x) return ret def _fix_shape(x, n, axis): """ Internal auxiliary function for _raw_fft, _raw_fftnd.""" s = list(x.shape) if s[axis] > n: index = [slice(None)]*len(s) index[axis] = slice(0,n) x = x[index] return x, False else: index = [slice(None)]*len(s) index[axis] = slice(0,s[axis]) s[axis] = n z = zeros(s,x.dtype.char) z[index] = x return z, True def _raw_fft(x, n, axis, direction, overwrite_x, work_function): """ Internal auxiliary function for fft, ifft, rfft, irfft.""" if n is None: n = x.shape[axis] elif n != x.shape[axis]: x, copy_made = _fix_shape(x,n,axis) overwrite_x = overwrite_x or copy_made if n < 1: raise ValueError("Invalid number of FFT data points " "(%d) specified." % n) if axis == -1 or axis == len(x.shape)-1: r = work_function(x,n,direction,overwrite_x=overwrite_x) else: x = swapaxes(x, axis, -1) r = work_function(x,n,direction,overwrite_x=overwrite_x) r = swapaxes(r, axis, -1) return r def fft(x, n=None, axis=-1, overwrite_x=False): """ Return discrete Fourier transform of real or complex sequence. The returned complex array contains ``y(0), y(1),..., y(n-1)`` where ``y(j) = (x * exp(-2*pi*sqrt(-1)*j*np.arange(n)/n)).sum()``. Parameters ---------- x : array_like Array to Fourier transform. n : int, optional Length of the Fourier transform. If ``n < x.shape[axis]``, `x` is truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The default results in ``n = x.shape[axis]``. axis : int, optional Axis along which the fft's are computed; the default is over the last axis (i.e., ``axis=-1``). overwrite_x : bool, optional If True, the contents of `x` can be destroyed; the default is False. Returns ------- z : complex ndarray with the elements:: [y(0),y(1),..,y(n/2),y(1-n/2),...,y(-1)] if n is even [y(0),y(1),..,y((n-1)/2),y(-(n-1)/2),...,y(-1)] if n is odd where:: y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k* 2*pi/n), j = 0..n-1 Note that ``y(-j) = y(n-j).conjugate()``. See Also -------- ifft : Inverse FFT rfft : FFT of a real sequence Notes ----- The packing of the result is "standard": If ``A = fft(a, n)``, then ``A[0]`` contains the zero-frequency term, ``A[1:n/2]`` contains the positive-frequency terms, and ``A[n/2:]`` contains the negative-frequency terms, in order of decreasingly negative frequency. So for an 8-point transform, the frequencies of the result are [0, 1, 2, 3, -4, -3, -2, -1]. To rearrange the fft output so that the zero-frequency component is centered, like [-4, -3, -2, -1, 0, 1, 2, 3], use `fftshift`. For `n` even, ``A[n/2]`` contains the sum of the positive and negative-frequency terms. For `n` even and `x` real, ``A[n/2]`` will always be real. This function is most efficient when `n` is a power of two, and least efficient when `n` is prime. If the data type of `x` is real, a "real FFT" algorithm is automatically used, which roughly halves the computation time. To increase efficiency a little further, use `rfft`, which does the same calculation, but only outputs half of the symmetrical spectrum. If the data is both real and symmetrical, the `dct` can again double the efficiency, by generating half of the spectrum from half of the signal. Examples -------- >>> from scipy.fftpack import fft, ifft >>> x = np.arange(5) >>> np.allclose(fft(ifft(x)), x, atol=1e-15) # within numerical accuracy. True """ tmp = _asfarray(x) try: work_function = _DTYPE_TO_FFT[tmp.dtype] except KeyError: raise ValueError("type %s is not supported" % tmp.dtype) if not (istype(tmp, numpy.complex64) or istype(tmp, numpy.complex128)): overwrite_x = 1 overwrite_x = overwrite_x or _datacopied(tmp, x) if n is None: n = tmp.shape[axis] elif n != tmp.shape[axis]: tmp, copy_made = _fix_shape(tmp,n,axis) overwrite_x = overwrite_x or copy_made if n < 1: raise ValueError("Invalid number of FFT data points " "(%d) specified." % n) if axis == -1 or axis == len(tmp.shape) - 1: return work_function(tmp,n,1,0,overwrite_x) tmp = swapaxes(tmp, axis, -1) tmp = work_function(tmp,n,1,0,overwrite_x) return swapaxes(tmp, axis, -1) def ifft(x, n=None, axis=-1, overwrite_x=False): """ Return discrete inverse Fourier transform of real or complex sequence. The returned complex array contains ``y(0), y(1),..., y(n-1)`` where ``y(j) = (x * exp(2*pi*sqrt(-1)*j*np.arange(n)/n)).mean()``. Parameters ---------- x : array_like Transformed data to invert. n : int, optional Length of the inverse Fourier transform. If ``n < x.shape[axis]``, `x` is truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The default results in ``n = x.shape[axis]``. axis : int, optional Axis along which the ifft's are computed; the default is over the last axis (i.e., ``axis=-1``). overwrite_x : bool, optional If True, the contents of `x` can be destroyed; the default is False. Returns ------- ifft : ndarray of floats The inverse discrete Fourier transform. See Also -------- fft : Forward FFT Notes ----- This function is most efficient when `n` is a power of two, and least efficient when `n` is prime. If the data type of `x` is real, a "real IFFT" algorithm is automatically used, which roughly halves the computation time. """ tmp = _asfarray(x) try: work_function = _DTYPE_TO_FFT[tmp.dtype] except KeyError: raise ValueError("type %s is not supported" % tmp.dtype) if not (istype(tmp, numpy.complex64) or istype(tmp, numpy.complex128)): overwrite_x = 1 overwrite_x = overwrite_x or _datacopied(tmp, x) if n is None: n = tmp.shape[axis] elif n != tmp.shape[axis]: tmp, copy_made = _fix_shape(tmp,n,axis) overwrite_x = overwrite_x or copy_made if n < 1: raise ValueError("Invalid number of FFT data points " "(%d) specified." % n) if axis == -1 or axis == len(tmp.shape) - 1: return work_function(tmp,n,-1,1,overwrite_x) tmp = swapaxes(tmp, axis, -1) tmp = work_function(tmp,n,-1,1,overwrite_x) return swapaxes(tmp, axis, -1) def rfft(x, n=None, axis=-1, overwrite_x=False): """ Discrete Fourier transform of a real sequence. Parameters ---------- x : array_like, real-valued The data to transform. n : int, optional Defines the length of the Fourier transform. If `n` is not specified (the default) then ``n = x.shape[axis]``. If ``n < x.shape[axis]``, `x` is truncated, if ``n > x.shape[axis]``, `x` is zero-padded. axis : int, optional The axis along which the transform is applied. The default is the last axis. overwrite_x : bool, optional If set to true, the contents of `x` can be overwritten. Default is False. Returns ------- z : real ndarray The returned real array contains:: [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))] if n is even [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))] if n is odd where:: y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k*2*pi/n) j = 0..n-1 Note that ``y(-j) == y(n-j).conjugate()``. See Also -------- fft, irfft, scipy.fftpack.basic Notes ----- Within numerical accuracy, ``y == rfft(irfft(y))``. Examples -------- >>> from scipy.fftpack import fft, rfft >>> a = [9, -9, 1, 3] >>> fft(a) array([ 4. +0.j, 8.+12.j, 16. +0.j, 8.-12.j]) >>> rfft(a) array([ 4., 8., 12., 16.]) """ tmp = _asfarray(x) if not numpy.isrealobj(tmp): raise TypeError("1st argument must be real sequence") try: work_function = _DTYPE_TO_RFFT[tmp.dtype] except KeyError: raise ValueError("type %s is not supported" % tmp.dtype) overwrite_x = overwrite_x or _datacopied(tmp, x) return _raw_fft(tmp,n,axis,1,overwrite_x,work_function) def irfft(x, n=None, axis=-1, overwrite_x=False): """ Return inverse discrete Fourier transform of real sequence x. The contents of `x` are interpreted as the output of the `rfft` function. Parameters ---------- x : array_like Transformed data to invert. n : int, optional Length of the inverse Fourier transform. If n < x.shape[axis], x is truncated. If n > x.shape[axis], x is zero-padded. The default results in n = x.shape[axis]. axis : int, optional Axis along which the ifft's are computed; the default is over the last axis (i.e., axis=-1). overwrite_x : bool, optional If True, the contents of `x` can be destroyed; the default is False. Returns ------- irfft : ndarray of floats The inverse discrete Fourier transform. See Also -------- rfft, ifft Notes ----- The returned real array contains:: [y(0),y(1),...,y(n-1)] where for n is even:: y(j) = 1/n (sum[k=1..n/2-1] (x[2*k-1]+sqrt(-1)*x[2*k]) * exp(sqrt(-1)*j*k* 2*pi/n) + c.c. + x[0] + (-1)**(j) x[n-1]) and for n is odd:: y(j) = 1/n (sum[k=1..(n-1)/2] (x[2*k-1]+sqrt(-1)*x[2*k]) * exp(sqrt(-1)*j*k* 2*pi/n) + c.c. + x[0]) c.c. denotes complex conjugate of preceding expression. For details on input parameters, see `rfft`. """ tmp = _asfarray(x) if not numpy.isrealobj(tmp): raise TypeError("1st argument must be real sequence") try: work_function = _DTYPE_TO_RFFT[tmp.dtype] except KeyError: raise ValueError("type %s is not supported" % tmp.dtype) overwrite_x = overwrite_x or _datacopied(tmp, x) return _raw_fft(tmp,n,axis,-1,overwrite_x,work_function) def _raw_fftnd(x, s, axes, direction, overwrite_x, work_function): """ Internal auxiliary function for fftnd, ifftnd.""" if s is None: if axes is None: s = x.shape else: s = numpy.take(x.shape, axes) s = tuple(s) if axes is None: noaxes = True axes = list(range(-x.ndim, 0)) else: noaxes = False if len(axes) != len(s): raise ValueError("when given, axes and shape arguments " "have to be of the same length") for dim in s: if dim < 1: raise ValueError("Invalid number of FFT data points " "(%s) specified." % (s,)) # No need to swap axes, array is in C order if noaxes: for i in axes: x, copy_made = _fix_shape(x, s[i], i) overwrite_x = overwrite_x or copy_made return work_function(x,s,direction,overwrite_x=overwrite_x) # We ordered axes, because the code below to push axes at the end of the # array assumes axes argument is in ascending order. id = numpy.argsort(axes) axes = [axes[i] for i in id] s = [s[i] for i in id] # Swap the request axes, last first (i.e. First swap the axis which ends up # at -1, then at -2, etc...), such as the request axes on which the # operation is carried become the last ones for i in range(1, len(axes)+1): x = numpy.swapaxes(x, axes[-i], -i) # We can now operate on the axes waxes, the p last axes (p = len(axes)), by # fixing the shape of the input array to 1 for any axis the fft is not # carried upon. waxes = list(range(x.ndim - len(axes), x.ndim)) shape = numpy.ones(x.ndim) shape[waxes] = s for i in range(len(waxes)): x, copy_made = _fix_shape(x, s[i], waxes[i]) overwrite_x = overwrite_x or copy_made r = work_function(x, shape, direction, overwrite_x=overwrite_x) # reswap in the reverse order (first axis first, etc...) to get original # order for i in range(len(axes), 0, -1): r = numpy.swapaxes(r, -i, axes[-i]) return r def fftn(x, shape=None, axes=None, overwrite_x=False): """ Return multidimensional discrete Fourier transform. The returned array contains:: y[j_1,..,j_d] = sum[k_1=0..n_1-1, ..., k_d=0..n_d-1] x[k_1,..,k_d] * prod[i=1..d] exp(-sqrt(-1)*2*pi/n_i * j_i * k_i) where d = len(x.shape) and n = x.shape. Note that ``y[..., -j_i, ...] = y[..., n_i-j_i, ...].conjugate()``. Parameters ---------- x : array_like The (n-dimensional) array to transform. shape : tuple of ints, optional The shape of the result. If both `shape` and `axes` (see below) are None, `shape` is ``x.shape``; if `shape` is None but `axes` is not None, then `shape` is ``scipy.take(x.shape, axes, axis=0)``. If ``shape[i] > x.shape[i]``, the i-th dimension is padded with zeros. If ``shape[i] < x.shape[i]``, the i-th dimension is truncated to length ``shape[i]``. axes : array_like of ints, optional The axes of `x` (`y` if `shape` is not None) along which the transform is applied. overwrite_x : bool, optional If True, the contents of `x` can be destroyed. Default is False. Returns ------- y : complex-valued n-dimensional numpy array The (n-dimensional) DFT of the input array. See Also -------- ifftn Examples -------- >>> from scipy.fftpack import fftn, ifftn >>> y = (-np.arange(16), 8 - np.arange(16), np.arange(16)) >>> np.allclose(y, fftn(ifftn(y))) True """ return _raw_fftn_dispatch(x, shape, axes, overwrite_x, 1) def _raw_fftn_dispatch(x, shape, axes, overwrite_x, direction): tmp = _asfarray(x) try: work_function = _DTYPE_TO_FFTN[tmp.dtype] except KeyError: raise ValueError("type %s is not supported" % tmp.dtype) if not (istype(tmp, numpy.complex64) or istype(tmp, numpy.complex128)): overwrite_x = 1 overwrite_x = overwrite_x or _datacopied(tmp, x) return _raw_fftnd(tmp,shape,axes,direction,overwrite_x,work_function) def ifftn(x, shape=None, axes=None, overwrite_x=False): """ Return inverse multi-dimensional discrete Fourier transform of arbitrary type sequence x. The returned array contains:: y[j_1,..,j_d] = 1/p * sum[k_1=0..n_1-1, ..., k_d=0..n_d-1] x[k_1,..,k_d] * prod[i=1..d] exp(sqrt(-1)*2*pi/n_i * j_i * k_i) where ``d = len(x.shape)``, ``n = x.shape``, and ``p = prod[i=1..d] n_i``. For description of parameters see `fftn`. See Also -------- fftn : for detailed information. """ return _raw_fftn_dispatch(x, shape, axes, overwrite_x, -1) def fft2(x, shape=None, axes=(-2,-1), overwrite_x=False): """ 2-D discrete Fourier transform. Return the two-dimensional discrete Fourier transform of the 2-D argument `x`. See Also -------- fftn : for detailed information. """ return fftn(x,shape,axes,overwrite_x) def ifft2(x, shape=None, axes=(-2,-1), overwrite_x=False): """ 2-D discrete inverse Fourier transform of real or complex sequence. Return inverse two-dimensional discrete Fourier transform of arbitrary type sequence x. See `ifft` for more information. See also -------- fft2, ifft """ return ifftn(x,shape,axes,overwrite_x)
bsd-3-clause
alexherns/biotite-scripts
cluster_coverage.py
1
2808
#!/usr/bin/env python2.7 import sys, operator, argparse from Bio import SeqIO parser = argparse.ArgumentParser(description='''Prints out the coverage values for each cluster, by sample and total. Also lists number of hits in each cluster.''', formatter_class=argparse.ArgumentDefaultsHelpFormatter, add_help=False, epilog= '''TSV of features and as downloaded from ggkbase. Scaffold_gene is in column 2. Coverage value is in column 5. Clusters file as generated from USEARCH ''') #Required arguments required = parser.add_argument_group('REQUIRED') required.add_argument('-c', help= 'clusters.uc', required=True, type=str) required.add_argument('-t', help= 'features.tsv', required=True, type=str) #Optional arguments optional = parser.add_argument_group('OPTIONAL') optional.add_argument('-h', action="help", help="show this help message and exit") args = parser.parse_args() cluster_file= args.c tsv_file= args.t #Create a dictionary of feature:coverage values #Read in the tsv of features handle= open(tsv_file, "r") feat2cov= {} samples= [] for line in handle: contig_features= line.strip().split("\t") samples.append(contig_features[1].split("_scaffold")[0]) feature, coverage= contig_features[1], contig_features[4] feat2cov[feature]= float(coverage) samples= list(set(samples)) handle.close() #Select all non-redundant cluster lines from file clusters= [line.strip().split("\t") for line in open(cluster_file) if line[0] in ["H", "C"]] #Extract unique list of all clusters cluster_names= list(set([line[1]for line in clusters])) #Dictionary of clusters: # clust_dict[cluster_name: [clust1, ..., clustN]] clust_dict= {} for cluster in clusters: if cluster[1] not in clust_dict: clust_dict[cluster[1]]= [] clust_dict[cluster[1]].append(cluster) #List to contain output lines cov_list= [] for cluster in clust_dict: #Each line in output, formatted as list clustercov= [cluster]+[0]*(len(samples)+3) for line in clust_dict[cluster]: scaf= line[8] #Append centroids if line[0]=="C": clustercov.append(scaf) sample= scaf.split("_scaffold")[0] if sample not in samples: print "FAIL: SCAF", scaf else: clustercov[samples.index(sample)+1]+=feat2cov[scaf.split(" ")[0]] #Number of samples with positive hits clustercov[-2]= len([i for i in clustercov[1:-4] if i > 0]) #Number of hits clustercov[-3]= len(clust_dict[cluster]) #Total (raw and not normalized) cluster coverage value clustercov[-4]= sum(clustercov[1:-4]) cov_list.append(clustercov) #Print header line print "TAX\t"+"\t".join(samples)+"\tTotal\t#Hits\t#Samples\tCentroid" #Print each line in output print "\n".join(["\t".join([str(i) for i in row]) for row in cov_list])
mit
alexanderturner/ansible
lib/ansible/modules/network/nxos/nxos_pim_rp_address.py
8
12638
#!/usr/bin/python # # 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 = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: nxos_pim_rp_address version_added: "2.2" short_description: Manages configuration of an PIM static RP address instance. description: - Manages configuration of an Protocol Independent Multicast (PIM) static rendezvous point (RP) address instance. author: Gabriele Gerbino (@GGabriele) extends_documentation_fragment: nxos notes: - C(state=absent) remove the whole rp-address configuration, if existing. options: rp_address: description: - Configures a Protocol Independent Multicast (PIM) static rendezvous point (RP) address. Valid values are unicast addresses. required: true group_list: description: - Group range for static RP. Valid values are multicast addresses. required: false default: null prefix_list: description: - Prefix list policy for static RP. Valid values are prefix-list policy names. required: false default: null route_map: description: - Route map policy for static RP. Valid values are route-map policy names. required: false default: null bidir: description: - Group range is treated in PIM bidirectional mode. required: false choices: ['true','false'] default: null ''' EXAMPLES = ''' - nxos_pim_rp_address: rp_address: "10.1.1.20" state: present username: "{{ un }}" password: "{{ pwd }}" host: "{{ inventory_hostname }}" ''' RETURN = ''' proposed: description: k/v pairs of parameters passed into module returned: verbose mode type: dict sample: {"rp_address": "10.1.1.21"} existing: description: list of existing pim rp-address configuration entries returned: verbose mode type: list sample: [] end_state: description: pim rp-address configuration entries after module execution returned: verbose mode type: list sample: [{"bidir": false, "group_list": "224.0.0.0/4", "rp_address": "10.1.1.21"}] updates: description: commands sent to the device returned: always type: list sample: ["router bgp 65535", "vrf test", "router-id 1.1.1.1"] changed: description: check to see if a change was made on the device returned: always type: boolean sample: true ''' # COMMON CODE FOR MIGRATION import re from ansible.module_utils.basic import get_exception from ansible.module_utils.netcfg import NetworkConfig, ConfigLine from ansible.module_utils.shell import ShellError try: from ansible.module_utils.nxos import get_module except ImportError: from ansible.module_utils.nxos import NetworkModule def to_list(val): if isinstance(val, (list, tuple)): return list(val) elif val is not None: return [val] else: return list() class CustomNetworkConfig(NetworkConfig): def expand_section(self, configobj, S=None): if S is None: S = list() S.append(configobj) for child in configobj.children: if child in S: continue self.expand_section(child, S) return S def get_object(self, path): for item in self.items: if item.text == path[-1]: parents = [p.text for p in item.parents] if parents == path[:-1]: return item def to_block(self, section): return '\n'.join([item.raw for item in section]) def get_section(self, path): try: section = self.get_section_objects(path) return self.to_block(section) except ValueError: return list() def get_section_objects(self, path): if not isinstance(path, list): path = [path] obj = self.get_object(path) if not obj: raise ValueError('path does not exist in config') return self.expand_section(obj) def add(self, lines, parents=None): """Adds one or lines of configuration """ ancestors = list() offset = 0 obj = None ## global config command if not parents: for line in to_list(lines): item = ConfigLine(line) item.raw = line if item not in self.items: self.items.append(item) else: for index, p in enumerate(parents): try: i = index + 1 obj = self.get_section_objects(parents[:i])[0] ancestors.append(obj) except ValueError: # add parent to config offset = index * self.indent obj = ConfigLine(p) obj.raw = p.rjust(len(p) + offset) if ancestors: obj.parents = list(ancestors) ancestors[-1].children.append(obj) self.items.append(obj) ancestors.append(obj) # add child objects for line in to_list(lines): # check if child already exists for child in ancestors[-1].children: if child.text == line: break else: offset = len(parents) * self.indent item = ConfigLine(line) item.raw = line.rjust(len(line) + offset) item.parents = ancestors ancestors[-1].children.append(item) self.items.append(item) def get_network_module(**kwargs): try: return get_module(**kwargs) except NameError: return NetworkModule(**kwargs) def get_config(module, include_defaults=False): config = module.params['config'] if not config: try: config = module.get_config() except AttributeError: defaults = module.params['include_defaults'] config = module.config.get_config(include_defaults=defaults) return CustomNetworkConfig(indent=2, contents=config) def load_config(module, candidate): config = get_config(module) commands = candidate.difference(config) commands = [str(c).strip() for c in commands] save_config = module.params['save'] result = dict(changed=False) if commands: if not module.check_mode: try: module.configure(commands) except AttributeError: module.config(commands) if save_config: try: module.config.save_config() except AttributeError: module.execute(['copy running-config startup-config']) result['changed'] = True result['updates'] = commands return result # END OF COMMON CODE BOOL_PARAMS = ['bidir'] PARAM_TO_COMMAND_KEYMAP = { 'rp_address': 'ip pim rp-address' } PARAM_TO_DEFAULT_KEYMAP = {} WARNINGS = [] def invoke(name, *args, **kwargs): func = globals().get(name) if func: return func(*args, **kwargs) def get_value(config, module): value_list = [] splitted_config = config.splitlines() for line in splitted_config: tmp = {} if 'ip pim rp-address' in line: splitted_line = line.split() tmp['rp_address'] = splitted_line[3] if len(splitted_line) > 5: value = splitted_line[5] if splitted_line[4] == 'route-map': tmp['route_map'] = value elif splitted_line[4] == 'prefix-list': tmp['prefix_list'] = value elif splitted_line[4] == 'group-list': tmp['group_list'] = value if 'bidir' in line: tmp['bidir'] = True else: tmp['bidir'] = False value_list.append(tmp) return value_list def get_existing(module, args): existing = {} config = str(get_config(module)) existing = get_value(config, module) return existing def apply_key_map(key_map, table): new_dict = {} for key, value in table.items(): new_key = key_map.get(key) if new_key: value = table.get(key) if value: new_dict[new_key] = value else: new_dict[new_key] = value return new_dict def state_present(module, existing, proposed, candidate): command = 'ip pim rp-address {0}'.format(module.params['rp_address']) commands = build_command(proposed, command) if commands: candidate.add(commands, parents=[]) def build_command(param_dict, command): for param in ['group_list', 'prefix_list', 'route_map']: if param_dict.get(param): command += ' {0} {1}'.format( param.replace('_', '-'), param_dict.get(param)) if param_dict.get('bidir'): command += ' bidir' return [command] def state_absent(module, existing, proposed, candidate): commands = list() for each in existing: if each.get('rp_address') == proposed['rp_address']: command = 'no ip pim rp-address {0}'.format(proposed['rp_address']) if each.get('group_list'): commands = build_command(each, command) else: commands = [command] if commands: candidate.add(commands, parents=[]) def main(): argument_spec = dict( rp_address=dict(required=True, type='str'), group_list=dict(required=False, type='str'), prefix_list=dict(required=False, type='str'), route_map=dict(required=False, type='str'), bidir=dict(required=False, type='bool'), state=dict(choices=['present', 'absent'], default='present', required=False), include_defaults=dict(default=False), config=dict(), save=dict(type='bool', default=False) ) module = get_network_module(argument_spec=argument_spec, mutually_exclusive=[['group_list', 'route_map'], ['group_list', 'prefix_list'], ['route_map', 'prefix_list']], supports_check_mode=True) state = module.params['state'] args = [ 'rp_address', 'group_list', 'prefix_list', 'route_map', 'bidir' ] existing = invoke('get_existing', module, args) end_state = existing proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) proposed = {} for key, value in proposed_args.items(): if str(value).lower() == 'true': value = True elif str(value).lower() == 'false': value = False for each in existing: if each.get(key) or (not each.get(key) and value): proposed[key] = value result = {} candidate = CustomNetworkConfig(indent=3) invoke('state_%s' % state, module, existing, proposed, candidate) try: response = load_config(module, candidate) result.update(response) except ShellError: exc = get_exception() module.fail_json(msg=str(exc)) result['connected'] = module.connected if module._verbosity > 0: end_state = invoke('get_existing', module, args) result['end_state'] = end_state result['existing'] = existing result['proposed'] = proposed_args if WARNINGS: result['warnings'] = WARNINGS module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
diorcety/intellij-community
python/lib/Lib/site-packages/django/utils/tree.py
310
5778
""" A class for storing a tree graph. Primarily used for filter constructs in the ORM. """ from django.utils.copycompat import deepcopy class Node(object): """ A single internal node in the tree graph. A Node should be viewed as a connection (the root) with the children being either leaf nodes or other Node instances. """ # Standard connector type. Clients usually won't use this at all and # subclasses will usually override the value. default = 'DEFAULT' def __init__(self, children=None, connector=None, negated=False): """ Constructs a new Node. If no connector is given, the default will be used. Warning: You probably don't want to pass in the 'negated' parameter. It is NOT the same as constructing a node and calling negate() on the result. """ self.children = children and children[:] or [] self.connector = connector or self.default self.subtree_parents = [] self.negated = negated # We need this because of django.db.models.query_utils.Q. Q. __init__() is # problematic, but it is a natural Node subclass in all other respects. def _new_instance(cls, children=None, connector=None, negated=False): """ This is called to create a new instance of this class when we need new Nodes (or subclasses) in the internal code in this class. Normally, it just shadows __init__(). However, subclasses with an __init__ signature that is not an extension of Node.__init__ might need to implement this method to allow a Node to create a new instance of them (if they have any extra setting up to do). """ obj = Node(children, connector, negated) obj.__class__ = cls return obj _new_instance = classmethod(_new_instance) def __str__(self): if self.negated: return '(NOT (%s: %s))' % (self.connector, ', '.join([str(c) for c in self.children])) return '(%s: %s)' % (self.connector, ', '.join([str(c) for c in self.children])) def __deepcopy__(self, memodict): """ Utility method used by copy.deepcopy(). """ obj = Node(connector=self.connector, negated=self.negated) obj.__class__ = self.__class__ obj.children = deepcopy(self.children, memodict) obj.subtree_parents = deepcopy(self.subtree_parents, memodict) return obj def __len__(self): """ The size of a node if the number of children it has. """ return len(self.children) def __nonzero__(self): """ For truth value testing. """ return bool(self.children) def __contains__(self, other): """ Returns True is 'other' is a direct child of this instance. """ return other in self.children def add(self, node, conn_type): """ Adds a new node to the tree. If the conn_type is the same as the root's current connector type, the node is added to the first level. Otherwise, the whole tree is pushed down one level and a new root connector is created, connecting the existing tree and the new node. """ if node in self.children and conn_type == self.connector: return if len(self.children) < 2: self.connector = conn_type if self.connector == conn_type: if isinstance(node, Node) and (node.connector == conn_type or len(node) == 1): self.children.extend(node.children) else: self.children.append(node) else: obj = self._new_instance(self.children, self.connector, self.negated) self.connector = conn_type self.children = [obj, node] def negate(self): """ Negate the sense of the root connector. This reorganises the children so that the current node has a single child: a negated node containing all the previous children. This slightly odd construction makes adding new children behave more intuitively. Interpreting the meaning of this negate is up to client code. This method is useful for implementing "not" arrangements. """ self.children = [self._new_instance(self.children, self.connector, not self.negated)] self.connector = self.default def start_subtree(self, conn_type): """ Sets up internal state so that new nodes are added to a subtree of the current node. The conn_type specifies how the sub-tree is joined to the existing children. """ if len(self.children) == 1: self.connector = conn_type elif self.connector != conn_type: self.children = [self._new_instance(self.children, self.connector, self.negated)] self.connector = conn_type self.negated = False self.subtree_parents.append(self.__class__(self.children, self.connector, self.negated)) self.connector = self.default self.negated = False self.children = [] def end_subtree(self): """ Closes off the most recently unmatched start_subtree() call. This puts the current state into a node of the parent tree and returns the current instances state to be the parent. """ obj = self.subtree_parents.pop() node = self.__class__(self.children, self.connector) self.connector = obj.connector self.negated = obj.negated self.children = obj.children self.children.append(node)
apache-2.0
mythmon/airmozilla
airmozilla/starred/tests/test_context_processors.py
12
1985
from nose.tools import eq_ from django.test.client import RequestFactory from django.contrib.auth.models import User, AnonymousUser from airmozilla.main.models import Event from airmozilla.base.tests.testbase import DjangoTestCase from airmozilla.starred.models import StarredEvent from airmozilla.starred.context_processors import stars class StarsTestCase(DjangoTestCase): def test_stars_anonymous(self): request = RequestFactory().get('/some/page/') request.user = AnonymousUser() result = stars(request) eq_(result, {}) def test_stars_user_empty(self): request = RequestFactory().get('/some/page/') request.user = User.objects.create( username='lisa' ) result = stars(request) eq_(result, {'star_ids': ''}) def test_stars_user_not_empty(self): request = RequestFactory().get('/some/page/') user = User.objects.create( username='lisa' ) request.user = user result = stars(request) eq_(result, {'star_ids': ''}) event = Event.objects.get(title='Test event') starred_event = StarredEvent.objects.create( event=event, user=user, ) result = stars(request) eq_(result, {'star_ids': str(event.id)}) # delete the starred event starred_event.delete() result = stars(request) eq_(result, {'star_ids': ''}) def test_stars_user_delete_event(self): request = RequestFactory().get('/some/page/') user = User.objects.create( username='lisa' ) request.user = user event = Event.objects.get(title='Test event') StarredEvent.objects.create( event=event, user=user, ) result = stars(request) eq_(result, {'star_ids': str(event.id)}) event.delete() result = stars(request) eq_(result, {'star_ids': ''})
bsd-3-clause
mackong/gitql
prettytable/prettytable.py
1
54214
#!/usr/bin/env python # # Copyright (c) 2009-2013, Luke Maurits <luke@maurits.id.au> # All rights reserved. # With contributions from: # * Chris Clark # * Klein Stephane # # 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. # * The name of the author may not 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. __version__ = "0.7.2" import copy import csv import random import re import sys import textwrap import itertools import unicodedata py3k = sys.version_info[0] >= 3 if py3k: unicode = str basestring = str itermap = map iterzip = zip uni_chr = chr from html.parser import HTMLParser else: itermap = itertools.imap iterzip = itertools.izip uni_chr = unichr from HTMLParser import HTMLParser if py3k and sys.version_info[1] >= 2: from html import escape else: from cgi import escape # hrule styles FRAME = 0 ALL = 1 NONE = 2 HEADER = 3 # Table styles DEFAULT = 10 MSWORD_FRIENDLY = 11 PLAIN_COLUMNS = 12 RANDOM = 20 _re = re.compile("\033\[[0-9;]*m") def _get_size(text): lines = text.split("\n") height = len(lines) width = max([_str_block_width(line) for line in lines]) return (width, height) class PrettyTable(object): def __init__(self, field_names=None, **kwargs): """Return a new PrettyTable instance Arguments: encoding - Unicode encoding scheme used to decode any encoded input field_names - list or tuple of field names fields - list or tuple of field names to include in displays start - index of first data row to include in output end - index of last data row to include in output PLUS ONE (list slice style) header - print a header showing field names (True or False) header_style - stylisation to apply to field names in header ("cap", "title", "upper", "lower" or None) border - print a border around the table (True or False) hrules - controls printing of horizontal rules after rows. Allowed values: FRAME, HEADER, ALL, NONE vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE int_format - controls formatting of integer data float_format - controls formatting of floating point data padding_width - number of spaces on either side of column data (only used if left and right paddings are None) left_padding_width - number of spaces on left hand side of column data right_padding_width - number of spaces on right hand side of column data vertical_char - single character string used to draw vertical lines horizontal_char - single character string used to draw horizontal lines junction_char - single character string used to draw line junctions sortby - name of field to sort rows by sort_key - sorting key function, applied to data points before sorting valign - default valign for each row (None, "t", "m" or "b") reversesort - True or False to sort in descending or ascending order""" self.encoding = kwargs.get("encoding", "UTF-8") # Data self._field_names = [] self._align = {} self._valign = {} self._max_width = {} self._rows = [] if field_names: self.field_names = field_names else: self._widths = [] # Options self._options = "start end fields header border sortby reversesort sort_key attributes format hrules vrules".split() self._options.extend("int_format float_format padding_width left_padding_width right_padding_width".split()) self._options.extend("vertical_char horizontal_char junction_char header_style valign xhtml print_empty".split()) for option in self._options: if option in kwargs: self._validate_option(option, kwargs[option]) else: kwargs[option] = None self._start = kwargs["start"] or 0 self._end = kwargs["end"] or None self._fields = kwargs["fields"] or None if kwargs["header"] in (True, False): self._header = kwargs["header"] else: self._header = True self._header_style = kwargs["header_style"] or None if kwargs["border"] in (True, False): self._border = kwargs["border"] else: self._border = True self._hrules = kwargs["hrules"] or FRAME self._vrules = kwargs["vrules"] or ALL self._sortby = kwargs["sortby"] or None if kwargs["reversesort"] in (True, False): self._reversesort = kwargs["reversesort"] else: self._reversesort = False self._sort_key = kwargs["sort_key"] or (lambda x: x) self._int_format = kwargs["int_format"] or {} self._float_format = kwargs["float_format"] or {} self._padding_width = kwargs["padding_width"] or 1 self._left_padding_width = kwargs["left_padding_width"] or None self._right_padding_width = kwargs["right_padding_width"] or None self._vertical_char = kwargs["vertical_char"] or self._unicode("|") self._horizontal_char = kwargs["horizontal_char"] or self._unicode("-") self._junction_char = kwargs["junction_char"] or self._unicode("+") if kwargs["print_empty"] in (True, False): self._print_empty = kwargs["print_empty"] else: self._print_empty = True self._format = kwargs["format"] or False self._xhtml = kwargs["xhtml"] or False self._attributes = kwargs["attributes"] or {} def _unicode(self, value): if not isinstance(value, basestring): value = str(value) if not isinstance(value, unicode): value = unicode(value, self.encoding, "strict") return value def _justify(self, text, width, align): excess = width - _str_block_width(text) if align == "l": return text + excess * " " elif align == "r": return excess * " " + text else: if excess % 2: # Uneven padding # Put more space on right if text is of odd length... if _str_block_width(text) % 2: return (excess//2)*" " + text + (excess//2 + 1)*" " # and more space on left if text is of even length else: return (excess//2 + 1)*" " + text + (excess//2)*" " # Why distribute extra space this way? To match the behaviour of # the inbuilt str.center() method. else: # Equal padding on either side return (excess//2)*" " + text + (excess//2)*" " def __getattr__(self, name): if name == "rowcount": return len(self._rows) elif name == "colcount": if self._field_names: return len(self._field_names) elif self._rows: return len(self._rows[0]) else: return 0 else: raise AttributeError(name) def __getitem__(self, index): new = PrettyTable() new.field_names = self.field_names for attr in self._options: setattr(new, "_"+attr, getattr(self, "_"+attr)) setattr(new, "_align", getattr(self, "_align")) if isinstance(index, slice): for row in self._rows[index]: new.add_row(row) elif isinstance(index, int): new.add_row(self._rows[index]) else: raise Exception("Index %s is invalid, must be an integer or slice" % str(index)) return new if py3k: def __str__(self): return self.__unicode__() else: def __str__(self): return self.__unicode__().encode(self.encoding) def __unicode__(self): return self.get_string() ############################## # ATTRIBUTE VALIDATORS # ############################## # The method _validate_option is all that should be used elsewhere in the code base to validate options. # It will call the appropriate validation method for that option. The individual validation methods should # never need to be called directly (although nothing bad will happen if they *are*). # Validation happens in TWO places. # Firstly, in the property setters defined in the ATTRIBUTE MANAGMENT section. # Secondly, in the _get_options method, where keyword arguments are mixed with persistent settings def _validate_option(self, option, val): if option in ("field_names"): self._validate_field_names(val) elif option in ("start", "end", "max_width", "padding_width", "left_padding_width", "right_padding_width", "format"): self._validate_nonnegative_int(option, val) elif option in ("sortby"): self._validate_field_name(option, val) elif option in ("sort_key"): self._validate_function(option, val) elif option in ("hrules"): self._validate_hrules(option, val) elif option in ("vrules"): self._validate_vrules(option, val) elif option in ("fields"): self._validate_all_field_names(option, val) elif option in ("header", "border", "reversesort", "xhtml", "print_empty"): self._validate_true_or_false(option, val) elif option in ("header_style"): self._validate_header_style(val) elif option in ("int_format"): self._validate_int_format(option, val) elif option in ("float_format"): self._validate_float_format(option, val) elif option in ("vertical_char", "horizontal_char", "junction_char"): self._validate_single_char(option, val) elif option in ("attributes"): self._validate_attributes(option, val) else: raise Exception("Unrecognised option: %s!" % option) def _validate_field_names(self, val): # Check for appropriate length if self._field_names: try: assert len(val) == len(self._field_names) except AssertionError: raise Exception("Field name list has incorrect number of values, (actual) %d!=%d (expected)" % (len(val), len(self._field_names))) if self._rows: try: assert len(val) == len(self._rows[0]) except AssertionError: raise Exception("Field name list has incorrect number of values, (actual) %d!=%d (expected)" % (len(val), len(self._rows[0]))) # # Check for uniqueness # try: # assert len(val) == len(set(val)) # except AssertionError: # raise Exception("Field names must be unique!") def _validate_header_style(self, val): try: assert val in ("cap", "title", "upper", "lower", None) except AssertionError: raise Exception("Invalid header style, use cap, title, upper, lower or None!") def _validate_align(self, val): try: assert val in ["l","c","r"] except AssertionError: raise Exception("Alignment %s is invalid, use l, c or r!" % val) def _validate_valign(self, val): try: assert val in ["t","m","b",None] except AssertionError: raise Exception("Alignment %s is invalid, use t, m, b or None!" % val) def _validate_nonnegative_int(self, name, val): try: assert int(val) >= 0 except AssertionError: raise Exception("Invalid value for %s: %s!" % (name, self._unicode(val))) def _validate_true_or_false(self, name, val): try: assert val in (True, False) except AssertionError: raise Exception("Invalid value for %s! Must be True or False." % name) def _validate_int_format(self, name, val): if val == "": return try: assert type(val) in (str, unicode) assert val.isdigit() except AssertionError: raise Exception("Invalid value for %s! Must be an integer format string." % name) def _validate_float_format(self, name, val): if val == "": return try: assert type(val) in (str, unicode) assert "." in val bits = val.split(".") assert len(bits) <= 2 assert bits[0] == "" or bits[0].isdigit() assert bits[1] == "" or bits[1].isdigit() except AssertionError: raise Exception("Invalid value for %s! Must be a float format string." % name) def _validate_function(self, name, val): try: assert hasattr(val, "__call__") except AssertionError: raise Exception("Invalid value for %s! Must be a function." % name) def _validate_hrules(self, name, val): try: assert val in (ALL, FRAME, HEADER, NONE) except AssertionError: raise Exception("Invalid value for %s! Must be ALL, FRAME, HEADER or NONE." % name) def _validate_vrules(self, name, val): try: assert val in (ALL, FRAME, NONE) except AssertionError: raise Exception("Invalid value for %s! Must be ALL, FRAME, or NONE." % name) def _validate_field_name(self, name, val): try: assert (val in self._field_names) or (val is None) except AssertionError: raise Exception("Invalid field name: %s!" % val) def _validate_all_field_names(self, name, val): try: for x in val: self._validate_field_name(name, x) except AssertionError: raise Exception("fields must be a sequence of field names!") def _validate_single_char(self, name, val): try: assert _str_block_width(val) == 1 except AssertionError: raise Exception("Invalid value for %s! Must be a string of length 1." % name) def _validate_attributes(self, name, val): try: assert isinstance(val, dict) except AssertionError: raise Exception("attributes must be a dictionary of name/value pairs!") ############################## # ATTRIBUTE MANAGEMENT # ############################## def _get_field_names(self): return self._field_names """The names of the fields Arguments: fields - list or tuple of field names""" def _set_field_names(self, val): val = [self._unicode(x) for x in val] self._validate_option("field_names", val) if self._field_names: old_names = self._field_names[:] self._field_names = val if self._align and old_names: for old_name, new_name in zip(old_names, val): self._align[new_name] = self._align[old_name] for old_name in old_names: if old_name not in self._align: self._align.pop(old_name) else: for field in self._field_names: self._align[field] = "c" if self._valign and old_names: for old_name, new_name in zip(old_names, val): self._valign[new_name] = self._valign[old_name] for old_name in old_names: if old_name not in self._valign: self._valign.pop(old_name) else: for field in self._field_names: self._valign[field] = "t" field_names = property(_get_field_names, _set_field_names) def _get_align(self): return self._align def _set_align(self, val): self._validate_align(val) for field in self._field_names: self._align[field] = val align = property(_get_align, _set_align) def _get_valign(self): return self._valign def _set_valign(self, val): self._validate_valign(val) for field in self._field_names: self._valign[field] = val valign = property(_get_valign, _set_valign) def _get_max_width(self): return self._max_width def _set_max_width(self, val): self._validate_option("max_width", val) for field in self._field_names: self._max_width[field] = val max_width = property(_get_max_width, _set_max_width) def _get_fields(self): """List or tuple of field names to include in displays Arguments: fields - list or tuple of field names to include in displays""" return self._fields def _set_fields(self, val): self._validate_option("fields", val) self._fields = val fields = property(_get_fields, _set_fields) def _get_start(self): """Start index of the range of rows to print Arguments: start - index of first data row to include in output""" return self._start def _set_start(self, val): self._validate_option("start", val) self._start = val start = property(_get_start, _set_start) def _get_end(self): """End index of the range of rows to print Arguments: end - index of last data row to include in output PLUS ONE (list slice style)""" return self._end def _set_end(self, val): self._validate_option("end", val) self._end = val end = property(_get_end, _set_end) def _get_sortby(self): """Name of field by which to sort rows Arguments: sortby - field name to sort by""" return self._sortby def _set_sortby(self, val): self._validate_option("sortby", val) self._sortby = val sortby = property(_get_sortby, _set_sortby) def _get_reversesort(self): """Controls direction of sorting (ascending vs descending) Arguments: reveresort - set to True to sort by descending order, or False to sort by ascending order""" return self._reversesort def _set_reversesort(self, val): self._validate_option("reversesort", val) self._reversesort = val reversesort = property(_get_reversesort, _set_reversesort) def _get_sort_key(self): """Sorting key function, applied to data points before sorting Arguments: sort_key - a function which takes one argument and returns something to be sorted""" return self._sort_key def _set_sort_key(self, val): self._validate_option("sort_key", val) self._sort_key = val sort_key = property(_get_sort_key, _set_sort_key) def _get_header(self): """Controls printing of table header with field names Arguments: header - print a header showing field names (True or False)""" return self._header def _set_header(self, val): self._validate_option("header", val) self._header = val header = property(_get_header, _set_header) def _get_header_style(self): """Controls stylisation applied to field names in header Arguments: header_style - stylisation to apply to field names in header ("cap", "title", "upper", "lower" or None)""" return self._header_style def _set_header_style(self, val): self._validate_header_style(val) self._header_style = val header_style = property(_get_header_style, _set_header_style) def _get_border(self): """Controls printing of border around table Arguments: border - print a border around the table (True or False)""" return self._border def _set_border(self, val): self._validate_option("border", val) self._border = val border = property(_get_border, _set_border) def _get_hrules(self): """Controls printing of horizontal rules after rows Arguments: hrules - horizontal rules style. Allowed values: FRAME, ALL, HEADER, NONE""" return self._hrules def _set_hrules(self, val): self._validate_option("hrules", val) self._hrules = val hrules = property(_get_hrules, _set_hrules) def _get_vrules(self): """Controls printing of vertical rules between columns Arguments: vrules - vertical rules style. Allowed values: FRAME, ALL, NONE""" return self._vrules def _set_vrules(self, val): self._validate_option("vrules", val) self._vrules = val vrules = property(_get_vrules, _set_vrules) def _get_int_format(self): """Controls formatting of integer data Arguments: int_format - integer format string""" return self._int_format def _set_int_format(self, val): # self._validate_option("int_format", val) for field in self._field_names: self._int_format[field] = val int_format = property(_get_int_format, _set_int_format) def _get_float_format(self): """Controls formatting of floating point data Arguments: float_format - floating point format string""" return self._float_format def _set_float_format(self, val): # self._validate_option("float_format", val) for field in self._field_names: self._float_format[field] = val float_format = property(_get_float_format, _set_float_format) def _get_padding_width(self): """The number of empty spaces between a column's edge and its content Arguments: padding_width - number of spaces, must be a positive integer""" return self._padding_width def _set_padding_width(self, val): self._validate_option("padding_width", val) self._padding_width = val padding_width = property(_get_padding_width, _set_padding_width) def _get_left_padding_width(self): """The number of empty spaces between a column's left edge and its content Arguments: left_padding - number of spaces, must be a positive integer""" return self._left_padding_width def _set_left_padding_width(self, val): self._validate_option("left_padding_width", val) self._left_padding_width = val left_padding_width = property(_get_left_padding_width, _set_left_padding_width) def _get_right_padding_width(self): """The number of empty spaces between a column's right edge and its content Arguments: right_padding - number of spaces, must be a positive integer""" return self._right_padding_width def _set_right_padding_width(self, val): self._validate_option("right_padding_width", val) self._right_padding_width = val right_padding_width = property(_get_right_padding_width, _set_right_padding_width) def _get_vertical_char(self): """The charcter used when printing table borders to draw vertical lines Arguments: vertical_char - single character string used to draw vertical lines""" return self._vertical_char def _set_vertical_char(self, val): val = self._unicode(val) self._validate_option("vertical_char", val) self._vertical_char = val vertical_char = property(_get_vertical_char, _set_vertical_char) def _get_horizontal_char(self): """The charcter used when printing table borders to draw horizontal lines Arguments: horizontal_char - single character string used to draw horizontal lines""" return self._horizontal_char def _set_horizontal_char(self, val): val = self._unicode(val) self._validate_option("horizontal_char", val) self._horizontal_char = val horizontal_char = property(_get_horizontal_char, _set_horizontal_char) def _get_junction_char(self): """The charcter used when printing table borders to draw line junctions Arguments: junction_char - single character string used to draw line junctions""" return self._junction_char def _set_junction_char(self, val): val = self._unicode(val) self._validate_option("vertical_char", val) self._junction_char = val junction_char = property(_get_junction_char, _set_junction_char) def _get_format(self): """Controls whether or not HTML tables are formatted to match styling options Arguments: format - True or False""" return self._format def _set_format(self, val): self._validate_option("format", val) self._format = val format = property(_get_format, _set_format) def _get_print_empty(self): """Controls whether or not empty tables produce a header and frame or just an empty string Arguments: print_empty - True or False""" return self._print_empty def _set_print_empty(self, val): self._validate_option("print_empty", val) self._print_empty = val print_empty = property(_get_print_empty, _set_print_empty) def _get_attributes(self): """A dictionary of HTML attribute name/value pairs to be included in the <table> tag when printing HTML Arguments: attributes - dictionary of attributes""" return self._attributes def _set_attributes(self, val): self._validate_option("attributes", val) self._attributes = val attributes = property(_get_attributes, _set_attributes) ############################## # OPTION MIXER # ############################## def _get_options(self, kwargs): options = {} for option in self._options: if option in kwargs: self._validate_option(option, kwargs[option]) options[option] = kwargs[option] else: options[option] = getattr(self, "_"+option) return options ############################## # PRESET STYLE LOGIC # ############################## def set_style(self, style): if style == DEFAULT: self._set_default_style() elif style == MSWORD_FRIENDLY: self._set_msword_style() elif style == PLAIN_COLUMNS: self._set_columns_style() elif style == RANDOM: self._set_random_style() else: raise Exception("Invalid pre-set style!") def _set_default_style(self): self.header = True self.border = True self._hrules = FRAME self._vrules = ALL self.padding_width = 1 self.left_padding_width = 1 self.right_padding_width = 1 self.vertical_char = "|" self.horizontal_char = "-" self.junction_char = "+" def _set_msword_style(self): self.header = True self.border = True self._hrules = NONE self.padding_width = 1 self.left_padding_width = 1 self.right_padding_width = 1 self.vertical_char = "|" def _set_columns_style(self): self.header = True self.border = False self.padding_width = 1 self.left_padding_width = 0 self.right_padding_width = 8 def _set_random_style(self): # Just for fun! self.header = random.choice((True, False)) self.border = random.choice((True, False)) self._hrules = random.choice((ALL, FRAME, HEADER, NONE)) self._vrules = random.choice((ALL, FRAME, NONE)) self.left_padding_width = random.randint(0,5) self.right_padding_width = random.randint(0,5) self.vertical_char = random.choice("~!@#$%^&*()_+|-=\{}[];':\",./;<>?") self.horizontal_char = random.choice("~!@#$%^&*()_+|-=\{}[];':\",./;<>?") self.junction_char = random.choice("~!@#$%^&*()_+|-=\{}[];':\",./;<>?") ############################## # DATA INPUT METHODS # ############################## def add_row(self, row): """Add a row to the table Arguments: row - row of data, should be a list with as many elements as the table has fields""" if self._field_names and len(row) != len(self._field_names): raise Exception("Row has incorrect number of values, (actual) %d!=%d (expected)" %(len(row),len(self._field_names))) if not self._field_names: self.field_names = [("Field %d" % (n+1)) for n in range(0,len(row))] self._rows.append(list(row)) def del_row(self, row_index): """Delete a row to the table Arguments: row_index - The index of the row you want to delete. Indexing starts at 0.""" if row_index > len(self._rows)-1: raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(self._rows))) del self._rows[row_index] def add_column(self, fieldname, column, align="c", valign="t"): """Add a column to the table. Arguments: fieldname - name of the field to contain the new column of data column - column of data, should be a list with as many elements as the table has rows align - desired alignment for this column - "l" for left, "c" for centre and "r" for right valign - desired vertical alignment for new columns - "t" for top, "m" for middle and "b" for bottom""" if len(self._rows) in (0, len(column)): self._validate_align(align) self._validate_valign(valign) self._field_names.append(fieldname) self._align[fieldname] = align self._valign[fieldname] = valign for i in range(0, len(column)): if len(self._rows) < i+1: self._rows.append([]) self._rows[i].append(column[i]) else: raise Exception("Column length %d does not match number of rows %d!" % (len(column), len(self._rows))) def clear_rows(self): """Delete all rows from the table but keep the current field names""" self._rows = [] def clear(self): """Delete all rows and field names from the table, maintaining nothing but styling options""" self._rows = [] self._field_names = [] self._widths = [] ############################## # MISC PUBLIC METHODS # ############################## def copy(self): return copy.deepcopy(self) ############################## # MISC PRIVATE METHODS # ############################## def _format_value(self, field, value): if isinstance(value, int) and field in self._int_format: value = self._unicode(("%%%sd" % self._int_format[field]) % value) elif isinstance(value, float) and field in self._float_format: value = self._unicode(("%%%sf" % self._float_format[field]) % value) return self._unicode(value) def _compute_widths(self, rows, options): if options["header"]: widths = [_get_size(field)[0] for field in self._field_names] else: widths = len(self.field_names) * [0] for row in rows: for index, value in enumerate(row): fieldname = self.field_names[index] if fieldname in self.max_width: widths[index] = max(widths[index], min(_get_size(value)[0], self.max_width[fieldname])) else: widths[index] = max(widths[index], _get_size(value)[0]) self._widths = widths def _get_padding_widths(self, options): if options["left_padding_width"] is not None: lpad = options["left_padding_width"] else: lpad = options["padding_width"] if options["right_padding_width"] is not None: rpad = options["right_padding_width"] else: rpad = options["padding_width"] return lpad, rpad def _get_rows(self, options): """Return only those data rows that should be printed, based on slicing and sorting. Arguments: options - dictionary of option settings.""" # Make a copy of only those rows in the slice range rows = copy.deepcopy(self._rows[options["start"]:options["end"]]) # Sort if necessary if options["sortby"]: sortindex = self._field_names.index(options["sortby"]) # Decorate rows = [[row[sortindex]]+row for row in rows] # Sort rows.sort(reverse=options["reversesort"], key=options["sort_key"]) # Undecorate rows = [row[1:] for row in rows] return rows def _format_row(self, row, options): return [self._format_value(field, value) for (field, value) in zip(self._field_names, row)] def _format_rows(self, rows, options): return [self._format_row(row, options) for row in rows] ############################## # PLAIN TEXT STRING METHODS # ############################## def get_string(self, **kwargs): """Return string representation of table in current state. Arguments: start - index of first data row to include in output end - index of last data row to include in output PLUS ONE (list slice style) fields - names of fields (columns) to include header - print a header showing field names (True or False) border - print a border around the table (True or False) hrules - controls printing of horizontal rules after rows. Allowed values: ALL, FRAME, HEADER, NONE vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE int_format - controls formatting of integer data float_format - controls formatting of floating point data padding_width - number of spaces on either side of column data (only used if left and right paddings are None) left_padding_width - number of spaces on left hand side of column data right_padding_width - number of spaces on right hand side of column data vertical_char - single character string used to draw vertical lines horizontal_char - single character string used to draw horizontal lines junction_char - single character string used to draw line junctions sortby - name of field to sort rows by sort_key - sorting key function, applied to data points before sorting reversesort - True or False to sort in descending or ascending order print empty - if True, stringify just the header for an empty table, if False return an empty string """ options = self._get_options(kwargs) lines = [] # Don't think too hard about an empty table # Is this the desired behaviour? Maybe we should still print the header? if self.rowcount == 0 and (not options["print_empty"] or not options["border"]): return "" # Get the rows we need to print, taking into account slicing, sorting, etc. rows = self._get_rows(options) # Turn all data in all rows into Unicode, formatted as desired formatted_rows = self._format_rows(rows, options) # Compute column widths self._compute_widths(formatted_rows, options) # Add header or top of border self._hrule = self._stringify_hrule(options) if options["header"]: lines.append(self._stringify_header(options)) elif options["border"] and options["hrules"] in (ALL, FRAME): lines.append(self._hrule) # Add rows for row in formatted_rows: lines.append(self._stringify_row(row, options)) # Add bottom of border if options["border"] and options["hrules"] == FRAME: lines.append(self._hrule) return self._unicode("\n").join(lines) def _stringify_hrule(self, options): if not options["border"]: return "" lpad, rpad = self._get_padding_widths(options) if options['vrules'] in (ALL, FRAME): bits = [options["junction_char"]] else: bits = [options["horizontal_char"]] # For tables with no data or fieldnames if not self._field_names: bits.append(options["junction_char"]) return "".join(bits) for field, width in zip(self._field_names, self._widths): if options["fields"] and field not in options["fields"]: continue bits.append((width+lpad+rpad)*options["horizontal_char"]) if options['vrules'] == ALL: bits.append(options["junction_char"]) else: bits.append(options["horizontal_char"]) if options["vrules"] == FRAME: bits.pop() bits.append(options["junction_char"]) return "".join(bits) def _stringify_header(self, options): bits = [] lpad, rpad = self._get_padding_widths(options) if options["border"]: if options["hrules"] in (ALL, FRAME): bits.append(self._hrule) bits.append("\n") if options["vrules"] in (ALL, FRAME): bits.append(options["vertical_char"]) else: bits.append(" ") # For tables with no data or field names if not self._field_names: if options["vrules"] in (ALL, FRAME): bits.append(options["vertical_char"]) else: bits.append(" ") for field, width, in zip(self._field_names, self._widths): if options["fields"] and field not in options["fields"]: continue if self._header_style == "cap": fieldname = field.capitalize() elif self._header_style == "title": fieldname = field.title() elif self._header_style == "upper": fieldname = field.upper() elif self._header_style == "lower": fieldname = field.lower() else: fieldname = field bits.append(" " * lpad + self._justify(fieldname, width, self._align[field]) + " " * rpad) if options["border"]: if options["vrules"] == ALL: bits.append(options["vertical_char"]) else: bits.append(" ") # If vrules is FRAME, then we just appended a space at the end # of the last field, when we really want a vertical character if options["border"] and options["vrules"] == FRAME: bits.pop() bits.append(options["vertical_char"]) if options["border"] and options["hrules"] != NONE: bits.append("\n") bits.append(self._hrule) return "".join(bits) def _stringify_row(self, row, options): for index, field, value, width, in zip(range(0,len(row)), self._field_names, row, self._widths): # Enforce max widths lines = value.split("\n") new_lines = [] for line in lines: if _str_block_width(line) > width: line = textwrap.fill(line, width) new_lines.append(line) lines = new_lines value = "\n".join(lines) row[index] = value row_height = 0 for c in row: h = _get_size(c)[1] if h > row_height: row_height = h bits = [] lpad, rpad = self._get_padding_widths(options) for y in range(0, row_height): bits.append([]) if options["border"]: if options["vrules"] in (ALL, FRAME): bits[y].append(self.vertical_char) else: bits[y].append(" ") for field, value, width, in zip(self._field_names, row, self._widths): valign = self._valign[field] lines = value.split("\n") dHeight = row_height - len(lines) if dHeight: if valign == "m": lines = [""] * int(dHeight / 2) + lines + [""] * (dHeight - int(dHeight / 2)) elif valign == "b": lines = [""] * dHeight + lines else: lines = lines + [""] * dHeight y = 0 for l in lines: if options["fields"] and field not in options["fields"]: continue bits[y].append(" " * lpad + self._justify(l, width, self._align[field]) + " " * rpad) if options["border"]: if options["vrules"] == ALL: bits[y].append(self.vertical_char) else: bits[y].append(" ") y += 1 # If vrules is FRAME, then we just appended a space at the end # of the last field, when we really want a vertical character for y in range(0, row_height): if options["border"] and options["vrules"] == FRAME: bits[y].pop() bits[y].append(options["vertical_char"]) if options["border"] and options["hrules"]== ALL: bits[row_height-1].append("\n") bits[row_height-1].append(self._hrule) for y in range(0, row_height): bits[y] = "".join(bits[y]) return "\n".join(bits) ############################## # HTML STRING METHODS # ############################## def get_html_string(self, **kwargs): """Return string representation of HTML formatted version of table in current state. Arguments: start - index of first data row to include in output end - index of last data row to include in output PLUS ONE (list slice style) fields - names of fields (columns) to include header - print a header showing field names (True or False) border - print a border around the table (True or False) hrules - controls printing of horizontal rules after rows. Allowed values: ALL, FRAME, HEADER, NONE vrules - controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE int_format - controls formatting of integer data float_format - controls formatting of floating point data padding_width - number of spaces on either side of column data (only used if left and right paddings are None) left_padding_width - number of spaces on left hand side of column data right_padding_width - number of spaces on right hand side of column data sortby - name of field to sort rows by sort_key - sorting key function, applied to data points before sorting attributes - dictionary of name/value pairs to include as HTML attributes in the <table> tag xhtml - print <br/> tags if True, <br> tags if false""" options = self._get_options(kwargs) if options["format"]: string = self._get_formatted_html_string(options) else: string = self._get_simple_html_string(options) return string def _get_simple_html_string(self, options): lines = [] if options["xhtml"]: linebreak = "<br/>" else: linebreak = "<br>" open_tag = [] open_tag.append("<table") if options["attributes"]: for attr_name in options["attributes"]: open_tag.append(" %s=\"%s\"" % (attr_name, options["attributes"][attr_name])) open_tag.append(">") lines.append("".join(open_tag)) # Headers if options["header"]: lines.append(" <tr>") for field in self._field_names: if options["fields"] and field not in options["fields"]: continue lines.append(" <th>%s</th>" % escape(field).replace("\n", linebreak)) lines.append(" </tr>") # Data rows = self._get_rows(options) formatted_rows = self._format_rows(rows, options) for row in formatted_rows: lines.append(" <tr>") for field, datum in zip(self._field_names, row): if options["fields"] and field not in options["fields"]: continue lines.append(" <td>%s</td>" % escape(datum).replace("\n", linebreak)) lines.append(" </tr>") lines.append("</table>") return self._unicode("\n").join(lines) def _get_formatted_html_string(self, options): lines = [] lpad, rpad = self._get_padding_widths(options) if options["xhtml"]: linebreak = "<br/>" else: linebreak = "<br>" open_tag = [] open_tag.append("<table") if options["border"]: if options["hrules"] == ALL and options["vrules"] == ALL: open_tag.append(" frame=\"box\" rules=\"all\"") elif options["hrules"] == FRAME and options["vrules"] == FRAME: open_tag.append(" frame=\"box\"") elif options["hrules"] == FRAME and options["vrules"] == ALL: open_tag.append(" frame=\"box\" rules=\"cols\"") elif options["hrules"] == FRAME: open_tag.append(" frame=\"hsides\"") elif options["hrules"] == ALL: open_tag.append(" frame=\"hsides\" rules=\"rows\"") elif options["vrules"] == FRAME: open_tag.append(" frame=\"vsides\"") elif options["vrules"] == ALL: open_tag.append(" frame=\"vsides\" rules=\"cols\"") if options["attributes"]: for attr_name in options["attributes"]: open_tag.append(" %s=\"%s\"" % (attr_name, options["attributes"][attr_name])) open_tag.append(">") lines.append("".join(open_tag)) # Headers if options["header"]: lines.append(" <tr>") for field in self._field_names: if options["fields"] and field not in options["fields"]: continue lines.append(" <th style=\"padding-left: %dem; padding-right: %dem; text-align: center\">%s</th>" % (lpad, rpad, escape(field).replace("\n", linebreak))) lines.append(" </tr>") # Data rows = self._get_rows(options) formatted_rows = self._format_rows(rows, options) aligns = [] valigns = [] for field in self._field_names: aligns.append({ "l" : "left", "r" : "right", "c" : "center" }[self._align[field]]) valigns.append({"t" : "top", "m" : "middle", "b" : "bottom"}[self._valign[field]]) for row in formatted_rows: lines.append(" <tr>") for field, datum, align, valign in zip(self._field_names, row, aligns, valigns): if options["fields"] and field not in options["fields"]: continue lines.append(" <td style=\"padding-left: %dem; padding-right: %dem; text-align: %s; vertical-align: %s\">%s</td>" % (lpad, rpad, align, valign, escape(datum).replace("\n", linebreak))) lines.append(" </tr>") lines.append("</table>") return self._unicode("\n").join(lines) ############################## # UNICODE WIDTH FUNCTIONS # ############################## def _char_block_width(char): # Basic Latin, which is probably the most common case #if char in xrange(0x0021, 0x007e): #if char >= 0x0021 and char <= 0x007e: if 0x0021 <= char <= 0x007e: return 1 # Chinese, Japanese, Korean (common) if 0x4e00 <= char <= 0x9fff: return 2 # Hangul if 0xac00 <= char <= 0xd7af: return 2 # Combining? if unicodedata.combining(uni_chr(char)): return 0 # Hiragana and Katakana if 0x3040 <= char <= 0x309f or 0x30a0 <= char <= 0x30ff: return 2 # Full-width Latin characters if 0xff01 <= char <= 0xff60: return 2 # CJK punctuation if 0x3000 <= char <= 0x303e: return 2 # Backspace and delete if char in (0x0008, 0x007f): return -1 # Other control characters elif char in (0x0000, 0x001f): return 0 # Take a guess return 1 def _str_block_width(val): return sum(itermap(_char_block_width, itermap(ord, _re.sub("", val)))) ############################## # TABLE FACTORIES # ############################## def from_csv(fp, field_names = None, **kwargs): dialect = csv.Sniffer().sniff(fp.read(1024)) fp.seek(0) reader = csv.reader(fp, dialect) table = PrettyTable(**kwargs) if field_names: table.field_names = field_names else: if py3k: table.field_names = [x.strip() for x in next(reader)] else: table.field_names = [x.strip() for x in reader.next()] for row in reader: table.add_row([x.strip() for x in row]) return table def from_db_cursor(cursor, **kwargs): if cursor.description: table = PrettyTable(**kwargs) table.field_names = [col[0] for col in cursor.description] for row in cursor.fetchall(): table.add_row(row) return table class TableHandler(HTMLParser): def __init__(self, **kwargs): HTMLParser.__init__(self) self.kwargs = kwargs self.tables = [] self.last_row = [] self.rows = [] self.max_row_width = 0 self.active = None self.last_content = "" self.is_last_row_header = False def handle_starttag(self,tag, attrs): self.active = tag if tag == "th": self.is_last_row_header = True def handle_endtag(self,tag): if tag in ["th", "td"]: stripped_content = self.last_content.strip() self.last_row.append(stripped_content) if tag == "tr": self.rows.append( (self.last_row, self.is_last_row_header)) self.max_row_width = max(self.max_row_width, len(self.last_row)) self.last_row = [] self.is_last_row_header = False if tag == "table": table = self.generate_table(self.rows) self.tables.append(table) self.rows = [] self.last_content = " " self.active = None def handle_data(self, data): self.last_content += data def generate_table(self, rows): """ Generates from a list of rows a PrettyTable object. """ table = PrettyTable(**self.kwargs) for row in self.rows: if len(row[0]) < self.max_row_width: appends = self.max_row_width - len(row[0]) for i in range(1,appends): row[0].append("-") if row[1] == True: self.make_fields_unique(row[0]) table.field_names = row[0] else: table.add_row(row[0]) return table def make_fields_unique(self, fields): """ iterates over the row and make each field unique """ for i in range(0, len(fields)): for j in range(i+1, len(fields)): if fields[i] == fields[j]: fields[j] += "'" def from_html(html_code, **kwargs): """ Generates a list of PrettyTables from a string of HTML code. Each <table> in the HTML becomes one PrettyTable object. """ parser = TableHandler(**kwargs) parser.feed(html_code) return parser.tables def from_html_one(html_code, **kwargs): """ Generates a PrettyTables from a string of HTML code which contains only a single <table> """ tables = from_html(html_code, **kwargs) try: assert len(tables) == 1 except AssertionError: raise Exception("More than one <table> in provided HTML code! Use from_html instead.") return tables[0] ############################## # MAIN (TEST FUNCTION) # ############################## def main(): x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"]) x.sortby = "Population" x.reversesort = True x.int_format["Area"] = "04d" x.float_format = "6.1f" x.align["City name"] = "l" # Left align city names x.add_row(["Adelaide", 1295, 1158259, 600.5]) x.add_row(["Brisbane", 5905, 1857594, 1146.4]) x.add_row(["Darwin", 112, 120900, 1714.7]) x.add_row(["Hobart", 1357, 205556, 619.5]) x.add_row(["Sydney", 2058, 4336374, 1214.8]) x.add_row(["Melbourne", 1566, 3806092, 646.9]) x.add_row(["Perth", 5386, 1554769, 869.4]) print(x) if __name__ == "__main__": main()
mit
wrouesnel/ansible
lib/ansible/modules/cloud/rackspace/rax_mon_notification_plan.py
45
5675
#!/usr/bin/python # Copyright: Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: rax_mon_notification_plan short_description: Create or delete a Rackspace Cloud Monitoring notification plan. description: - Create or delete a Rackspace Cloud Monitoring notification plan by associating existing rax_mon_notifications with severity levels. Rackspace monitoring module flow | rax_mon_entity -> rax_mon_check -> rax_mon_notification -> *rax_mon_notification_plan* -> rax_mon_alarm version_added: "2.0" options: state: description: - Ensure that the notification plan with this C(label) exists or does not exist. choices: ['present', 'absent'] label: description: - Defines a friendly name for this notification plan. String between 1 and 255 characters long. required: true critical_state: description: - Notification list to use when the alarm state is CRITICAL. Must be an array of valid rax_mon_notification ids. warning_state: description: - Notification list to use when the alarm state is WARNING. Must be an array of valid rax_mon_notification ids. ok_state: description: - Notification list to use when the alarm state is OK. Must be an array of valid rax_mon_notification ids. author: Ash Wilson extends_documentation_fragment: rackspace.openstack ''' EXAMPLES = ''' - name: Example notification plan gather_facts: False hosts: local connection: local tasks: - name: Establish who gets called when. rax_mon_notification_plan: credentials: ~/.rax_pub state: present label: defcon1 critical_state: - "{{ everyone['notification']['id'] }}" warning_state: - "{{ opsfloor['notification']['id'] }}" register: defcon1 ''' try: import pyrax HAS_PYRAX = True except ImportError: HAS_PYRAX = False from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.rax import rax_argument_spec, rax_required_together, setup_rax_module def notification_plan(module, state, label, critical_state, warning_state, ok_state): if len(label) < 1 or len(label) > 255: module.fail_json(msg='label must be between 1 and 255 characters long') changed = False notification_plan = None cm = pyrax.cloud_monitoring if not cm: module.fail_json(msg='Failed to instantiate client. This typically ' 'indicates an invalid region or an incorrectly ' 'capitalized region name.') existing = [] for n in cm.list_notification_plans(): if n.label == label: existing.append(n) if existing: notification_plan = existing[0] if state == 'present': should_create = False should_delete = False if len(existing) > 1: module.fail_json(msg='%s notification plans are labelled %s.' % (len(existing), label)) if notification_plan: should_delete = (critical_state and critical_state != notification_plan.critical_state) or \ (warning_state and warning_state != notification_plan.warning_state) or \ (ok_state and ok_state != notification_plan.ok_state) if should_delete: notification_plan.delete() should_create = True else: should_create = True if should_create: notification_plan = cm.create_notification_plan(label=label, critical_state=critical_state, warning_state=warning_state, ok_state=ok_state) changed = True else: for np in existing: np.delete() changed = True if notification_plan: notification_plan_dict = { "id": notification_plan.id, "critical_state": notification_plan.critical_state, "warning_state": notification_plan.warning_state, "ok_state": notification_plan.ok_state, "metadata": notification_plan.metadata } module.exit_json(changed=changed, notification_plan=notification_plan_dict) else: module.exit_json(changed=changed) def main(): argument_spec = rax_argument_spec() argument_spec.update( dict( state=dict(default='present', choices=['present', 'absent']), label=dict(required=True), critical_state=dict(type='list'), warning_state=dict(type='list'), ok_state=dict(type='list') ) ) module = AnsibleModule( argument_spec=argument_spec, required_together=rax_required_together() ) if not HAS_PYRAX: module.fail_json(msg='pyrax is required for this module') state = module.params.get('state') label = module.params.get('label') critical_state = module.params.get('critical_state') warning_state = module.params.get('warning_state') ok_state = module.params.get('ok_state') setup_rax_module(module, pyrax) notification_plan(module, state, label, critical_state, warning_state, ok_state) if __name__ == '__main__': main()
gpl-3.0
mjudsp/Tsallis
sklearn/metrics/tests/test_score_objects.py
23
15933
import pickle import tempfile import shutil import os import numbers import numpy as np from sklearn.utils.testing import assert_almost_equal from sklearn.utils.testing import assert_array_equal from sklearn.utils.testing import assert_raises from sklearn.utils.testing import assert_raises_regexp from sklearn.utils.testing import assert_true from sklearn.utils.testing import ignore_warnings from sklearn.utils.testing import assert_not_equal from sklearn.base import BaseEstimator from sklearn.metrics import (f1_score, r2_score, roc_auc_score, fbeta_score, log_loss, precision_score, recall_score) from sklearn.metrics.cluster import adjusted_rand_score from sklearn.metrics.scorer import (check_scoring, _PredictScorer, _passthrough_scorer) from sklearn.metrics import make_scorer, get_scorer, SCORERS from sklearn.svm import LinearSVC from sklearn.pipeline import make_pipeline from sklearn.cluster import KMeans from sklearn.dummy import DummyRegressor from sklearn.linear_model import Ridge, LogisticRegression from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor from sklearn.datasets import make_blobs from sklearn.datasets import make_classification from sklearn.datasets import make_multilabel_classification from sklearn.datasets import load_diabetes from sklearn.model_selection import train_test_split, cross_val_score from sklearn.model_selection import GridSearchCV from sklearn.multiclass import OneVsRestClassifier from sklearn.externals import joblib REGRESSION_SCORERS = ['r2', 'mean_absolute_error', 'mean_squared_error', 'median_absolute_error'] CLF_SCORERS = ['accuracy', 'f1', 'f1_weighted', 'f1_macro', 'f1_micro', 'roc_auc', 'average_precision', 'precision', 'precision_weighted', 'precision_macro', 'precision_micro', 'recall', 'recall_weighted', 'recall_macro', 'recall_micro', 'log_loss', 'adjusted_rand_score' # not really, but works ] MULTILABEL_ONLY_SCORERS = ['precision_samples', 'recall_samples', 'f1_samples'] def _make_estimators(X_train, y_train, y_ml_train): # Make estimators that make sense to test various scoring methods sensible_regr = DummyRegressor(strategy='median') sensible_regr.fit(X_train, y_train) sensible_clf = DecisionTreeClassifier(random_state=0) sensible_clf.fit(X_train, y_train) sensible_ml_clf = DecisionTreeClassifier(random_state=0) sensible_ml_clf.fit(X_train, y_ml_train) return dict( [(name, sensible_regr) for name in REGRESSION_SCORERS] + [(name, sensible_clf) for name in CLF_SCORERS] + [(name, sensible_ml_clf) for name in MULTILABEL_ONLY_SCORERS] ) X_mm, y_mm, y_ml_mm = None, None, None ESTIMATORS = None TEMP_FOLDER = None def setup_module(): # Create some memory mapped data global X_mm, y_mm, y_ml_mm, TEMP_FOLDER, ESTIMATORS TEMP_FOLDER = tempfile.mkdtemp(prefix='sklearn_test_score_objects_') X, y = make_classification(n_samples=30, n_features=5, random_state=0) _, y_ml = make_multilabel_classification(n_samples=X.shape[0], random_state=0) filename = os.path.join(TEMP_FOLDER, 'test_data.pkl') joblib.dump((X, y, y_ml), filename) X_mm, y_mm, y_ml_mm = joblib.load(filename, mmap_mode='r') ESTIMATORS = _make_estimators(X_mm, y_mm, y_ml_mm) def teardown_module(): global X_mm, y_mm, y_ml_mm, TEMP_FOLDER, ESTIMATORS # GC closes the mmap file descriptors X_mm, y_mm, y_ml_mm, ESTIMATORS = None, None, None, None shutil.rmtree(TEMP_FOLDER) class EstimatorWithoutFit(object): """Dummy estimator to test check_scoring""" pass class EstimatorWithFit(BaseEstimator): """Dummy estimator to test check_scoring""" def fit(self, X, y): return self class EstimatorWithFitAndScore(object): """Dummy estimator to test check_scoring""" def fit(self, X, y): return self def score(self, X, y): return 1.0 class EstimatorWithFitAndPredict(object): """Dummy estimator to test check_scoring""" def fit(self, X, y): self.y = y return self def predict(self, X): return self.y class DummyScorer(object): """Dummy scorer that always returns 1.""" def __call__(self, est, X, y): return 1 def test_all_scorers_repr(): # Test that all scorers have a working repr for name, scorer in SCORERS.items(): repr(scorer) def test_check_scoring(): # Test all branches of check_scoring estimator = EstimatorWithoutFit() pattern = (r"estimator should be an estimator implementing 'fit' method," r" .* was passed") assert_raises_regexp(TypeError, pattern, check_scoring, estimator) estimator = EstimatorWithFitAndScore() estimator.fit([[1]], [1]) scorer = check_scoring(estimator) assert_true(scorer is _passthrough_scorer) assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) estimator = EstimatorWithFitAndPredict() estimator.fit([[1]], [1]) pattern = (r"If no scoring is specified, the estimator passed should have" r" a 'score' method\. The estimator .* does not\.") assert_raises_regexp(TypeError, pattern, check_scoring, estimator) scorer = check_scoring(estimator, "accuracy") assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) estimator = EstimatorWithFit() scorer = check_scoring(estimator, "accuracy") assert_true(isinstance(scorer, _PredictScorer)) estimator = EstimatorWithFit() scorer = check_scoring(estimator, allow_none=True) assert_true(scorer is None) def test_check_scoring_gridsearchcv(): # test that check_scoring works on GridSearchCV and pipeline. # slightly redundant non-regression test. grid = GridSearchCV(LinearSVC(), param_grid={'C': [.1, 1]}) scorer = check_scoring(grid, "f1") assert_true(isinstance(scorer, _PredictScorer)) pipe = make_pipeline(LinearSVC()) scorer = check_scoring(pipe, "f1") assert_true(isinstance(scorer, _PredictScorer)) # check that cross_val_score definitely calls the scorer # and doesn't make any assumptions about the estimator apart from having a # fit. scores = cross_val_score(EstimatorWithFit(), [[1], [2], [3]], [1, 0, 1], scoring=DummyScorer()) assert_array_equal(scores, 1) def test_make_scorer(): # Sanity check on the make_scorer factory function. f = lambda *args: 0 assert_raises(ValueError, make_scorer, f, needs_threshold=True, needs_proba=True) def test_classification_scores(): # Test classification scorers. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LinearSVC(random_state=0) clf.fit(X_train, y_train) for prefix, metric in [('f1', f1_score), ('precision', precision_score), ('recall', recall_score)]: score1 = get_scorer('%s_weighted' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=None, average='weighted') assert_almost_equal(score1, score2) score1 = get_scorer('%s_macro' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=None, average='macro') assert_almost_equal(score1, score2) score1 = get_scorer('%s_micro' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=None, average='micro') assert_almost_equal(score1, score2) score1 = get_scorer('%s' % prefix)(clf, X_test, y_test) score2 = metric(y_test, clf.predict(X_test), pos_label=1) assert_almost_equal(score1, score2) # test fbeta score that takes an argument scorer = make_scorer(fbeta_score, beta=2) score1 = scorer(clf, X_test, y_test) score2 = fbeta_score(y_test, clf.predict(X_test), beta=2) assert_almost_equal(score1, score2) # test that custom scorer can be pickled unpickled_scorer = pickle.loads(pickle.dumps(scorer)) score3 = unpickled_scorer(clf, X_test, y_test) assert_almost_equal(score1, score3) # smoke test the repr: repr(fbeta_score) def test_regression_scorers(): # Test regression scorers. diabetes = load_diabetes() X, y = diabetes.data, diabetes.target X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = Ridge() clf.fit(X_train, y_train) score1 = get_scorer('r2')(clf, X_test, y_test) score2 = r2_score(y_test, clf.predict(X_test)) assert_almost_equal(score1, score2) def test_thresholded_scorers(): # Test scorers that take thresholds. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf = LogisticRegression(random_state=0) clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.decision_function(X_test)) score3 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) assert_almost_equal(score1, score2) assert_almost_equal(score1, score3) logscore = get_scorer('log_loss')(clf, X_test, y_test) logloss = log_loss(y_test, clf.predict_proba(X_test)) assert_almost_equal(-logscore, logloss) # same for an estimator without decision_function clf = DecisionTreeClassifier() clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) assert_almost_equal(score1, score2) # test with a regressor (no decision_function) reg = DecisionTreeRegressor() reg.fit(X_train, y_train) score1 = get_scorer('roc_auc')(reg, X_test, y_test) score2 = roc_auc_score(y_test, reg.predict(X_test)) assert_almost_equal(score1, score2) # Test that an exception is raised on more than two classes X, y = make_blobs(random_state=0, centers=3) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) clf.fit(X_train, y_train) assert_raises(ValueError, get_scorer('roc_auc'), clf, X_test, y_test) def test_thresholded_scorers_multilabel_indicator_data(): # Test that the scorer work with multilabel-indicator format # for multilabel and multi-output multi-class classifier X, y = make_multilabel_classification(allow_unlabeled=False, random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) # Multi-output multi-class predict_proba clf = DecisionTreeClassifier() clf.fit(X_train, y_train) y_proba = clf.predict_proba(X_test) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, np.vstack(p[:, -1] for p in y_proba).T) assert_almost_equal(score1, score2) # Multi-output multi-class decision_function # TODO Is there any yet? clf = DecisionTreeClassifier() clf.fit(X_train, y_train) clf._predict_proba = clf.predict_proba clf.predict_proba = None clf.decision_function = lambda X: [p[:, 1] for p in clf._predict_proba(X)] y_proba = clf.decision_function(X_test) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, np.vstack(p for p in y_proba).T) assert_almost_equal(score1, score2) # Multilabel predict_proba clf = OneVsRestClassifier(DecisionTreeClassifier()) clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.predict_proba(X_test)) assert_almost_equal(score1, score2) # Multilabel decision function clf = OneVsRestClassifier(LinearSVC(random_state=0)) clf.fit(X_train, y_train) score1 = get_scorer('roc_auc')(clf, X_test, y_test) score2 = roc_auc_score(y_test, clf.decision_function(X_test)) assert_almost_equal(score1, score2) def test_unsupervised_scorers(): # Test clustering scorers against gold standard labeling. # We don't have any real unsupervised Scorers yet. X, y = make_blobs(random_state=0, centers=2) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) km = KMeans(n_clusters=3) km.fit(X_train) score1 = get_scorer('adjusted_rand_score')(km, X_test, y_test) score2 = adjusted_rand_score(y_test, km.predict(X_test)) assert_almost_equal(score1, score2) @ignore_warnings def test_raises_on_score_list(): # Test that when a list of scores is returned, we raise proper errors. X, y = make_blobs(random_state=0) f1_scorer_no_average = make_scorer(f1_score, average=None) clf = DecisionTreeClassifier() assert_raises(ValueError, cross_val_score, clf, X, y, scoring=f1_scorer_no_average) grid_search = GridSearchCV(clf, scoring=f1_scorer_no_average, param_grid={'max_depth': [1, 2]}) assert_raises(ValueError, grid_search.fit, X, y) @ignore_warnings def test_scorer_sample_weight(): # Test that scorers support sample_weight or raise sensible errors # Unlike the metrics invariance test, in the scorer case it's harder # to ensure that, on the classifier output, weighted and unweighted # scores really should be unequal. X, y = make_classification(random_state=0) _, y_ml = make_multilabel_classification(n_samples=X.shape[0], random_state=0) split = train_test_split(X, y, y_ml, random_state=0) X_train, X_test, y_train, y_test, y_ml_train, y_ml_test = split sample_weight = np.ones_like(y_test) sample_weight[:10] = 0 # get sensible estimators for each metric estimator = _make_estimators(X_train, y_train, y_ml_train) for name, scorer in SCORERS.items(): if name in MULTILABEL_ONLY_SCORERS: target = y_ml_test else: target = y_test try: weighted = scorer(estimator[name], X_test, target, sample_weight=sample_weight) ignored = scorer(estimator[name], X_test[10:], target[10:]) unweighted = scorer(estimator[name], X_test, target) assert_not_equal(weighted, unweighted, msg="scorer {0} behaves identically when " "called with sample weights: {1} vs " "{2}".format(name, weighted, unweighted)) assert_almost_equal(weighted, ignored, err_msg="scorer {0} behaves differently when " "ignoring samples and setting sample_weight to" " 0: {1} vs {2}".format(name, weighted, ignored)) except TypeError as e: assert_true("sample_weight" in str(e), "scorer {0} raises unhelpful exception when called " "with sample weights: {1}".format(name, str(e))) @ignore_warnings # UndefinedMetricWarning for P / R scores def check_scorer_memmap(scorer_name): scorer, estimator = SCORERS[scorer_name], ESTIMATORS[scorer_name] if scorer_name in MULTILABEL_ONLY_SCORERS: score = scorer(estimator, X_mm, y_ml_mm) else: score = scorer(estimator, X_mm, y_mm) assert isinstance(score, numbers.Number), scorer_name def test_scorer_memmap_input(): # Non-regression test for #6147: some score functions would # return singleton memmap when computed on memmap data instead of scalar # float values. for name in SCORERS.keys(): yield check_scorer_memmap, name
bsd-3-clause
chrisenuf/fullerite
src/diamond/collectors/ipmisensor/test/testipmisensor.py
29
3995
#!/usr/bin/python # coding=utf-8 ################################################################################ from test import CollectorTestCase from test import get_collector_config from test import unittest from mock import Mock from mock import patch from diamond.collector import Collector from ipmisensor import IPMISensorCollector ################################################################################ class TestIPMISensorCollector(CollectorTestCase): def setUp(self, thresholds=False): config = get_collector_config('IPMISensorCollector', { 'interval': 10, 'bin': 'true', 'use_sudo': False, 'thresholds': thresholds, }) self.collector = IPMISensorCollector(config, None) def test_import(self): self.assertTrue(IPMISensorCollector) @patch('os.access', Mock(return_value=True)) @patch.object(Collector, 'publish') def test_should_work_with_real_data(self, publish_mock): patch_communicate = patch( 'subprocess.Popen.communicate', Mock(return_value=(self.getFixture('ipmitool.out').getvalue(), ''))) patch_communicate.start() self.collector.collect() patch_communicate.stop() metrics = { 'CPU1.Temp': 0.0, 'CPU2.Temp': 0.0, 'System.Temp': 32.000000, 'CPU1.Vcore': 1.080000, 'CPU2.Vcore': 1.000000, 'CPU1.VTT': 1.120000, 'CPU2.VTT': 1.176000, 'CPU1.DIMM': 1.512000, 'CPU2.DIMM': 1.512000, '+1_5V': 1.512000, '+1_8V': 1.824000, '+5V': 4.992000, '+12V': 12.031000, '+1_1V': 1.112000, '+3_3V': 3.288000, '+3_3VSB': 3.240000, 'VBAT': 3.240000, 'Fan1': 4185.000000, 'Fan2': 4185.000000, 'Fan3': 4185.000000, 'Fan7': 3915.000000, 'Fan8': 3915.000000, 'Intrusion': 0.000000, 'PS.Status': 0.000000, 'P1-DIMM1A.Temp': 41.000000, 'P1-DIMM1B.Temp': 39.000000, 'P1-DIMM2A.Temp': 38.000000, 'P1-DIMM2B.Temp': 40.000000, 'P1-DIMM3A.Temp': 37.000000, 'P1-DIMM3B.Temp': 38.000000, 'P2-DIMM1A.Temp': 39.000000, 'P2-DIMM1B.Temp': 38.000000, 'P2-DIMM2A.Temp': 39.000000, 'P2-DIMM2B.Temp': 39.000000, 'P2-DIMM3A.Temp': 39.000000, 'P2-DIMM3B.Temp': 40.000000, } self.setDocExample(collector=self.collector.__class__.__name__, metrics=metrics, defaultpath=self.collector.config['path']) self.assertPublishedMany(publish_mock, metrics) @patch('os.access', Mock(return_value=True)) @patch.object(Collector, 'publish') def test_thresholds(self, publish_mock): self.setUp(thresholds=True) patch_communicate = patch( 'subprocess.Popen.communicate', Mock(return_value=(self.getFixture('ipmitool.out').getvalue(), ''))) patch_communicate.start() self.collector.collect() patch_communicate.stop() metrics = { 'System.Temp.Reading': 32.0, 'System.Temp.Lower.NonRecoverable': 0.0, 'System.Temp.Lower.Critical': 0.0, 'System.Temp.Lower.NonCritical': 0.0, 'System.Temp.Upper.NonCritical': 81.0, 'System.Temp.Upper.Critical': 82.0, 'System.Temp.Upper.NonRecoverable': 83.0, } self.setDocExample(collector=self.collector.__class__.__name__, metrics=metrics, defaultpath=self.collector.config['path']) self.assertPublishedMany(publish_mock, metrics) ################################################################################ if __name__ == "__main__": unittest.main()
apache-2.0
powerlim2/project_free_insight
data_api/venv/lib/python2.7/site-packages/pip/_vendor/requests/packages/chardet/eucjpprober.py
2919
3678
######################## BEGIN LICENSE BLOCK ######################## # The Original Code is mozilla.org code. # # The Initial Developer of the Original Code is # Netscape Communications Corporation. # Portions created by the Initial Developer are Copyright (C) 1998 # the Initial Developer. All Rights Reserved. # # Contributor(s): # Mark Pilgrim - port to Python # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA # 02110-1301 USA ######################### END LICENSE BLOCK ######################### import sys from . import constants from .mbcharsetprober import MultiByteCharSetProber from .codingstatemachine import CodingStateMachine from .chardistribution import EUCJPDistributionAnalysis from .jpcntx import EUCJPContextAnalysis from .mbcssm import EUCJPSMModel class EUCJPProber(MultiByteCharSetProber): def __init__(self): MultiByteCharSetProber.__init__(self) self._mCodingSM = CodingStateMachine(EUCJPSMModel) self._mDistributionAnalyzer = EUCJPDistributionAnalysis() self._mContextAnalyzer = EUCJPContextAnalysis() self.reset() def reset(self): MultiByteCharSetProber.reset(self) self._mContextAnalyzer.reset() def get_charset_name(self): return "EUC-JP" def feed(self, aBuf): aLen = len(aBuf) for i in range(0, aLen): # PY3K: aBuf is a byte array, so aBuf[i] is an int, not a byte codingState = self._mCodingSM.next_state(aBuf[i]) if codingState == constants.eError: if constants._debug: sys.stderr.write(self.get_charset_name() + ' prober hit error at byte ' + str(i) + '\n') self._mState = constants.eNotMe break elif codingState == constants.eItsMe: self._mState = constants.eFoundIt break elif codingState == constants.eStart: charLen = self._mCodingSM.get_current_charlen() if i == 0: self._mLastChar[1] = aBuf[0] self._mContextAnalyzer.feed(self._mLastChar, charLen) self._mDistributionAnalyzer.feed(self._mLastChar, charLen) else: self._mContextAnalyzer.feed(aBuf[i - 1:i + 1], charLen) self._mDistributionAnalyzer.feed(aBuf[i - 1:i + 1], charLen) self._mLastChar[0] = aBuf[aLen - 1] if self.get_state() == constants.eDetecting: if (self._mContextAnalyzer.got_enough_data() and (self.get_confidence() > constants.SHORTCUT_THRESHOLD)): self._mState = constants.eFoundIt return self.get_state() def get_confidence(self): contxtCf = self._mContextAnalyzer.get_confidence() distribCf = self._mDistributionAnalyzer.get_confidence() return max(contxtCf, distribCf)
bsd-3-clause
croxis/SpaceDrive
spacedrive/renderpipeline/rpplugins/vxgi/voxelization_stage.py
1
8394
""" RenderPipeline Copyright (c) 2014-2016 tobspr <tobias.springer1@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import division from rpcore.globals import Globals from rpcore.image import Image from rpcore.render_stage import RenderStage from panda3d.core import Camera, OrthographicLens, NodePath, CullFaceAttrib from panda3d.core import DepthTestAttrib, Vec4, PTALVecBase3, Vec3, SamplerState from panda3d.core import ColorWriteAttrib class VoxelizationStage(RenderStage): """ This stage voxelizes the whole scene """ required_inputs = ["DefaultEnvmap", "AllLightsData", "maxLightIndex"] required_pipes = [] # The different states of voxelization S_disabled = 0 S_voxelize_x = 1 S_voxelize_y = 2 S_voxelize_z = 3 S_gen_mipmaps = 4 def __init__(self, pipeline): RenderStage.__init__(self, pipeline) self.voxel_resolution = 256 self.voxel_world_size = -1 self.state = self.S_disabled self.create_ptas() def set_grid_position(self, pos): self.pta_next_grid_pos[0] = pos def create_ptas(self): self.pta_next_grid_pos = PTALVecBase3.empty_array(1) self.pta_grid_pos = PTALVecBase3.empty_array(1) @property def produced_inputs(self): return {"voxelGridPosition": self.pta_grid_pos} @property def produced_pipes(self): return {"SceneVoxels": self.voxel_grid} def create(self): # Create the voxel grid used to generate the voxels self.voxel_temp_grid = Image.create_3d( "VoxelsTemp", self.voxel_resolution, self.voxel_resolution, self.voxel_resolution, "RGBA8") self.voxel_temp_grid.set_clear_color(Vec4(0)) self.voxel_temp_nrm_grid = Image.create_3d( "VoxelsTemp", self.voxel_resolution, self.voxel_resolution, self.voxel_resolution, "R11G11B10") self.voxel_temp_nrm_grid.set_clear_color(Vec4(0)) # Create the voxel grid which is a copy of the temporary grid, but stable self.voxel_grid = Image.create_3d( "Voxels", self.voxel_resolution, self.voxel_resolution, self.voxel_resolution, "RGBA8") self.voxel_grid.set_clear_color(Vec4(0)) self.voxel_grid.set_minfilter(SamplerState.FT_linear_mipmap_linear) # Create the camera for voxelization self.voxel_cam = Camera("VoxelizeCam") self.voxel_cam.set_camera_mask(self._pipeline.tag_mgr.get_voxelize_mask()) self.voxel_cam_lens = OrthographicLens() self.voxel_cam_lens.set_film_size( -2.0 * self.voxel_world_size, 2.0 * self.voxel_world_size) self.voxel_cam_lens.set_near_far(0.0, 2.0 * self.voxel_world_size) self.voxel_cam.set_lens(self.voxel_cam_lens) self.voxel_cam_np = Globals.base.render.attach_new_node(self.voxel_cam) self._pipeline.tag_mgr.register_camera("voxelize", self.voxel_cam) # Create the voxelization target self.voxel_target = self.create_target("VoxelizeScene") self.voxel_target.size = self.voxel_resolution self.voxel_target.prepare_render(self.voxel_cam_np) # Create the target which copies the voxel grid self.copy_target = self.create_target("CopyVoxels") self.copy_target.size = self.voxel_resolution self.copy_target.prepare_buffer() # TODO! Does not work with the new render target yet - maybe add option # to post process region for instances? self.copy_target.instance_count = self.voxel_resolution self.copy_target.set_shader_input("SourceTex", self.voxel_temp_grid) self.copy_target.set_shader_input("DestTex", self.voxel_grid) # Create the target which generates the mipmaps self.mip_targets = [] mip_size, mip = self.voxel_resolution, 0 while mip_size > 1: mip_size, mip = mip_size // 2, mip + 1 mip_target = self.create_target("GenMipmaps:" + str(mip)) mip_target.size = mip_size mip_target.prepare_buffer() mip_target.instance_count = mip_size mip_target.set_shader_input("SourceTex", self.voxel_grid) mip_target.set_shader_input("sourceMip", mip - 1) mip_target.set_shader_input("DestTex", self.voxel_grid, False, True, -1, mip, 0) self.mip_targets.append(mip_target) # Create the initial state used for rendering voxels initial_state = NodePath("VXGIInitialState") initial_state.set_attrib(CullFaceAttrib.make(CullFaceAttrib.M_cull_none), 100000) initial_state.set_attrib(DepthTestAttrib.make(DepthTestAttrib.M_none), 100000) initial_state.set_attrib(ColorWriteAttrib.make(ColorWriteAttrib.C_off), 100000) self.voxel_cam.set_initial_state(initial_state.get_state()) Globals.base.render.set_shader_input("voxelGridPosition", self.pta_next_grid_pos) Globals.base.render.set_shader_input("VoxelGridDest", self.voxel_temp_grid) def update(self): self.voxel_cam_np.show() self.voxel_target.active = True self.copy_target.active = False for target in self.mip_targets: target.active = False # Voxelization disable if self.state == self.S_disabled: self.voxel_cam_np.hide() self.voxel_target.active = False # Voxelization from X-Axis elif self.state == self.S_voxelize_x: # Clear voxel grid self.voxel_temp_grid.clear_image() self.voxel_cam_np.set_pos( self.pta_next_grid_pos[0] + Vec3(self.voxel_world_size, 0, 0)) self.voxel_cam_np.look_at(self.pta_next_grid_pos[0]) # Voxelization from Y-Axis elif self.state == self.S_voxelize_y: self.voxel_cam_np.set_pos( self.pta_next_grid_pos[0] + Vec3(0, self.voxel_world_size, 0)) self.voxel_cam_np.look_at(self.pta_next_grid_pos[0]) # Voxelization from Z-Axis elif self.state == self.S_voxelize_z: self.voxel_cam_np.set_pos( self.pta_next_grid_pos[0] + Vec3(0, 0, self.voxel_world_size)) self.voxel_cam_np.look_at(self.pta_next_grid_pos[0]) # Generate mipmaps elif self.state == self.S_gen_mipmaps: self.voxel_target.active = False self.copy_target.active = True self.voxel_cam_np.hide() for target in self.mip_targets: target.active = True # As soon as we generate the mipmaps, we need to update the grid position # as well self.pta_grid_pos[0] = self.pta_next_grid_pos[0] def reload_shaders(self): self.copy_target.shader = self.load_plugin_shader( "/$$rp/shader/default_post_process_instanced.vert.glsl", "copy_voxels.frag.glsl") mip_shader = self.load_plugin_shader( "/$$rp/shader/default_post_process_instanced.vert.glsl", "generate_mipmaps.frag.glsl") for target in self.mip_targets: target.shader = mip_shader def set_shader_input(self, *args): Globals.render.set_shader_input(*args)
mit
gfarmerfr/nicotine-plus
pynicotine/pynicotine.py
2
73335
# -*- coding: utf-8 -*- # # COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr> # COPYRIGHT (C) 2016 Mutnick <muhing@yahoo.com> # COPYRIGHT (C) 2013 eL_vErDe <gandalf@le-vert.net> # COPYRIGHT (C) 2008-2012 Quinox <quinox@users.sf.net> # COPYRIGHT (C) 2009 Hedonist <ak@sensi.org> # COPYRIGHT (C) 2006-2009 Daelstorm <daelstorm@gmail.com> # COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org> # COPYRIGHT (C) 2001-2003 Alexander Kanavin # # GNU GENERAL PUBLIC LICENSE # Version 3, 29 June 2007 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ This is the actual client code. Actual GUI classes are in the separate modules """ from __future__ import division import time import datetime import shutil from urllib import urlencode import slskproto import slskmessages from slskmessages import newId, PopupMessage, ToBeEncoded import transfers import Queue import threading from config import * import string import types import locale import utils from shares import Shares from utils import CleanFile, findBestEncoding import os import logging from ConfigParser import Error as ConfigParserError class PeerConnection: """ Holds information about a peer connection. Not every field may be set to something. addr is (ip, port) address, conn is a socket object, msgs is a list of outgoing pending messages, token is a reverse-handshake number (protocol feature), init is a PeerInit protocol message. (read slskmessages docstrings for explanation of these) """ def __init__(self, addr=None, username=None, conn=None, msgs=None, token=None, init=None, conntimer=None, tryaddr=None): self.addr = addr self.username = username self.conn = conn self.msgs = msgs self.token = token self.init = init self.conntimer = conntimer self.tryaddr = tryaddr class Timeout: def __init__(self, callback): self.callback = callback def timeout(self): try: self.callback([self]) except Exception, e: print("Exception in callback %s: %s" % (self.callback, e)) class ConnectToPeerTimeout(Timeout): def __init__(self, conn, callback): self.conn = conn self.callback = callback class RespondToDistributedSearchesTimeout(Timeout): pass class NetworkEventProcessor: """ This class contains handlers for various messages from the networking thread""" def __init__(self, frame, callback, writelog, setstatus, bindip, configfile): self.frame = frame self.callback = callback self.logMessage = writelog self.setStatus = setstatus try: self.config = Config(configfile) except ConfigParserError: corruptfile = ".".join([configfile, CleanFile(datetime.datetime.now().strftime("%Y-%M-%d_%H:%M:%S")), "corrupt"]) shutil.move(configfile, corruptfile) short = _("Your config file is corrupt") long = _("We're sorry, but it seems your configuration file is corrupt. Please reconfigure Nicotine+.\n\nWe renamed your old configuration file to\n%(corrupt)s\nIf you open this file with a text editor you might be able to rescue some of your settings.") % {'corrupt': corruptfile} log.addwarning(long) self.config = Config(configfile) self.callback([PopupMessage(short, long)]) self.bindip = bindip self.config.frame = frame self.config.readConfig() self.peerconns = [] self.watchedusers = [] self.ipblock_requested = {} self.ipignore_requested = {} self.ip_requested = [] self.PrivateMessageQueue = {} self.users = {} self.queue = Queue.Queue(0) self.shares = Shares(self) try: import GeoIP self.geoip = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE) except ImportError: try: import _GeoIP self.geoip = _GeoIP.new(_GeoIP.GEOIP_MEMORY_CACHE) except ImportError: self.geoip = None self.protothread = slskproto.SlskProtoThread(self.frame.networkcallback, self.queue, self.bindip, self.config, self) uselimit = self.config.sections["transfers"]["uselimit"] uploadlimit = self.config.sections["transfers"]["uploadlimit"] limitby = self.config.sections["transfers"]["limitby"] self.queue.put(slskmessages.SetUploadLimit(uselimit, uploadlimit, limitby)) self.queue.put(slskmessages.SetDownloadLimit(self.config.sections["transfers"]["downloadlimit"])) if self.config.sections["transfers"]["geoblock"]: panic = self.config.sections["transfers"]["geopanic"] cc = self.config.sections["transfers"]["geoblockcc"] self.queue.put(slskmessages.SetGeoBlock([panic, cc])) else: self.queue.put(slskmessages.SetGeoBlock(None)) self.serverconn = None self.waitport = None self.chatrooms = None self.privatechat = None self.globallist = None self.userinfo = None self.userbrowse = None self.search = None self.transfers = None self.userlist = None self.logintime = None self.ipaddress = None self.privileges_left = None self.servertimer = None self.servertimeout = -1 self.distribcache = {} self.branchlevel = 0 self.branchroot = None self.requestedInfo = {} self.requestedFolders = {} self.speed = 0 self.respondDistributed = True responddistributedtimeout = RespondToDistributedSearchesTimeout(self.callback) self.respondDistributedTimer = threading.Timer(60, responddistributedtimeout.timeout) self.respondDistributedTimer.start() # Callback handlers for messages self.events = { slskmessages.ConnectToServer: self.ConnectToServer, slskmessages.ConnectError: self.ConnectError, slskmessages.IncPort: self.IncPort, slskmessages.ServerConn: self.ServerConn, slskmessages.ConnClose: self.ConnClose, slskmessages.Login: self.Login, slskmessages.ChangePassword: self.ChangePassword, slskmessages.MessageUser: self.MessageUser, slskmessages.PMessageUser: self.PMessageUser, slskmessages.ExactFileSearch: self.ExactFileSearch, slskmessages.UserJoinedRoom: self.UserJoinedRoom, slskmessages.SayChatroom: self.SayChatRoom, slskmessages.JoinRoom: self.JoinRoom, slskmessages.UserLeftRoom: self.UserLeftRoom, slskmessages.QueuedDownloads: self.QueuedDownloads, slskmessages.GetPeerAddress: self.GetPeerAddress, slskmessages.OutConn: self.OutConn, slskmessages.UserInfoReply: self.UserInfoReply, slskmessages.UserInfoRequest: self.UserInfoRequest, slskmessages.PierceFireWall: self.PierceFireWall, slskmessages.CantConnectToPeer: self.CantConnectToPeer, slskmessages.PeerTransfer: self.PeerTransfer, slskmessages.SharedFileList: self.SharedFileList, slskmessages.GetSharedFileList: self.shares.GetSharedFileList, slskmessages.FileSearchRequest: self.FileSearchRequest, slskmessages.FileSearchResult: self.FileSearchResult, slskmessages.ConnectToPeer: self.ConnectToPeer, slskmessages.GetUserStatus: self.GetUserStatus, slskmessages.GetUserStats: self.GetUserStats, slskmessages.Relogged: self.Relogged, slskmessages.PeerInit: self.PeerInit, slskmessages.DownloadFile: self.FileDownload, slskmessages.UploadFile: self.FileUpload, slskmessages.FileRequest: self.FileRequest, slskmessages.TransferRequest: self.TransferRequest, slskmessages.TransferResponse: self.TransferResponse, slskmessages.QueueUpload: self.QueueUpload, slskmessages.QueueFailed: self.QueueFailed, slskmessages.UploadFailed: self.UploadFailed, slskmessages.PlaceInQueue: self.PlaceInQueue, slskmessages.FileError: self.FileError, slskmessages.FolderContentsResponse: self.FolderContentsResponse, slskmessages.FolderContentsRequest: self.shares.FolderContentsRequest, slskmessages.RoomList: self.RoomList, slskmessages.LeaveRoom: self.LeaveRoom, slskmessages.GlobalUserList: self.GlobalUserList, slskmessages.AddUser: self.AddUser, slskmessages.PrivilegedUsers: self.PrivilegedUsers, slskmessages.AddToPrivileged: self.AddToPrivileged, slskmessages.CheckPrivileges: self.CheckPrivileges, slskmessages.ServerPing: self.DummyMessage, slskmessages.ParentMinSpeed: self.DummyMessage, slskmessages.ParentSpeedRatio: self.DummyMessage, slskmessages.Msg85: self.DummyMessage, slskmessages.Msg12547: self.Msg12547, slskmessages.ParentInactivityTimeout: self.ParentInactivityTimeout, slskmessages.SearchInactivityTimeout: self.SearchInactivityTimeout, slskmessages.MinParentsInCache: self.MinParentsInCache, slskmessages.Msg89: self.DummyMessage, slskmessages.WishlistInterval: self.WishlistInterval, slskmessages.DistribAliveInterval: self.DummyMessage, slskmessages.ChildDepth: self.ChildDepth, slskmessages.BranchLevel: self.BranchLevel, slskmessages.BranchRoot: self.BranchRoot, slskmessages.DistribChildDepth: self.DistribChildDepth, slskmessages.DistribBranchLevel: self.DistribBranchLevel, slskmessages.DistribBranchRoot: self.DistribBranchRoot, slskmessages.DistribMessage9: self.DistribMessage9, slskmessages.AdminMessage: self.AdminMessage, slskmessages.TunneledMessage: self.TunneledMessage, slskmessages.IncConn: self.IncConn, slskmessages.PlaceholdUpload: self.PlaceholdUpload, slskmessages.PlaceInQueueRequest: self.PlaceInQueueRequest, slskmessages.UploadQueueNotification: self.UploadQueueNotification, slskmessages.SearchRequest: self.SearchRequest, slskmessages.FileSearch: self.SearchRequest, slskmessages.RoomSearch: self.RoomSearchRequest, slskmessages.UserSearch: self.SearchRequest, slskmessages.NetInfo: self.NetInfo, slskmessages.DistribAlive: self.DistribAlive, slskmessages.DistribSearch: self.DistribSearch, ConnectToPeerTimeout: self.ConnectToPeerTimeout, RespondToDistributedSearchesTimeout: self.ToggleRespondDistributed, transfers.TransferTimeout: self.TransferTimeout, slskmessages.RescanShares: self.shares.RescanShares, slskmessages.RescanBuddyShares: self.shares.RescanBuddyShares, str: self.Notify, slskmessages.PopupMessage: self.PopupMessage, slskmessages.InternalData: self.DisplaySockets, slskmessages.DebugMessage: self.DebugMessage, slskmessages.GlobalRecommendations: self.GlobalRecommendations, slskmessages.Recommendations: self.Recommendations, slskmessages.ItemRecommendations: self.ItemRecommendations, slskmessages.SimilarUsers: self.SimilarUsers, slskmessages.ItemSimilarUsers: self.ItemSimilarUsers, slskmessages.UserInterests: self.UserInterests, slskmessages.RoomTickerState: self.RoomTickerState, slskmessages.RoomTickerAdd: self.RoomTickerAdd, slskmessages.RoomTickerRemove: self.RoomTickerRemove, slskmessages.UserPrivileged: self.UserPrivileged, slskmessages.AckNotifyPrivileges: self.AckNotifyPrivileges, slskmessages.NotifyPrivileges: self.NotifyPrivileges, slskmessages.PrivateRoomUsers: self.PrivateRoomUsers, slskmessages.PrivateRoomOwned: self.PrivateRoomOwned, slskmessages.PrivateRoomAddUser: self.PrivateRoomAddUser, slskmessages.PrivateRoomRemoveUser: self.PrivateRoomRemoveUser, slskmessages.PrivateRoomAdded: self.PrivateRoomAdded, slskmessages.PrivateRoomRemoved: self.PrivateRoomRemoved, slskmessages.PrivateRoomDisown: self.PrivateRoomDisown, slskmessages.PrivateRoomToggle: self.PrivateRoomToggle, slskmessages.PrivateRoomSomething: self.PrivateRoomSomething, slskmessages.PrivateRoomOperatorAdded: self.PrivateRoomOperatorAdded, slskmessages.PrivateRoomOperatorRemoved: self.PrivateRoomOperatorRemoved, slskmessages.PrivateRoomAddOperator: self.PrivateRoomAddOperator, slskmessages.PrivateRoomRemoveOperator: self.PrivateRoomRemoveOperator, slskmessages.PublicRoomMessage: self.PublicRoomMessage, } def ProcessRequestToPeer(self, user, message, window=None, address=None): """ Sends message to a peer and possibly sets up a window to display the result. """ conn = None for i in self.peerconns: if i.username == user and i.init.type == 'P' and message.__class__ is not slskmessages.FileRequest: conn = i break if conn is not None and conn.conn is not None: message.conn = conn.conn self.queue.put(message) if window is not None: window.InitWindow(conn.username, conn.conn) if message.__class__ is slskmessages.TransferRequest and self.transfers is not None: self.transfers.gotConnect(message.req, conn.conn) return else: if message.__class__ is slskmessages.FileRequest: type = 'F' elif message.__class__ is slskmessages.DistribConn: type = 'D' else: type = 'P' init = slskmessages.PeerInit(None, self.config.sections["server"]["login"], type, 0) firewalled = self.config.sections["server"]["firewalled"] addr = None behindfw = None token = None if user in self.users: addr = self.users[user].addr behindfw = self.users[user].behindfw elif address is not None: self.users[user] = UserAddr(status=-1, addr=address) addr = address if firewalled: if addr is None: self.queue.put(slskmessages.GetPeerAddress(user)) elif behindfw is None: self.queue.put(slskmessages.OutConn(None, addr)) else: firewalled = 0 if not firewalled: token = newId() self.queue.put(slskmessages.ConnectToPeer(token, user, type)) conn = PeerConnection(addr=addr, username=user, msgs=[message], token=token, init=init) self.peerconns.append(conn) if token is not None: timeout = 120.0 conntimeout = ConnectToPeerTimeout(self.peerconns[-1], self.callback) timer = threading.Timer(timeout, conntimeout.timeout) self.peerconns[-1].conntimer = timer timer.start() if message.__class__ is slskmessages.TransferRequest and self.transfers is not None: if conn.addr is None: self.transfers.gettingAddress(message.req) elif conn.token is None: self.transfers.gotAddress(message.req) else: self.transfers.gotConnectError(message.req) def setServerTimer(self): if self.servertimeout == -1: self.servertimeout = 15 elif 0 < self.servertimeout < 600: self.servertimeout = self.servertimeout * 2 self.servertimer = threading.Timer(self.servertimeout, self.ServerTimeout) self.servertimer.start() logging.info(_("The server seems to be down or not responding, retrying in %i seconds") % (self.servertimeout)) def ServerTimeout(self): if self.config.needConfig() <= 1: self.callback([slskmessages.ConnectToServer()]) def StopTimers(self): for i in self.peerconns: if i.conntimer is not None: i.conntimer.cancel() if self.servertimer is not None: self.servertimer.cancel() if self.respondDistributedTimer is not None: self.respondDistributedTimer.cancel() if self.transfers is not None: self.transfers.AbortTransfers() def ConnectToServer(self, msg): self.frame.OnConnect(None) def encodeuser(self, string, user=None): coding = None config = self.config.sections if user and user in config["server"]["userencoding"]: coding = config["server"]["userencoding"][user] string = self.decode(string, coding) try: return string.encode(locale.nl_langinfo(locale.CODESET)) except: return string def encode(self, str, networkenc=None): if networkenc is None: networkenc = self.config.sections["server"]["enc"] if type(str) is types.UnicodeType: return str.encode(networkenc, 'replace') else: return str.decode("utf-8", 'replace').encode(networkenc, 'replace') def decode(self, string, networkenc=None): if networkenc is None: networkenc = self.config.sections["server"]["enc"] return str(string).decode(networkenc, 'replace').encode("utf-8", "replace") def getencodings(self): # Encodings and descriptions for ComboBoxes return [ ["Latin", 'ascii'], ["US-Canada", 'cp037'], ['Hebrew', 'cp424'], ['US English', 'cp437'], ['International', 'cp500'], ['Greek', 'cp737'], ['Estonian', 'cp775'], ['Western European', 'cp850'], ['Central European', 'cp852'], ['Cyrillic', 'cp855'], ['Cyrillic', 'cp856'], ['Turkish', 'cp857'], ['Portuguese', 'cp860'], ['Icelandic', 'cp861'], ['Hebrew', 'cp862'], ['French Canadian', 'cp863'], ['Arabic', 'cp864'], ['Nordic', 'cp865'], ['Cyrillic', 'cp866'], ['Latin-9', 'cp869'], ['Thai', 'cp874'], ['Greek', 'cp875'], ['Japanese', 'cp932'], ['Chinese Simple', 'cp936'], ['Korean', 'cp949'], ['Chinese Traditional', 'cp950'], ['Urdu', 'cp1006'], ['Turkish', 'cp1026'], ['Latin', 'cp1140'], ['Central European', 'cp1250'], ['Cyrillic', 'cp1251'], ['Latin', 'cp1252'], ['Greek', 'cp1253'], ['Turkish', 'cp1254'], ['Hebrew', 'cp1255'], ['Arabic', 'cp1256'], ['Baltic', 'cp1257'], ['Vietnamese', 'cp1258'], ['Latin', 'iso8859-1'], ['Latin 2', 'iso8859-2'], ['South European', 'iso8859-3'], ['North European', 'iso8859-4'], ['Cyrillic', 'iso8859-5'], ['Arabic', 'iso8859-6'], ['Greek', 'iso8859-7'], ['Hebrew', 'iso8859-8'], ['Turkish', 'iso8859-9'], ['Nordic', 'iso8859-10'], ['Thai', 'iso8859-11'], ['Baltic', 'iso8859-13'], ['Celtic', 'iso8859-14'], ['Western European', 'iso8859-15'], ['South-Eastern European', 'iso8859-16'], ['Cyrillic', 'koi8-r'], ['Latin', 'latin-1'], ['Japanese', 'shift_jis'], ['Korean', 'euc_kr'], ['Cyrillic', 'mac-cyrillic'], ['Greek', 'mac-greek'], ['Icelandic', 'mac-iceland'], ['Latin 2', 'mac-latin2'], ['Latin', 'mac-roman'], ['Turkish', 'mac-turkish'], ['International', 'utf-16'], ['International', 'utf-7'], ['International', 'utf-8'] ] # Notify user of error when recieving or sending a message # @param self NetworkEventProcessor (Class) # @param string a string containing an error message def Notify(self, string): self.logMessage("%s" % self.decode(string)) def PopupMessage(self, msg): self.setStatus(_(msg.title)) self.frame.PopupMessage(msg) def DebugMessage(self, msg): self.logMessage(msg.msg, msg.debugLevel) def DisplaySockets(self, msg): self.frame.SetSocketStatus(msg.msg) def ConnectError(self, msg): if msg.connobj.__class__ is slskmessages.ServerConn: self.setStatus( _("Can't connect to server %(host)s:%(port)s: %(error)s") % { 'host': msg.connobj.addr[0], 'port': msg.connobj.addr[1], 'error': self.decode(msg.err) } ) self.setServerTimer() if self.serverconn is not None: self.serverconn = None self.frame.ConnectError(msg) elif msg.connobj.__class__ is slskmessages.OutConn: for i in self.peerconns[:]: if i.addr == msg.connobj.addr and i.conn is None: if i.token is None: i.token = newId() self.queue.put(slskmessages.ConnectToPeer(i.token, i.username, i.init.type)) if i.username in self.users: self.users[i.username].behindfw = "yes" for j in i.msgs: if j.__class__ is slskmessages.TransferRequest and self.transfers is not None: self.transfers.gotConnectError(j.req) conntimeout = ConnectToPeerTimeout(i, self.callback) timer = threading.Timer(120.0, conntimeout.timeout) timer.start() if i.conntimer is not None: i.conntimer.cancel() i.conntimer = timer else: for j in i.msgs: if j.__class__ in [slskmessages.TransferRequest, slskmessages.FileRequest] and self.transfers is not None: self.transfers.gotCantConnect(j.req) self.logMessage( _("Can't connect to %s, sending notification via the server") % (i.username), 3 ) self.queue.put(slskmessages.CantConnectToPeer(i.token, i.username)) if i.conntimer is not None: i.conntimer.cancel() self.peerconns.remove(i) break else: self.logMessage("%s %s %s" % (msg.err, msg.__class__, vars(msg)), 4) else: self.logMessage("%s %s %s" % (msg.err, msg.__class__, vars(msg)), 4) self.ClosedConnection(msg.connobj.conn, msg.connobj.addr) def IncPort(self, msg): self.waitport = msg.port self.setStatus(_("Listening on port %i") % (msg.port)) def ServerConn(self, msg): self.setStatus( _("Connected to server %(host)s:%(port)s, logging in...") % { 'host': msg.addr[0], 'port': msg.addr[1] } ) time.sleep(1) self.serverconn = msg.conn self.servertimeout = -1 self.users = {} self.queue.put( slskmessages.Login( self.config.sections["server"]["login"], self.config.sections["server"]["passw"], 157 # 155, 156, 157, 180 ) ) if self.waitport is not None: self.queue.put(slskmessages.SetWaitPort(self.waitport)) def PeerInit(self, msg): self.peerconns.append( PeerConnection( addr=msg.conn.addr, username=msg.user, conn=msg.conn.conn, init=msg, msgs=[] ) ) def ConnClose(self, msg): self.ClosedConnection(msg.conn, msg.addr) def ClosedConnection(self, conn, addr): if conn == self.serverconn: self.setStatus( _("Disconnected from server %(host)s:%(port)s") % { 'host': addr[0], 'port': addr[1] } ) userchoice = bool(self.frame.manualdisconnect) if not self.frame.manualdisconnect: self.setServerTimer() else: self.frame.manualdisconnect = 0 if self.respondDistributedTimer is not None: self.respondDistributedTimer.cancel() self.serverconn = None self.watchedusers = [] if self.transfers is not None: self.transfers.AbortTransfers() self.transfers.SaveDownloads() self.privatechat = self.chatrooms = self.userinfo = self.userbrowse = self.search = self.transfers = self.userlist = None self.frame.ConnClose(conn, addr) self.frame.pluginhandler.ServerDisconnectNotification(userchoice) else: for i in self.peerconns[:]: if i.conn == conn: self.logMessage(_("Connection closed by peer: %s") % self.decode(vars(i)), 3) if i.conntimer is not None: i.conntimer.cancel() if self.transfers is not None: self.transfers.ConnClose(conn, addr) if i == self.GetDistribConn(): self.DistribConnClosed(i) self.peerconns.remove(i) break else: self.logMessage( _("Removed connection closed by peer: %(conn_obj)s %(address)s") % { 'conn_obj': conn, 'address': addr }, 3 ) self.queue.put(slskmessages.ConnClose(conn)) def Login(self, msg): self.logintime = time.time() conf = self.config.sections if msg.success: self.setStatus(_("Logged in, getting the list of rooms...")) self.transfers = transfers.Transfers(conf["transfers"]["downloads"], self.peerconns, self.queue, self, self.users) if msg.ip is not None: self.ipaddress = msg.ip self.privatechat, self.chatrooms, self.userinfo, self.userbrowse, self.search, downloads, uploads, self.userlist = self.frame.InitInterface(msg) self.transfers.setTransferPanels(downloads, uploads) self.shares.sendNumSharedFoldersFiles() self.queue.put(slskmessages.SetStatus((not self.frame.away)+1)) for thing in self.config.sections["interests"]["likes"]: self.queue.put(slskmessages.AddThingILike(self.encode(thing))) for thing in self.config.sections["interests"]["dislikes"]: self.queue.put(slskmessages.AddThingIHate(self.encode(thing))) if not len(self.distribcache): self.queue.put(slskmessages.HaveNoParent(1)) self.queue.put(slskmessages.NotifyPrivileges(1, self.config.sections["server"]["login"])) self.privatechat.Login() self.queue.put(slskmessages.CheckPrivileges()) self.queue.put(slskmessages.PrivateRoomToggle(self.config.sections["server"]["private_chatrooms"])) else: self.frame.manualdisconnect = 1 self.setStatus(_("Can not log in, reason: %s") % (msg.reason)) self.logMessage(_("Can not log in, reason: %s") % (msg.reason)) self.frame.settingswindow.SetSettings(self.config.sections) self.frame.settingswindow.SwitchToPage("Server") def ChangePassword(self, msg): password = msg.password self.config.sections["server"]["passw"] = password self.config.writeConfig() self.callback([PopupMessage(_("Your password has been changed"), "Password is %s" % password)]) def NotifyPrivileges(self, msg): if msg.token is not None: pass self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def UserPrivileged(self, msg): if self.transfers is not None: if msg.privileged is True: self.transfers.addToPrivileged(msg.user) def AckNotifyPrivileges(self, msg): if msg.token is not None: # Until I know the syntax, sending this message is probably a bad idea self.queue.put(slskmessages.AckNotifyPrivileges(msg.token)) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PMessageUser(self, msg): user = ip = port = None # Get peer's username, ip and port for i in self.peerconns: if i.conn is msg.conn.conn: user = i.username if i.addr is not None: ip, port = i.addr break if user is None: # No peer connection return if user != msg.user: text = _("(Warning: %(realuser)s is attempting to spoof %(fakeuser)s) ") % {"realuser": user, "fakeuser": msg.user} + msg.msg msg.user = user else: text = msg.msg if self.privatechat is not None: self.privatechat.ShowMessage(msg, text, status=0) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def MessageUser(self, msg): if msg.user in self.config.sections["server"]["userencoding"]: encodings = [self.config.sections["server"]["userencoding"][msg.user]] + self.config.sections["server"]["fallbackencodings"] encodings.append(self.config.sections["server"]["enc"]) else: encodings = [self.config.sections["server"]["enc"]] + self.config.sections["server"]["fallbackencodings"] msg.msg = findBestEncoding(msg.msg, encodings) status = 0 if self.logintime: if time.time() <= self.logintime + 2: # Offline message status = 1 if self.privatechat is not None: tuple = self.frame.pluginhandler.IncomingPrivateChatEvent(msg.user, msg.msg) if tuple is not None: (u, msg.msg) = tuple self.privatechat.ShowMessage(msg, msg.msg, status=status) self.frame.pluginhandler.IncomingPrivateChatNotification(msg.user, msg.msg) self.queue.put(slskmessages.MessageAcked(msg.msgid)) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def UserJoinedRoom(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.UserJoinedRoom(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PublicRoomMessage(self, msg): msg.msg = findBestEncoding(msg.msg, [self.config.sections["server"]["enc"]] + self.config.sections["server"]["fallbackencodings"]) if self.chatrooms is not None: self.chatrooms.roomsctrl.PublicRoomMessage(msg, msg.msg) self.frame.pluginhandler.PublicRoomMessageNotification(msg.room, msg.user, msg.msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def JoinRoom(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.JoinRoom(msg) ticker = "" if msg.room in self.config.sections["ticker"]["rooms"]: ticker = self.config.sections["ticker"]["rooms"][msg.room] elif self.config.sections["ticker"]["default"]: ticker = self.config.sections["ticker"]["default"] if ticker: encoding = self.config.sections["server"]["enc"] if msg.room in self.config.sections["server"]["roomencoding"]: encoding = self.config.sections["server"]["roomencoding"][msg.room] self.queue.put(slskmessages.RoomTickerSet(msg.room, ToBeEncoded(ticker, encoding))) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PrivateRoomUsers(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.PrivateRoomUsers(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PrivateRoomOwned(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.PrivateRoomOwned(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PrivateRoomAddUser(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.PrivateRoomAddUser(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PrivateRoomRemoveUser(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.PrivateRoomRemoveUser(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PrivateRoomOperatorAdded(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.PrivateRoomOperatorAdded(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PrivateRoomOperatorRemoved(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.PrivateRoomOperatorRemoved(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PrivateRoomAddOperator(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.PrivateRoomAddOperator(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PrivateRoomRemoveOperator(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.PrivateRoomRemoveOperator(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PrivateRoomAdded(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.PrivateRoomAdded(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PrivateRoomRemoved(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.PrivateRoomRemoved(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PrivateRoomDisown(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.PrivateRoomDisown(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PrivateRoomToggle(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.TogglePrivateRooms(msg.enabled) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PrivateRoomSomething(self, msg): pass def LeaveRoom(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.LeaveRoom(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PrivateMessageQueueAdd(self, msg, text): user = msg.user if user not in self.PrivateMessageQueue: self.PrivateMessageQueue[user] = [[msg, text]] else: self.PrivateMessageQueue[user].append([msg, text]) def PrivateMessageQueueProcess(self, user): if user in self.PrivateMessageQueue: for data in self.PrivateMessageQueue[user][:]: msg, text = data self.PrivateMessageQueue[user].remove(data) self.privatechat.ShowMessage(msg, text, status=0) def ipIgnored(self, address): if address is None: return True ips = self.config.sections["server"]["ipignorelist"] s_address = address.split(".") for ip in ips: # No Wildcard in IP if "*" not in ip: if address == ip: return True continue # Wildcard in IP parts = ip.split(".") seg = 0 for part in parts: # Stop if there's no wildcard or matching string number if part not in (s_address[seg], "*"): break seg += 1 # Last time around if seg == 4: # Wildcard blocked return True # Not blocked return False def SayChatRoom(self, msg): if msg.room in self.config.sections["server"]["roomencoding"]: encodings = [self.config.sections["server"]["roomencoding"][msg.room]] + self.config.sections["server"]["fallbackencodings"] encodings.append(self.config.sections["server"]["enc"]) else: encodings = [self.config.sections["server"]["enc"]] + self.config.sections["server"]["fallbackencodings"] msg.msg = findBestEncoding(msg.msg, encodings) if self.chatrooms is not None: event = self.frame.pluginhandler.IncomingPublicChatEvent(msg.room, msg.user, msg.msg) if event is not None: (r, n, msg.msg) = event self.chatrooms.roomsctrl.SayChatRoom(msg, msg.msg) self.frame.pluginhandler.IncomingPublicChatNotification(msg.room, msg.user, msg.msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def AddUser(self, msg): if msg.user not in self.watchedusers: self.watchedusers.append(msg.user) if not msg.userexists: if msg.user not in self.users: self.users[msg.user] = UserAddr(status=-1) if self.search is not None: self.search.NonExistantUser(msg.user) if self.transfers is not None: self.transfers.getAddUser(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) if msg.status is not None: self.GetUserStatus(msg) elif msg.userexists and msg.status is None: self.queue.put(slskmessages.GetUserStatus(msg.user)) if msg.files is not None: self.GetUserStats(msg) elif msg.userexists and msg.files is None: self.queue.put(slskmessages.GetUserStats(msg.user)) def PrivilegedUsers(self, msg): if self.transfers is not None: self.transfers.setPrivilegedUsers(msg.users) self.logMessage(_("%i privileged users") % (len(msg.users))) self.queue.put(slskmessages.HaveNoParent(1)) self.queue.put(slskmessages.GetUserStats(self.config.sections["server"]["login"])) self.frame.pluginhandler.ServerConnectNotification() else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def AddToPrivileged(self, msg): if self.transfers is not None: self.transfers.addToPrivileged(msg.user) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def CheckPrivileges(self, msg): mins = msg.seconds // 60 hours = mins // 60 days = hours // 24 wheretogetthem = " " + _("You can acquire privileges by donating at %(url)s") % { 'url': 'http://www.slsknet.org/userlogin.php?' + urlencode({ 'username': self.config.sections["server"]["login"] }) } if msg.seconds == 0: self.logMessage( _("You have no privileges left. They are not needed for Nicotine+ to function properly.") + wheretogetthem ) else: self.logMessage( _("%(days)i days, %(hours)i hours, %(minutes)i minutes, %(seconds)i seconds of download privileges left.") % { 'days': days, 'hours': hours % 24, 'minutes': mins % 60, 'seconds': msg.seconds % 60 } + wheretogetthem ) self.privileges_left = msg.seconds def AdminMessage(self, msg): self.logMessage("%s" % (msg.msg)) def ChildDepth(self, msg): # TODO: Distributed search messages need to implemented self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def BranchLevel(self, msg): # TODO: Distributed search messages need to implemented self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def BranchRoot(self, msg): # TODO: Distributed search messages need to implemented self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def DistribChildDepth(self, msg): # TODO: Distributed search messages need to implemented self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def DistribBranchLevel(self, msg): # TODO: Distributed search messages need to implemented self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def DistribBranchRoot(self, msg): # TODO: Distributed search messages need to implemented self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def DistribMessage9(self, msg): # TODO: Distributed search messages need to implemented self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def DummyMessage(self, msg): self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def Msg12547(self, msg): self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def ParentInactivityTimeout(self, msg): pass def SearchInactivityTimeout(self, msg): pass def MinParentsInCache(self, msg): pass def WishlistInterval(self, msg): if self.search is not None: self.search.SetInterval(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def GetUserStatus(self, msg): # Causes recursive requests when privileged? # self.queue.put(slskmessages.AddUser(msg.user)) if msg.user in self.users: if msg.status == 0: self.users[msg.user] = UserAddr(status=msg.status) else: self.users[msg.user].status = msg.status else: self.users[msg.user] = UserAddr(status=msg.status) if msg.privileged is not None: if msg.privileged == 1: if self.transfers is not None: self.transfers.addToPrivileged(msg.user) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) self.frame.GetUserStatus(msg) if self.userlist is not None: self.userlist.GetUserStatus(msg) if self.transfers is not None: self.transfers.GetUserStatus(msg) if self.privatechat is not None: self.privatechat.GetUserStatus(msg) if self.userinfo is not None: self.userinfo.GetUserStatus(msg) if self.userbrowse is not None: self.userbrowse.GetUserStatus(msg) if self.search is not None: self.search.GetUserStatus(msg) if self.chatrooms is not None: self.chatrooms.roomsctrl.GetUserStatus(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def UserInterests(self, msg): if self.userinfo is not None: self.userinfo.ShowInterests(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def GetUserStats(self, msg): if msg.user == self.config.sections["server"]["login"]: self.speed = msg.avgspeed self.frame.GetUserStats(msg) if self.chatrooms is not None: self.chatrooms.roomsctrl.GetUserStats(msg) if self.userinfo is not None: self.userinfo.GetUserStats(msg) if self.userlist is not None: self.userlist.GetUserStats(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) stats = { 'avgspeed': msg.avgspeed, 'downloadnum': msg.downloadnum, 'files': msg.files, 'dirs': msg.dirs, } self.frame.pluginhandler.UserStatsNotification(msg.user, stats) def UserLeftRoom(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.UserLeftRoom(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def QueuedDownloads(self, msg): self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def GetPeerAddress(self, msg): for i in self.peerconns: if i.username == msg.user and i.addr is None: if msg.port != 0 or i.tryaddr == 10: if i.tryaddr == 10: self.logMessage( _("Server reported port 0 for the 10th time for user %(user)s, giving up") % { 'user': msg.user }, 3 ) elif i.tryaddr is not None: self.logMessage( _("Server reported non-zero port for user %(user)s after %(tries)i retries") % { 'user': msg.user, 'tries': i.tryaddr }, 3 ) i.addr = (msg.ip, msg.port) i.tryaddr = None self.queue.put(slskmessages.OutConn(None, i.addr)) for j in i.msgs: if j.__class__ is slskmessages.TransferRequest and self.transfers is not None: self.transfers.gotAddress(j.req) else: if i.tryaddr is None: i.tryaddr = 1 self.logMessage( _("Server reported port 0 for user %(user)s, retrying") % { 'user': msg.user }, 3 ) else: i.tryaddr += 1 self.queue.put(slskmessages.GetPeerAddress(msg.user)) break else: if msg.user in self.users: self.users[msg.user].addr = (msg.ip, msg.port) else: self.users[msg.user] = UserAddr(addr=(msg.ip, msg.port)) if msg.user in self.ipblock_requested: if self.ipblock_requested[msg.user]: self.frame.OnUnBlockUser(msg.user) else: self.frame.OnBlockUser(msg.user) del self.ipblock_requested[msg.user] return if msg.user in self.ipignore_requested: if self.ipignore_requested[msg.user]: self.frame.OnUnIgnoreUser(msg.user) else: self.frame.OnIgnoreUser(msg.user) del self.ipignore_requested[msg.user] return # From this point on all paths should call # self.frame.pluginhandler.UserResolveNotification precisely once if msg.user in self.PrivateMessageQueue: self.PrivateMessageQueueProcess(msg.user) if msg.user not in self.ip_requested: self.frame.pluginhandler.UserResolveNotification(msg.user, msg.ip, msg.port) return self.ip_requested.remove(msg.user) import socket if self.geoip: cc = self.geoip.country_name_by_addr(msg.ip) cn = self.geoip.country_code_by_addr(msg.ip) if cn is not None: self.frame.HasUserFlag(msg.user, "flag_"+cn) else: cc = "" if cc: cc = " (%s)" % cc else: cc = "" try: hostname = socket.gethostbyaddr(msg.ip)[0] message = _("IP address of %(user)s is %(ip)s, name %(host)s, port %(port)i%(country)s") % { 'user': msg.user, 'ip': msg.ip, 'host': hostname, 'port': msg.port, 'country': cc } except: message = _("IP address of %(user)s is %(ip)s, port %(port)i%(country)s") % { 'user': msg.user, 'ip': msg.ip, 'port': msg.port, 'country': cc } self.logMessage(message) self.frame.pluginhandler.UserResolveNotification(msg.user, msg.ip, msg.port, cc) def Relogged(self, msg): self.logMessage(_("Someone else is logging in with the same nickname, server is going to disconnect us")) self.frame.manualdisconnect = 1 self.frame.pluginhandler.ServerDisconnectNotification(False) def OutConn(self, msg): for i in self.peerconns: if i.addr == msg.addr and i.conn is None: if i.token is None: i.init.conn = msg.conn self.queue.put(i.init) else: self.queue.put(slskmessages.PierceFireWall(msg.conn, i.token)) i.conn = msg.conn for j in i.msgs: if j.__class__ is slskmessages.UserInfoRequest and self.userinfo is not None: self.userinfo.InitWindow(i.username, msg.conn) if j.__class__ is slskmessages.GetSharedFileList and self.userbrowse is not None: self.userbrowse.InitWindow(i.username, msg.conn) if j.__class__ is slskmessages.FileRequest and self.transfers is not None: self.transfers.gotFileConnect(j.req, msg.conn) if j.__class__ is slskmessages.TransferRequest and self.transfers is not None: self.transfers.gotConnect(j.req, msg.conn) j.conn = msg.conn self.queue.put(j) i.msgs = [] break self.logMessage("%s %s" % (msg.__class__, vars(msg)), 3) def IncConn(self, msg): self.logMessage("%s %s" % (msg.__class__, vars(msg)), 3) def ConnectToPeer(self, msg): init = slskmessages.PeerInit(None, msg.user, msg.type, 0) self.queue.put(slskmessages.OutConn(None, (msg.ip, msg.port), init)) self.peerconns.append( PeerConnection( addr=(msg.ip, msg.port), username=msg.user, msgs=[], token=msg.token, init=init ) ) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 3) def CheckUser(self, user, addr): """ Check if this user is banned, geoip-blocked, and which shares it is allowed to access based on transfer and shares settings. """ if user in self.config.sections["server"]["banlist"]: if self.config.sections["transfers"]["usecustomban"]: return 0, _("Banned (%s)") % self.config.sections["transfers"]["customban"] else: return 0, _("Banned") if user in [i[0] for i in self.config.sections["server"]["userlist"]] and self.config.sections["transfers"]["enablebuddyshares"]: # For sending buddy-only shares return 2, "" if user in [i[0] for i in self.config.sections["server"]["userlist"]]: return 1, "" if self.config.sections["transfers"]["friendsonly"]: return 0, _("Sorry, friends only") if not self.geoip or not self.config.sections["transfers"]["geoblock"]: return 1, _("geoip") cc = None if addr is not None: cc = self.geoip.country_code_by_addr(addr) if not cc: if self.config.sections["transfers"]["geopanic"]: return 0, _("Sorry, geographical paranoia") else: return 1, "" if self.config.sections["transfers"]["geoblockcc"][0].find(cc) >= 0: return 0, _("Sorry, your country is blocked") return 1, "" def CheckSpoof(self, user, ip, port): if user not in self.users: return 0 if self.users[user].addr is not None: if len(self.users[user].addr) == 2: if self.users[user].addr is not None: u_ip, u_port = self.users[user].addr if u_ip != ip: warning = _("IP %(ip)s:%(port)s is spoofing user %(user)s with a peer request, blocking because it does not match IP: %(real_ip)s") % { 'ip': ip, 'port': port, 'user': user, 'real_ip': u_ip } self.logMessage(warning, 1) print warning return 1 return 0 def ClosePeerConnection(self, peerconn): if peerconn is None: return for i in self.peerconns[:]: if i.conn == peerconn: if not self.protothread.socketStillActive(i.conn): self.queue.put(slskmessages.ConnClose(i.conn)) self.peerconns.remove(i) break def UserInfoReply(self, msg): for i in self.peerconns: if i.conn is msg.conn.conn and self.userinfo is not None: # probably impossible to do this if i.username != self.config.sections["server"]["login"]: self.userinfo.ShowInfo(i.username, msg) def UserInfoRequest(self, msg): user = ip = port = None # Get peer's username, ip and port for i in self.peerconns: if i.conn is msg.conn.conn: user = i.username if i.addr is not None: ip, port = i.addr break if user is None: # No peer connection return requestTime = time.time() if user in self.requestedInfo: if not requestTime > 10 + self.requestedInfo[user]: # Ignoring request, because it's 10 or less seconds since the # last one by this user return self.requestedInfo[user] = requestTime # Check address is spoofed, if possible if user == self.config.sections["server"]["login"]: if ip is not None and port is not None: self.logMessage( _("Blocking %(user)s from making a UserInfo request, possible spoofing attempt from IP %(ip)s port %(port)s") % { 'user': user, 'ip': ip, 'port': port }, 1 ) else: self.logMessage( _("Blocking %s from making a UserInfo request, possible spoofing attempt from an unknown IP & port") % (user), 1 ) if msg.conn.conn is not None: self.queue.put(slskmessages.ConnClose(msg.conn.conn)) return if user in self.config.sections["server"]["banlist"]: self.logMessage( _("%(user)s is banned, but is making a UserInfo request") % { 'user': user }, 1 ) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 1) return try: if sys.platform == "win32": userpic = u"%s" % self.config.sections["userinfo"]["pic"] if not os.path.exists(userpic): userpic = self.config.sections["userinfo"]["pic"] else: userpic = self.config.sections["userinfo"]["pic"] f = open(userpic, 'rb') pic = f.read() f.close() except: pic = None descr = self.encode(eval(self.config.sections["userinfo"]["descr"], {})).replace("\n", "\r\n") if self.transfers is not None: totalupl = self.transfers.getTotalUploadsAllowed() queuesize = self.transfers.getUploadQueueSizes()[0] slotsavail = self.transfers.allowNewUploads() ua = self.frame.np.config.sections["transfers"]["remotedownloads"] if ua: uploadallowed = self.frame.np.config.sections["transfers"]["uploadallowed"] else: uploadallowed = ua self.queue.put(slskmessages.UserInfoReply(msg.conn.conn, descr, pic, totalupl, queuesize, slotsavail, uploadallowed)) self.logMessage( _("%(user)s is making a UserInfo request") % { 'user': user }, 1 ) def SharedFileList(self, msg): for i in self.peerconns: if i.conn is msg.conn.conn and self.userbrowse is not None: if i.username != self.config.sections["server"]["login"]: self.userbrowse.ShowInfo(i.username, msg) def FileSearchResult(self, msg): for i in self.peerconns: if i.conn is msg.conn.conn and self.search is not None: if self.geoip: if i.addr: country = self.geoip.country_code_by_addr(i.addr[0]) else: country = "" else: country = "" if country is None: country = "" self.search.ShowResult(msg, i.username, country) self.ClosePeerConnection(i.conn) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PierceFireWall(self, msg): for i in self.peerconns: if i.token == msg.token and i.conn is None: if i.conntimer is not None: i.conntimer.cancel() i.init.conn = msg.conn.conn self.queue.put(i.init) i.conn = msg.conn.conn for j in i.msgs: if j.__class__ is slskmessages.UserInfoRequest and self.userinfo is not None: self.userinfo.InitWindow(i.username, msg.conn.conn) if j.__class__ is slskmessages.GetSharedFileList and self.userbrowse is not None: self.userbrowse.InitWindow(i.username, msg.conn.conn) if j.__class__ is slskmessages.FileRequest and self.transfers is not None: self.transfers.gotFileConnect(j.req, msg.conn.conn) if j.__class__ is slskmessages.TransferRequest and self.transfers is not None: self.transfers.gotConnect(j.req, msg.conn.conn) j.conn = msg.conn.conn self.queue.put(j) i.msgs = [] break self.logMessage("%s %s" % (msg.__class__, vars(msg)), 3) def CantConnectToPeer(self, msg): for i in self.peerconns[:]: if i.token == msg.token: if i.conntimer is not None: i.conntimer.cancel() if i == self.GetDistribConn(): self.DistribConnClosed(i) self.peerconns.remove(i) self.logMessage(_("Can't connect to %s (either way), giving up") % (i.username), 3) for j in i.msgs: if j.__class__ in [slskmessages.TransferRequest, slskmessages.FileRequest] and self.transfers is not None: self.transfers.gotCantConnect(j.req) def ConnectToPeerTimeout(self, msg): for i in self.peerconns[:]: if i == msg.conn: if i == self.GetDistribConn(): self.DistribConnClosed(i) self.peerconns.remove(i) self.logMessage(_("User %s does not respond to connect request, giving up") % (i.username), 3) for j in i.msgs: if j.__class__ in [slskmessages.TransferRequest, slskmessages.FileRequest] and self.transfers is not None: self.transfers.gotCantConnect(j.req) def TransferTimeout(self, msg): if self.transfers is not None: self.transfers.TransferTimeout(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def FileDownload(self, msg): if self.transfers is not None: self.transfers.FileDownload(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def FileUpload(self, msg): if self.transfers is not None: self.transfers.FileUpload(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def FileRequest(self, msg): if self.transfers is not None: self.transfers.FileRequest(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def FileError(self, msg): if self.transfers is not None: self.transfers.FileError(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def TransferRequest(self, msg): if self.transfers is not None: self.transfers.TransferRequest(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def TransferResponse(self, msg): if self.transfers is not None: self.transfers.TransferResponse(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def QueueUpload(self, msg): if self.transfers is not None: self.transfers.QueueUpload(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def QueueFailed(self, msg): if self.transfers is not None: self.transfers.QueueFailed(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PlaceholdUpload(self, msg): self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PlaceInQueueRequest(self, msg): if self.transfers is not None: self.transfers.PlaceInQueueRequest(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def UploadQueueNotification(self, msg): self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) self.transfers.UploadQueueNotification(msg) def UploadFailed(self, msg): if self.transfers is not None: self.transfers.UploadFailed(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PlaceInQueue(self, msg): if self.transfers is not None: self.transfers.PlaceInQueue(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def FolderContentsResponse(self, msg): if self.transfers is not None: for i in self.peerconns: if i.conn is msg.conn.conn: username = i.username # Check for a large number of files many = False folder = "" files = [] for i in msg.list.keys(): for j in msg.list[i].keys(): if os.path.commonprefix([i, j]) == j: files = msg.list[i][j] numfiles = len(files) if numfiles > 100: many = True folder = j if many: self.frame.download_large_folder(username, folder, files, numfiles, msg) else: self.transfers.FolderContentsResponse(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def RoomList(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.SetRoomList(msg) self.setStatus("") else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def GlobalUserList(self, msg): if self.globallist is not None: self.globallist.setGlobalUsersList(msg) else: self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def PeerTransfer(self, msg): if self.userinfo is not None and msg.msg is slskmessages.UserInfoReply: self.userinfo.UpdateGauge(msg) if self.userbrowse is not None and msg.msg is slskmessages.SharedFileList: self.userbrowse.UpdateGauge(msg) def TunneledMessage(self, msg): if msg.code in self.protothread.peerclasses: peermsg = self.protothread.peerclasses[msg.code](None) peermsg.parseNetworkMessage(msg.msg) peermsg.tunneleduser = msg.user peermsg.tunneledreq = msg.req peermsg.tunneledaddr = msg.addr self.callback([peermsg]) else: self.logMessage(_("Unknown tunneled message: %s") % (vars(msg)), 4) def ExactFileSearch(self, msg): ''' Depreciated ''' self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) for i in self.peerconns: if i.conn == msg.conn.conn: user = i.username self.shares.processExactSearchRequest(msg.searchterm, user, msg.searchid, direct=1, checksum=msg.checksum) def FileSearchRequest(self, msg): self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) for i in self.peerconns: if i.conn == msg.conn.conn: user = i.username self.shares.processSearchRequest(msg.searchterm, user, msg.searchid, direct=1) def SearchRequest(self, msg): self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) self.shares.processSearchRequest(msg.searchterm, msg.user, msg.searchid, direct=0) self.frame.pluginhandler.SearchRequestNotification(msg.searchterm, msg.user, msg.searchid) def RoomSearchRequest(self, msg): self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) self.shares.processSearchRequest(msg.searchterm, msg.room, msg.searchid, direct=0) def ToggleRespondDistributed(self, msg, settings=False): """ Toggle responding to distributed search each (default: 60sec) interval """ if not self.config.sections["searches"]["search_results"]: # Don't return _any_ results when this option is disabled if self.respondDistributedTimer is not None: self.respondDistributedTimer.cancel() self.respondDistributed = False return if self.respondDistributedTimer is not None: self.respondDistributedTimer.cancel() if self.config.sections["searches"]["distrib_timer"]: if not settings: # Don't toggle when just changing the settings self.respondDistributed = not self.respondDistributed responddistributedtimeout = RespondToDistributedSearchesTimeout(self.callback) self.respondDistributedTimer = threading.Timer(self.config.sections["searches"]["distrib_ignore"], responddistributedtimeout.timeout) self.respondDistributedTimer.start() else: # Always respond self.respondDistributed = True def DistribSearch(self, msg): if self.respondDistributed: # set in ToggleRespondDistributed self.shares.processSearchRequest(msg.searchterm, msg.user, msg.searchid, 0) self.frame.pluginhandler.DistribSearchNotification(msg.searchterm, msg.user, msg.searchid) def NetInfo(self, msg): self.distribcache.update(msg.list) if len(self.distribcache) > 0: self.queue.put(slskmessages.HaveNoParent(0)) if not self.GetDistribConn(): user = self.distribcache.keys()[0] addr = self.distribcache[user] self.queue.put(slskmessages.SearchParent(addr[0])) self.ProcessRequestToPeer(user, slskmessages.DistribConn(), None, addr) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def DistribAlive(self, msg): self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def GetDistribConn(self): for i in self.peerconns: if i.init.type == 'D': return i return None def DistribConnClosed(self, conn): del self.distribcache[conn.username] if len(self.distribcache) > 0: user = self.distribcache.keys()[0] addr = self.distribcache[user] self.queue.put(slskmessages.SearchParent(addr[0])) self.ProcessRequestToPeer(user, slskmessages.DistribConn(), None, addr) else: self.queue.put(slskmessages.HaveNoParent(1)) def GlobalRecommendations(self, msg): self.frame.GlobalRecommendations(msg) def Recommendations(self, msg): self.frame.Recommendations(msg) def ItemRecommendations(self, msg): self.frame.ItemRecommendations(msg) def SimilarUsers(self, msg): self.frame.SimilarUsers(msg) def ItemSimilarUsers(self, msg): self.frame.ItemSimilarUsers(msg) def RoomTickerState(self, msg): if msg.room in self.config.sections["server"]["roomencoding"]: encodings = [self.config.sections["server"]["roomencoding"][msg.room]] + self.config.sections["server"]["fallbackencodings"] encodings.append(self.config.sections["server"]["enc"]) else: encodings = [self.config.sections["server"]["enc"]] + self.config.sections["server"]["fallbackencodings"] unicodes = {} for user, bytes in msg.msgs.iteritems(): unicodes[user] = findBestEncoding(bytes, encodings) msg.msgs = unicodes if self.chatrooms is not None: self.chatrooms.roomsctrl.TickerSet(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def RoomTickerAdd(self, msg): if msg.room in self.config.sections["server"]["roomencoding"]: encodings = [self.config.sections["server"]["roomencoding"][msg.room]] + self.config.sections["server"]["fallbackencodings"] encodings.append(self.config.sections["server"]["enc"]) else: encodings = [self.config.sections["server"]["enc"]] + self.config.sections["server"]["fallbackencodings"] msg.msg = findBestEncoding(msg.msg, encodings) if self.chatrooms is not None: self.chatrooms.roomsctrl.TickerAdd(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def RoomTickerRemove(self, msg): if self.chatrooms is not None: self.chatrooms.roomsctrl.TickerRemove(msg) self.logMessage("%s %s" % (msg.__class__, vars(msg)), 4) def logTransfer(self, message, toUI=0): if self.config.sections["logging"]["transfers"]: fn = os.path.join(self.config.sections["logging"]["logsdir"], "transfers.log") try: f = open(fn, "a") f.write(time.strftime("%c")) f.write(" %s\n" % message) f.close() except IOError, error: self.logMessage(_("Couldn't write to transfer log: %s") % error) if toUI: self.logMessage(message) class UserAddr: def __init__(self, addr=None, behindfw=None, status=None): self.addr = addr self.behindfw = behindfw self.status = status
gpl-3.0
cliftonmcintosh/openstates
openstates/md/committees.py
2
6091
import lxml.html from billy.scrape.committees import CommitteeScraper, Committee def clean_name(com_name): if com_name.startswith("Joint "): com_name = com_name.replace("Joint ", "", 1) com_name = com_name.replace("Special Committee on ", "") com_name = com_name.replace("Committee on ", "") if com_name.endswith("Committee"): com_name = com_name.replace(" Committee", "") com_name = com_name.strip() if com_name.startswith('the'): com_name = com_name.replace('the', 'The') return com_name def define_role(name): if name.endswith(' (House Chair)'): name = name.replace(' (House Chair)', '') role = 'house chair' elif name.endswith(' (Senate Chair)'): name = name.replace(' (Senate Chair)', '') role = 'senate chair' elif name.endswith(' (Chair)'): name = name.replace(' (Chair)', '') role = 'chair' elif name.endswith(' (Senate Vice Chair)'): name = name.replace(' (Senate Vice Chair)', '') role = 'vice chair' elif name.endswith(' (Senate Co-Chair)'): name = name.replace(' (Senate Co-Chair)', '') role = 'co-chair' elif name.endswith(' (House Vice Chair)'): name = name.replace(' (House Vice Chair)', '') role = 'vice chair' elif name.endswith(' (House Co-Chair)'): name = name.replace(' (House Co-Chair)', '') role = 'co-chair' elif name.startswith('House Chair:'): name = name.replace('House Chair:', '') role = 'house chair' elif name.startswith('Senate Chair:'): name = name.replace('Senate Chair:', '') role = 'senate chair' elif name.endswith(' (Vice Chair)'): name = name.replace(' (Vice Chair)', '') role = 'vice chair' elif name.endswith(' (Co-Chair)'): name = name.replace(' (Co-Chair)', '') role = 'co-chair' else: role = 'member' if name.startswith("Delegate "): name = name.replace("Delegate", "", 1).strip() if name.startswith("Senator "): name = name.replace("Senator", "", 1).strip() return (name, role) class MDCommitteeScraper(CommitteeScraper): jurisdiction = 'md' def scrape(self, term, chamber): # committee list url = 'http://mgaleg.maryland.gov/webmga/frmcommittees.aspx?pid=commpage&tab=subject7' html = self.get(url).text doc = lxml.html.fromstring(html) doc.make_links_absolute(url) for a in doc.xpath('//a[contains(@href, "cmtepage")]'): url = a.get('href') chamber_name = a.xpath('../../..//th/text()')[0] if chamber_name == 'Senate Standing': url = url.replace('stab=01', 'stab=04') if chamber_name == 'House Standing': url = url.replace('stab=01', 'stab=04') com_name = a.text if com_name is None: continue com_name = clean_name(com_name) if 'Senate' in chamber_name: chamber = 'upper' elif 'House' in chamber_name: chamber = 'lower' elif 'Joint' in chamber_name: chamber = 'joint' elif 'Statutory' in chamber_name: chamber = 'joint' elif 'Special Joint' in chamber_name: chamber = 'joint' elif 'Other' in chamber_name: chamber = 'joint' else: self.logger.warning("No committee chamber available for committee '%s'" % com_name) continue self.scrape_committee(chamber, com_name, url) for a in doc.xpath('//a[contains(@href, "AELR")]'): url = a.get('href') chamber_name = a.xpath('../../..//th/text()')[0] chamber = 'joint' com_name = a.text if com_name is None: continue com_name = clean_name(com_name) self.scrape_committee(chamber, com_name, url) def scrape_committee(self, chamber, com_name, url): html = self.get(url).text doc = lxml.html.fromstring(html) doc.make_links_absolute(url) com = Committee(chamber, com_name) com.add_source(url) if 'stab=04' in url: for table in doc.xpath('//table[@class="grid"]'): rows = table.xpath('tr') sub_name = rows[0].getchildren()[0].text.strip() # new table - subcommittee if sub_name != 'Full Committee': sub_name = sub_name.replace("Subcommittee", "").strip() com = Committee(chamber, com_name, subcommittee=sub_name) com.add_source(url) for row in rows[1:]: name = row.getchildren()[0].text_content().strip() name, role = define_role(name) com.add_member(name, role) self.save_committee(com) else: table_source = doc.xpath('//table[@class="noncogrid"]') if table_source != []: for table in table_source: row = table.xpath('tr/td/a[contains(@href, "sponpage")]/text()') sub_name_source = table.xpath('tr/th/text()') if "Subcommittee" in sub_name_source[0]: sub_name = sub_name_source[0] sub_name = sub_name.replace("Subcommittee", "").strip() com = Committee(chamber, com_name, subcommittee=sub_name) com.add_source(url) for name in row: name, role = define_role(name) com.add_member(name, role) self.save_committee(com) else: row = doc.xpath('//table[@class="spco"]/tr[1]/td/text()') for name in row: name, role = define_role(name) com.add_member(name, role) self.save_committee(com)
gpl-3.0
yashodhank/erpnext
erpnext/stock/report/itemwise_recommended_reorder_level/itemwise_recommended_reorder_level.py
37
3345
# 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 import _ from frappe.utils import getdate, flt def execute(filters=None): if not filters: filters = {} float_preceision = frappe.db.get_default("float_preceision") condition =get_condition(filters) avg_daily_outgoing = 0 diff = ((getdate(filters.get("to_date")) - getdate(filters.get("from_date"))).days)+1 if diff <= 0: frappe.throw(_("'From Date' must be after 'To Date'")) columns = get_columns() items = get_item_info() consumed_item_map = get_consumed_items(condition) delivered_item_map = get_delivered_items(condition) data = [] for item in items: total_outgoing = consumed_item_map.get(item.name, 0)+delivered_item_map.get(item.name,0) avg_daily_outgoing = flt(total_outgoing/diff, float_preceision) reorder_level = (avg_daily_outgoing * flt(item.lead_time_days)) + flt(item.safety_stock) data.append([item.name, item.item_name, item.description, item.safety_stock, item.lead_time_days, consumed_item_map.get(item.name, 0), delivered_item_map.get(item.name,0), total_outgoing, avg_daily_outgoing, reorder_level]) return columns , data def get_columns(): return[ _("Item") + ":Link/Item:120", _("Item Name") + ":Data:120", _("Description") + "::160", _("Safety Stock") + ":Float:160", _("Lead Time Days") + ":Float:120", _("Consumed") + ":Float:120", _("Delivered") + ":Float:120", _("Total Outgoing") + ":Float:120", _("Avg Daily Outgoing") + ":Float:160", _("Reorder Level") + ":Float:120" ] def get_item_info(): return frappe.db.sql("""select name, item_name, description, safety_stock, lead_time_days from tabItem""", as_dict=1) def get_consumed_items(condition): cn_items = frappe.db.sql("""select se_item.item_code, sum(se_item.actual_qty) as 'consume_qty' from `tabStock Entry` se, `tabStock Entry Detail` se_item where se.name = se_item.parent and se.docstatus = 1 and ifnull(se_item.t_warehouse, '') = '' %s group by se_item.item_code""" % (condition), as_dict=1) cn_items_map = {} for item in cn_items: cn_items_map.setdefault(item.item_code, item.consume_qty) return cn_items_map def get_delivered_items(condition): dn_items = frappe.db.sql("""select dn_item.item_code, sum(dn_item.qty) as dn_qty from `tabDelivery Note` dn, `tabDelivery Note Item` dn_item where dn.name = dn_item.parent and dn.docstatus = 1 %s group by dn_item.item_code""" % (condition), as_dict=1) si_items = frappe.db.sql("""select si_item.item_name, sum(si_item.qty) as si_qty from `tabSales Invoice` si, `tabSales Invoice Item` si_item where si.name = si_item.parent and si.docstatus = 1 and si.update_stock = 1 and si.is_pos = 1 %s group by si_item.item_name""" % (condition), as_dict=1) dn_item_map = {} for item in dn_items: dn_item_map.setdefault(item.item_code, item.dn_qty) for item in si_items: dn_item_map.setdefault(item.item_code, item.si_qty) return dn_item_map def get_condition(filters): conditions = "" if filters.get("from_date") and filters.get("to_date"): conditions += " and posting_date between '%s' and '%s'" % (filters["from_date"],filters["to_date"]) else: frappe.throw(_("From and To dates required")) return conditions
agpl-3.0
rameshg87/pyremotevbox
pyremotevbox/ZSI/twisted/WSsecurity.py
1
13760
########################################################################### # Joshua R. Boverhof, LBNL # See Copyright for copyright notice! # $Id: WSsecurity.py 1134 2006-02-24 00:23:06Z boverhof $ ########################################################################### import sys, time, warnings import sha, base64 # twisted & related imports from zope.interface import classProvides, implements, Interface from twisted.python import log, failure from twisted.web.error import NoResource from twisted.web.server import NOT_DONE_YET from twisted.internet import reactor import twisted.web.http import twisted.web.resource # ZSI imports from pyremotevbox.ZSI import _get_element_nsuri_name, EvaluateException, ParseException from pyremotevbox.ZSI.parse import ParsedSoap from pyremotevbox.ZSI.writer import SoapWriter from pyremotevbox.ZSI.TC import _get_global_element_declaration as GED from pyremotevbox.ZSI import fault from pyremotevbox.ZSI.wstools.Namespaces import OASIS, DSIG from WSresource import DefaultHandlerChain, HandlerChainInterface,\ WSAddressCallbackHandler, DataHandler, WSAddressHandler # # Global Element Declarations # UsernameTokenDec = GED(OASIS.WSSE, "UsernameToken") SecurityDec = GED(OASIS.WSSE, "Security") SignatureDec = GED(DSIG.BASE, "Signature") PasswordDec = GED(OASIS.WSSE, "Password") NonceDec = GED(OASIS.WSSE, "Nonce") CreatedDec = GED(OASIS.UTILITY, "Created") if None in [UsernameTokenDec,SecurityDec,SignatureDec,PasswordDec,NonceDec,CreatedDec]: raise ImportError, 'required global element(s) unavailable: %s ' %({ (OASIS.WSSE, "UsernameToken"):UsernameTokenDec, (OASIS.WSSE, "Security"):SecurityDec, (DSIG.BASE, "Signature"):SignatureDec, (OASIS.WSSE, "Password"):PasswordDec, (OASIS.WSSE, "Nonce"):NonceDec, (OASIS.UTILITY, "Created"):CreatedDec, }) # # Stability: Unstable, Untested, Not Finished. # class WSSecurityHandler: """Web Services Security: SOAP Message Security 1.0 Class Variables: debug -- If True provide more detailed SOAP:Fault information to clients. """ classProvides(HandlerChainInterface) debug = True @classmethod def processRequest(cls, ps, **kw): if type(ps) is not ParsedSoap: raise TypeError,'Expecting ParsedSoap instance' security = ps.ParseHeaderElements([cls.securityDec]) # Assume all security headers are supposed to be processed here. for pyobj in security or []: for any in pyobj.Any or []: if any.typecode is UsernameTokenDec: try: ps = cls.UsernameTokenProfileHandler.processRequest(ps, any) except Exception, ex: if cls.debug: raise raise RuntimeError, 'Unauthorized Username/passphrase combination' continue if any.typecode is SignatureDec: try: ps = cls.SignatureHandler.processRequest(ps, any) except Exception, ex: if cls.debug: raise raise RuntimeError, 'Invalid Security Header' continue raise RuntimeError, 'WS-Security, Unsupported token %s' %str(any) return ps @classmethod def processResponse(cls, output, **kw): return output class UsernameTokenProfileHandler: """Web Services Security UsernameToken Profile 1.0 Class Variables: targetNamespace -- """ classProvides(HandlerChainInterface) # Class Variables targetNamespace = OASIS.WSSE sweepInterval = 60*5 nonces = None # Set to None to disable PasswordText = targetNamespace + "#PasswordText" PasswordDigest = targetNamespace + "#PasswordDigest" # Override passwordCallback passwordCallback = lambda cls,username: None @classmethod def sweep(cls, index): """remove nonces every sweepInterval. Parameters: index -- remove all nonces up to this index. """ if cls.nonces is None: cls.nonces = [] seconds = cls.sweepInterval cls.nonces = cls.nonces[index:] reactor.callLater(seconds, cls.sweep, len(cls.nonces)) @classmethod def processRequest(cls, ps, token, **kw): """ Parameters: ps -- ParsedSoap instance token -- UsernameToken pyclass instance """ if token.typecode is not UsernameTokenDec: raise TypeError, 'expecting GED (%s,%s) representation.' %( UsernameTokenDec.nspname, UsernameTokenDec.pname) username = token.Username # expecting only one password # may have a nonce and a created password = nonce = timestamp = None for any in token.Any or []: if any.typecode is PasswordDec: password = any continue if any.typecode is NonceTypeDec: nonce = any continue if any.typecode is CreatedTypeDec: timestamp = any continue raise TypeError, 'UsernameTokenProfileHander unexpected %s' %str(any) if password is None: raise RuntimeError, 'Unauthorized, no password' # TODO: not yet supporting complexType simpleContent in pyclass_type attrs = getattr(password, password.typecode.attrs_aname, {}) pwtype = attrs.get('Type', cls.PasswordText) # Clear Text Passwords if cls.PasswordText is not None and pwtype == cls.PasswordText: if password == cls.passwordCallback(username): return ps raise RuntimeError, 'Unauthorized, clear text password failed' if cls.nonces is None: cls.sweep(0) if nonce is not None: if nonce in cls.nonces: raise RuntimeError, 'Invalid Nonce' # created was 10 seconds ago or sooner if created is not None and created < time.gmtime(time.time()-10): raise RuntimeError, 'UsernameToken created is expired' cls.nonces.append(nonce) # PasswordDigest, recommended that implemenations # require a Nonce and Created if cls.PasswordDigest is not None and pwtype == cls.PasswordDigest: digest = sha.sha() for i in (nonce, created, cls.passwordCallback(username)): if i is None: continue digest.update(i) if password == base64.encodestring(digest.digest()).strip(): return ps raise RuntimeError, 'Unauthorized, digest failed' raise RuntimeError, 'Unauthorized, contents of UsernameToken unknown' @classmethod def processResponse(cls, output, **kw): return output @staticmethod def hmac_sha1(xml): return class SignatureHandler: """Web Services Security UsernameToken Profile 1.0 """ digestMethods = { DSIG.BASE+"#sha1":sha.sha, } signingMethods = { DSIG.BASE+"#hmac-sha1":hmac_sha1, } canonicalizationMethods = { DSIG.C14N_EXCL:lambda node: Canonicalize(node, unsuppressedPrefixes=[]), DSIG.C14N:lambda node: Canonicalize(node), } @classmethod def processRequest(cls, ps, signature, **kw): """ Parameters: ps -- ParsedSoap instance signature -- Signature pyclass instance """ if token.typecode is not SignatureDec: raise TypeError, 'expecting GED (%s,%s) representation.' %( SignatureDec.nspname, SignatureDec.pname) si = signature.SignedInfo si.CanonicalizationMethod calgo = si.CanonicalizationMethod.get_attribute_Algorithm() for any in si.CanonicalizationMethod.Any: pass # Check Digest si.Reference context = XPath.Context.Context(ps.dom, processContents={'wsu':OASIS.UTILITY}) exp = XPath.Compile('//*[@wsu:Id="%s"]' %si.Reference.get_attribute_URI()) nodes = exp.evaluate(context) if len(nodes) != 1: raise RuntimeError, 'A SignedInfo Reference must refer to one node %s.' %( si.Reference.get_attribute_URI()) try: xml = cls.canonicalizeMethods[calgo](nodes[0]) except IndexError: raise RuntimeError, 'Unsupported canonicalization algorithm' try: digest = cls.digestMethods[salgo] except IndexError: raise RuntimeError, 'unknown digestMethods Algorithm' digestValue = base64.encodestring(digest(xml).digest()).strip() if si.Reference.DigestValue != digestValue: raise RuntimeError, 'digest does not match' if si.Reference.Transforms: pass signature.KeyInfo signature.KeyInfo.KeyName signature.KeyInfo.KeyValue signature.KeyInfo.RetrievalMethod signature.KeyInfo.X509Data signature.KeyInfo.PGPData signature.KeyInfo.SPKIData signature.KeyInfo.MgmtData signature.KeyInfo.Any signature.Object # TODO: Check Signature signature.SignatureValue si.SignatureMethod salgo = si.SignatureMethod.get_attribute_Algorithm() if si.SignatureMethod.HMACOutputLength: pass for any in si.SignatureMethod.Any: pass # <SignedInfo><Reference URI=""> exp = XPath.Compile('//child::*[attribute::URI = "%s"]/..' %( si.Reference.get_attribute_URI())) nodes = exp.evaluate(context) if len(nodes) != 1: raise RuntimeError, 'A SignedInfo Reference must refer to one node %s.' %( si.Reference.get_attribute_URI()) try: xml = cls.canonicalizeMethods[calgo](nodes[0]) except IndexError: raise RuntimeError, 'Unsupported canonicalization algorithm' # TODO: Check SignatureValue @classmethod def processResponse(cls, output, **kw): return output class X509TokenProfileHandler: """Web Services Security UsernameToken Profile 1.0 """ targetNamespace = DSIG.BASE # Token Types singleCertificate = targetNamespace + "#X509v3" certificatePath = targetNamespace + "#X509PKIPathv1" setCerticatesCRLs = targetNamespace + "#PKCS7" @classmethod def processRequest(cls, ps, signature, **kw): return ps """ <element name="KeyInfo" type="ds:KeyInfoType"/> <complexType name="KeyInfoType" mixed="true"> <choice maxOccurs="unbounded"> <element ref="ds:KeyName"/> <element ref="ds:KeyValue"/> <element ref="ds:RetrievalMethod"/> <element ref="ds:X509Data"/> <element ref="ds:PGPData"/> <element ref="ds:SPKIData"/> <element ref="ds:MgmtData"/> <any processContents="lax" namespace="##other"/> <!-- (1,1) elements from (0,unbounded) namespaces --> </choice> <attribute name="Id" type="ID" use="optional"/> </complexType> <element name="Signature" type="ds:SignatureType"/> <complexType name="SignatureType"> <sequence> <element ref="ds:SignedInfo"/> <element ref="ds:SignatureValue"/> <element ref="ds:KeyInfo" minOccurs="0"/> <element ref="ds:Object" minOccurs="0" maxOccurs="unbounded"/> </sequence> <attribute name="Id" type="ID" use="optional"/> </complexType> <element name="SignatureValue" type="ds:SignatureValueType"/> <complexType name="SignatureValueType"> <simpleContent> <extension base="base64Binary"> <attribute name="Id" type="ID" use="optional"/> </extension> </simpleContent> </complexType> <!-- Start SignedInfo --> <element name="SignedInfo" type="ds:SignedInfoType"/> <complexType name="SignedInfoType"> <sequence> <element ref="ds:CanonicalizationMethod"/> <element ref="ds:SignatureMethod"/> <element ref="ds:Reference" maxOccurs="unbounded"/> </sequence> <attribute name="Id" type="ID" use="optional"/> </complexType> """ class WSSecurityHandlerChainFactory: protocol = DefaultHandlerChain @classmethod def newInstance(cls): return cls.protocol(WSAddressCallbackHandler, DataHandler, WSSecurityHandler, WSAddressHandler())
apache-2.0
o5k/openerp-oemedical-v0.1
openerp/addons/smsclient/smsclient.py
1
17026
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). # Copyright (C) 2011 SYLEAM (<http://syleam.fr/>) # Copyright (C) 2013 Julius Network Solutions SARL <contact@julius.fr> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time import urllib from openerp.osv import fields, orm from openerp.tools.translate import _ import logging _logger = logging.getLogger(__name__) try: from SOAPpy import WSDL except : _logger.warning("ERROR IMPORTING SOAPpy, if not installed, please install it:" " e.g.: apt-get install python-soappy") class partner_sms_send(orm.Model): _name = "partner.sms.send" def _default_get_mobile(self, cr, uid, fields, context=None): if context is None: context = {} partner_pool = self.pool.get('res.partner') active_ids = fields.get('active_ids') res = {} i = 0 for partner in partner_pool.browse(cr, uid, active_ids, context=context): i += 1 res = partner.mobile if i > 1: raise orm.except_orm(_('Error'), _('You can only select one partner')) return res def _default_get_gateway(self, cr, uid, fields, context=None): if context is None: context = {} sms_obj = self.pool.get('sms.smsclient') gateway_ids = sms_obj.search(cr, uid, [], limit=1, context=context) return gateway_ids and gateway_ids[0] or False def onchange_gateway(self, cr, uid, ids, gateway_id, context=None): if context is None: context = {} sms_obj = self.pool.get('sms.smsclient') if not gateway_id: return {} gateway = sms_obj.browse(cr, uid, gateway_id, context=context) return { 'value': { 'validity': gateway.validity, 'classes': gateway.classes, 'deferred': gateway.deferred, 'priority': gateway.priority, 'coding': gateway.coding, 'tag': gateway.tag, 'nostop': gateway.nostop, } } _columns = { 'mobile_to': fields.char('To', size=256, required=True), 'app_id': fields.char('API ID', size=256), 'user': fields.char('Login', size=256), 'password': fields.char('Password', size=256), 'text': fields.text('SMS Message', required=True), 'gateway': fields.many2one('sms.smsclient', 'SMS Gateway', required=True), 'validity': fields.integer('Validity', help='the maximum time -in minute(s)- before the message is dropped'), 'classes': fields.selection([ ('0', 'Flash'), ('1', 'Phone display'), ('2', 'SIM'), ('3', 'Toolkit') ], 'Class', help='the sms class: flash(0), phone display(1), SIM(2), toolkit(3)'), 'deferred': fields.integer('Deferred', help='the time -in minute(s)- to wait before sending the message'), 'priority': fields.selection([ ('0','0'), ('1','1'), ('2','2'), ('3','3') ], 'Priority', help='The priority of the message'), 'coding': fields.selection([ ('1', '7 bit'), ('2', 'Unicode') ], 'Coding', help='The SMS coding: 1 for 7 bit or 2 for unicode'), 'tag': fields.char('Tag', size=256, help='an optional tag'), 'nostop': fields.boolean('NoStop', help='Do not display STOP clause in the message, this requires that this is not an advertising message'), } _defaults = { 'mobile_to': _default_get_mobile, 'gateway': _default_get_gateway, } def sms_send(self, cr, uid, ids, context=None): if context is None: context = {} client_obj = self.pool.get('sms.smsclient') for data in self.browse(cr, uid, ids, context=context): if not data.gateway: raise orm.except_orm(_('Error'), _('No Gateway Found')) else: client_obj._send_message(cr, uid, data, context=context) return {} class SMSClient(orm.Model): _name = 'sms.smsclient' _description = 'SMS Client' _columns = { 'name': fields.char('Gateway Name', size=256, required=True), 'url': fields.char('Gateway URL', size=256, required=True, help='Base url for message'), 'property_ids': fields.one2many('sms.smsclient.parms', 'gateway_id', 'Parameters'), 'history_line': fields.one2many('sms.smsclient.history', 'gateway_id', 'History'), 'method': fields.selection([ ('http', 'HTTP Method'), ('smpp', 'SMPP Method') ], 'API Method', select=True), 'state': fields.selection([ ('new', 'Not Verified'), ('waiting', 'Waiting for Verification'), ('confirm', 'Verified'), ], 'Gateway Status', select=True, readonly=True), 'users_id': fields.many2many('res.users', 'res_smsserver_group_rel', 'sid', 'uid', 'Users Allowed'), 'code': fields.char('Verification Code', size=256), 'body': fields.text('Message', help="The message text that will be send along with the email which is send through this server"), 'validity': fields.integer('Validity', help='The maximum time -in minute(s)- before the message is dropped'), 'classes': fields.selection([ ('0', 'Flash'), ('1', 'Phone display'), ('2', 'SIM'), ('3', 'Toolkit') ], 'Class', help='The SMS class: flash(0),phone display(1),SIM(2),toolkit(3)'), 'deferred': fields.integer('Deferred', help='The time -in minute(s)- to wait before sending the message'), 'priority': fields.selection([ ('0', '0'), ('1', '1'), ('2', '2'), ('3', '3') ], 'Priority', help='The priority of the message '), 'coding': fields.selection([ ('1', '7 bit'), ('2', 'Unicode') ],'Coding', help='The SMS coding: 1 for 7 bit or 2 for unicode'), 'tag': fields.char('Tag', size=256, help='an optional tag'), 'nostop': fields.boolean('NoStop', help='Do not display STOP clause in the message, this requires that this is not an advertising message'), 'char_limit' : fields.boolean('Character Limit'), } _defaults = { 'state': 'new', 'method': 'http', 'validity': 10, 'classes': '1', 'deferred': 0, 'priority': '3', 'coding': '1', 'nostop': True, 'char_limit' : True, } def _check_permissions(self, cr, uid, id, context=None): cr.execute('select * from res_smsserver_group_rel where sid=%s and uid=%s' % (id, uid)) data = cr.fetchall() if len(data) <= 0: return False return True def _prepare_smsclient_queue(self, cr, uid, data, name, context=None): return { 'name': name, 'gateway_id': data.gateway.id, 'state': 'draft', 'mobile': data.mobile_to, 'msg': data.text, 'validity': data.validity, 'classes': data.classes, 'deffered': data.deferred, 'priorirty': data.priority, 'coding': data.coding, 'tag': data.tag, 'nostop': data.nostop, } def _send_message(self, cr, uid, data, context=None): if context is None: context = {} gateway = data.gateway if gateway: if not self._check_permissions(cr, uid, gateway.id, context=context): raise orm.except_orm(_('Permission Error!'), _('You have no permission to access %s ') % (gateway.name,)) url = gateway.url name = url if gateway.method == 'http': prms = {} for p in data.gateway.property_ids: if p.type == 'user': prms[p.name] = p.value elif p.type == 'password': prms[p.name] = p.value elif p.type == 'to': prms[p.name] = data.mobile_to elif p.type == 'sms': prms[p.name] = data.text elif p.type == 'extra': prms[p.name] = p.value params = urllib.urlencode(prms) name = url + "?" + params queue_obj = self.pool.get('sms.smsclient.queue') vals = self._prepare_smsclient_queue(cr, uid, data, name, context=context) queue_obj.create(cr, uid, vals, context=context) return True def _check_queue(self, cr, uid, context=None): if context is None: context = {} queue_obj = self.pool.get('sms.smsclient.queue') history_obj = self.pool.get('sms.smsclient.history') sids = queue_obj.search(cr, uid, [ ('state', '!=', 'send'), ('state', '!=', 'sending') ], limit=30, context=context) queue_obj.write(cr, uid, sids, {'state': 'sending'}, context=context) error_ids = [] sent_ids = [] for sms in queue_obj.browse(cr, uid, sids, context=context): if sms.gateway_id.char_limit: if len(sms.msg) > 160: error_ids.append(sms.id) continue if sms.gateway_id.method == 'http': try: urllib.urlopen(sms.name) except Exception as e: raise orm.except_orm('Error', e) ### New Send Process OVH Dedicated ### ## Parameter Fetch ## if sms.gateway_id.method == 'smpp': for p in sms.gateway_id.property_ids: if p.type == 'user': login = p.value elif p.type == 'password': pwd = p.value elif p.type == 'sender': sender = p.value elif p.type == 'sms': account = p.value try: soap = WSDL.Proxy(sms.gateway_id.url) message = '' if sms.coding == '2': message = str(sms.msg).decode('iso-8859-1').encode('utf8') if sms.coding == '1': message = str(sms.msg) result = soap.telephonySmsUserSend(str(login), str(pwd), str(account), str(sender), str(sms.mobile), message, int(sms.validity), int(sms.classes), int(sms.deferred), int(sms.priority), int(sms.coding),str(sms.gateway_id.tag), int(sms.gateway_id.nostop)) ### End of the new process ### except Exception as e: raise orm.except_orm('Error', e) history_obj.create(cr, uid, { 'name': _('SMS Sent'), 'gateway_id': sms.gateway_id.id, 'sms': sms.msg, 'to': sms.mobile, }, context=context) sent_ids.append(sms.id) queue_obj.write(cr, uid, sent_ids, {'state': 'send'}, context=context) queue_obj.write(cr, uid, error_ids, { 'state': 'error', 'error': 'Size of SMS should not be more then 160 char' }, context=context) return True class SMSQueue(orm.Model): _name = 'sms.smsclient.queue' _description = 'SMS Queue' _columns = { 'name': fields.text('SMS Request', size=256, required=True, readonly=True, states={'draft': [('readonly', False)]}), 'msg': fields.text('SMS Text', size=256, required=True, readonly=True, states={'draft': [('readonly', False)]}), 'mobile': fields.char('Mobile No', size=256, required=True, readonly=True, states={'draft': [('readonly', False)]}), 'gateway_id': fields.many2one('sms.smsclient', 'SMS Gateway', readonly=True, states={'draft': [('readonly', False)]}), 'state': fields.selection([ ('draft', 'Queued'), ('sending', 'Waiting'), ('send', 'Sent'), ('error', 'Error'), ], 'Message Status', select=True, readonly=True), 'error': fields.text('Last Error', size=256, readonly=True, states={'draft': [('readonly', False)]}), 'date_create': fields.datetime('Date', readonly=True), 'validity': fields.integer('Validity', help='The maximum time -in minute(s)- before the message is dropped'), 'classes': fields.selection([ ('0', 'Flash'), ('1', 'Phone display'), ('2', 'SIM'), ('3', 'Toolkit') ], 'Class', help='The sms class: flash(0), phone display(1), SIM(2), toolkit(3)'), 'deferred': fields.integer('Deferred', help='The time -in minute(s)- to wait before sending the message'), 'priority': fields.selection([ ('0', '0'), ('1', '1'), ('2', '2'), ('3', '3') ], 'Priority', help='The priority of the message '), 'coding': fields.selection([ ('1', '7 bit'), ('2', 'Unicode') ], 'Coding', help='The sms coding: 1 for 7 bit or 2 for unicode'), 'tag': fields.char('Tag', size=256, help='An optional tag'), 'nostop': fields.boolean('NoStop', help='Do not display STOP clause in the message, this requires that this is not an advertising message'), } _defaults = { 'date_create': fields.datetime.now, 'state': 'draft', } class Properties(orm.Model): _name = 'sms.smsclient.parms' _description = 'SMS Client Properties' _columns = { 'name': fields.char('Property name', size=256, help='Name of the property whom appear on the URL'), 'value': fields.char('Property value', size=256, help='Value associate on the property for the URL'), 'gateway_id': fields.many2one('sms.smsclient', 'SMS Gateway'), 'type': fields.selection([ ('user', 'User'), ('password', 'Password'), ('sender', 'Sender Name'), ('to', 'Recipient No'), ('sms', 'SMS Message'), ('extra', 'Extra Info') ], 'API Method', select=True, help='If parameter concern a value to substitute, indicate it'), } class HistoryLine(orm.Model): _name = 'sms.smsclient.history' _description = 'SMS Client History' _columns = { 'name': fields.char('Description', size=160, required=True, readonly=True), 'date_create': fields.datetime('Date', readonly=True), 'user_id': fields.many2one('res.users', 'Username', readonly=True, select=True), 'gateway_id': fields.many2one('sms.smsclient', 'SMS Gateway', ondelete='set null', required=True), 'to': fields.char('Mobile No', size=15, readonly=True), 'sms': fields.text('SMS', size=160, readonly=True), } _defaults = { 'date_create': fields.datetime.now, 'user_id': lambda obj, cr, uid, context: uid, } def create(self, cr, uid, vals, context=None): if context is None: context = {} super(HistoryLine, self).create(cr, uid, vals, context=context) cr.commit() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
mrquim/repository.mrquim
plugin.program.indigo/libs/requests/packages/urllib3/util/retry.py
86
14123
from __future__ import absolute_import import time import logging from collections import namedtuple from itertools import takewhile import email import re from ..exceptions import ( ConnectTimeoutError, MaxRetryError, ProtocolError, ReadTimeoutError, ResponseError, InvalidHeader, ) from ..packages import six log = logging.getLogger(__name__) # Data structure for representing the metadata of requests that result in a retry. RequestHistory = namedtuple('RequestHistory', ["method", "url", "error", "status", "redirect_location"]) class Retry(object): """ Retry configuration. Each retry attempt will create a new Retry object with updated values, so they can be safely reused. Retries can be defined as a default for a pool:: retries = Retry(connect=5, read=2, redirect=5) http = PoolManager(retries=retries) response = http.request('GET', 'http://example.com/') Or per-request (which overrides the default for the pool):: response = http.request('GET', 'http://example.com/', retries=Retry(10)) Retries can be disabled by passing ``False``:: response = http.request('GET', 'http://example.com/', retries=False) Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless retries are disabled, in which case the causing exception will be raised. :param int total: Total number of retries to allow. Takes precedence over other counts. Set to ``None`` to remove this constraint and fall back on other counts. It's a good idea to set this to some sensibly-high value to account for unexpected edge cases and avoid infinite retry loops. Set to ``0`` to fail on the first retry. Set to ``False`` to disable and imply ``raise_on_redirect=False``. :param int connect: How many connection-related errors to retry on. These are errors raised before the request is sent to the remote server, which we assume has not triggered the server to process the request. Set to ``0`` to fail on the first retry of this type. :param int read: How many times to retry on read errors. These errors are raised after the request was sent to the server, so the request may have side-effects. Set to ``0`` to fail on the first retry of this type. :param int redirect: How many redirects to perform. Limit this to avoid infinite redirect loops. A redirect is a HTTP response with a status code 301, 302, 303, 307 or 308. Set to ``0`` to fail on the first retry of this type. Set to ``False`` to disable and imply ``raise_on_redirect=False``. :param iterable method_whitelist: Set of uppercased HTTP method verbs that we should retry on. By default, we only retry on methods which are considered to be idempotent (multiple requests with the same parameters end with the same state). See :attr:`Retry.DEFAULT_METHOD_WHITELIST`. Set to a ``False`` value to retry on any verb. :param iterable status_forcelist: A set of integer HTTP status codes that we should force a retry on. A retry is initiated if the request method is in ``method_whitelist`` and the response status code is in ``status_forcelist``. By default, this is disabled with ``None``. :param float backoff_factor: A backoff factor to apply between attempts after the second try (most errors are resolved immediately by a second try without a delay). urllib3 will sleep for:: {backoff factor} * (2 ^ ({number of total retries} - 1)) seconds. If the backoff_factor is 0.1, then :func:`.sleep` will sleep for [0.0s, 0.2s, 0.4s, ...] between retries. It will never be longer than :attr:`Retry.BACKOFF_MAX`. By default, backoff is disabled (set to 0). :param bool raise_on_redirect: Whether, if the number of redirects is exhausted, to raise a MaxRetryError, or to return a response with a response code in the 3xx range. :param bool raise_on_status: Similar meaning to ``raise_on_redirect``: whether we should raise an exception, or return a response, if status falls in ``status_forcelist`` range and retries have been exhausted. :param tuple history: The history of the request encountered during each call to :meth:`~Retry.increment`. The list is in the order the requests occurred. Each list item is of class :class:`RequestHistory`. :param bool respect_retry_after_header: Whether to respect Retry-After header on status codes defined as :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not. """ DEFAULT_METHOD_WHITELIST = frozenset([ 'HEAD', 'GET', 'PUT', 'DELETE', 'OPTIONS', 'TRACE']) RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503]) #: Maximum backoff time. BACKOFF_MAX = 120 def __init__(self, total=10, connect=None, read=None, redirect=None, method_whitelist=DEFAULT_METHOD_WHITELIST, status_forcelist=None, backoff_factor=0, raise_on_redirect=True, raise_on_status=True, history=None, respect_retry_after_header=True): self.total = total self.connect = connect self.read = read if redirect is False or total is False: redirect = 0 raise_on_redirect = False self.redirect = redirect self.status_forcelist = status_forcelist or set() self.method_whitelist = method_whitelist self.backoff_factor = backoff_factor self.raise_on_redirect = raise_on_redirect self.raise_on_status = raise_on_status self.history = history or tuple() self.respect_retry_after_header = respect_retry_after_header def new(self, **kw): params = dict( total=self.total, connect=self.connect, read=self.read, redirect=self.redirect, method_whitelist=self.method_whitelist, status_forcelist=self.status_forcelist, backoff_factor=self.backoff_factor, raise_on_redirect=self.raise_on_redirect, raise_on_status=self.raise_on_status, history=self.history, ) params.update(kw) return type(self)(**params) @classmethod def from_int(cls, retries, redirect=True, default=None): """ Backwards-compatibility for the old retries format.""" if retries is None: retries = default if default is not None else cls.DEFAULT if isinstance(retries, Retry): return retries redirect = bool(redirect) and None new_retries = cls(retries, redirect=redirect) log.debug("Converted retries value: %r -> %r", retries, new_retries) return new_retries def get_backoff_time(self): """ Formula for computing the current backoff :rtype: float """ # We want to consider only the last consecutive errors sequence (Ignore redirects). consecutive_errors_len = len(list(takewhile(lambda x: x.redirect_location is None, reversed(self.history)))) if consecutive_errors_len <= 1: return 0 backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1)) return min(self.BACKOFF_MAX, backoff_value) def parse_retry_after(self, retry_after): # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4 if re.match(r"^\s*[0-9]+\s*$", retry_after): seconds = int(retry_after) else: retry_date_tuple = email.utils.parsedate(retry_after) if retry_date_tuple is None: raise InvalidHeader("Invalid Retry-After header: %s" % retry_after) retry_date = time.mktime(retry_date_tuple) seconds = retry_date - time.time() if seconds < 0: seconds = 0 return seconds def get_retry_after(self, response): """ Get the value of Retry-After in seconds. """ retry_after = response.getheader("Retry-After") if retry_after is None: return None return self.parse_retry_after(retry_after) def sleep_for_retry(self, response=None): retry_after = self.get_retry_after(response) if retry_after: time.sleep(retry_after) return True return False def _sleep_backoff(self): backoff = self.get_backoff_time() if backoff <= 0: return time.sleep(backoff) def sleep(self, response=None): """ Sleep between retry attempts. This method will respect a server's ``Retry-After`` response header and sleep the duration of the time requested. If that is not present, it will use an exponential backoff. By default, the backoff factor is 0 and this method will return immediately. """ if response: slept = self.sleep_for_retry(response) if slept: return self._sleep_backoff() def _is_connection_error(self, err): """ Errors when we're fairly sure that the server did not receive the request, so it should be safe to retry. """ return isinstance(err, ConnectTimeoutError) def _is_read_error(self, err): """ Errors that occur after the request has been started, so we should assume that the server began processing it. """ return isinstance(err, (ReadTimeoutError, ProtocolError)) def _is_method_retryable(self, method): """ Checks if a given HTTP method should be retried upon, depending if it is included on the method whitelist. """ if self.method_whitelist and method.upper() not in self.method_whitelist: return False return True def is_retry(self, method, status_code, has_retry_after=False): """ Is this method/status code retryable? (Based on whitelists and control variables such as the number of total retries to allow, whether to respect the Retry-After header, whether this header is present, and whether the returned status code is on the list of status codes to be retried upon on the presence of the aforementioned header) """ if not self._is_method_retryable(method): return False if self.status_forcelist and status_code in self.status_forcelist: return True return (self.total and self.respect_retry_after_header and has_retry_after and (status_code in self.RETRY_AFTER_STATUS_CODES)) def is_exhausted(self): """ Are we out of retries? """ retry_counts = (self.total, self.connect, self.read, self.redirect) retry_counts = list(filter(None, retry_counts)) if not retry_counts: return False return min(retry_counts) < 0 def increment(self, method=None, url=None, response=None, error=None, _pool=None, _stacktrace=None): """ Return a new Retry object with incremented retry counters. :param response: A response object, or None, if the server did not return a response. :type response: :class:`~urllib3.response.HTTPResponse` :param Exception error: An error encountered during the request, or None if the response was received successfully. :return: A new ``Retry`` object. """ if self.total is False and error: # Disabled, indicate to re-raise the error. raise six.reraise(type(error), error, _stacktrace) total = self.total if total is not None: total -= 1 connect = self.connect read = self.read redirect = self.redirect cause = 'unknown' status = None redirect_location = None if error and self._is_connection_error(error): # Connect retry? if connect is False: raise six.reraise(type(error), error, _stacktrace) elif connect is not None: connect -= 1 elif error and self._is_read_error(error): # Read retry? if read is False or not self._is_method_retryable(method): raise six.reraise(type(error), error, _stacktrace) elif read is not None: read -= 1 elif response and response.get_redirect_location(): # Redirect retry? if redirect is not None: redirect -= 1 cause = 'too many redirects' redirect_location = response.get_redirect_location() status = response.status else: # Incrementing because of a server error like a 500 in # status_forcelist and a the given method is in the whitelist cause = ResponseError.GENERIC_ERROR if response and response.status: cause = ResponseError.SPECIFIC_ERROR.format( status_code=response.status) status = response.status history = self.history + (RequestHistory(method, url, error, status, redirect_location),) new_retry = self.new( total=total, connect=connect, read=read, redirect=redirect, history=history) if new_retry.is_exhausted(): raise MaxRetryError(_pool, url, error or ResponseError(cause)) log.debug("Incremented Retry for (url='%s'): %r", url, new_retry) return new_retry def __repr__(self): return ('{cls.__name__}(total={self.total}, connect={self.connect}, ' 'read={self.read}, redirect={self.redirect})').format( cls=type(self), self=self) # For backwards compatibility (equivalent to pre-v1.9): Retry.DEFAULT = Retry(3)
gpl-2.0
crtrott/lammps
tools/moltemplate/src/nbody_Dihedrals.py
19
2460
from nbody_graph_search import Ugraph # This file defines how dihedral interactions are generated by moltemplate.sh # by default. It can be overridden by supplying your own custom file. # To find 4-body "dihedral" interactions, we would use this subgraph: # # 1st bond connects atoms 0 and 1 # *---*---*---* => 2nd bond connects atoms 1 and 2 # 0 1 2 3 3rd bond connects atoms 2 and 3 # bond_pattern = Ugraph([(0,1), (1,2), (2,3)]) # (Ugraph atom indices begin at 0, not 1) def canonical_order(match): """ Before defining a new interaction, we must check to see if an interaction between these same 4 atoms has already been created (perhaps listed in a different, but equivalent order). If we don't check for this this, we will create many unnecessary redundant interactions (which can slow down he simulation). To avoid this, I define a "canonical_order" function which sorts the atoms and bonds in a way which is consistent with the symmetry of the interaction being generated... Later the re-ordered list of atom and bond ids will be tested against the list of atom/bond ids in the matches-found-so-far, before it is added to the list of interactions found so far. Note that the energy of a dihedral interaction is a function of the dihedral-angle. The dihedral-angle is usually defined as the angle between planes formed by atoms 0,1,2 & 1,2,3. This angle does not change when reversing the order of the atoms. So it does not make sense to define a separate dihedral interaction between atoms 0,1,2,3 AS WELL AS between 3,2,1,0. So we sort the atoms so that the first atom has a lower atomID than the last atom. (Later we will check to see if we have already defined an interaction between these 4 atoms. If not then we create a new one.) """ # match[0][0:3] contains the ID numbers of the 4 atoms in the match atom0 = match[0][0] atom1 = match[0][1] atom2 = match[0][2] atom3 = match[0][3] # match[1][0:2] contains the ID numbers of the the 3 bonds bond0 = match[1][0] bond1 = match[1][1] bond2 = match[1][2] if atom0 < atom3: #return ((atom0, atom1, atom2, atom3), (bond0, bond1, bond2)) same as: return match else: return ((atom3, atom2, atom1, atom0), (bond2, bond1, bond0))
gpl-2.0
40223214/-2015cd_midterm2
static/Brython3.1.1-20150328-091302/Lib/posixpath.py
722
14212
"""Common operations on Posix pathnames. Instead of importing this module directly, import os and refer to this module as os.path. The "os.path" name is an alias for this module on Posix systems; on other systems (e.g. Mac, Windows), os.path provides the same operations in a manner specific to that platform, and is an alias to another module (e.g. macpath, ntpath). Some of this can actually be useful on non-Posix systems too, e.g. for manipulation of the pathname component of URLs. """ import os import sys import stat import genericpath from genericpath import * __all__ = ["normcase","isabs","join","splitdrive","split","splitext", "basename","dirname","commonprefix","getsize","getmtime", "getatime","getctime","islink","exists","lexists","isdir","isfile", "ismount", "expanduser","expandvars","normpath","abspath", "samefile","sameopenfile","samestat", "curdir","pardir","sep","pathsep","defpath","altsep","extsep", "devnull","realpath","supports_unicode_filenames","relpath"] # Strings representing various path-related bits and pieces. # These are primarily for export; internally, they are hardcoded. curdir = '.' pardir = '..' extsep = '.' sep = '/' pathsep = ':' defpath = ':/bin:/usr/bin' altsep = None devnull = '/dev/null' def _get_sep(path): if isinstance(path, bytes): return b'/' else: return '/' # Normalize the case of a pathname. Trivial in Posix, string.lower on Mac. # On MS-DOS this may also turn slashes into backslashes; however, other # normalizations (such as optimizing '../' away) are not allowed # (another function should be defined to do that). def normcase(s): """Normalize case of pathname. Has no effect under Posix""" # TODO: on Mac OS X, this should really return s.lower(). if not isinstance(s, (bytes, str)): raise TypeError("normcase() argument must be str or bytes, " "not '{}'".format(s.__class__.__name__)) return s # Return whether a path is absolute. # Trivial in Posix, harder on the Mac or MS-DOS. def isabs(s): """Test whether a path is absolute""" sep = _get_sep(s) return s.startswith(sep) # Join pathnames. # Ignore the previous parts if a part is absolute. # Insert a '/' unless the first part is empty or already ends in '/'. def join(a, *p): """Join two or more pathname components, inserting '/' as needed. If any component is an absolute path, all previous path components will be discarded. An empty last part will result in a path that ends with a separator.""" sep = _get_sep(a) path = a try: for b in p: if b.startswith(sep): path = b elif not path or path.endswith(sep): path += b else: path += sep + b except TypeError: valid_types = all(isinstance(s, (str, bytes, bytearray)) for s in (a, ) + p) if valid_types: # Must have a mixture of text and binary data raise TypeError("Can't mix strings and bytes in path " "components.") from None raise return path # Split a path in head (everything up to the last '/') and tail (the # rest). If the path ends in '/', tail will be empty. If there is no # '/' in the path, head will be empty. # Trailing '/'es are stripped from head unless it is the root. def split(p): """Split a pathname. Returns tuple "(head, tail)" where "tail" is everything after the final slash. Either part may be empty.""" sep = _get_sep(p) i = p.rfind(sep) + 1 head, tail = p[:i], p[i:] if head and head != sep*len(head): head = head.rstrip(sep) return head, tail # Split a path in root and extension. # The extension is everything starting at the last dot in the last # pathname component; the root is everything before that. # It is always true that root + ext == p. def splitext(p): if isinstance(p, bytes): sep = b'/' extsep = b'.' else: sep = '/' extsep = '.' return genericpath._splitext(p, sep, None, extsep) splitext.__doc__ = genericpath._splitext.__doc__ # Split a pathname into a drive specification and the rest of the # path. Useful on DOS/Windows/NT; on Unix, the drive is always empty. def splitdrive(p): """Split a pathname into drive and path. On Posix, drive is always empty.""" return p[:0], p # Return the tail (basename) part of a path, same as split(path)[1]. def basename(p): """Returns the final component of a pathname""" sep = _get_sep(p) i = p.rfind(sep) + 1 return p[i:] # Return the head (dirname) part of a path, same as split(path)[0]. def dirname(p): """Returns the directory component of a pathname""" sep = _get_sep(p) i = p.rfind(sep) + 1 head = p[:i] if head and head != sep*len(head): head = head.rstrip(sep) return head # Is a path a symbolic link? # This will always return false on systems where os.lstat doesn't exist. def islink(path): """Test whether a path is a symbolic link""" try: st = os.lstat(path) except (os.error, AttributeError): return False return stat.S_ISLNK(st.st_mode) # Being true for dangling symbolic links is also useful. def lexists(path): """Test whether a path exists. Returns True for broken symbolic links""" try: os.lstat(path) except os.error: return False return True # Are two filenames really pointing to the same file? def samefile(f1, f2): """Test whether two pathnames reference the same actual file""" s1 = os.stat(f1) s2 = os.stat(f2) return samestat(s1, s2) # Are two open files really referencing the same file? # (Not necessarily the same file descriptor!) def sameopenfile(fp1, fp2): """Test whether two open file objects reference the same file""" s1 = os.fstat(fp1) s2 = os.fstat(fp2) return samestat(s1, s2) # Are two stat buffers (obtained from stat, fstat or lstat) # describing the same file? def samestat(s1, s2): """Test whether two stat buffers reference the same file""" return s1.st_ino == s2.st_ino and \ s1.st_dev == s2.st_dev # Is a path a mount point? # (Does this work for all UNIXes? Is it even guaranteed to work by Posix?) def ismount(path): """Test whether a path is a mount point""" if islink(path): # A symlink can never be a mount point return False try: s1 = os.lstat(path) if isinstance(path, bytes): parent = join(path, b'..') else: parent = join(path, '..') s2 = os.lstat(parent) except os.error: return False # It doesn't exist -- so not a mount point :-) dev1 = s1.st_dev dev2 = s2.st_dev if dev1 != dev2: return True # path/.. on a different device as path ino1 = s1.st_ino ino2 = s2.st_ino if ino1 == ino2: return True # path/.. is the same i-node as path return False # Expand paths beginning with '~' or '~user'. # '~' means $HOME; '~user' means that user's home directory. # If the path doesn't begin with '~', or if the user or $HOME is unknown, # the path is returned unchanged (leaving error reporting to whatever # function is called with the expanded path as argument). # See also module 'glob' for expansion of *, ? and [...] in pathnames. # (A function should also be defined to do full *sh-style environment # variable expansion.) def expanduser(path): """Expand ~ and ~user constructions. If user or $HOME is unknown, do nothing.""" if isinstance(path, bytes): tilde = b'~' else: tilde = '~' if not path.startswith(tilde): return path sep = _get_sep(path) i = path.find(sep, 1) if i < 0: i = len(path) if i == 1: if 'HOME' not in os.environ: import pwd userhome = pwd.getpwuid(os.getuid()).pw_dir else: userhome = os.environ['HOME'] else: import pwd name = path[1:i] if isinstance(name, bytes): name = str(name, 'ASCII') try: pwent = pwd.getpwnam(name) except KeyError: return path userhome = pwent.pw_dir if isinstance(path, bytes): userhome = os.fsencode(userhome) root = b'/' else: root = '/' userhome = userhome.rstrip(root) return (userhome + path[i:]) or root # Expand paths containing shell variable substitutions. # This expands the forms $variable and ${variable} only. # Non-existent variables are left unchanged. _varprog = None _varprogb = None def expandvars(path): """Expand shell variables of form $var and ${var}. Unknown variables are left unchanged.""" global _varprog, _varprogb if isinstance(path, bytes): if b'$' not in path: return path if not _varprogb: import re _varprogb = re.compile(br'\$(\w+|\{[^}]*\})', re.ASCII) search = _varprogb.search start = b'{' end = b'}' else: if '$' not in path: return path if not _varprog: import re _varprog = re.compile(r'\$(\w+|\{[^}]*\})', re.ASCII) search = _varprog.search start = '{' end = '}' i = 0 while True: m = search(path, i) if not m: break i, j = m.span(0) name = m.group(1) if name.startswith(start) and name.endswith(end): name = name[1:-1] if isinstance(name, bytes): name = str(name, 'ASCII') if name in os.environ: tail = path[j:] value = os.environ[name] if isinstance(path, bytes): value = value.encode('ASCII') path = path[:i] + value i = len(path) path += tail else: i = j return path # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B. # It should be understood that this may change the meaning of the path # if it contains symbolic links! def normpath(path): """Normalize path, eliminating double slashes, etc.""" if isinstance(path, bytes): sep = b'/' empty = b'' dot = b'.' dotdot = b'..' else: sep = '/' empty = '' dot = '.' dotdot = '..' if path == empty: return dot initial_slashes = path.startswith(sep) # POSIX allows one or two initial slashes, but treats three or more # as single slash. if (initial_slashes and path.startswith(sep*2) and not path.startswith(sep*3)): initial_slashes = 2 comps = path.split(sep) new_comps = [] for comp in comps: if comp in (empty, dot): continue if (comp != dotdot or (not initial_slashes and not new_comps) or (new_comps and new_comps[-1] == dotdot)): new_comps.append(comp) elif new_comps: new_comps.pop() comps = new_comps path = sep.join(comps) if initial_slashes: path = sep*initial_slashes + path return path or dot def abspath(path): """Return an absolute path.""" if not isabs(path): if isinstance(path, bytes): cwd = os.getcwdb() else: cwd = os.getcwd() path = join(cwd, path) return normpath(path) # Return a canonical path (i.e. the absolute location of a file on the # filesystem). def realpath(filename): """Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path.""" path, ok = _joinrealpath(filename[:0], filename, {}) return abspath(path) # Join two paths, normalizing ang eliminating any symbolic links # encountered in the second path. def _joinrealpath(path, rest, seen): if isinstance(path, bytes): sep = b'/' curdir = b'.' pardir = b'..' else: sep = '/' curdir = '.' pardir = '..' if isabs(rest): rest = rest[1:] path = sep while rest: name, _, rest = rest.partition(sep) if not name or name == curdir: # current dir continue if name == pardir: # parent dir if path: path, name = split(path) if name == pardir: path = join(path, pardir, pardir) else: path = pardir continue newpath = join(path, name) if not islink(newpath): path = newpath continue # Resolve the symbolic link if newpath in seen: # Already seen this path path = seen[newpath] if path is not None: # use cached value continue # The symlink is not resolved, so we must have a symlink loop. # Return already resolved part + rest of the path unchanged. return join(newpath, rest), False seen[newpath] = None # not resolved symlink path, ok = _joinrealpath(path, os.readlink(newpath), seen) if not ok: return join(path, rest), False seen[newpath] = path # resolved symlink return path, True supports_unicode_filenames = (sys.platform == 'darwin') def relpath(path, start=None): """Return a relative version of a path""" if not path: raise ValueError("no path specified") if isinstance(path, bytes): curdir = b'.' sep = b'/' pardir = b'..' else: curdir = '.' sep = '/' pardir = '..' if start is None: start = curdir start_list = [x for x in abspath(start).split(sep) if x] path_list = [x for x in abspath(path).split(sep) if x] # Work out how much of the filepath is shared by start and path. i = len(commonprefix([start_list, path_list])) rel_list = [pardir] * (len(start_list)-i) + path_list[i:] if not rel_list: return curdir return join(*rel_list)
agpl-3.0
bloyl/mne-python
tutorials/inverse/30_mne_dspm_loreta.py
3
5666
""" .. _tut-inverse-methods: Source localization with MNE/dSPM/sLORETA/eLORETA ================================================= The aim of this tutorial is to teach you how to compute and apply a linear minimum-norm inverse method on evoked/raw/epochs data. """ import os.path as op import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import sample from mne.minimum_norm import make_inverse_operator, apply_inverse ############################################################################### # Process MEG data data_path = sample.data_path() raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_filt-0-40_raw.fif') raw = mne.io.read_raw_fif(raw_fname) # already has an average reference events = mne.find_events(raw, stim_channel='STI 014') event_id = dict(aud_l=1) # event trigger and conditions tmin = -0.2 # start of each epoch (200ms before the trigger) tmax = 0.5 # end of each epoch (500ms after the trigger) raw.info['bads'] = ['MEG 2443', 'EEG 053'] baseline = (None, 0) # means from the first instant to t = 0 reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6) epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=('meg', 'eog'), baseline=baseline, reject=reject) ############################################################################### # Compute regularized noise covariance # ------------------------------------ # For more details see :ref:`tut-compute-covariance`. noise_cov = mne.compute_covariance( epochs, tmax=0., method=['shrunk', 'empirical'], rank=None, verbose=True) fig_cov, fig_spectra = mne.viz.plot_cov(noise_cov, raw.info) ############################################################################### # Compute the evoked response # --------------------------- # Let's just use the MEG channels for simplicity. evoked = epochs.average().pick('meg') evoked.plot(time_unit='s') evoked.plot_topomap(times=np.linspace(0.05, 0.15, 5), ch_type='mag', time_unit='s') ############################################################################### # It's also a good idea to look at whitened data: evoked.plot_white(noise_cov, time_unit='s') del epochs, raw # to save memory ############################################################################### # Inverse modeling: MNE/dSPM on evoked and raw data # ------------------------------------------------- # Here we first read the forward solution. You will likely need to compute # one for your own data -- see :ref:`tut-forward` for information on how # to do it. fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif' fwd = mne.read_forward_solution(fname_fwd) ############################################################################### # Next, we make an MEG inverse operator. inverse_operator = make_inverse_operator( evoked.info, fwd, noise_cov, loose=0.2, depth=0.8) del fwd # You can write it to disk with:: # # >>> from mne.minimum_norm import write_inverse_operator # >>> write_inverse_operator('sample_audvis-meg-oct-6-inv.fif', # inverse_operator) ############################################################################### # Compute inverse solution # ------------------------ # We can use this to compute the inverse solution and obtain source time # courses: method = "dSPM" snr = 3. lambda2 = 1. / snr ** 2 stc, residual = apply_inverse(evoked, inverse_operator, lambda2, method=method, pick_ori=None, return_residual=True, verbose=True) ############################################################################### # Visualization # ------------- # We can look at different dipole activations: fig, ax = plt.subplots() ax.plot(1e3 * stc.times, stc.data[::100, :].T) ax.set(xlabel='time (ms)', ylabel='%s value' % method) ############################################################################### # Examine the original data and the residual after fitting: fig, axes = plt.subplots(2, 1) evoked.plot(axes=axes) for ax in axes: ax.texts = [] for line in ax.lines: line.set_color('#98df81') residual.plot(axes=axes) ############################################################################### # Here we use peak getter to move visualization to the time point of the peak # and draw a marker at the maximum peak vertex. # sphinx_gallery_thumbnail_number = 9 vertno_max, time_max = stc.get_peak(hemi='rh') subjects_dir = data_path + '/subjects' surfer_kwargs = dict( hemi='rh', subjects_dir=subjects_dir, clim=dict(kind='value', lims=[8, 12, 15]), views='lateral', initial_time=time_max, time_unit='s', size=(800, 800), smoothing_steps=10) brain = stc.plot(**surfer_kwargs) brain.add_foci(vertno_max, coords_as_verts=True, hemi='rh', color='blue', scale_factor=0.6, alpha=0.5) brain.add_text(0.1, 0.9, 'dSPM (plus location of maximal activation)', 'title', font_size=14) # The documentation website's movie is generated with: # brain.save_movie(..., tmin=0.05, tmax=0.15, interpolation='linear', # time_dilation=20, framerate=10, time_viewer=True) ############################################################################### # There are many other ways to visualize and work with source data, see # for example: # # - :ref:`tut-viz-stcs` # - :ref:`ex-morph-surface` # - :ref:`ex-morph-volume` # - :ref:`ex-vector-mne-solution` # - :ref:`tut-dipole-orientations` # - :ref:`tut-mne-fixed-free` # - :ref:`examples using apply_inverse # <sphx_glr_backreferences_mne.minimum_norm.apply_inverse>`.
bsd-3-clause
snickl/buildroot-iu
support/testing/infra/builder.py
3
2028
import os import shutil import subprocess import infra class Builder(object): def __init__(self, config, builddir, logtofile): self.config = '\n'.join([line.lstrip() for line in config.splitlines()]) + '\n' self.builddir = builddir self.logfile = infra.open_log_file(builddir, "build", logtofile) def configure(self): if not os.path.isdir(self.builddir): os.makedirs(self.builddir) config_file = os.path.join(self.builddir, ".config") with open(config_file, "w+") as cf: cf.write(self.config) # dump the defconfig to the logfile for easy debugging self.logfile.write("> start defconfig\n" + self.config + "> end defconfig\n") self.logfile.flush() env = {"PATH": os.environ["PATH"]} cmd = ["make", "O={}".format(self.builddir), "olddefconfig"] ret = subprocess.call(cmd, stdout=self.logfile, stderr=self.logfile, env=env) if ret != 0: raise SystemError("Cannot olddefconfig") def build(self): env = {"PATH": os.environ["PATH"]} if "http_proxy" in os.environ: self.logfile.write("Using system proxy: " + os.environ["http_proxy"] + "\n") env['http_proxy'] = os.environ["http_proxy"] env['https_proxy'] = os.environ["http_proxy"] cmd = ["make", "-C", self.builddir] ret = subprocess.call(cmd, stdout=self.logfile, stderr=self.logfile, env=env) if ret != 0: raise SystemError("Build failed") open(self.stamp_path(), 'a').close() def stamp_path(self): return os.path.join(self.builddir, "build-done") def is_finished(self): return os.path.exists(self.stamp_path()) def delete(self): if os.path.exists(self.builddir): shutil.rmtree(self.builddir)
gpl-2.0
bderembl/mitgcm_configs
eddy_airsea/analysis/ode_wave.py
1
1112
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import scipy.integrate as integrate plt.ion() f0 = 1e-4 u0 = 1.0 R0 = 40e3 # radius vmax = -1.0 # m/s def v1(rr): v = -vmax*rr/R0*np.exp(-0.5*(rr/R0)**2) # v = -vmax*np.tanh(rr/R0)/(np.cosh(rr/R0))**2/(np.tanh(1.0)/(np.cosh(1.0))**2) return v def dv1(rr): v = -vmax/R0*np.exp(-0.5*(rr/R0)**2)*(1-(rr/R0)**2) # v = -vmax*2/R0*np.tanh(rr/R0)/((np.cosh(rr/R0))**2)*(1/(np.cosh(rr/R0))**2 - (np.tanh(rr/R0))**2)/(np.tanh(1.0)/(np.cosh(1.0))**2) return v def f(r, t): omega = np.sqrt((dv1(r)+v1(r)/r + f0)*(2*v1(r)/r + f0)) return u0*np.sin(omega*t) si_r = 30 si_t = 30000 r0 = np.linspace(1,5*R0,si_r) t = np.linspace(0, si_t/f0/1000, si_t) ra = np.zeros((si_t,si_r)) for ni in range(0,si_r): ra[:,ni] = integrate.odeint(f, r0[ni], t).squeeze() plt.figure() plt.plot(t*f0/(2*np.pi),ra/R0,'k',linewidth=1) plt.xlabel(r'$tf/2\pi$') plt.ylabel(r'$r_p/R_0$') plt.xlim([np.min(t*f0/(2*np.pi)), np.max(t*f0/(2*np.pi))]) plt.ylim([np.min(ra/R0), 1.05*np.max(ra/R0)]) plt.savefig("ode_k0.pdf",bbox_inches='tight')
mit
wndias/bc.repository
script.module.youtube.dl/lib/youtube_dl/extractor/chilloutzone.py
169
3600
from __future__ import unicode_literals import re import base64 import json from .common import InfoExtractor from ..utils import ( clean_html, ExtractorError ) class ChilloutzoneIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?chilloutzone\.net/video/(?P<id>[\w|-]+)\.html' _TESTS = [{ 'url': 'http://www.chilloutzone.net/video/enemene-meck-alle-katzen-weg.html', 'md5': 'a76f3457e813ea0037e5244f509e66d1', 'info_dict': { 'id': 'enemene-meck-alle-katzen-weg', 'ext': 'mp4', 'title': 'Enemene Meck - Alle Katzen weg', 'description': 'Ist das der Umkehrschluss des Niesenden Panda-Babys?', }, }, { 'note': 'Video hosted at YouTube', 'url': 'http://www.chilloutzone.net/video/eine-sekunde-bevor.html', 'info_dict': { 'id': '1YVQaAgHyRU', 'ext': 'mp4', 'title': '16 Photos Taken 1 Second Before Disaster', 'description': 'md5:58a8fcf6a459fe0a08f54140f0ad1814', 'uploader': 'BuzzFeedVideo', 'uploader_id': 'BuzzFeedVideo', 'upload_date': '20131105', }, }, { 'note': 'Video hosted at Vimeo', 'url': 'http://www.chilloutzone.net/video/icon-blending.html', 'md5': '2645c678b8dc4fefcc0e1b60db18dac1', 'info_dict': { 'id': '85523671', 'ext': 'mp4', 'title': 'The Sunday Times - Icons', 'description': 're:(?s)^Watch the making of - makingoficons.com.{300,}', 'uploader': 'Us', 'uploader_id': 'usfilms', 'upload_date': '20140131' }, }] def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) video_id = mobj.group('id') webpage = self._download_webpage(url, video_id) base64_video_info = self._html_search_regex( r'var cozVidData = "(.+?)";', webpage, 'video data') decoded_video_info = base64.b64decode(base64_video_info.encode('utf-8')).decode('utf-8') video_info_dict = json.loads(decoded_video_info) # get video information from dict video_url = video_info_dict['mediaUrl'] description = clean_html(video_info_dict.get('description')) title = video_info_dict['title'] native_platform = video_info_dict['nativePlatform'] native_video_id = video_info_dict['nativeVideoId'] source_priority = video_info_dict['sourcePriority'] # If nativePlatform is None a fallback mechanism is used (i.e. youtube embed) if native_platform is None: youtube_url = self._html_search_regex( r'<iframe.* src="((?:https?:)?//(?:[^.]+\.)?youtube\.com/.+?)"', webpage, 'fallback video URL', default=None) if youtube_url is not None: return self.url_result(youtube_url, ie='Youtube') # Non Fallback: Decide to use native source (e.g. youtube or vimeo) or # the own CDN if source_priority == 'native': if native_platform == 'youtube': return self.url_result(native_video_id, ie='Youtube') if native_platform == 'vimeo': return self.url_result( 'http://vimeo.com/' + native_video_id, ie='Vimeo') if not video_url: raise ExtractorError('No video found') return { 'id': video_id, 'url': video_url, 'ext': 'mp4', 'title': title, 'description': description, }
gpl-2.0
Changaco/oh-mainline
vendor/packages/twisted/twisted/scripts/test/test_tap2rpm.py
18
12479
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ Tests for L{twisted.scripts.tap2rpm}. """ import os from twisted.trial.unittest import TestCase, SkipTest from twisted.python import procutils from twisted.python.failure import Failure from twisted.internet import utils from twisted.scripts import tap2rpm # When we query the RPM metadata, we get back a string we'll have to parse, so # we'll use suitably rare delimiter characters to split on. Luckily, ASCII # defines some for us! RECORD_SEPARATOR = "\x1E" UNIT_SEPARATOR = "\x1F" def _makeRPMs(tapfile=None, maintainer=None, protocol=None, description=None, longDescription=None, setVersion=None, rpmfile=None, type_=None): """ Helper function to invoke tap2rpm with the given parameters. """ args = [] if not tapfile: tapfile = "dummy-tap-file" handle = open(tapfile, "w") handle.write("# Dummy TAP file\n") handle.close() args.extend(["--quiet", "--tapfile", tapfile]) if maintainer: args.extend(["--maintainer", maintainer]) if protocol: args.extend(["--protocol", protocol]) if description: args.extend(["--description", description]) if longDescription: args.extend(["--long_description", longDescription]) if setVersion: args.extend(["--set-version", setVersion]) if rpmfile: args.extend(["--rpmfile", rpmfile]) if type_: args.extend(["--type", type_]) return tap2rpm.run(args) def _queryRPMTags(rpmfile, taglist): """ Helper function to read the given header tags from the given RPM file. Returns a Deferred that fires with dictionary mapping a tag name to a list of the associated values in the RPM header. If a tag has only a single value in the header (like NAME or VERSION), it will be returned as a 1-item list. Run "rpm --querytags" to see what tags can be queried. """ # Build a query format string that will return appropriately delimited # results. Every field is treated as an array field, so single-value tags # like VERSION will be returned as 1-item lists. queryFormat = RECORD_SEPARATOR.join([ "[%%{%s}%s]" % (tag, UNIT_SEPARATOR) for tag in taglist ]) def parseTagValues(output): res = {} for tag, values in zip(taglist, output.split(RECORD_SEPARATOR)): values = values.strip(UNIT_SEPARATOR).split(UNIT_SEPARATOR) res[tag] = values return res def checkErrorResult(failure): # The current rpm packages on Debian and Ubuntu don't properly set up # the RPM database, which causes rpm to print a harmless warning to # stderr. Unfortunately, .getProcessOutput() assumes all warnings are # catastrophic and panics whenever it sees one. # # See also: # http://twistedmatrix.com/trac/ticket/3292#comment:42 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=551669 # http://rpm.org/ticket/106 failure.trap(IOError) # Depending on kernel scheduling, we might read the whole error # message, or only the first few bytes. if str(failure.value).startswith("got stderr: 'error: "): newFailure = Failure(SkipTest("rpm is missing its package " "database. Run 'sudo rpm -qa > /dev/null' to create one.")) else: # Not the exception we were looking for; we should report the # original failure. newFailure = failure # We don't want to raise the exception right away; we want to wait for # the process to exit, otherwise we'll get extra useless errors # reported. d = failure.value.processEnded d.addBoth(lambda _: newFailure) return d d = utils.getProcessOutput("rpm", ("-q", "--queryformat", queryFormat, "-p", rpmfile)) d.addCallbacks(parseTagValues, checkErrorResult) return d class TestTap2RPM(TestCase): def setUp(self): return self._checkForRpmbuild() def _checkForRpmbuild(self): """ tap2rpm requires rpmbuild; skip tests if rpmbuild is not present. """ if not procutils.which("rpmbuild"): raise SkipTest("rpmbuild must be present to test tap2rpm") def _makeTapFile(self, basename="dummy"): """ Make a temporary .tap file and returns the absolute path. """ path = basename + ".tap" handle = open(path, "w") handle.write("# Dummy .tap file") handle.close() return path def _verifyRPMTags(self, rpmfile, **tags): """ Check the given file has the given tags set to the given values. """ d = _queryRPMTags(rpmfile, tags.keys()) d.addCallback(self.assertEquals, tags) return d def test_optionDefaults(self): """ Commandline options should default to sensible values. "sensible" here is defined as "the same values that previous versions defaulted to". """ config = tap2rpm.MyOptions() config.parseOptions([]) self.assertEquals(config['tapfile'], 'twistd.tap') self.assertEquals(config['maintainer'], 'tap2rpm') self.assertEquals(config['protocol'], 'twistd') self.assertEquals(config['description'], 'A TCP server for twistd') self.assertEquals(config['long_description'], 'Automatically created by tap2rpm') self.assertEquals(config['set-version'], '1.0') self.assertEquals(config['rpmfile'], 'twisted-twistd') self.assertEquals(config['type'], 'tap') self.assertEquals(config['quiet'], False) self.assertEquals(config['twistd_option'], 'file') self.assertEquals(config['release-name'], 'twisted-twistd-1.0') def test_protocolCalculatedFromTapFile(self): """ The protocol name defaults to a value based on the tapfile value. """ config = tap2rpm.MyOptions() config.parseOptions(['--tapfile', 'pancakes.tap']) self.assertEquals(config['tapfile'], 'pancakes.tap') self.assertEquals(config['protocol'], 'pancakes') def test_optionsDefaultToProtocolValue(self): """ Many options default to a value calculated from the protocol name. """ config = tap2rpm.MyOptions() config.parseOptions([ '--tapfile', 'sausages.tap', '--protocol', 'eggs', ]) self.assertEquals(config['tapfile'], 'sausages.tap') self.assertEquals(config['maintainer'], 'tap2rpm') self.assertEquals(config['protocol'], 'eggs') self.assertEquals(config['description'], 'A TCP server for eggs') self.assertEquals(config['long_description'], 'Automatically created by tap2rpm') self.assertEquals(config['set-version'], '1.0') self.assertEquals(config['rpmfile'], 'twisted-eggs') self.assertEquals(config['type'], 'tap') self.assertEquals(config['quiet'], False) self.assertEquals(config['twistd_option'], 'file') self.assertEquals(config['release-name'], 'twisted-eggs-1.0') def test_releaseNameDefaultsToRpmfileValue(self): """ The release-name option is calculated from rpmfile and set-version. """ config = tap2rpm.MyOptions() config.parseOptions([ "--rpmfile", "beans", "--set-version", "1.2.3", ]) self.assertEquals(config['release-name'], 'beans-1.2.3') def test_basicOperation(self): """ Calling tap2rpm should produce an RPM and SRPM with default metadata. """ basename = "frenchtoast" # Create RPMs based on a TAP file with this name. rpm, srpm = _makeRPMs(tapfile=self._makeTapFile(basename)) # Verify the resulting RPMs have the correct tags. d = self._verifyRPMTags(rpm, NAME=["twisted-%s" % (basename,)], VERSION=["1.0"], RELEASE=["1"], SUMMARY=["A TCP server for %s" % (basename,)], DESCRIPTION=["Automatically created by tap2rpm"], ) d.addCallback(lambda _: self._verifyRPMTags(srpm, NAME=["twisted-%s" % (basename,)], VERSION=["1.0"], RELEASE=["1"], SUMMARY=["A TCP server for %s" % (basename,)], DESCRIPTION=["Automatically created by tap2rpm"], )) return d def test_protocolOverride(self): """ Setting 'protocol' should change the name of the resulting package. """ basename = "acorn" protocol = "banana" # Create RPMs based on a TAP file with this name. rpm, srpm = _makeRPMs(tapfile=self._makeTapFile(basename), protocol=protocol) # Verify the resulting RPMs have the correct tags. d = self._verifyRPMTags(rpm, NAME=["twisted-%s" % (protocol,)], SUMMARY=["A TCP server for %s" % (protocol,)], ) d.addCallback(lambda _: self._verifyRPMTags(srpm, NAME=["twisted-%s" % (protocol,)], SUMMARY=["A TCP server for %s" % (protocol,)], )) return d def test_rpmfileOverride(self): """ Setting 'rpmfile' should change the name of the resulting package. """ basename = "cherry" rpmfile = "donut" # Create RPMs based on a TAP file with this name. rpm, srpm = _makeRPMs(tapfile=self._makeTapFile(basename), rpmfile=rpmfile) # Verify the resulting RPMs have the correct tags. d = self._verifyRPMTags(rpm, NAME=[rpmfile], SUMMARY=["A TCP server for %s" % (basename,)], ) d.addCallback(lambda _: self._verifyRPMTags(srpm, NAME=[rpmfile], SUMMARY=["A TCP server for %s" % (basename,)], )) return d def test_descriptionOverride(self): """ Setting 'description' should change the SUMMARY tag. """ description = "eggplant" # Create RPMs based on a TAP file with this name. rpm, srpm = _makeRPMs(tapfile=self._makeTapFile(), description=description) # Verify the resulting RPMs have the correct tags. d = self._verifyRPMTags(rpm, SUMMARY=[description], ) d.addCallback(lambda _: self._verifyRPMTags(srpm, SUMMARY=[description], )) return d def test_longDescriptionOverride(self): """ Setting 'longDescription' should change the DESCRIPTION tag. """ longDescription = "fig" # Create RPMs based on a TAP file with this name. rpm, srpm = _makeRPMs(tapfile=self._makeTapFile(), longDescription=longDescription) # Verify the resulting RPMs have the correct tags. d = self._verifyRPMTags(rpm, DESCRIPTION=[longDescription], ) d.addCallback(lambda _: self._verifyRPMTags(srpm, DESCRIPTION=[longDescription], )) return d def test_setVersionOverride(self): """ Setting 'setVersion' should change the RPM's version info. """ version = "123.456" # Create RPMs based on a TAP file with this name. rpm, srpm = _makeRPMs(tapfile=self._makeTapFile(), setVersion=version) # Verify the resulting RPMs have the correct tags. d = self._verifyRPMTags(rpm, VERSION=["123.456"], RELEASE=["1"], ) d.addCallback(lambda _: self._verifyRPMTags(srpm, VERSION=["123.456"], RELEASE=["1"], )) return d def test_tapInOtherDirectory(self): """ tap2rpm handles tapfiles outside the current directory. """ # Make a tapfile outside the current directory. tempdir = self.mktemp() os.mkdir(tempdir) tapfile = self._makeTapFile(os.path.join(tempdir, "bacon")) # Try and make an RPM from that tapfile. _makeRPMs(tapfile=tapfile)
agpl-3.0
gilneidp/FinalProject
ALL_FILES/pox/messenger/example.py
46
3835
# Copyright 2011,2012 James McCauley # # 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. """ Messenger can be used in many ways. This shows a few of them. Creates a channel called "time" which broadcasts the time. Creates a channel called "chat" which relays messages to its members. Listens for channels called "echo_..." and responds to message in them. Listens for messages on a channel named "upper" and responds in upper case. Creates a bot ("GreetBot") which can be invited to other channels. Note that the echo and upper are really similar, but echo uses the channel mechanism (e.g., clients join a channel), whereas upper keeps track of members itself and clients are not expected to actually join the upper channel -- it's just used like an address to send messages to. This is just showing that there are multiple ways to go about doing things. """ from pox.core import core from pox.messenger import * log = core.getLogger() class UpperService (object): def __init__ (self, parent, con, event): self.con = con self.parent = parent self.listeners = con.addListeners(self) self.count = 0 # We only just added the listener, so dispatch the first # message manually. self._handle_MessageReceived(event, event.msg) def _handle_ConnectionClosed (self, event): self.con.removeListeners(self.listeners) self.parent.clients.pop(self.con, None) def _handle_MessageReceived (self, event, msg): self.count += 1 self.con.send(reply(msg, count = self.count, msg = str(msg.get('msg').upper()))) class UpperBot (ChannelBot): def _init (self, extra): self.clients = {} def _unhandled (self, event): connection = event.con if connection not in self.clients: self.clients[connection] = UpperService(self, connection, event) class EchoBot (ChannelBot): count = 0 def _exec_msg (self, event, value): self.count += 1 self.reply(event, msg = "%i: %s" % (self.count, value)) class GreetBot (ChannelBot): def _join (self, event, connection, msg): from random import choice greet = choice(['hello','aloha','greeings','hi',"g'day"]) greet += ", " + str(connection) self.send({'greeting':greet}) class MessengerExample (object): def __init__ (self): core.listen_to_dependencies(self) def _all_dependencies_met (self): # Set up the chat channel chat_channel = core.MessengerNexus.get_channel("chat") def handle_chat (event, msg): m = str(msg.get("msg")) chat_channel.send({"msg":str(event.con) + " says " + m}) chat_channel.addListener(MessageReceived, handle_chat) # Set up the time channel... time_channel = core.MessengerNexus.get_channel("time") import time def timer (): time_channel.send({'msg':"It's " + time.strftime("%I:%M:%S %p")}) from pox.lib.recoco import Timer Timer(10, timer, recurring=True) # Set up the "upper" service UpperBot(core.MessengerNexus.get_channel("upper")) # Make GreetBot invitable to other channels using "invite" core.MessengerNexus.default_bot.add_bot(GreetBot) def _handle_MessengerNexus_ChannelCreate (self, event): if event.channel.name.startswith("echo_"): # Ah, it's a new echo channel -- put in an EchoBot EchoBot(event.channel) def launch (): MessengerExample()
mit
xxsergzzxx/python-for-android
python3-alpha/python3-src/Lib/distutils/command/build_py.py
46
16957
"""distutils.command.build_py Implements the Distutils 'build_py' command.""" import sys, os import sys from glob import glob from distutils.core import Command from distutils.errors import * from distutils.util import convert_path, Mixin2to3 from distutils import log class build_py (Command): description = "\"build\" pure Python modules (copy to build directory)" user_options = [ ('build-lib=', 'd', "directory to \"build\" (copy) to"), ('compile', 'c', "compile .py to .pyc"), ('no-compile', None, "don't compile .py files [default]"), ('optimize=', 'O', "also compile with optimization: -O1 for \"python -O\", " "-O2 for \"python -OO\", and -O0 to disable [default: -O0]"), ('force', 'f', "forcibly build everything (ignore file timestamps)"), ] boolean_options = ['compile', 'force'] negative_opt = {'no-compile' : 'compile'} def initialize_options(self): self.build_lib = None self.py_modules = None self.package = None self.package_data = None self.package_dir = None self.compile = 0 self.optimize = 0 self.force = None def finalize_options(self): self.set_undefined_options('build', ('build_lib', 'build_lib'), ('force', 'force')) # Get the distribution options that are aliases for build_py # options -- list of packages and list of modules. self.packages = self.distribution.packages self.py_modules = self.distribution.py_modules self.package_data = self.distribution.package_data self.package_dir = {} if self.distribution.package_dir: for name, path in self.distribution.package_dir.items(): self.package_dir[name] = convert_path(path) self.data_files = self.get_data_files() # Ick, copied straight from install_lib.py (fancy_getopt needs a # type system! Hell, *everything* needs a type system!!!) if not isinstance(self.optimize, int): try: self.optimize = int(self.optimize) assert 0 <= self.optimize <= 2 except (ValueError, AssertionError): raise DistutilsOptionError("optimize must be 0, 1, or 2") def run(self): # XXX copy_file by default preserves atime and mtime. IMHO this is # the right thing to do, but perhaps it should be an option -- in # particular, a site administrator might want installed files to # reflect the time of installation rather than the last # modification time before the installed release. # XXX copy_file by default preserves mode, which appears to be the # wrong thing to do: if a file is read-only in the working # directory, we want it to be installed read/write so that the next # installation of the same module distribution can overwrite it # without problems. (This might be a Unix-specific issue.) Thus # we turn off 'preserve_mode' when copying to the build directory, # since the build directory is supposed to be exactly what the # installation will look like (ie. we preserve mode when # installing). # Two options control which modules will be installed: 'packages' # and 'py_modules'. The former lets us work with whole packages, not # specifying individual modules at all; the latter is for # specifying modules one-at-a-time. if self.py_modules: self.build_modules() if self.packages: self.build_packages() self.build_package_data() self.byte_compile(self.get_outputs(include_bytecode=0)) def get_data_files(self): """Generate list of '(package,src_dir,build_dir,filenames)' tuples""" data = [] if not self.packages: return data for package in self.packages: # Locate package source directory src_dir = self.get_package_dir(package) # Compute package build directory build_dir = os.path.join(*([self.build_lib] + package.split('.'))) # Length of path to strip from found files plen = 0 if src_dir: plen = len(src_dir)+1 # Strip directory from globbed filenames filenames = [ file[plen:] for file in self.find_data_files(package, src_dir) ] data.append((package, src_dir, build_dir, filenames)) return data def find_data_files(self, package, src_dir): """Return filenames for package's data files in 'src_dir'""" globs = (self.package_data.get('', []) + self.package_data.get(package, [])) files = [] for pattern in globs: # Each pattern has to be converted to a platform-specific path filelist = glob(os.path.join(src_dir, convert_path(pattern))) # Files that match more than one pattern are only added once files.extend([fn for fn in filelist if fn not in files]) return files def build_package_data(self): """Copy data files into build directory""" lastdir = None for package, src_dir, build_dir, filenames in self.data_files: for filename in filenames: target = os.path.join(build_dir, filename) self.mkpath(os.path.dirname(target)) self.copy_file(os.path.join(src_dir, filename), target, preserve_mode=False) def get_package_dir(self, package): """Return the directory, relative to the top of the source distribution, where package 'package' should be found (at least according to the 'package_dir' option, if any).""" path = package.split('.') if not self.package_dir: if path: return os.path.join(*path) else: return '' else: tail = [] while path: try: pdir = self.package_dir['.'.join(path)] except KeyError: tail.insert(0, path[-1]) del path[-1] else: tail.insert(0, pdir) return os.path.join(*tail) else: # Oops, got all the way through 'path' without finding a # match in package_dir. If package_dir defines a directory # for the root (nameless) package, then fallback on it; # otherwise, we might as well have not consulted # package_dir at all, as we just use the directory implied # by 'tail' (which should be the same as the original value # of 'path' at this point). pdir = self.package_dir.get('') if pdir is not None: tail.insert(0, pdir) if tail: return os.path.join(*tail) else: return '' def check_package(self, package, package_dir): # Empty dir name means current directory, which we can probably # assume exists. Also, os.path.exists and isdir don't know about # my "empty string means current dir" convention, so we have to # circumvent them. if package_dir != "": if not os.path.exists(package_dir): raise DistutilsFileError( "package directory '%s' does not exist" % package_dir) if not os.path.isdir(package_dir): raise DistutilsFileError( "supposed package directory '%s' exists, " "but is not a directory" % package_dir) # Require __init__.py for all but the "root package" if package: init_py = os.path.join(package_dir, "__init__.py") if os.path.isfile(init_py): return init_py else: log.warn(("package init file '%s' not found " + "(or not a regular file)"), init_py) # Either not in a package at all (__init__.py not expected), or # __init__.py doesn't exist -- so don't return the filename. return None def check_module(self, module, module_file): if not os.path.isfile(module_file): log.warn("file %s (for module %s) not found", module_file, module) return False else: return True def find_package_modules(self, package, package_dir): self.check_package(package, package_dir) module_files = glob(os.path.join(package_dir, "*.py")) modules = [] setup_script = os.path.abspath(self.distribution.script_name) for f in module_files: abs_f = os.path.abspath(f) if abs_f != setup_script: module = os.path.splitext(os.path.basename(f))[0] modules.append((package, module, f)) else: self.debug_print("excluding %s" % setup_script) return modules def find_modules(self): """Finds individually-specified Python modules, ie. those listed by module name in 'self.py_modules'. Returns a list of tuples (package, module_base, filename): 'package' is a tuple of the path through package-space to the module; 'module_base' is the bare (no packages, no dots) module name, and 'filename' is the path to the ".py" file (relative to the distribution root) that implements the module. """ # Map package names to tuples of useful info about the package: # (package_dir, checked) # package_dir - the directory where we'll find source files for # this package # checked - true if we have checked that the package directory # is valid (exists, contains __init__.py, ... ?) packages = {} # List of (package, module, filename) tuples to return modules = [] # We treat modules-in-packages almost the same as toplevel modules, # just the "package" for a toplevel is empty (either an empty # string or empty list, depending on context). Differences: # - don't check for __init__.py in directory for empty package for module in self.py_modules: path = module.split('.') package = '.'.join(path[0:-1]) module_base = path[-1] try: (package_dir, checked) = packages[package] except KeyError: package_dir = self.get_package_dir(package) checked = 0 if not checked: init_py = self.check_package(package, package_dir) packages[package] = (package_dir, 1) if init_py: modules.append((package, "__init__", init_py)) # XXX perhaps we should also check for just .pyc files # (so greedy closed-source bastards can distribute Python # modules too) module_file = os.path.join(package_dir, module_base + ".py") if not self.check_module(module, module_file): continue modules.append((package, module_base, module_file)) return modules def find_all_modules(self): """Compute the list of all modules that will be built, whether they are specified one-module-at-a-time ('self.py_modules') or by whole packages ('self.packages'). Return a list of tuples (package, module, module_file), just like 'find_modules()' and 'find_package_modules()' do.""" modules = [] if self.py_modules: modules.extend(self.find_modules()) if self.packages: for package in self.packages: package_dir = self.get_package_dir(package) m = self.find_package_modules(package, package_dir) modules.extend(m) return modules def get_source_files(self): return [module[-1] for module in self.find_all_modules()] def get_module_outfile(self, build_dir, package, module): outfile_path = [build_dir] + list(package) + [module + ".py"] return os.path.join(*outfile_path) def get_outputs(self, include_bytecode=1): modules = self.find_all_modules() outputs = [] for (package, module, module_file) in modules: package = package.split('.') filename = self.get_module_outfile(self.build_lib, package, module) outputs.append(filename) if include_bytecode: if self.compile: outputs.append(filename + "c") if self.optimize > 0: outputs.append(filename + "o") outputs += [ os.path.join(build_dir, filename) for package, src_dir, build_dir, filenames in self.data_files for filename in filenames ] return outputs def build_module(self, module, module_file, package): if isinstance(package, str): package = package.split('.') elif not isinstance(package, (list, tuple)): raise TypeError( "'package' must be a string (dot-separated), list, or tuple") # Now put the module source file into the "build" area -- this is # easy, we just copy it somewhere under self.build_lib (the build # directory for Python source). outfile = self.get_module_outfile(self.build_lib, package, module) dir = os.path.dirname(outfile) self.mkpath(dir) return self.copy_file(module_file, outfile, preserve_mode=0) def build_modules(self): modules = self.find_modules() for (package, module, module_file) in modules: # Now "build" the module -- ie. copy the source file to # self.build_lib (the build directory for Python source). # (Actually, it gets copied to the directory for this package # under self.build_lib.) self.build_module(module, module_file, package) def build_packages(self): for package in self.packages: # Get list of (package, module, module_file) tuples based on # scanning the package directory. 'package' is only included # in the tuple so that 'find_modules()' and # 'find_package_tuples()' have a consistent interface; it's # ignored here (apart from a sanity check). Also, 'module' is # the *unqualified* module name (ie. no dots, no package -- we # already know its package!), and 'module_file' is the path to # the .py file, relative to the current directory # (ie. including 'package_dir'). package_dir = self.get_package_dir(package) modules = self.find_package_modules(package, package_dir) # Now loop over the modules we found, "building" each one (just # copy it to self.build_lib). for (package_, module, module_file) in modules: assert package == package_ self.build_module(module, module_file, package) def byte_compile(self, files): if sys.dont_write_bytecode: self.warn('byte-compiling is disabled, skipping.') return from distutils.util import byte_compile prefix = self.build_lib if prefix[-1] != os.sep: prefix = prefix + os.sep # XXX this code is essentially the same as the 'byte_compile() # method of the "install_lib" command, except for the determination # of the 'prefix' string. Hmmm. if self.compile: byte_compile(files, optimize=0, force=self.force, prefix=prefix, dry_run=self.dry_run) if self.optimize > 0: byte_compile(files, optimize=self.optimize, force=self.force, prefix=prefix, dry_run=self.dry_run) class build_py_2to3(build_py, Mixin2to3): def run(self): self.updated_files = [] # Base class code if self.py_modules: self.build_modules() if self.packages: self.build_packages() self.build_package_data() # 2to3 self.run_2to3(self.updated_files) # Remaining base class code self.byte_compile(self.get_outputs(include_bytecode=0)) def build_module(self, module, module_file, package): res = build_py.build_module(self, module, module_file, package) if res[1]: # file was copied self.updated_files.append(res[0]) return res
apache-2.0
MIPS/external-chromium_org
tools/telemetry/telemetry/page/actions/wait.py
33
2372
# 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. import time from telemetry.core import util from telemetry.page.actions import page_action class WaitAction(page_action.PageAction): DEFAULT_TIMEOUT = 60 def __init__(self, attributes=None): super(WaitAction, self).__init__(attributes) def RunsPreviousAction(self): assert hasattr(self, 'condition') return self.condition == 'navigate' or self.condition == 'href_change' def RunAction(self, page, tab, previous_action): assert hasattr(self, 'condition') if self.condition == 'duration': assert hasattr(self, 'seconds') time.sleep(self.seconds) elif self.condition == 'navigate': if not previous_action: raise page_action.PageActionFailed('You need to perform an action ' 'before waiting for navigate.') previous_action.WillRunAction() action_to_perform = lambda: previous_action.RunAction(page, tab, None) tab.PerformActionAndWaitForNavigate(action_to_perform) elif self.condition == 'href_change': if not previous_action: raise page_action.PageActionFailed('You need to perform an action ' 'before waiting for a href change.') previous_action.WillRunAction() old_url = tab.EvaluateJavaScript('document.location.href') previous_action.RunAction(page, tab, None) util.WaitFor(lambda: tab.EvaluateJavaScript( 'document.location.href') != old_url, self.DEFAULT_TIMEOUT) elif self.condition == 'element': assert hasattr(self, 'text') or hasattr(self, 'selector') if self.text: callback_code = 'function(element) { return element != null; }' util.WaitFor( lambda: util.FindElementAndPerformAction( tab, self.text, callback_code), self.DEFAULT_TIMEOUT) elif self.selector: util.WaitFor(lambda: tab.EvaluateJavaScript( 'document.querySelector("%s") != null' % self.selector), self.DEFAULT_TIMEOUT) elif self.condition == 'javascript': assert hasattr(self, 'javascript') util.WaitFor(lambda: tab.EvaluateJavaScript(self.javascript), self.DEFAULT_TIMEOUT)
bsd-3-clause
Opentrons/labware
api/src/opentrons/calibration_storage/helpers.py
2
2397
""" opentrons.calibration_storage.helpers: various miscellaneous functions This module has functions that you can import to save robot or labware calibration to its designated file location. """ import typing import json from hashlib import sha256 from . import types as local_types if typing.TYPE_CHECKING: from opentrons_shared_data.labware.dev_types import LabwareDefinition def hash_labware_def(labware_def: 'LabwareDefinition') -> str: """ Helper function to take in a labware definition and return a hashed string of key elemenets from the labware definition to make it a unique identifier. :param labware_def: Full labware definitino :returns: sha256 string """ # remove keys that do not affect run blocklist = ['metadata', 'brand', 'groups'] def_no_metadata = { k: v for k, v in labware_def.items() if k not in blocklist} sorted_def_str = json.dumps( def_no_metadata, sort_keys=True, separators=(',', ':')) return sha256(sorted_def_str.encode('utf-8')).hexdigest() def details_from_uri(uri: str, delimiter='/') -> local_types.UriDetails: """ Unpack a labware URI to get the namespace, loadname and version """ if uri: info = uri.split(delimiter) return local_types.UriDetails( namespace=info[0], load_name=info[1], version=int(info[2])) else: # Here we are assuming that the 'uri' passed in is actually # the loadname, though sometimes it may be an empty string. return local_types.UriDetails( namespace='', load_name=uri, version=1) def uri_from_details(namespace: str, load_name: str, version: typing.Union[str, int], delimiter='/') -> str: """ Build a labware URI from its details. A labware URI is a string that uniquely specifies a labware definition. :returns str: The URI. """ return f'{namespace}{delimiter}{load_name}{delimiter}{version}' def uri_from_definition(definition: 'LabwareDefinition', delimiter='/') -> str: """ Build a labware URI from its definition. A labware URI is a string that uniquely specifies a labware definition. :returns str: The URI. """ return uri_from_details(definition['namespace'], definition['parameters']['loadName'], definition['version'])
apache-2.0
cmc333333/regulations-parser
regparser/tree/paragraph.py
1
6226
import hashlib import re from regparser.tree import struct from regparser.tree.depth import markers as mtypes from regparser.search import segments p_levels = [list(mtypes.lower), list(mtypes.ints), list(mtypes.roman), list(mtypes.upper), list(mtypes.em_ints), list(mtypes.em_roman)] def p_level_of(marker): """Given a marker(string), determine the possible paragraph levels it could fall into. This is useful for determining the order of paragraphs""" potential_levels = [] for level, markers in enumerate(p_levels): if marker in markers: potential_levels.append(level) return potential_levels _NONWORDS = re.compile(r'\W+') def hash_for_paragraph(text): """Hash a chunk of text and convert it into an integer for use with a MARKERLESS paragraph identifier. We'll trim to just 8 hex characters for legibility. We don't need to fear hash collisions as we'll have 16**8 ~ 4 billion possibilities. The birthday paradox tells us we'd only expect collisions after ~ 60 thousand entries. We're expecting at most a few hundred""" phrase = _NONWORDS.sub('', text.lower()) hashed = hashlib.sha1(phrase).hexdigest()[:8] return int(hashed, 16) class ParagraphParser(): def __init__(self, p_regex, node_type): """p_regex is the regular expression used when searching through paragraphs. It should contain a %s for the next paragraph 'part' (e.g. 'a', 'A', '1', 'i', etc.) inner_label_fn is a function which takes the current label, and the next paragraph 'part' and produces a new label.""" self.p_regex = p_regex self.node_type = node_type def matching_subparagraph_ids(self, p_level, paragraph): """Return a list of matches if this paragraph id matches one of the subparagraph ids (e.g. letter (i) and roman numeral (i).""" matches = [] for depth in range(p_level+1, len(p_levels)): for sub_id, sub in enumerate(p_levels[depth]): if sub == p_levels[p_level][paragraph]: matches.append((depth, sub_id)) return matches def best_start(self, text, p_level, paragraph, starts, exclude=[]): """Given a list of potential paragraph starts, pick the best based on knowledge of subparagraph structure. Do this by checking if the id following the subparagraph (e.g. ii) is between the first match and the second. If so, skip it, as that implies the first match was a subparagraph.""" subparagraph_hazards = self.matching_subparagraph_ids( p_level, paragraph) starts = starts + [(len(text), len(text))] for i in range(1, len(starts)): _, prev_end = starts[i-1] next_start, _ = starts[i] s_text = text[prev_end:next_start] s_exclude = [ (e_start + prev_end, e_end + prev_end) for e_start, e_end in exclude] is_subparagraph = False for hazard_level, hazard_idx in subparagraph_hazards: if self.find_paragraph_start_match( s_text, hazard_level, hazard_idx + 1, s_exclude): is_subparagraph = True if not is_subparagraph: return starts[i-1] def find_paragraph_start_match(self, text, p_level, paragraph, exclude=[]): """Find the positions for the start and end of the requested label. p_Level is one of 0,1,2,3; paragraph is the index within that label. Return None if not present. Does not return results in the exclude list (a list of start/stop indices). """ if len(p_levels) <= p_level or len(p_levels[p_level]) <= paragraph: return None match_starts = [(m.start(), m.end()) for m in re.finditer( self.p_regex % p_levels[p_level][paragraph], text)] match_starts = [ (start, end) for start, end in match_starts if all([end < es or start > ee for es, ee in exclude])] if len(match_starts) == 0: return None elif len(match_starts) == 1: return match_starts[0] else: return self.best_start( text, p_level, paragraph, match_starts, exclude) def paragraph_offsets(self, text, p_level, paragraph, exclude=[]): """Find the start/end of the requested paragraph. Assumes the text does not just up a p_level -- see build_paragraph_tree below.""" start = self.find_paragraph_start_match( text, p_level, paragraph, exclude) if start is None: return None id_start, id_end = start end = self.find_paragraph_start_match( text[id_end:], p_level, paragraph + 1, [(e_start - id_end, e_end - id_end) for e_start, e_end in exclude]) if end is None: end = len(text) else: end = end[0] + id_end return (id_start, end) def paragraphs(self, text, p_level, exclude=[]): """Return a list of paragraph offsets defined by the level param.""" def offsets_fn(remaining_text, p_idx, exclude): return self.paragraph_offsets( remaining_text, p_level, p_idx, exclude) return segments(text, offsets_fn, exclude) def build_tree(self, text, p_level=0, exclude=[], label=[], title=''): """ Build a dict to represent the text hierarchy. """ subparagraphs = self.paragraphs(text, p_level, exclude) if subparagraphs: body_text = text[0:subparagraphs[0][0]] else: body_text = text children = [] for paragraph, (start, end) in enumerate(subparagraphs): new_text = text[start:end] new_excludes = [(e[0] - start, e[1] - start) for e in exclude] new_label = label + [p_levels[p_level][paragraph]] children.append( self.build_tree( new_text, p_level + 1, new_excludes, new_label)) return struct.Node(body_text, children, label, title, self.node_type)
cc0-1.0
ivanbusthomi/inasafe
safe/test/test_init.py
15
1925
# coding=utf-8 """Tests for map creation in QGIS plugin.""" __author__ = 'Tim Sutton <tim@kartoza.com>' __revision__ = '$Format:%H$' __date__ = '17/10/2010' __license__ = "GPL" __copyright__ = 'Copyright 2012, Australia Indonesia Facility for ' __copyright__ += 'Disaster Reduction' import os import unittest import logging import ConfigParser LOGGER = logging.getLogger('InaSAFE') class TestInit(unittest.TestCase): """Test that the plugin init is usable for QGIS. Based heavily on the validator class by Alessandro Passoti available here: http://github.com/qgis/qgis-django/blob/master/qgis-app/ plugins/validator.py """ def test_read_init(self): """Test that the plugin __init__ will validate on plugins.qgis.org.""" # You should update this list according to the latest in # https://github.com/qgis/qgis-django/blob/master/qgis-app/ # plugins/validator.py required_metadata = [ 'name', 'description', 'version', 'qgisMinimumVersion', 'email', 'author'] file_path = os.path.abspath( os.path.join( os.path.dirname(__file__), os.pardir, '../metadata.txt')) LOGGER.info(file_path) metadata = [] parser = ConfigParser.ConfigParser() parser.optionxform = str parser.read(file_path) message = 'Cannot find a section named "general" in %s' % file_path self.assertTrue(parser.has_section('general'), message) metadata.extend(parser.items('general')) for expectation in required_metadata: message = ('Cannot find metadata "%s" in metadata source (%s).' % ( expectation, file_path)) self.assertIn(expectation, dict(metadata), message) if __name__ == '__main__': unittest.main()
gpl-3.0
louiskun/flaskGIT
venv/lib/python2.7/site-packages/sqlalchemy/sql/ddl.py
34
37540
# sql/ddl.py # Copyright (C) 2009-2016 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ Provides the hierarchy of DDL-defining schema items as well as routines to invoke them for a create/drop call. """ from .. import util from .elements import ClauseElement from .base import Executable, _generative, SchemaVisitor, _bind_or_error from ..util import topological from .. import event from .. import exc class _DDLCompiles(ClauseElement): def _compiler(self, dialect, **kw): """Return a compiler appropriate for this ClauseElement, given a Dialect.""" return dialect.ddl_compiler(dialect, self, **kw) class DDLElement(Executable, _DDLCompiles): """Base class for DDL expression constructs. This class is the base for the general purpose :class:`.DDL` class, as well as the various create/drop clause constructs such as :class:`.CreateTable`, :class:`.DropTable`, :class:`.AddConstraint`, etc. :class:`.DDLElement` integrates closely with SQLAlchemy events, introduced in :ref:`event_toplevel`. An instance of one is itself an event receiving callable:: event.listen( users, 'after_create', AddConstraint(constraint).execute_if(dialect='postgresql') ) .. seealso:: :class:`.DDL` :class:`.DDLEvents` :ref:`event_toplevel` :ref:`schema_ddl_sequences` """ _execution_options = Executable.\ _execution_options.union({'autocommit': True}) target = None on = None dialect = None callable_ = None def _execute_on_connection(self, connection, multiparams, params): return connection._execute_ddl(self, multiparams, params) def execute(self, bind=None, target=None): """Execute this DDL immediately. Executes the DDL statement in isolation using the supplied :class:`.Connectable` or :class:`.Connectable` assigned to the ``.bind`` property, if not supplied. If the DDL has a conditional ``on`` criteria, it will be invoked with None as the event. :param bind: Optional, an ``Engine`` or ``Connection``. If not supplied, a valid :class:`.Connectable` must be present in the ``.bind`` property. :param target: Optional, defaults to None. The target SchemaItem for the execute call. Will be passed to the ``on`` callable if any, and may also provide string expansion data for the statement. See ``execute_at`` for more information. """ if bind is None: bind = _bind_or_error(self) if self._should_execute(target, bind): return bind.execute(self.against(target)) else: bind.engine.logger.info( "DDL execution skipped, criteria not met.") @util.deprecated("0.7", "See :class:`.DDLEvents`, as well as " ":meth:`.DDLElement.execute_if`.") def execute_at(self, event_name, target): """Link execution of this DDL to the DDL lifecycle of a SchemaItem. Links this ``DDLElement`` to a ``Table`` or ``MetaData`` instance, executing it when that schema item is created or dropped. The DDL statement will be executed using the same Connection and transactional context as the Table create/drop itself. The ``.bind`` property of this statement is ignored. :param event: One of the events defined in the schema item's ``.ddl_events``; e.g. 'before-create', 'after-create', 'before-drop' or 'after-drop' :param target: The Table or MetaData instance for which this DDLElement will be associated with. A DDLElement instance can be linked to any number of schema items. ``execute_at`` builds on the ``append_ddl_listener`` interface of :class:`.MetaData` and :class:`.Table` objects. Caveat: Creating or dropping a Table in isolation will also trigger any DDL set to ``execute_at`` that Table's MetaData. This may change in a future release. """ def call_event(target, connection, **kw): if self._should_execute_deprecated(event_name, target, connection, **kw): return connection.execute(self.against(target)) event.listen(target, "" + event_name.replace('-', '_'), call_event) @_generative def against(self, target): """Return a copy of this DDL against a specific schema item.""" self.target = target @_generative def execute_if(self, dialect=None, callable_=None, state=None): """Return a callable that will execute this DDLElement conditionally. Used to provide a wrapper for event listening:: event.listen( metadata, 'before_create', DDL("my_ddl").execute_if(dialect='postgresql') ) :param dialect: May be a string, tuple or a callable predicate. If a string, it will be compared to the name of the executing database dialect:: DDL('something').execute_if(dialect='postgresql') If a tuple, specifies multiple dialect names:: DDL('something').execute_if(dialect=('postgresql', 'mysql')) :param callable_: A callable, which will be invoked with four positional arguments as well as optional keyword arguments: :ddl: This DDL element. :target: The :class:`.Table` or :class:`.MetaData` object which is the target of this event. May be None if the DDL is executed explicitly. :bind: The :class:`.Connection` being used for DDL execution :tables: Optional keyword argument - a list of Table objects which are to be created/ dropped within a MetaData.create_all() or drop_all() method call. :state: Optional keyword argument - will be the ``state`` argument passed to this function. :checkfirst: Keyword argument, will be True if the 'checkfirst' flag was set during the call to ``create()``, ``create_all()``, ``drop()``, ``drop_all()``. If the callable returns a true value, the DDL statement will be executed. :param state: any value which will be passed to the callable\_ as the ``state`` keyword argument. .. seealso:: :class:`.DDLEvents` :ref:`event_toplevel` """ self.dialect = dialect self.callable_ = callable_ self.state = state def _should_execute(self, target, bind, **kw): if self.on is not None and \ not self._should_execute_deprecated(None, target, bind, **kw): return False if isinstance(self.dialect, util.string_types): if self.dialect != bind.engine.name: return False elif isinstance(self.dialect, (tuple, list, set)): if bind.engine.name not in self.dialect: return False if (self.callable_ is not None and not self.callable_(self, target, bind, state=self.state, **kw)): return False return True def _should_execute_deprecated(self, event, target, bind, **kw): if self.on is None: return True elif isinstance(self.on, util.string_types): return self.on == bind.engine.name elif isinstance(self.on, (tuple, list, set)): return bind.engine.name in self.on else: return self.on(self, event, target, bind, **kw) def __call__(self, target, bind, **kw): """Execute the DDL as a ddl_listener.""" if self._should_execute(target, bind, **kw): return bind.execute(self.against(target)) def _check_ddl_on(self, on): if (on is not None and (not isinstance(on, util.string_types + (tuple, list, set)) and not util.callable(on))): raise exc.ArgumentError( "Expected the name of a database dialect, a tuple " "of names, or a callable for " "'on' criteria, got type '%s'." % type(on).__name__) def bind(self): if self._bind: return self._bind def _set_bind(self, bind): self._bind = bind bind = property(bind, _set_bind) def _generate(self): s = self.__class__.__new__(self.__class__) s.__dict__ = self.__dict__.copy() return s class DDL(DDLElement): """A literal DDL statement. Specifies literal SQL DDL to be executed by the database. DDL objects function as DDL event listeners, and can be subscribed to those events listed in :class:`.DDLEvents`, using either :class:`.Table` or :class:`.MetaData` objects as targets. Basic templating support allows a single DDL instance to handle repetitive tasks for multiple tables. Examples:: from sqlalchemy import event, DDL tbl = Table('users', metadata, Column('uid', Integer)) event.listen(tbl, 'before_create', DDL('DROP TRIGGER users_trigger')) spow = DDL('ALTER TABLE %(table)s SET secretpowers TRUE') event.listen(tbl, 'after_create', spow.execute_if(dialect='somedb')) drop_spow = DDL('ALTER TABLE users SET secretpowers FALSE') connection.execute(drop_spow) When operating on Table events, the following ``statement`` string substitions are available:: %(table)s - the Table name, with any required quoting applied %(schema)s - the schema name, with any required quoting applied %(fullname)s - the Table name including schema, quoted if needed The DDL's "context", if any, will be combined with the standard substitutions noted above. Keys present in the context will override the standard substitutions. """ __visit_name__ = "ddl" def __init__(self, statement, on=None, context=None, bind=None): """Create a DDL statement. :param statement: A string or unicode string to be executed. Statements will be processed with Python's string formatting operator. See the ``context`` argument and the ``execute_at`` method. A literal '%' in a statement must be escaped as '%%'. SQL bind parameters are not available in DDL statements. :param on: .. deprecated:: 0.7 See :meth:`.DDLElement.execute_if`. Optional filtering criteria. May be a string, tuple or a callable predicate. If a string, it will be compared to the name of the executing database dialect:: DDL('something', on='postgresql') If a tuple, specifies multiple dialect names:: DDL('something', on=('postgresql', 'mysql')) If a callable, it will be invoked with four positional arguments as well as optional keyword arguments: :ddl: This DDL element. :event: The name of the event that has triggered this DDL, such as 'after-create' Will be None if the DDL is executed explicitly. :target: The ``Table`` or ``MetaData`` object which is the target of this event. May be None if the DDL is executed explicitly. :connection: The ``Connection`` being used for DDL execution :tables: Optional keyword argument - a list of Table objects which are to be created/ dropped within a MetaData.create_all() or drop_all() method call. If the callable returns a true value, the DDL statement will be executed. :param context: Optional dictionary, defaults to None. These values will be available for use in string substitutions on the DDL statement. :param bind: Optional. A :class:`.Connectable`, used by default when ``execute()`` is invoked without a bind argument. .. seealso:: :class:`.DDLEvents` :ref:`event_toplevel` """ if not isinstance(statement, util.string_types): raise exc.ArgumentError( "Expected a string or unicode SQL statement, got '%r'" % statement) self.statement = statement self.context = context or {} self._check_ddl_on(on) self.on = on self._bind = bind def __repr__(self): return '<%s@%s; %s>' % ( type(self).__name__, id(self), ', '.join([repr(self.statement)] + ['%s=%r' % (key, getattr(self, key)) for key in ('on', 'context') if getattr(self, key)])) class _CreateDropBase(DDLElement): """Base class for DDL constructs that represent CREATE and DROP or equivalents. The common theme of _CreateDropBase is a single ``element`` attribute which refers to the element to be created or dropped. """ def __init__(self, element, on=None, bind=None): self.element = element self._check_ddl_on(on) self.on = on self.bind = bind def _create_rule_disable(self, compiler): """Allow disable of _create_rule using a callable. Pass to _create_rule using util.portable_instancemethod(self._create_rule_disable) to retain serializability. """ return False class CreateSchema(_CreateDropBase): """Represent a CREATE SCHEMA statement. .. versionadded:: 0.7.4 The argument here is the string name of the schema. """ __visit_name__ = "create_schema" def __init__(self, name, quote=None, **kw): """Create a new :class:`.CreateSchema` construct.""" self.quote = quote super(CreateSchema, self).__init__(name, **kw) class DropSchema(_CreateDropBase): """Represent a DROP SCHEMA statement. The argument here is the string name of the schema. .. versionadded:: 0.7.4 """ __visit_name__ = "drop_schema" def __init__(self, name, quote=None, cascade=False, **kw): """Create a new :class:`.DropSchema` construct.""" self.quote = quote self.cascade = cascade super(DropSchema, self).__init__(name, **kw) class CreateTable(_CreateDropBase): """Represent a CREATE TABLE statement.""" __visit_name__ = "create_table" def __init__( self, element, on=None, bind=None, include_foreign_key_constraints=None): """Create a :class:`.CreateTable` construct. :param element: a :class:`.Table` that's the subject of the CREATE :param on: See the description for 'on' in :class:`.DDL`. :param bind: See the description for 'bind' in :class:`.DDL`. :param include_foreign_key_constraints: optional sequence of :class:`.ForeignKeyConstraint` objects that will be included inline within the CREATE construct; if omitted, all foreign key constraints that do not specify use_alter=True are included. .. versionadded:: 1.0.0 """ super(CreateTable, self).__init__(element, on=on, bind=bind) self.columns = [CreateColumn(column) for column in element.columns ] self.include_foreign_key_constraints = include_foreign_key_constraints class _DropView(_CreateDropBase): """Semi-public 'DROP VIEW' construct. Used by the test suite for dialect-agnostic drops of views. This object will eventually be part of a public "view" API. """ __visit_name__ = "drop_view" class CreateColumn(_DDLCompiles): """Represent a :class:`.Column` as rendered in a CREATE TABLE statement, via the :class:`.CreateTable` construct. This is provided to support custom column DDL within the generation of CREATE TABLE statements, by using the compiler extension documented in :ref:`sqlalchemy.ext.compiler_toplevel` to extend :class:`.CreateColumn`. Typical integration is to examine the incoming :class:`.Column` object, and to redirect compilation if a particular flag or condition is found:: from sqlalchemy import schema from sqlalchemy.ext.compiler import compiles @compiles(schema.CreateColumn) def compile(element, compiler, **kw): column = element.element if "special" not in column.info: return compiler.visit_create_column(element, **kw) text = "%s SPECIAL DIRECTIVE %s" % ( column.name, compiler.type_compiler.process(column.type) ) default = compiler.get_column_default_string(column) if default is not None: text += " DEFAULT " + default if not column.nullable: text += " NOT NULL" if column.constraints: text += " ".join( compiler.process(const) for const in column.constraints) return text The above construct can be applied to a :class:`.Table` as follows:: from sqlalchemy import Table, Metadata, Column, Integer, String from sqlalchemy import schema metadata = MetaData() table = Table('mytable', MetaData(), Column('x', Integer, info={"special":True}, primary_key=True), Column('y', String(50)), Column('z', String(20), info={"special":True}) ) metadata.create_all(conn) Above, the directives we've added to the :attr:`.Column.info` collection will be detected by our custom compilation scheme:: CREATE TABLE mytable ( x SPECIAL DIRECTIVE INTEGER NOT NULL, y VARCHAR(50), z SPECIAL DIRECTIVE VARCHAR(20), PRIMARY KEY (x) ) The :class:`.CreateColumn` construct can also be used to skip certain columns when producing a ``CREATE TABLE``. This is accomplished by creating a compilation rule that conditionally returns ``None``. This is essentially how to produce the same effect as using the ``system=True`` argument on :class:`.Column`, which marks a column as an implicitly-present "system" column. For example, suppose we wish to produce a :class:`.Table` which skips rendering of the Postgresql ``xmin`` column against the Postgresql backend, but on other backends does render it, in anticipation of a triggered rule. A conditional compilation rule could skip this name only on Postgresql:: from sqlalchemy.schema import CreateColumn @compiles(CreateColumn, "postgresql") def skip_xmin(element, compiler, **kw): if element.element.name == 'xmin': return None else: return compiler.visit_create_column(element, **kw) my_table = Table('mytable', metadata, Column('id', Integer, primary_key=True), Column('xmin', Integer) ) Above, a :class:`.CreateTable` construct will generate a ``CREATE TABLE`` which only includes the ``id`` column in the string; the ``xmin`` column will be omitted, but only against the Postgresql backend. .. versionadded:: 0.8.3 The :class:`.CreateColumn` construct supports skipping of columns by returning ``None`` from a custom compilation rule. .. versionadded:: 0.8 The :class:`.CreateColumn` construct was added to support custom column creation styles. """ __visit_name__ = 'create_column' def __init__(self, element): self.element = element class DropTable(_CreateDropBase): """Represent a DROP TABLE statement.""" __visit_name__ = "drop_table" class CreateSequence(_CreateDropBase): """Represent a CREATE SEQUENCE statement.""" __visit_name__ = "create_sequence" class DropSequence(_CreateDropBase): """Represent a DROP SEQUENCE statement.""" __visit_name__ = "drop_sequence" class CreateIndex(_CreateDropBase): """Represent a CREATE INDEX statement.""" __visit_name__ = "create_index" class DropIndex(_CreateDropBase): """Represent a DROP INDEX statement.""" __visit_name__ = "drop_index" class AddConstraint(_CreateDropBase): """Represent an ALTER TABLE ADD CONSTRAINT statement.""" __visit_name__ = "add_constraint" def __init__(self, element, *args, **kw): super(AddConstraint, self).__init__(element, *args, **kw) element._create_rule = util.portable_instancemethod( self._create_rule_disable) class DropConstraint(_CreateDropBase): """Represent an ALTER TABLE DROP CONSTRAINT statement.""" __visit_name__ = "drop_constraint" def __init__(self, element, cascade=False, **kw): self.cascade = cascade super(DropConstraint, self).__init__(element, **kw) element._create_rule = util.portable_instancemethod( self._create_rule_disable) class DDLBase(SchemaVisitor): def __init__(self, connection): self.connection = connection class SchemaGenerator(DDLBase): def __init__(self, dialect, connection, checkfirst=False, tables=None, **kwargs): super(SchemaGenerator, self).__init__(connection, **kwargs) self.checkfirst = checkfirst self.tables = tables self.preparer = dialect.identifier_preparer self.dialect = dialect self.memo = {} def _can_create_table(self, table): self.dialect.validate_identifier(table.name) if table.schema: self.dialect.validate_identifier(table.schema) return not self.checkfirst or \ not self.dialect.has_table(self.connection, table.name, schema=table.schema) def _can_create_sequence(self, sequence): return self.dialect.supports_sequences and \ ( (not self.dialect.sequences_optional or not sequence.optional) and ( not self.checkfirst or not self.dialect.has_sequence( self.connection, sequence.name, schema=sequence.schema) ) ) def visit_metadata(self, metadata): if self.tables is not None: tables = self.tables else: tables = list(metadata.tables.values()) collection = sort_tables_and_constraints( [t for t in tables if self._can_create_table(t)]) seq_coll = [s for s in metadata._sequences.values() if s.column is None and self._can_create_sequence(s)] event_collection = [ t for (t, fks) in collection if t is not None ] metadata.dispatch.before_create(metadata, self.connection, tables=event_collection, checkfirst=self.checkfirst, _ddl_runner=self) for seq in seq_coll: self.traverse_single(seq, create_ok=True) for table, fkcs in collection: if table is not None: self.traverse_single( table, create_ok=True, include_foreign_key_constraints=fkcs, _is_metadata_operation=True) else: for fkc in fkcs: self.traverse_single(fkc) metadata.dispatch.after_create(metadata, self.connection, tables=event_collection, checkfirst=self.checkfirst, _ddl_runner=self) def visit_table( self, table, create_ok=False, include_foreign_key_constraints=None, _is_metadata_operation=False): if not create_ok and not self._can_create_table(table): return table.dispatch.before_create( table, self.connection, checkfirst=self.checkfirst, _ddl_runner=self, _is_metadata_operation=_is_metadata_operation) for column in table.columns: if column.default is not None: self.traverse_single(column.default) if not self.dialect.supports_alter: # e.g., don't omit any foreign key constraints include_foreign_key_constraints = None self.connection.execute( CreateTable( table, include_foreign_key_constraints=include_foreign_key_constraints )) if hasattr(table, 'indexes'): for index in table.indexes: self.traverse_single(index) table.dispatch.after_create( table, self.connection, checkfirst=self.checkfirst, _ddl_runner=self, _is_metadata_operation=_is_metadata_operation) def visit_foreign_key_constraint(self, constraint): if not self.dialect.supports_alter: return self.connection.execute(AddConstraint(constraint)) def visit_sequence(self, sequence, create_ok=False): if not create_ok and not self._can_create_sequence(sequence): return self.connection.execute(CreateSequence(sequence)) def visit_index(self, index): self.connection.execute(CreateIndex(index)) class SchemaDropper(DDLBase): def __init__(self, dialect, connection, checkfirst=False, tables=None, **kwargs): super(SchemaDropper, self).__init__(connection, **kwargs) self.checkfirst = checkfirst self.tables = tables self.preparer = dialect.identifier_preparer self.dialect = dialect self.memo = {} def visit_metadata(self, metadata): if self.tables is not None: tables = self.tables else: tables = list(metadata.tables.values()) try: unsorted_tables = [t for t in tables if self._can_drop_table(t)] collection = list(reversed( sort_tables_and_constraints( unsorted_tables, filter_fn=lambda constraint: False if not self.dialect.supports_alter or constraint.name is None else None ) )) except exc.CircularDependencyError as err2: if not self.dialect.supports_alter: util.warn( "Can't sort tables for DROP; an " "unresolvable foreign key " "dependency exists between tables: %s, and backend does " "not support ALTER. To restore at least a partial sort, " "apply use_alter=True to ForeignKey and " "ForeignKeyConstraint " "objects involved in the cycle to mark these as known " "cycles that will be ignored." % ( ", ".join(sorted([t.fullname for t in err2.cycles])) ) ) collection = [(t, ()) for t in unsorted_tables] else: util.raise_from_cause( exc.CircularDependencyError( err2.args[0], err2.cycles, err2.edges, msg="Can't sort tables for DROP; an " "unresolvable foreign key " "dependency exists between tables: %s. Please ensure " "that the ForeignKey and ForeignKeyConstraint objects " "involved in the cycle have " "names so that they can be dropped using " "DROP CONSTRAINT." % ( ", ".join(sorted([t.fullname for t in err2.cycles])) ) ) ) seq_coll = [ s for s in metadata._sequences.values() if s.column is None and self._can_drop_sequence(s) ] event_collection = [ t for (t, fks) in collection if t is not None ] metadata.dispatch.before_drop( metadata, self.connection, tables=event_collection, checkfirst=self.checkfirst, _ddl_runner=self) for table, fkcs in collection: if table is not None: self.traverse_single( table, drop_ok=True, _is_metadata_operation=True) else: for fkc in fkcs: self.traverse_single(fkc) for seq in seq_coll: self.traverse_single(seq, drop_ok=True) metadata.dispatch.after_drop( metadata, self.connection, tables=event_collection, checkfirst=self.checkfirst, _ddl_runner=self) def _can_drop_table(self, table): self.dialect.validate_identifier(table.name) if table.schema: self.dialect.validate_identifier(table.schema) return not self.checkfirst or self.dialect.has_table( self.connection, table.name, schema=table.schema) def _can_drop_sequence(self, sequence): return self.dialect.supports_sequences and \ ((not self.dialect.sequences_optional or not sequence.optional) and (not self.checkfirst or self.dialect.has_sequence( self.connection, sequence.name, schema=sequence.schema)) ) def visit_index(self, index): self.connection.execute(DropIndex(index)) def visit_table(self, table, drop_ok=False, _is_metadata_operation=False): if not drop_ok and not self._can_drop_table(table): return table.dispatch.before_drop( table, self.connection, checkfirst=self.checkfirst, _ddl_runner=self, _is_metadata_operation=_is_metadata_operation) for column in table.columns: if column.default is not None: self.traverse_single(column.default) self.connection.execute(DropTable(table)) table.dispatch.after_drop( table, self.connection, checkfirst=self.checkfirst, _ddl_runner=self, _is_metadata_operation=_is_metadata_operation) def visit_foreign_key_constraint(self, constraint): if not self.dialect.supports_alter: return self.connection.execute(DropConstraint(constraint)) def visit_sequence(self, sequence, drop_ok=False): if not drop_ok and not self._can_drop_sequence(sequence): return self.connection.execute(DropSequence(sequence)) def sort_tables(tables, skip_fn=None, extra_dependencies=None): """sort a collection of :class:`.Table` objects based on dependency. This is a dependency-ordered sort which will emit :class:`.Table` objects such that they will follow their dependent :class:`.Table` objects. Tables are dependent on another based on the presence of :class:`.ForeignKeyConstraint` objects as well as explicit dependencies added by :meth:`.Table.add_is_dependent_on`. .. warning:: The :func:`.sort_tables` function cannot by itself accommodate automatic resolution of dependency cycles between tables, which are usually caused by mutually dependent foreign key constraints. To resolve these cycles, either the :paramref:`.ForeignKeyConstraint.use_alter` parameter may be appled to those constraints, or use the :func:`.sql.sort_tables_and_constraints` function which will break out foreign key constraints involved in cycles separately. :param tables: a sequence of :class:`.Table` objects. :param skip_fn: optional callable which will be passed a :class:`.ForeignKey` object; if it returns True, this constraint will not be considered as a dependency. Note this is **different** from the same parameter in :func:`.sort_tables_and_constraints`, which is instead passed the owning :class:`.ForeignKeyConstraint` object. :param extra_dependencies: a sequence of 2-tuples of tables which will also be considered as dependent on each other. .. seealso:: :func:`.sort_tables_and_constraints` :meth:`.MetaData.sorted_tables` - uses this function to sort """ if skip_fn is not None: def _skip_fn(fkc): for fk in fkc.elements: if skip_fn(fk): return True else: return None else: _skip_fn = None return [ t for (t, fkcs) in sort_tables_and_constraints( tables, filter_fn=_skip_fn, extra_dependencies=extra_dependencies) if t is not None ] def sort_tables_and_constraints( tables, filter_fn=None, extra_dependencies=None): """sort a collection of :class:`.Table` / :class:`.ForeignKeyConstraint` objects. This is a dependency-ordered sort which will emit tuples of ``(Table, [ForeignKeyConstraint, ...])`` such that each :class:`.Table` follows its dependent :class:`.Table` objects. Remaining :class:`.ForeignKeyConstraint` objects that are separate due to dependency rules not satisifed by the sort are emitted afterwards as ``(None, [ForeignKeyConstraint ...])``. Tables are dependent on another based on the presence of :class:`.ForeignKeyConstraint` objects, explicit dependencies added by :meth:`.Table.add_is_dependent_on`, as well as dependencies stated here using the :paramref:`~.sort_tables_and_constraints.skip_fn` and/or :paramref:`~.sort_tables_and_constraints.extra_dependencies` parameters. :param tables: a sequence of :class:`.Table` objects. :param filter_fn: optional callable which will be passed a :class:`.ForeignKeyConstraint` object, and returns a value based on whether this constraint should definitely be included or excluded as an inline constraint, or neither. If it returns False, the constraint will definitely be included as a dependency that cannot be subject to ALTER; if True, it will **only** be included as an ALTER result at the end. Returning None means the constraint is included in the table-based result unless it is detected as part of a dependency cycle. :param extra_dependencies: a sequence of 2-tuples of tables which will also be considered as dependent on each other. .. versionadded:: 1.0.0 .. seealso:: :func:`.sort_tables` """ fixed_dependencies = set() mutable_dependencies = set() if extra_dependencies is not None: fixed_dependencies.update(extra_dependencies) remaining_fkcs = set() for table in tables: for fkc in table.foreign_key_constraints: if fkc.use_alter is True: remaining_fkcs.add(fkc) continue if filter_fn: filtered = filter_fn(fkc) if filtered is True: remaining_fkcs.add(fkc) continue dependent_on = fkc.referred_table if dependent_on is not table: mutable_dependencies.add((dependent_on, table)) fixed_dependencies.update( (parent, table) for parent in table._extra_dependencies ) try: candidate_sort = list( topological.sort( fixed_dependencies.union(mutable_dependencies), tables, deterministic_order=True ) ) except exc.CircularDependencyError as err: for edge in err.edges: if edge in mutable_dependencies: table = edge[1] can_remove = [ fkc for fkc in table.foreign_key_constraints if filter_fn is None or filter_fn(fkc) is not False] remaining_fkcs.update(can_remove) for fkc in can_remove: dependent_on = fkc.referred_table if dependent_on is not table: mutable_dependencies.discard((dependent_on, table)) candidate_sort = list( topological.sort( fixed_dependencies.union(mutable_dependencies), tables, deterministic_order=True ) ) return [ (table, table.foreign_key_constraints.difference(remaining_fkcs)) for table in candidate_sort ] + [(None, list(remaining_fkcs))]
mit
jhawkesworth/ansible
lib/ansible/modules/notification/catapult.py
52
4251
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2016, Jonathan Mainguy <jon@soh.re> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # # basis of code taken from the ansible twillio and nexmo modules from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: catapult version_added: 2.4 short_description: Send a sms / mms using the catapult bandwidth api description: - Allows notifications to be sent using sms / mms via the catapult bandwidth api. options: src: description: - One of your catapult telephone numbers the message should come from (must be in E.164 format, like C(+19195551212)). required: true dest: description: - The phone number or numbers the message should be sent to (must be in E.164 format, like C(+19195551212)). required: true msg: description: - The contents of the text message (must be 2048 characters or less). required: true media: description: - For MMS messages, a media url to the location of the media to be sent with the message. user_id: description: - User Id from Api account page. required: true api_token: description: - Api Token from Api account page. required: true api_secret: description: - Api Secret from Api account page. required: true author: "Jonathan Mainguy (@Jmainguy)" notes: - Will return changed even if the media url is wrong. - Will return changed if the destination number is invalid. ''' EXAMPLES = ''' - name: Send a mms to multiple users catapult: src: "+15035555555" dest: - "+12525089000" - "+12018994225" media: "http://example.com/foobar.jpg" msg: "Task is complete" user_id: "{{ user_id }}" api_token: "{{ api_token }}" api_secret: "{{ api_secret }}" - name: Send a sms to a single user catapult: src: "+15035555555" dest: "+12018994225" msg: "Consider yourself notified" user_id: "{{ user_id }}" api_token: "{{ api_token }}" api_secret: "{{ api_secret }}" ''' RETURN = ''' changed: description: Whether the api accepted the message. returned: always type: bool sample: True ''' import json from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.urls import fetch_url def send(module, src, dest, msg, media, user_id, api_token, api_secret): """ Send the message """ AGENT = "Ansible" URI = "https://api.catapult.inetwork.com/v1/users/%s/messages" % user_id data = {'from': src, 'to': dest, 'text': msg} if media: data['media'] = media headers = {'User-Agent': AGENT, 'Content-type': 'application/json'} # Hack module params to have the Basic auth params that fetch_url expects module.params['url_username'] = api_token.replace('\n', '') module.params['url_password'] = api_secret.replace('\n', '') return fetch_url(module, URI, data=json.dumps(data), headers=headers, method="post") def main(): module = AnsibleModule( argument_spec=dict( src=dict(required=True), dest=dict(required=True, type='list'), msg=dict(required=True), user_id=dict(required=True), api_token=dict(required=True, no_log=True), api_secret=dict(required=True, no_log=True), media=dict(default=None, required=False), ), ) src = module.params['src'] dest = module.params['dest'] msg = module.params['msg'] media = module.params['media'] user_id = module.params['user_id'] api_token = module.params['api_token'] api_secret = module.params['api_secret'] for number in dest: rc, info = send(module, src, number, msg, media, user_id, api_token, api_secret) if info["status"] != 201: body = json.loads(info["body"]) fail_msg = body["message"] module.fail_json(msg=fail_msg) changed = True module.exit_json(changed=changed) if __name__ == '__main__': main()
gpl-3.0
DanielSBrown/osf.io
scripts/approve_embargo_terminations.py
17
2819
"""EmbargoTerminationApprovals are the Sanction subclass that allows users to make Embargoes public before the official end date. Like RegistrationAprpovals and Embargoes, if an admin fails to approve or reject this request within 48 hours it is approved automagically. Run nightly, this script will approve any embargo termination requests for which not all admins have responded within the 48 hour window. Makes the Embargoed Node and its components public. """ import datetime import logging import sys from modularodm import Q from framework.transactions.context import TokuTransaction from framework.celery_tasks import app as celery_app from website import models, settings from website.app import init_app from scripts import utils as scripts_utils logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def get_pending_embargo_termination_requests(): auto_approve_time = datetime.datetime.now() - settings.EMBARGO_TERMINATION_PENDING_TIME return models.EmbargoTerminationApproval.find( Q('initiation_date', 'lt', auto_approve_time) & Q('state', 'eq', models.EmbargoTerminationApproval.UNAPPROVED) ) def main(): pending_embargo_termination_requests = get_pending_embargo_termination_requests() count = 0 for request in pending_embargo_termination_requests: registration = models.Node.find_one(Q('embargo_termination_approval', 'eq', request)) if not registration.is_embargoed: logger.warning("Registration {0} associated with this embargo termination request ({0}) is not embargoed.".format( registration._id, request._id )) continue embargo = registration.embargo if not embargo: logger.warning("No Embargo associated with this embargo termination request ({0}) on Node: {1}".format( request._id, registration._id )) continue else: count += 1 logger.info("Ending the Embargo ({0}) of Registration ({1}) early. Making the registration and all of its children public now.".format(embargo._id, registration._id)) request._on_complete() registration.reload() assert registration.is_embargoed is False assert registration.is_public is True logger.info("Auto-approved {0} of {1} embargo termination requests".format(count, len(pending_embargo_termination_requests))) @celery_app.task(name='scripts.approve_embargo_terminations') def run_main(dry_run=True): if not dry_run: scripts_utils.add_file_logger(logger, __file__) init_app(routes=False) with TokuTransaction(): main() if dry_run: raise RuntimeError("Dry run, rolling back transaction")
apache-2.0
cyberden/CouchPotatoServer
couchpotato/core/media/movie/providers/trailer/youtube_dl/extractor/space.py
127
1528
from __future__ import unicode_literals import re from .common import InfoExtractor from .brightcove import BrightcoveIE from ..utils import RegexNotFoundError, ExtractorError class SpaceIE(InfoExtractor): _VALID_URL = r'https?://(?:(?:www|m)\.)?space\.com/\d+-(?P<title>[^/\.\?]*?)-video\.html' _TEST = { 'add_ie': ['Brightcove'], 'url': 'http://www.space.com/23373-huge-martian-landforms-detail-revealed-by-european-probe-video.html', 'info_dict': { 'id': '2780937028001', 'ext': 'mp4', 'title': 'Huge Martian Landforms\' Detail Revealed By European Probe | Video', 'description': 'md5:db81cf7f3122f95ed234b631a6ea1e61', 'uploader': 'TechMedia Networks', }, } def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) title = mobj.group('title') webpage = self._download_webpage(url, title) try: # Some videos require the playerKey field, which isn't define in # the BrightcoveExperience object brightcove_url = self._og_search_video_url(webpage) except RegexNotFoundError: # Other videos works fine with the info from the object brightcove_url = BrightcoveIE._extract_brightcove_url(webpage) if brightcove_url is None: raise ExtractorError( 'The webpage does not contain a video', expected=True) return self.url_result(brightcove_url, BrightcoveIE.ie_key())
gpl-3.0
sbalde/edx-platform
common/djangoapps/student/tests/test_verification_status.py
20
14997
"""Tests for per-course verification status on the dashboard. """ from datetime import datetime, timedelta import unittest import ddt from mock import patch from pytz import UTC from django.core.urlresolvers import reverse from django.conf import settings from student.helpers import ( VERIFY_STATUS_NEED_TO_VERIFY, VERIFY_STATUS_SUBMITTED, VERIFY_STATUS_APPROVED, VERIFY_STATUS_MISSED_DEADLINE, VERIFY_STATUS_NEED_TO_REVERIFY ) from xmodule.modulestore.tests.factories import CourseFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from student.tests.factories import UserFactory, CourseEnrollmentFactory from course_modes.tests.factories import CourseModeFactory from verify_student.models import SoftwareSecurePhotoVerification # pylint: disable=F0401 from util.testing import UrlResetMixin @patch.dict(settings.FEATURES, {'AUTOMATIC_VERIFY_STUDENT_IDENTITY_FOR_TESTING': True}) @unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') @ddt.ddt class TestCourseVerificationStatus(UrlResetMixin, ModuleStoreTestCase): """Tests for per-course verification status on the dashboard. """ PAST = datetime.now(UTC) - timedelta(days=5) FUTURE = datetime.now(UTC) + timedelta(days=5) def setUp(self): # Invoke UrlResetMixin super(TestCourseVerificationStatus, self).setUp('verify_student.urls') self.user = UserFactory(password="edx") self.course = CourseFactory.create() success = self.client.login(username=self.user.username, password="edx") self.assertTrue(success, msg="Did not log in successfully") self.dashboard_url = reverse('dashboard') def test_enrolled_as_non_verified(self): self._setup_mode_and_enrollment(None, "honor") # Expect that the course appears on the dashboard # without any verification messaging self._assert_course_verification_status(None) def test_no_verified_mode_available(self): # Enroll the student in a verified mode, but don't # create any verified course mode. # This won't happen unless someone deletes a course mode, # but if so, make sure we handle it gracefully. CourseEnrollmentFactory( course_id=self.course.id, user=self.user, mode="verified" ) # The default course has no verified mode, # so no verification status should be displayed self._assert_course_verification_status(None) def test_need_to_verify_no_expiration(self): self._setup_mode_and_enrollment(None, "verified") # Since the student has not submitted a photo verification, # the student should see a "need to verify" message self._assert_course_verification_status(VERIFY_STATUS_NEED_TO_VERIFY) # Start the photo verification process, but do not submit # Since we haven't submitted the verification, we should still # see the "need to verify" message attempt = SoftwareSecurePhotoVerification.objects.create(user=self.user) self._assert_course_verification_status(VERIFY_STATUS_NEED_TO_VERIFY) # Upload images, but don't submit to the verification service # We should still need to verify attempt.mark_ready() self._assert_course_verification_status(VERIFY_STATUS_NEED_TO_VERIFY) def test_need_to_verify_expiration(self): self._setup_mode_and_enrollment(self.FUTURE, "verified") response = self.client.get(self.dashboard_url) self.assertContains(response, self.BANNER_ALT_MESSAGES[VERIFY_STATUS_NEED_TO_VERIFY]) self.assertContains(response, "You only have 4 days left to verify for this course.") @ddt.data(None, FUTURE) def test_waiting_approval(self, expiration): self._setup_mode_and_enrollment(expiration, "verified") # The student has submitted a photo verification attempt = SoftwareSecurePhotoVerification.objects.create(user=self.user) attempt.mark_ready() attempt.submit() # Now the student should see a "verification submitted" message self._assert_course_verification_status(VERIFY_STATUS_SUBMITTED) @ddt.data(None, FUTURE) def test_fully_verified(self, expiration): self._setup_mode_and_enrollment(expiration, "verified") # The student has an approved verification attempt = SoftwareSecurePhotoVerification.objects.create(user=self.user) attempt.mark_ready() attempt.submit() attempt.approve() # Expect that the successfully verified message is shown self._assert_course_verification_status(VERIFY_STATUS_APPROVED) # Check that the "verification good until" date is displayed response = self.client.get(self.dashboard_url) self.assertContains(response, attempt.expiration_datetime.strftime("%m/%d/%Y")) def test_missed_verification_deadline(self): # Expiration date in the past self._setup_mode_and_enrollment(self.PAST, "verified") # The student does NOT have an approved verification # so the status should show that the student missed the deadline. self._assert_course_verification_status(VERIFY_STATUS_MISSED_DEADLINE) def test_missed_verification_deadline_verification_was_expired(self): # Expiration date in the past self._setup_mode_and_enrollment(self.PAST, "verified") # Create a verification, but the expiration date of the verification # occurred before the deadline. attempt = SoftwareSecurePhotoVerification.objects.create(user=self.user) attempt.mark_ready() attempt.submit() attempt.approve() attempt.created_at = self.PAST - timedelta(days=900) attempt.save() # The student didn't have an approved verification at the deadline, # so we should show that the student missed the deadline. self._assert_course_verification_status(VERIFY_STATUS_MISSED_DEADLINE) def test_missed_verification_deadline_but_later_verified(self): # Expiration date in the past self._setup_mode_and_enrollment(self.PAST, "verified") # Successfully verify, but after the deadline has already passed attempt = SoftwareSecurePhotoVerification.objects.create(user=self.user) attempt.mark_ready() attempt.submit() attempt.approve() attempt.created_at = self.PAST - timedelta(days=900) attempt.save() # The student didn't have an approved verification at the deadline, # so we should show that the student missed the deadline. self._assert_course_verification_status(VERIFY_STATUS_MISSED_DEADLINE) def test_verification_denied(self): # Expiration date in the future self._setup_mode_and_enrollment(self.FUTURE, "verified") # Create a verification with the specified status attempt = SoftwareSecurePhotoVerification.objects.create(user=self.user) attempt.mark_ready() attempt.submit() attempt.deny("Not valid!") # Since this is not a status we handle, don't display any # messaging relating to verification self._assert_course_verification_status(None) def test_verification_error(self): # Expiration date in the future self._setup_mode_and_enrollment(self.FUTURE, "verified") # Create a verification with the specified status attempt = SoftwareSecurePhotoVerification.objects.create(user=self.user) attempt.status = "must_retry" attempt.system_error("Error!") # Since this is not a status we handle, don't display any # messaging relating to verification self._assert_course_verification_status(None) def test_verification_will_expire_by_deadline(self): # Expiration date in the future self._setup_mode_and_enrollment(self.FUTURE, "verified") # Create a verification attempt that: # 1) Is current (submitted in the last year) # 2) Will expire by the deadline for the course attempt = SoftwareSecurePhotoVerification.objects.create(user=self.user) attempt.mark_ready() attempt.submit() # This attempt will expire tomorrow, before the course deadline attempt.created_at = attempt.created_at - timedelta(days=364) attempt.save() # Expect that the "verify now" message is hidden # (since the user isn't allowed to submit another attempt while # a verification is active). self._assert_course_verification_status(VERIFY_STATUS_NEED_TO_REVERIFY) def test_verification_occurred_after_deadline(self): # Expiration date in the past self._setup_mode_and_enrollment(self.PAST, "verified") # The deadline has passed, and we've asked the student # to reverify (through the support team). attempt = SoftwareSecurePhotoVerification.objects.create(user=self.user) attempt.mark_ready() attempt.submit() # Expect that the user's displayed enrollment mode is verified. self._assert_course_verification_status(VERIFY_STATUS_APPROVED) def test_with_two_verifications(self): # checking if a user has two verification and but most recent verification course deadline is expired self._setup_mode_and_enrollment(self.FUTURE, "verified") # The student has an approved verification attempt = SoftwareSecurePhotoVerification.objects.create(user=self.user) attempt.mark_ready() attempt.submit() attempt.approve() # Making created at to previous date to differentiate with 2nd attempt. attempt.created_at = datetime.now(UTC) - timedelta(days=1) attempt.save() # Expect that the successfully verified message is shown self._assert_course_verification_status(VERIFY_STATUS_APPROVED) # Check that the "verification good until" date is displayed response = self.client.get(self.dashboard_url) self.assertContains(response, attempt.expiration_datetime.strftime("%m/%d/%Y")) # Adding another verification with different course. # Its created_at is greater than course deadline. course2 = CourseFactory.create() CourseModeFactory( course_id=course2.id, mode_slug="verified", expiration_datetime=self.PAST ) CourseEnrollmentFactory( course_id=course2.id, user=self.user, mode="verified" ) # The student has an approved verification attempt2 = SoftwareSecurePhotoVerification.objects.create(user=self.user) attempt2.mark_ready() attempt2.submit() attempt2.approve() attempt2.save() # Mark the attemp2 as approved so its date will appear on dasboard. self._assert_course_verification_status(VERIFY_STATUS_APPROVED) response2 = self.client.get(self.dashboard_url) self.assertContains(response2, attempt2.expiration_datetime.strftime("%m/%d/%Y")) self.assertEqual(response2.content.count(attempt2.expiration_datetime.strftime("%m/%d/%Y")), 2) def _setup_mode_and_enrollment(self, deadline, enrollment_mode): """Create a course mode and enrollment. Arguments: deadline (datetime): The deadline for submitting your verification. enrollment_mode (str): The mode of the enrollment. """ CourseModeFactory( course_id=self.course.id, mode_slug="verified", expiration_datetime=deadline ) CourseEnrollmentFactory( course_id=self.course.id, user=self.user, mode=enrollment_mode ) BANNER_ALT_MESSAGES = { None: "Honor", VERIFY_STATUS_NEED_TO_VERIFY: "ID verification pending", VERIFY_STATUS_SUBMITTED: "ID verification pending", VERIFY_STATUS_APPROVED: "ID Verified Ribbon/Badge", VERIFY_STATUS_MISSED_DEADLINE: "Honor", VERIFY_STATUS_NEED_TO_REVERIFY: "Honor" } NOTIFICATION_MESSAGES = { VERIFY_STATUS_NEED_TO_VERIFY: [ "You still need to verify for this course.", "Verification not yet complete" ], VERIFY_STATUS_SUBMITTED: ["Thanks for your patience as we process your request."], VERIFY_STATUS_APPROVED: ["You have already verified your ID!"], VERIFY_STATUS_NEED_TO_REVERIFY: ["Your verification will expire soon!"] } MODE_CLASSES = { None: "honor", VERIFY_STATUS_NEED_TO_VERIFY: "verified", VERIFY_STATUS_SUBMITTED: "verified", VERIFY_STATUS_APPROVED: "verified", VERIFY_STATUS_MISSED_DEADLINE: "honor", VERIFY_STATUS_NEED_TO_REVERIFY: "honor" } def _assert_course_verification_status(self, status): """Check whether the specified verification status is shown on the dashboard. Arguments: status (str): One of the verification status constants. If None, check that *none* of the statuses are displayed. Raises: AssertionError """ response = self.client.get(self.dashboard_url) # Sanity check: verify that the course is on the page self.assertContains(response, unicode(self.course.id)) # Verify that the correct banner is rendered on the dashboard self.assertContains(response, self.BANNER_ALT_MESSAGES[status]) # Verify that the correct banner color is rendered self.assertContains( response, "<article class=\"course {}\">".format(self.MODE_CLASSES[status]) ) # Verify that the correct copy is rendered on the dashboard if status is not None: if status in self.NOTIFICATION_MESSAGES: # Different states might have different messaging # so in some cases we check several possibilities # and fail if none of these are found. found_msg = False for message in self.NOTIFICATION_MESSAGES[status]: if message in response.content: found_msg = True break fail_msg = "Could not find any of these messages: {expected}".format( expected=self.NOTIFICATION_MESSAGES[status] ) self.assertTrue(found_msg, msg=fail_msg) else: # Combine all possible messages into a single list all_messages = [] for msg_group in self.NOTIFICATION_MESSAGES.values(): all_messages.extend(msg_group) # Verify that none of the messages are displayed for msg in all_messages: self.assertNotContains(response, msg)
agpl-3.0
JoseBlanca/ngs_crumbs
test/seq/test_guess_seq_format.py
1
8427
# Copyright 2012 Jose Blanca, Peio Ziarsolo, COMAV-Univ. Politecnica Valencia # This file is part of ngs_crumbs. # ngs_crumbs 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. # ngs_crumbs 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 ngs_crumbs. If not, see <http://www.gnu.org/licenses/>. import unittest import os.path from subprocess import check_output, CalledProcessError from tempfile import NamedTemporaryFile from StringIO import StringIO from crumbs.utils.bin_utils import SEQ_BIN_DIR from crumbs.seq.utils.file_formats import get_format, _guess_format from crumbs.exceptions import (UnknownFormatError, FileIsEmptyError, UndecidedFastqVersionError) # pylint: disable=R0201 # pylint: disable=R0904 class GuessFormatBinTest(unittest.TestCase): 'It tests the guess_seq_format binary' def test_guess_format(self): 'It tests guess_seq_format' guess_bin = os.path.join(SEQ_BIN_DIR, 'guess_seq_format') assert 'usage' in check_output([guess_bin, '-h']) # a fasta file fasta_fhand = NamedTemporaryFile() fasta_fhand.write('>seq\nACTA\n') fasta_fhand.flush() assert check_output([guess_bin, fasta_fhand.name]) == 'fasta\n' # Unknown_format bad_fhand = NamedTemporaryFile() bad_fhand.write('bad file') bad_fhand.flush() stderr = NamedTemporaryFile() try: check_output([guess_bin, bad_fhand.name], stderr=stderr) self.fail('Error expected') except CalledProcessError: assert open(stderr.name).read().startswith('Sequence file of unkn') def test_stdin(self): 'It works with stdin' guess_bin = os.path.join(SEQ_BIN_DIR, 'guess_seq_format') fasta_fhand = NamedTemporaryFile() fasta_fhand.write('>seq\nACTA\n') fasta_fhand.flush() fmt = check_output([guess_bin], stdin=open(fasta_fhand.name)) assert fmt == 'fasta\n' def test_version(self): 'It can return its version number' guess_bin = os.path.join(SEQ_BIN_DIR, 'guess_seq_format') stderr = NamedTemporaryFile() check_output([guess_bin, '--version'], stderr=stderr) assert 'from ngs_crumbs version:' in open(stderr.name).read() class GuessFormatTest(unittest.TestCase): 'It tests the function that guess the sequence format' def test_fasta(self): 'It guess fasta formats' fhand = StringIO('>seq\nACTC\n') assert get_format(fhand) == 'fasta' # multiline fasta fhand = StringIO('>seq\nACTC\nACTG\n>seq2\nACTG\n') assert get_format(fhand) == 'fasta' # qual fhand = StringIO('>seq\n10 20\n') assert get_format(fhand) == 'qual' # qual qual = ">seq1\n30 30 30 30 30 30 30 30\n>seq2\n30 30 30 30 30 30 30" qual += " 30\n>seq3\n30 30 30 30 30 30 30 30\n" fhand = StringIO(qual) assert get_format(fhand) == 'qual' def test_with_long_desc(self): fhand = StringIO('''>comp27222_c1_seq1 len=4926 path=[89166356:0-46 89167522:47-85 89315292:86-121 89170132:122-176 89377211:177-217 89377235:218-244 89172846:245-247 89172856:248-251 89173028:252-276 89174386:277-292 89174684:293-506 89377352:507-582 89183669:583-587 89183821:588-613 89184868:614-644 89185624:645-719 89187914:720-723 89187935:724-870 89191280:871-887 89377494:888-907 89191517:908-927 89193046:928-1071 89198507:1072-1109 89199632:1110-1170 89201544:1171-1194 89202607:1195-1247 89377606:1248-1252 89377611:1253-1591 89215759:1592-1606 89215815:1607-1636 89216359:1637-1664 89377693:1665-1678 88727916:1679-2152 88743802:2153-2171 88744738:2172-2623 88759485:2624-2648 88759762:2649-2953 88769199:2954-2971 88769596:2972-3657 88791809:3658-3665 88792014:3666-3723 88793720:3724-3731 88794381:3732-3812 88799277:3813-3813 88799328:3814-3996 88807093:3997-3999 88807177:4000-4215 88813164:4216-4246 88814188:4247-4287 88815355:4288-4308 88816198:4309-4352 88817845:4353-4369 88818294:4370-4403 88818879:4404-4465 88821150:4466-4469 88821188:4470-4925] GAAGGATCGATCGGCCTCGGCGGTGTTCCCAAAAATCTAAGAGCGTTTACTCCAAGCTTC''') get_format(fhand) def test_unkown(self): 'It tests unkown formats' fhand = StringIO('xseq\nACTC\n') try: get_format(fhand) self.fail('UnknownFormatError expected') except UnknownFormatError: pass def test_empty_file(self): 'It guesses the format of an empty file' fhand = StringIO() try: get_format(fhand) self.fail('FileIsEmptyError expected') except FileIsEmptyError: pass def test_fastq(self): 'It guesses the format for the solexa and illumina fastq' txt = '@HWI-EAS209_0006_FC706VJ:5:58:5894:21141#ATCACG/1\n' txt += 'TTAATTGGTAAATAAATCTCCTAATAGCTTAGATNTTACCTTNNNNNNNNNNTAGTTTCT\n' txt += '+HWI-EAS209_0006_FC706VJ:5:58:5894:21141#ATCACG/1\n' txt += 'efcfffffcfeefffcffffffddf`feed]`]_Ba_^__[YBBBBBBBBBBRTT\]][]\n' fhand = StringIO(txt) assert get_format(fhand) == 'fastq-illumina' txt = '@HWI-EAS209_0006_FC706VJ:5:58:5894:21141#ATCACG/1\n' txt += 'TTAATTGGTAAATAAATCTCCTAATAGCTTAGATNTTACCTTNNNNNNNNNNTAGTTTCT\n' txt += 'TTAATTGGTAAATAAATCTCCTAATAGCTTAGATNTTACCTTNNNNNNNNNNTAGTTTCT\n' txt += '+HWI-EAS209_0006_FC706VJ:5:58:5894:21141#ATCACG/1\n' txt += 'efcfffffcfeefffcffffffddf`feed]`]_Ba_^__[YBBBBBBBBBBRTT\]][]\n' txt += 'efcfffffcfeefffcffffffddf`feed]`]_Ba_^__[YBBBBBBBBBBRTT\]][]\n' fhand = StringIO(txt + txt) assert get_format(fhand) == 'fastq-illumina' fhand = StringIO('@HWI-EAS209\n@') try: assert get_format(fhand) == 'fasta' self.fail('UndecidedFastqVersionError expected') except UndecidedFastqVersionError: pass # sanger txt = '@HWI-EAS209_0006_FC706VJ:5:58:5894:21141#ATCACG/1\n' txt += 'TTAATTGGTAAATAAATCTCCTAATAGCTTAGATNTTACCTTNNNNNNNNNNTAGTTTCT\n' txt += '+HWI-EAS209_0006_FC706VJ:5:58:5894:21141#ATCACG/1\n' txt += '000000000000000000000000000000000000000000000000000000000000\n' fhand = StringIO(txt) assert get_format(fhand) == 'fastq' def test_long_illumina(self): 'The qualities seem illumina, but the reads are too lengthly' txt = '@read\n' txt += 'T' * 400 + '\n' txt += '+\n' txt += '@' * 400 + '\n' fhand = StringIO(txt) try: get_format(fhand) self.fail('UndecidedFastqVersionError expected') except UndecidedFastqVersionError: pass def test_non_seekable(self): 'Fastq version guessing using the non-seekable route' txt = '@HWI-EAS209_0006_FC706VJ:5:58:5894:21141#ATCACG/1\n' txt += 'TTAATTGGTAAATAAATCTCCTAATAGCTTAGATNTTACCTTNNNNNNNNNNTAGTTTCT\n' txt += '+HWI-EAS209_0006_FC706VJ:5:58:5894:21141#ATCACG/1\n' txt += 'efcfffffcfeefffcffffffddf`feed]`]_Ba_^__[YBBBBBBBBBBRTT\]][]\n' fhand = StringIO(txt) assert _guess_format(fhand, True) == 'fastq-illumina' fhand = StringIO('@HWI-EAS209\n@') try: assert _guess_format(fhand, True) == 'fasta' self.fail('UndecidedFastqVersionError expected') except UndecidedFastqVersionError: pass # sanger txt = '@HWI-EAS209_0006_FC706VJ:5:58:5894:21141#ATCACG/1\n' txt += 'TTAATTGGTAAATAAATCTCCTAATAGCTTAGATNTTACCTTNNNNNNNNNNTAGTTTCT\n' txt += '+HWI-EAS209_0006_FC706VJ:5:58:5894:21141#ATCACG/1\n' txt += '000000000000000000000000000000000000000000000000000000000000\n' fhand = StringIO(txt) assert _guess_format(fhand, True) == 'fastq' if __name__ == '__main__': #import sys;sys.argv = ['', 'SffExtractTest.test_items_in_gff'] unittest.main()
gpl-3.0
eamars/webserver
site-package/roster/sql.py
1
4194
import mysql.connector SQL_CREATE_TABLE = \ """ CREATE TABLE `{}` ( `date` date NOT NULL UNIQUE, `chair` char(64) NOT NULL DEFAULT '', `minute` char(64) NOT NULL DEFAULT '', PRIMARY KEY (`date`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 """ def create_database(cursor, database_name): try: cursor.execute("CREATE DATABASE `{}` DEFAULT CHARACTER SET 'utf8'".format(database_name)) except mysql.connector.Error as e: print("Error [{}]: failed to create database [{}]".format(e, database_name)) raise Exception("MySQL") def create_table(cursor, table_name): try: cursor.execute(SQL_CREATE_TABLE.format(table_name)) except mysql.connector.Error as e: print("Error [{}]: failed to create table [{}]".format(e, table_name)) raise Exception("MySQL") def establish_connection(config): # Connection to server connection = mysql.connector.connect(**config) return connection def close_connection(connection): connection.close() def connect_database(connection, database_name): # Connect to database, or create a new one try: connection.database = database_name except mysql.connector.Error as e: if e.errno == 1049: # Get cursor cursor = connection.cursor() print("Creating database [{}]".format(database_name)) create_database(cursor, database_name) # Close cursor cursor.close() connection.database = database_name else: print("Error [{}]: connect database".format(e)) raise Exception("MySQL") def entry_exists(connection, table_name, condition): cursor = connection.cursor() sql = "SELECT COUNT(*) FROM `{}` WHERE {}".format(table_name, condition) # print(sql) try: cursor.execute(sql) for result in cursor: if result[0] == 0: cursor.close() return False else: cursor.close() return True except mysql.connector.Error as e: if e.errno == 1146: # Table doesn't exist print("Creating table [{}]".format(table_name)) create_table(cursor, table_name) cursor.close() return False else: print("Error [{}]: entry exists".format(e)) print(sql) cursor.close() raise Exception("MySQL") def fetch_entry(connection, table_name, condition): cursor = connection.cursor() sql = "SELECT `chair`, `minute` from `{}` WHERE {}".format(table_name, condition) try: cursor.execute(sql) for result in cursor: return result[0], result[1] except mysql.connector.Error as e: if e.errno == 1146: # Table doesn't exist print("Creating table [{}]".format(table_name)) create_table(cursor, table_name) cursor.close() return False else: print("Error [{}]: entry exists".format(e)) print(sql) cursor.close() raise Exception("MySQL") def insert_entry(connection, table_name, value): cursor = connection.cursor() sql = "INSERT INTO `{}` {}".format(table_name, value) # print(sql) try: cursor.execute(sql) cursor.close() except mysql.connector.Error as e: if e.errno == 1146: # Table doesn't exist print("Creating table [{}]".format(table_name)) create_table(cursor, table_name) # Try to execute again cursor.execute(sql) cursor.close() else: print("Error [{}]: insert entry".format(e)) print(sql) cursor.close() raise Exception("MySQL") def main(): SQL_CONFIG = { "host": "192.168.2.5", "user": "eamars", "password": "931105", "autocommit": True } connection = establish_connection(SQL_CONFIG) connect_database(connection, "test") print(entry_exists(connection, "roster", "chair=`Ran Bao`")) close_connection(connection) if __name__ == "__main__": main()
mit
vhanla/CudaText
app/cudatext.app/Contents/Resources/py/cuda_addonman/work_cudatext_updates.py
4
2356
import sys import os import re import platform import tempfile import webbrowser import cudatext as app from .work_remote import * p = sys.platform X64 = platform.architecture()[0]=='64bit' ##p = 'win32' ##X64 = False DOWNLOAD_PAGE = \ 'https://sourceforge.net/projects/cudatext/files/release/Linux/' if p.startswith('linux')\ else 'https://sourceforge.net/projects/cudatext/files/release/Windows/' if p.startswith('win')\ else 'https://sourceforge.net/projects/cudatext/files/release/macOS/' if p=='darwin'\ else 'https://sourceforge.net/projects/cudatext/files/release/FreeBSD/' if p.startswith('freebsd')\ else '?' if p=='darwin': TEXT_CPU = '' REGEX_GROUP_VER = 1 else: TEXT_CPU = '(amd64|x64)' if X64 else '(i386|x32)' REGEX_GROUP_VER = 2 DOWNLOAD_REGEX = \ ' href="(\w+://[\w\.]+/projects/cudatext/files/release/\w+/cudatext-[\w\-]+?'+TEXT_CPU+'[\w\-]*?-([\d\.]+?)\.(zip|dmg|tar\.xz)/download)"' def versions_ordered(s1, s2): """ compare "1.10.0" and "1.9.0" correctly """ n1 = list(map(int, s1.split('.'))) n2 = list(map(int, s2.split('.'))) return n1<=n2 def check_cudatext(): fn = os.path.join(tempfile.gettempdir(), 'cudatext_download.html') app.msg_status('Downloading: '+DOWNLOAD_PAGE, True) get_url(DOWNLOAD_PAGE, fn, True) app.msg_status('') if not os.path.isfile(fn): app.msg_status('Cannot download: '+DOWNLOAD_PAGE) return text = open(fn, encoding='utf8').read() items = re.findall(DOWNLOAD_REGEX, text) if not items: app.msg_status('Cannot find download links') return items = sorted(items, key=lambda i:i[REGEX_GROUP_VER], reverse=True) print('Found links:') for i in items: print(' '+i[0]) url = items[0][0] ver_inet = items[0][REGEX_GROUP_VER] ver_local = app.app_exe_version() if versions_ordered(ver_inet, ver_local): app.msg_box('Latest CudaText is already here.\nLocal: %s\nInternet: %s' %(ver_local, ver_inet), app.MB_OK+app.MB_ICONINFO) return if app.msg_box('CudaText update is available.\nLocal: %s\nInternet: %s\n\nOpen download URL in browser?' %(ver_local, ver_inet), app.MB_YESNO+app.MB_ICONINFO) == app.ID_YES: webbrowser.open_new_tab(url) print('Opened download URL')
mpl-2.0
YongseopKim/coreclr
src/ToolBox/SOS/tests/t_cmd_name2ee.py
43
1390
import lldb import re import testutils as test def runScenario(assembly, debugger, target): process = target.GetProcess() res = lldb.SBCommandReturnObject() ci = debugger.GetCommandInterpreter() # Run debugger, wait until libcoreclr is loaded, # set breakpoint at Test.Main and stop there test.stop_in_main(debugger, assembly) ci.HandleCommand("name2ee " + assembly + " Test.Main", res) print(res.GetOutput()) print(res.GetError()) # Interpreter must have this command and able to run it test.assertTrue(res.Succeeded()) output = res.GetOutput() # Output is not empty test.assertTrue(len(output) > 0) match = re.search('Module:\s+[0-9a-fA-F]+', output) test.assertTrue(match) match = re.search('Assembly:\s+\S+', output) test.assertTrue(match) match = re.search('Token:\s+[0-9a-fA-F]+', output) test.assertTrue(match) match = re.search('MethodDesc:\s+[0-9a-fA-F]+', output) test.assertTrue(match) match = re.search('Name:\s+\S+', output) test.assertTrue(match) process.Continue() # Process must exit test.assertEqual(process.GetState(), lldb.eStateExited) # Process must exit with zero code test.assertEqual(process.GetExitStatus(), 0) # TODO: test other use cases # Continue current process and checks its exit code test.exit_lldb(debugger, assembly)
mit
coberger/DIRAC
WorkloadManagementSystem/JobWrapper/WatchdogLinux.py
4
4118
######################################################################## # $HeadURL$ # Author: Stuart Paterson # eMail : Stuart.Paterson@cern.ch ######################################################################## """ The Watchdog class is used by the Job Wrapper to resolve and monitor the system CPU and memory consumed. The Watchdog can determine if a running job is stalled and indicate this to the Job Wrapper. This is the Unix / Linux compatible Watchdog subclass. """ __RCSID__ = "$Id$" from DIRAC.WorkloadManagementSystem.JobWrapper.Watchdog import Watchdog from DIRAC.Core.Utilities.Subprocess import shellCall from DIRAC import S_OK, S_ERROR from DIRAC.Core.Utilities.Os import getDiskSpace import string import socket class WatchdogLinux(Watchdog): def __init__(self, pid, thread, spObject, jobCPUtime, memoryLimit = 0, systemFlag='linux'): """ Constructor, takes system flag as argument. """ Watchdog.__init__( self, pid, thread, spObject, jobCPUtime, memoryLimit, systemFlag ) self.systemFlag = systemFlag self.pid = pid ############################################################################ def getNodeInformation(self): """Try to obtain system HostName, CPU, Model, cache and memory. This information is not essential to the running of the jobs but will be reported if available. """ result = S_OK() try: cpuInfo = open ( "/proc/cpuinfo", "r" ) info = cpuInfo.readlines() cpuInfo.close() result["HostName"] = socket.gethostname() result["CPU(MHz)"] = string.replace(string.replace(string.split(info[6],":")[1]," ",""),"\n","") result["ModelName"] = string.replace(string.replace(string.split(info[4],":")[1]," ",""),"\n","") result["CacheSize(kB)"] = string.replace(string.replace(string.split(info[7],":")[1]," ",""),"\n","") memInfo = open ( "/proc/meminfo", "r" ) info = memInfo.readlines() memInfo.close() result["Memory(kB)"] = string.replace(string.replace(string.split(info[3],":")[1]," ",""),"\n","") account = 'Unknown' localID = shellCall(10,'whoami') if localID['OK']: account = localID['Value'][1].strip() result["LocalAccount"] = account except Exception, x: self.log.fatal('Watchdog failed to obtain node information with Exception:') self.log.fatal(str(x)) result = S_ERROR() result['Message']='Failed to obtain system information for '+self.systemFlag return result return result ############################################################################ def getLoadAverage(self): """Obtains the load average. """ result = S_OK() comm = '/bin/cat /proc/loadavg' loadAvgDict = shellCall(5,comm) if loadAvgDict['OK']: la = float(string.split(loadAvgDict['Value'][1])[0]) result['Value'] = la else: result = S_ERROR('Could not obtain load average') self.log.warn('Could not obtain load average') result['Value'] = 0 return result ############################################################################# def getMemoryUsed(self): """Obtains the memory used. """ result = S_OK() comm = '/usr/bin/free' memDict = shellCall(5,comm) if memDict['OK']: mem = string.split(memDict['Value'][1]) [8] result['Value'] = float(mem) else: result = S_ERROR('Could not obtain memory used') self.log.warn('Could not obtain memory used') result['Value'] = 0 return result ############################################################################# def getDiskSpace(self): """Obtains the disk space used. """ result = S_OK() diskSpace = getDiskSpace() if diskSpace == -1: result = S_ERROR('Could not obtain disk usage') self.log.warn('Could not obtain disk usage') result['Value'] = -1 result['Value'] = float(diskSpace) return result #EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#
gpl-3.0
Gateworks/platform-external-chromium_org
third_party/protobuf/python/google/protobuf/internal/wire_format.py
561
8431
# Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # http://code.google.com/p/protobuf/ # # 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. """Constants and static functions to support protocol buffer wire format.""" __author__ = 'robinson@google.com (Will Robinson)' import struct from google.protobuf import descriptor from google.protobuf import message TAG_TYPE_BITS = 3 # Number of bits used to hold type info in a proto tag. TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1 # 0x7 # These numbers identify the wire type of a protocol buffer value. # We use the least-significant TAG_TYPE_BITS bits of the varint-encoded # tag-and-type to store one of these WIRETYPE_* constants. # These values must match WireType enum in google/protobuf/wire_format.h. WIRETYPE_VARINT = 0 WIRETYPE_FIXED64 = 1 WIRETYPE_LENGTH_DELIMITED = 2 WIRETYPE_START_GROUP = 3 WIRETYPE_END_GROUP = 4 WIRETYPE_FIXED32 = 5 _WIRETYPE_MAX = 5 # Bounds for various integer types. INT32_MAX = int((1 << 31) - 1) INT32_MIN = int(-(1 << 31)) UINT32_MAX = (1 << 32) - 1 INT64_MAX = (1 << 63) - 1 INT64_MIN = -(1 << 63) UINT64_MAX = (1 << 64) - 1 # "struct" format strings that will encode/decode the specified formats. FORMAT_UINT32_LITTLE_ENDIAN = '<I' FORMAT_UINT64_LITTLE_ENDIAN = '<Q' FORMAT_FLOAT_LITTLE_ENDIAN = '<f' FORMAT_DOUBLE_LITTLE_ENDIAN = '<d' # We'll have to provide alternate implementations of AppendLittleEndian*() on # any architectures where these checks fail. if struct.calcsize(FORMAT_UINT32_LITTLE_ENDIAN) != 4: raise AssertionError('Format "I" is not a 32-bit number.') if struct.calcsize(FORMAT_UINT64_LITTLE_ENDIAN) != 8: raise AssertionError('Format "Q" is not a 64-bit number.') def PackTag(field_number, wire_type): """Returns an unsigned 32-bit integer that encodes the field number and wire type information in standard protocol message wire format. Args: field_number: Expected to be an integer in the range [1, 1 << 29) wire_type: One of the WIRETYPE_* constants. """ if not 0 <= wire_type <= _WIRETYPE_MAX: raise message.EncodeError('Unknown wire type: %d' % wire_type) return (field_number << TAG_TYPE_BITS) | wire_type def UnpackTag(tag): """The inverse of PackTag(). Given an unsigned 32-bit number, returns a (field_number, wire_type) tuple. """ return (tag >> TAG_TYPE_BITS), (tag & TAG_TYPE_MASK) def ZigZagEncode(value): """ZigZag Transform: Encodes signed integers so that they can be effectively used with varint encoding. See wire_format.h for more details. """ if value >= 0: return value << 1 return (value << 1) ^ (~0) def ZigZagDecode(value): """Inverse of ZigZagEncode().""" if not value & 0x1: return value >> 1 return (value >> 1) ^ (~0) # The *ByteSize() functions below return the number of bytes required to # serialize "field number + type" information and then serialize the value. def Int32ByteSize(field_number, int32): return Int64ByteSize(field_number, int32) def Int32ByteSizeNoTag(int32): return _VarUInt64ByteSizeNoTag(0xffffffffffffffff & int32) def Int64ByteSize(field_number, int64): # Have to convert to uint before calling UInt64ByteSize(). return UInt64ByteSize(field_number, 0xffffffffffffffff & int64) def UInt32ByteSize(field_number, uint32): return UInt64ByteSize(field_number, uint32) def UInt64ByteSize(field_number, uint64): return TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(uint64) def SInt32ByteSize(field_number, int32): return UInt32ByteSize(field_number, ZigZagEncode(int32)) def SInt64ByteSize(field_number, int64): return UInt64ByteSize(field_number, ZigZagEncode(int64)) def Fixed32ByteSize(field_number, fixed32): return TagByteSize(field_number) + 4 def Fixed64ByteSize(field_number, fixed64): return TagByteSize(field_number) + 8 def SFixed32ByteSize(field_number, sfixed32): return TagByteSize(field_number) + 4 def SFixed64ByteSize(field_number, sfixed64): return TagByteSize(field_number) + 8 def FloatByteSize(field_number, flt): return TagByteSize(field_number) + 4 def DoubleByteSize(field_number, double): return TagByteSize(field_number) + 8 def BoolByteSize(field_number, b): return TagByteSize(field_number) + 1 def EnumByteSize(field_number, enum): return UInt32ByteSize(field_number, enum) def StringByteSize(field_number, string): return BytesByteSize(field_number, string.encode('utf-8')) def BytesByteSize(field_number, b): return (TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(len(b)) + len(b)) def GroupByteSize(field_number, message): return (2 * TagByteSize(field_number) # START and END group. + message.ByteSize()) def MessageByteSize(field_number, message): return (TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(message.ByteSize()) + message.ByteSize()) def MessageSetItemByteSize(field_number, msg): # First compute the sizes of the tags. # There are 2 tags for the beginning and ending of the repeated group, that # is field number 1, one with field number 2 (type_id) and one with field # number 3 (message). total_size = (2 * TagByteSize(1) + TagByteSize(2) + TagByteSize(3)) # Add the number of bytes for type_id. total_size += _VarUInt64ByteSizeNoTag(field_number) message_size = msg.ByteSize() # The number of bytes for encoding the length of the message. total_size += _VarUInt64ByteSizeNoTag(message_size) # The size of the message. total_size += message_size return total_size def TagByteSize(field_number): """Returns the bytes required to serialize a tag with this field number.""" # Just pass in type 0, since the type won't affect the tag+type size. return _VarUInt64ByteSizeNoTag(PackTag(field_number, 0)) # Private helper function for the *ByteSize() functions above. def _VarUInt64ByteSizeNoTag(uint64): """Returns the number of bytes required to serialize a single varint using boundary value comparisons. (unrolled loop optimization -WPierce) uint64 must be unsigned. """ if uint64 <= 0x7f: return 1 if uint64 <= 0x3fff: return 2 if uint64 <= 0x1fffff: return 3 if uint64 <= 0xfffffff: return 4 if uint64 <= 0x7ffffffff: return 5 if uint64 <= 0x3ffffffffff: return 6 if uint64 <= 0x1ffffffffffff: return 7 if uint64 <= 0xffffffffffffff: return 8 if uint64 <= 0x7fffffffffffffff: return 9 if uint64 > UINT64_MAX: raise message.EncodeError('Value out of range: %d' % uint64) return 10 NON_PACKABLE_TYPES = ( descriptor.FieldDescriptor.TYPE_STRING, descriptor.FieldDescriptor.TYPE_GROUP, descriptor.FieldDescriptor.TYPE_MESSAGE, descriptor.FieldDescriptor.TYPE_BYTES ) def IsTypePackable(field_type): """Return true iff packable = true is valid for fields of this type. Args: field_type: a FieldDescriptor::Type value. Returns: True iff fields of this type are packable. """ return field_type not in NON_PACKABLE_TYPES
bsd-3-clause
elizahyde/goog-python-learning
basic/solution/list2.py
207
2774
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # Additional basic list exercises # D. Given a list of numbers, return a list where # all adjacent == elements have been reduced to a single element, # so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or # modify the passed in list. def remove_adjacent(nums): # +++your code here+++ # LAB(begin solution) result = [] for num in nums: if len(result) == 0 or num != result[-1]: result.append(num) return result # LAB(replace solution) # return # LAB(end solution) # E. Given two lists sorted in increasing order, create and return a merged # list of all the elements in sorted order. You may modify the passed in lists. # Ideally, the solution should work in "linear" time, making a single # pass of both lists. def linear_merge(list1, list2): # +++your code here+++ # LAB(begin solution) result = [] # Look at the two lists so long as both are non-empty. # Take whichever element [0] is smaller. while len(list1) and len(list2): if list1[0] < list2[0]: result.append(list1.pop(0)) else: result.append(list2.pop(0)) # Now tack on what's left result.extend(list1) result.extend(list2) return result # LAB(replace solution) # return # LAB(end solution) # Note: the solution above is kind of cute, but unforunately list.pop(0) # is not constant time with the standard python list implementation, so # the above is not strictly linear time. # An alternate approach uses pop(-1) to remove the endmost elements # from each list, building a solution list which is backwards. # Then use reversed() to put the result back in the correct order. That # solution works in linear time, but is more ugly. # Simple provided test() function used in main() to print # what each function returns vs. what it's supposed to return. def test(got, expected): if got == expected: prefix = ' OK ' else: prefix = ' X ' print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected)) # Calls the above functions with interesting inputs. def main(): print 'remove_adjacent' test(remove_adjacent([1, 2, 2, 3]), [1, 2, 3]) test(remove_adjacent([2, 2, 3, 3, 3]), [2, 3]) test(remove_adjacent([]), []) print print 'linear_merge' test(linear_merge(['aa', 'xx', 'zz'], ['bb', 'cc']), ['aa', 'bb', 'cc', 'xx', 'zz']) test(linear_merge(['aa', 'xx'], ['bb', 'cc', 'zz']), ['aa', 'bb', 'cc', 'xx', 'zz']) test(linear_merge(['aa', 'aa'], ['aa', 'bb', 'bb']), ['aa', 'aa', 'aa', 'bb', 'bb']) if __name__ == '__main__': main()
apache-2.0
crazy-cat/incubator-mxnet
example/speech-demo/lstm_proj.py
25
7073
# 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. # pylint:skip-file import mxnet as mx import numpy as np from collections import namedtuple LSTMState = namedtuple("LSTMState", ["c", "h"]) LSTMParam = namedtuple("LSTMParam", ["i2h_weight", "i2h_bias", "h2h_weight", "h2h_bias", "ph2h_weight", "c2i_bias", "c2f_bias", "c2o_bias"]) LSTMModel = namedtuple("LSTMModel", ["rnn_exec", "symbol", "init_states", "last_states", "seq_data", "seq_labels", "seq_outputs", "param_blocks"]) def lstm(num_hidden, indata, prev_state, param, seqidx, layeridx, dropout=0., num_hidden_proj=0): """LSTM Cell symbol""" if dropout > 0.: indata = mx.sym.Dropout(data=indata, p=dropout) i2h = mx.sym.FullyConnected(data=indata, weight=param.i2h_weight, bias=param.i2h_bias, num_hidden=num_hidden * 4, name="t%d_l%d_i2h" % (seqidx, layeridx)) h2h = mx.sym.FullyConnected(data=prev_state.h, weight=param.h2h_weight, #bias=param.h2h_bias, no_bias=True, num_hidden=num_hidden * 4, name="t%d_l%d_h2h" % (seqidx, layeridx)) gates = i2h + h2h slice_gates = mx.sym.SliceChannel(gates, num_outputs=4, name="t%d_l%d_slice" % (seqidx, layeridx)) Wcidc = mx.sym.broadcast_mul(param.c2i_bias, prev_state.c) + slice_gates[0] in_gate = mx.sym.Activation(Wcidc, act_type="sigmoid") in_transform = mx.sym.Activation(slice_gates[1], act_type="tanh") Wcfdc = mx.sym.broadcast_mul(param.c2f_bias, prev_state.c) + slice_gates[2] forget_gate = mx.sym.Activation(Wcfdc, act_type="sigmoid") next_c = (forget_gate * prev_state.c) + (in_gate * in_transform) Wcoct = mx.sym.broadcast_mul(param.c2o_bias, next_c) + slice_gates[3] out_gate = mx.sym.Activation(Wcoct, act_type="sigmoid") next_h = out_gate * mx.sym.Activation(next_c, act_type="tanh") if num_hidden_proj > 0: proj_next_h = mx.sym.FullyConnected(data=next_h, weight=param.ph2h_weight, no_bias=True, num_hidden=num_hidden_proj, name="t%d_l%d_ph2h" % (seqidx, layeridx)) return LSTMState(c=next_c, h=proj_next_h) else: return LSTMState(c=next_c, h=next_h) def lstm_unroll(num_lstm_layer, seq_len, input_size, num_hidden, num_label, dropout=0., output_states=False, take_softmax=True, num_hidden_proj=0): cls_weight = mx.sym.Variable("cls_weight") cls_bias = mx.sym.Variable("cls_bias") param_cells = [] last_states = [] for i in range(num_lstm_layer): param_cells.append(LSTMParam(i2h_weight = mx.sym.Variable("l%d_i2h_weight" % i), i2h_bias = mx.sym.Variable("l%d_i2h_bias" % i), h2h_weight = mx.sym.Variable("l%d_h2h_weight" % i), h2h_bias = mx.sym.Variable("l%d_h2h_bias" % i), ph2h_weight = mx.sym.Variable("l%d_ph2h_weight" % i), c2i_bias = mx.sym.Variable("l%d_c2i_bias" % i, shape=(1,num_hidden)), c2f_bias = mx.sym.Variable("l%d_c2f_bias" % i, shape=(1,num_hidden)), c2o_bias = mx.sym.Variable("l%d_c2o_bias" % i, shape=(1, num_hidden)) )) state = LSTMState(c=mx.sym.Variable("l%d_init_c" % i), h=mx.sym.Variable("l%d_init_h" % i)) last_states.append(state) assert(len(last_states) == num_lstm_layer) data = mx.sym.Variable('data') label = mx.sym.Variable('softmax_label') dataSlice = mx.sym.SliceChannel(data=data, num_outputs=seq_len, squeeze_axis=1) hidden_all = [] for seqidx in range(seq_len): hidden = dataSlice[seqidx] # stack LSTM for i in range(num_lstm_layer): if i == 0: dp = 0. else: dp = dropout next_state = lstm(num_hidden, indata=hidden, prev_state=last_states[i], param=param_cells[i], seqidx=seqidx, layeridx=i, dropout=dp, num_hidden_proj=num_hidden_proj) hidden = next_state.h last_states[i] = next_state # decoder if dropout > 0.: hidden = mx.sym.Dropout(data=hidden, p=dropout) hidden_all.append(hidden) hidden_concat = mx.sym.Concat(*hidden_all, dim=1) if num_hidden_proj > 0: hidden_final = mx.sym.Reshape(hidden_concat, target_shape=(0, num_hidden_proj)) else: hidden_final = mx.sym.Reshape(hidden_concat, target_shape=(0, num_hidden)) pred = mx.sym.FullyConnected(data=hidden_final, num_hidden=num_label, weight=cls_weight, bias=cls_bias, name='pred') pred = mx.sym.Reshape(pred, shape=(-1, num_label)) label = mx.sym.Reshape(label, shape=(-1,)) if take_softmax: sm = mx.sym.SoftmaxOutput(data=pred, label=label, ignore_label=0, use_ignore=True, name='softmax') else: sm = pred if output_states: # block the gradients of output states for i in range(num_lstm_layer): state = last_states[i] state = LSTMState(c=mx.sym.BlockGrad(state.c, name="l%d_last_c" % i), h=mx.sym.BlockGrad(state.h, name="l%d_last_h" % i)) last_states[i] = state # also output states, used in truncated-bptt to copy over states unpack_c = [state.c for state in last_states] unpack_h = [state.h for state in last_states] sm = mx.sym.Group([sm] + unpack_c + unpack_h) return sm
apache-2.0
hoytak/SFrame
cxxtest/python/cxxtest/cxxtest_fog.py
55
4022
#------------------------------------------------------------------------- # CxxTest: A lightweight C++ unit testing library. # Copyright (c) 2008 Sandia Corporation. # This software is distributed under the LGPL License v3 # For more information, see the COPYING file in the top CxxTest directory. # Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, # the U.S. Government retains certain rights in this software. #------------------------------------------------------------------------- # # TODO: add line number info # TODO: add test function names # from __future__ import division import sys import re from cxxtest_misc import abort import cxx_parser import re def cstr( str ): '''Convert a string to its C representation''' return '"' + re.sub('\\\\', '\\\\\\\\', str ) + '"' def scanInputFiles(files, _options): '''Scan all input files for test suites''' suites=[] for file in files: try: print "Parsing file "+file, sys.stdout.flush() parse_info = cxx_parser.parse_cpp(filename=file,optimize=1) except IOError, err: print " error." print str(err) continue print "done." sys.stdout.flush() # # WEH: see if it really makes sense to use parse information to # initialize this data. I don't think so... # _options.haveStandardLibrary=1 if not parse_info.noExceptionLogic: _options.haveExceptionHandling=1 # keys = list(parse_info.index.keys()) tpat = re.compile("[Tt][Ee][Ss][Tt]") for key in keys: if parse_info.index[key].scope_t == "class" and parse_info.is_baseclass(key,"CxxTest::TestSuite"): name=parse_info.index[key].name if key.startswith('::'): fullname = key[2:] else: fullname = key suite = { 'fullname' : fullname, 'name' : name, 'file' : file, 'cfile' : cstr(file), 'line' : str(parse_info.index[key].lineno), 'generated' : 0, 'object' : 'suite_%s' % fullname.replace('::','_'), 'dobject' : 'suiteDescription_%s' % fullname.replace('::','_'), 'tlist' : 'Tests_%s' % fullname.replace('::','_'), 'tests' : [], 'lines' : [] } for fn in parse_info.get_functions(key,quiet=True): tname = fn[0] lineno = str(fn[1]) if tname.startswith('createSuite'): # Indicate that we're using a dynamically generated test suite suite['create'] = str(lineno) # (unknown line) if tname.startswith('destroySuite'): # Indicate that we're using a dynamically generated test suite suite['destroy'] = str(lineno) # (unknown line) if not tpat.match(tname): # Skip non-test methods continue test = { 'name' : tname, 'suite' : suite, 'class' : 'TestDescription_suite_%s_%s' % (suite['fullname'].replace('::','_'), tname), 'object' : 'testDescription_suite_%s_%s' % (suite['fullname'].replace('::','_'), tname), 'line' : lineno, } suite['tests'].append(test) suites.append(suite) if not _options.root: ntests = 0 for suite in suites: ntests += len(suite['tests']) if ntests == 0: abort( 'No tests defined' ) # return [_options, suites]
bsd-3-clause
shear/rppy
rppy/fluid.py
2
5952
#!/usr/bin/env python # -*- coding: utf-8 -*- # rppy - a geophysical library for Python # Copyright (c) 2014, Sean M. Contenti # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. 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. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; # OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import numpy as np def ciz_shapiro(K0, Kdry, Kf, u0, udry, uf, phi, Kphi=None, uphi=None): """ Generalized form of Gassmann's equation to perform fluid substitution to allow for a solid (non-zero shear modulus) pore-filling material. """ if Kphi is None: Kphi = K0 Ksat = (1/Kdry - (1/Kdry - 1/K0)**2 / (phi*(1/Kf - 1/Kphi) + (1/Kdry - 1/K0))) usat = (1/udry - (1/udry - 1/u0)**2 / (phi*(1/uf - 1/uphi) + (1/udry - 1/u0))) return(Ksat, usat) def gassmann(K0, Kin, Kfin, Kfout, phi): """ Use Gassmann's equation to perform fluid substitution. Use the bulk modulus of a rock saturated with one fluid (or dry frame, Kfin=0) to preduct the bulk modulus of a rock second with a second fluid. :param K0: Frame mineral modulus (Gpa) :param Kin: Input rock modulus (can be fluid saturated or dry) :param Kfin: Bulk modulus of the pore-filling fluid of the inital rock (0 if input is the dry-rock modulus) :param Kfout: Bulk modulus of the pore-filling fluid of the output (0 if output is dry-rock modulus) :param phi: Porosity of the rock """ A = Kfout / (phi*(K0 - Kfout)) B = Kin / (K0 - Kin) C = Kfin / (phi*(K0 - Kfin)) D = A + B - C Kout = K0*D / (1 + D) return(Kout) def batzle_wang(P, T, fluid, S=None, G=None, api=None): """ Calculate the elastic properties of reservoir fluids using the Batzle & Wang [1992] equations. :param P: Pressure (MPa) :param T: Temperature {deg C) :param fluid: Fluid type to calculate: brine, gas, or oil :param S: Salinity (brine only, in ppm) :param G: Gas gravity (gas mode only, ratio of gas density to air density at 15.6C and atmospheric pressure) :param api: American Petroleum Insitute (API) oil gravity """ if fluid == 'brine': S = S / (10**6) # ppm to fraction of one w = np.array([ [1402.85, 1.524, 3.437e-3, -1.197e-5], [4.871, -0.0111, 1.739e-4, -1.628e-6], [-0.04783, 2.747e-4, -2.135e-6, 1.237e-8], [1.487e-4, -6.503e-7, -1.455e-8, 1.327e-10], [-2.197e-7, 7.987e-10, 5.230e-11, -4.614e-13], ]) rhow = (1 + (10**-6)*(-80*T - 3.3*(T**2) + 0.00175*(T**3) + 489*P - 2*T*P + 0.016*(T**2)*P - (1.3e-5)*(T**3)*P - 0.333*(P**2) - 0.002*T*(P**2))) rhob = rhow + S*(0.668 + 0.44*S + (10**-6)*(300*P - 2400*P*S + T*(80 + 3*T - 3300*S - 13*P + 47*P*S))) Vw = 0 for i in range(4): for j in range(3): Vw = Vw + w[i][j]*T**i*P**j Vb = (Vw + S*(1170 - 9.8*T + 0.055*T**2 - 8.5e-5*T**3 + 2.6*P - 0.0029*T*P - 0.0476*P**2) + S**(3/2)*(780 - 10*P + 0.16*P**2) - 1820*S**2) out = {'rho': rhob, 'Vp': Vb} elif fluid == 'oil': Rg = 2.03*G*(P*np.exp(0.02878*api - 0.00377*T))**1.205 rho0 = 141.5 / (api + 131.5) B0 = 0.972 + 0.00038*(2.4*Rg*(G/rho0)**0.5 + T + 17.8)**(1.175) rho_r = (rho0/B0)*(1 + 0.001*Rg)**-1 # pseudo-density of oil rhog = (rho0 + 0.0012*G*Rg)/B0 # density of oil with gas rhop = (rhog + (0.00277*P - # correct for pressure 1.71e-7*P**3)*(rhog - 1.15)**2 + 3.49e-4*P) rho = rhop / (0.972 + 3.81e-4*(T + 17.78)**1.175) # correct for temp Vp = 2096*(rho_r / (2.6 - rho_r))**0.5 - 3.7*T + 4.64*P + 0.0115*( 4.12*(1.08/rho_r - 1)**0.5 -1)*T*P out = {'rho': rho, 'Vp': Vp} elif fluid == 'gas': Ta = T + 273.15 # absolute temperature Pr = P / (4.892 - 0.4048*G) # pseudo-pressure Tr = Ta / (94.72 + 170.75*G) # pseudo-temperature R = 8.31441 d = np.exp(-(0.45 + 8*(0.56 - 1/Tr)**2)*Pr**1.2/Tr) c = 0.109*(3.85 - Tr)**2 b = 0.642*Tr - 0.007*Tr**4 - 0.52 a = 0.03 + 0.00527*(3.5 - Tr)**3 m = 1.2*(-(0.45 + 8*(0.56 - 1/Tr)**2)*Pr**0.2/Tr) y = (0.85 + 5.6/(Pr + 2) + 27.1/(Pr + 3.5)**2 - 8.7*np.exp(-0.65*(Pr + 1))) f = c*d*m + a E = c*d Z = a*Pr + b + E rhog = (28.8*G*P) / (Z*R*Ta) Kg = P*y / (1 - Pr*f/Z) out = {'rho': rhog, 'K': Kg} else: out = None return(out)
bsd-2-clause
cmacmackin/ford
ford/graphs.py
1
48315
#!/usr/bin/env python # -*- coding: utf-8 -*- # # graphs.py # This file is part of FORD. # # Copyright 2015 Christopher MacMackin <cmacmackin@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301, USA. # # from __future__ import print_function import os import shutil import re import copy import colorsys from graphviz import Digraph from ford.sourceform import FortranFunction, FortranSubroutine, FortranInterface, FortranProgram, FortranType, FortranModule, FortranSubmodule, FortranSubmoduleProcedure, FortranSourceFile, FortranBlockData _coloured_edges = False def set_coloured_edges(val): ''' Public accessor to set whether to use coloured edges in graph or just use black ones. ''' global _coloured_edges _coloured_edges = val _parentdir = '' def set_graphs_parentdir(val): ''' Public accessor to set the parent directory of the graphs. Needed for relative paths. ''' global _parentdir _parentdir = val def rainbowcolour(depth, maxd): if _coloured_edges: (r, g, b) = colorsys.hsv_to_rgb(float(depth) / maxd, 1.0, 1.0) R, G, B = int(255 * r), int(255 * g), int(255 * b) return R, G, B else: return 0, 0, 0 HYPERLINK_RE = re.compile("^\s*<\s*a\s+.*href=(\"[^\"]+\"|'[^']+').*>(.*)</\s*a\s*>\s*$",re.IGNORECASE) WIDTH_RE = re.compile('width="(.*?)pt"',re.IGNORECASE) HEIGHT_RE = re.compile('height="(.*?)pt"',re.IGNORECASE) EM_RE = re.compile('<em>(.*)</em>',re.IGNORECASE) graphviz_installed = True def newdict(old,key,val): new = copy.copy(old) new[key] = val return new def is_module(obj,cls): return isinstance(obj,FortranModule) or issubclass(cls,FortranModule) def is_submodule(obj,cls): return isinstance(obj,FortranSubmodule) or issubclass(cls,FortranSubmodule) def is_type(obj,cls): return isinstance(obj,FortranType) or issubclass(cls,FortranType) def is_proc(obj,cls): return (isinstance(obj,(FortranFunction,FortranSubroutine, FortranInterface,FortranSubmoduleProcedure)) or issubclass(cls,(FortranFunction,FortranSubroutine, FortranInterface,FortranSubmoduleProcedure))) def is_program(obj, cls): return isinstance(obj,FortranProgram) or issubclass(cls,FortranProgram) def is_sourcefile(obj, cls): return isinstance(obj,FortranSourceFile) or issubclass(cls,FortranSourceFile) def is_blockdata(obj, cls): return isinstance(obj,FortranBlockData) or issubclass(cls,FortranBlockData) class GraphData(object): """ Contains all of the nodes which may be displayed on a graph. """ def __init__(self): self.submodules = {} self.modules = {} self.types = {} self.procedures = {} self.programs = {} self.sourcefiles = {} self.blockdata = {} def register(self,obj,cls=type(None),hist={}): """ Takes a FortranObject and adds it to the appropriate list, if not already present. """ #~ ident = getattr(obj,'ident',obj) if is_submodule(obj,cls): if obj not in self.submodules: self.submodules[obj] = SubmodNode(obj,self) elif is_module(obj,cls): if obj not in self.modules: self.modules[obj] = ModNode(obj,self) elif is_type(obj,cls): if obj not in self.types: self.types[obj] = TypeNode(obj,self,hist) elif is_proc(obj,cls): if obj not in self.procedures: self.procedures[obj] = ProcNode(obj,self,hist) elif is_program(obj,cls): if obj not in self.programs: self.programs[obj] = ProgNode(obj,self) elif is_sourcefile(obj,cls): if obj not in self.sourcefiles: self.sourcefiles[obj] = FileNode(obj,self) elif is_blockdata(obj,cls): if obj not in self.blockdata: self.blockdata[obj] = BlockNode(obj,self) else: raise BadType("Object type {} not recognized by GraphData".format(type(obj).__name__)) def get_node(self,obj,cls=type(None),hist={}): """ Returns the node corresponding to obj. If does not already exist then it will create it. """ #~ ident = getattr(obj,'ident',obj) if obj in self.modules and is_module(obj,cls): return self.modules[obj] elif obj in self.submodules and is_submodule(obj,cls): return self.submodules[obj] elif obj in self.types and is_type(obj,cls): return self.types[obj] elif obj in self.procedures and is_proc(obj,cls): return self.procedures[obj] elif obj in self.programs and is_program(obj,cls): return self.programs[obj] elif obj in self.sourcefiles and is_sourcefile(obj,cls): return self.sourcefiles[obj] elif obj in self.blockdata and is_blockdata(obj,cls): return self.blockdata[obj] else: self.register(obj,cls,hist) return self.get_node(obj,cls,hist) class BaseNode(object): colour = '#777777' def __init__(self,obj): self.attribs = {'color':self.colour, 'fontcolor':'white', 'style':'filled'} self.fromstr = type(obj) is str self.url = None if self.fromstr: m = HYPERLINK_RE.match(obj) if m: self.url = m.group(1)[1:-1] self.name = m.group(2) else: self.name = obj self.ident = self.name else: d = obj.get_dir() if not d: d = 'none' self.ident = d + '~' + obj.ident self.name = obj.name m = EM_RE.search(self.name) if m: self.name = '<<i>'+m.group(1).strip()+'</i>>' self.url = obj.get_url() self.attribs['label'] = self.name if self.url and getattr(obj,'visible',True): if self.fromstr: self.attribs['URL'] = self.url else: self.attribs['URL'] = _parentdir + self.url self.afferent = 0 self.efferent = 0 def __eq__(self, other): return self.ident == other.ident def __hash__(self): return hash(self.ident) class ModNode(BaseNode): colour = '#337AB7' def __init__(self,obj,gd): super(ModNode,self).__init__(obj) self.uses = set() self.used_by = set() self.children = set() if not self.fromstr: for u in obj.uses: n = gd.get_node(u,FortranModule) n.used_by.add(self) n.afferent += 1 self.uses.add(n) self.efferent += n.efferent class SubmodNode(ModNode): colour = '#5bc0de' def __init__(self,obj,gd): super(SubmodNode,self).__init__(obj,gd) del self.used_by if not self.fromstr: if obj.ancestor: self.ancestor = gd.get_node(obj.ancestor,FortranSubmodule) else: self.ancestor = gd.get_node(obj.ancestor_mod,FortranModule) self.ancestor.children.add(self) self.efferent += 1 self.ancestor.afferent += 1 class TypeNode(BaseNode): colour = '#5cb85c' def __init__(self,obj,gd,hist={}): super(TypeNode,self).__init__(obj) self.ancestor = None self.children = set() self.comp_types = dict() self.comp_of = dict() if not self.fromstr: if obj.extends: if obj.extends in hist: self.ancestor = hist[obj.extends] else: self.ancestor = gd.get_node(obj.extends,FortranType,newdict(hist,obj,self)) self.ancestor.children.add(self) self.ancestor.visible = getattr(obj.extends,'visible',True) for var in obj.local_variables: if (var.vartype == 'type' or var.vartype == 'class') and var.proto[0] != '*': if var.proto[0] == obj: n = self elif var.proto[0] in hist: n = hist[var.proto[0]] else: n = gd.get_node(var.proto[0],FortranType,newdict(hist,obj,self)) n.visible = getattr(var.proto[0],'visible',True) if self in n.comp_of: n.comp_of[self] += ', ' + var.name else: n.comp_of[self] = var.name if n in self.comp_types: self.comp_types[n] += ', ' + var.name else: self.comp_types[n] = var.name class ProcNode(BaseNode): @property def colour(self): if self.proctype.lower() == 'subroutine': return '#d9534f' elif self.proctype.lower() == 'function': return '#d94e8f' elif self.proctype.lower() == 'interface': return '#A7506F' #~ return '#c77c25' else: return super(ProcNode,self).colour def __init__(self,obj,gd,hist={}): #ToDo: Figure out appropriate way to handle interfaces to routines in submodules. self.proctype = getattr(obj,'proctype','') super(ProcNode,self).__init__(obj) self.uses = set() self.calls = set() self.called_by = set() self.interfaces = set() self.interfaced_by = set() if not self.fromstr: for u in getattr(obj,'uses',[]): n = gd.get_node(u,FortranModule) n.used_by.add(self) self.uses.add(n) for c in getattr(obj,'calls',[]): if getattr(c,'visible',True): if c == obj: n = self elif c in hist: n = hist[c] else: n = gd.get_node(c,FortranSubroutine,newdict(hist,obj,self)) n.called_by.add(self) self.calls.add(n) if obj.proctype.lower() == 'interface': for m in getattr(obj,'modprocs',[]): if m.procedure and getattr(m.procedure,'visible',True): if m.procedure in hist: n = hist[m.procedure] else: n = gd.get_node(m.procedure,FortranSubroutine,newdict(hist,obj,self)) n.interfaced_by.add(self) self.interfaces.add(n) if hasattr(obj,'procedure') and obj.procedure.module and obj.procedure.module != True and getattr(obj.procedure.module,'visible',True): if obj.procedure.module in hist: n = hist[obj.procedure.module] else: n = gd.get_node(obj.procedure.module,FortranSubroutine,newdict(hist,obj,self)) n.interfaced_by.add(self) self.interfaces.add(n) class ProgNode(BaseNode): colour = '#f0ad4e' def __init__(self,obj,gd): super(ProgNode,self).__init__(obj) self.uses = set() self.calls = set() if not self.fromstr: for u in obj.uses: n = gd.get_node(u,FortranModule) n.used_by.add(self) self.uses.add(n) for c in obj.calls: if getattr(c,'visible',True): n = gd.get_node(c,FortranSubroutine) n.called_by.add(self) self.calls.add(n) class BlockNode(BaseNode): colour = '#5cb85c' def __init__(self,obj,gd): super(BlockNode,self).__init__(obj) self.uses = set() if not self.fromstr: for u in obj.uses: n = gd.get_node(u,FortranModule) n.used_by.add(self) self.uses.add(n) class FileNode(BaseNode): colour = '#f0ad4e' def __init__(self,obj,gd,hist={}): super(FileNode,self).__init__(obj) self.afferent = set() # Things depending on this file self.efferent = set() # Things this file depends on if not self.fromstr: for mod in obj.modules: for dep in mod.deplist: if dep.hierarchy[0] == obj: continue elif dep.hierarchy[0] in hist: n = hist[dep.hierarchy[0]] else: n = gd.get_node(dep.hierarchy[0],FortranSourceFile,newdict(hist,obj,self)) n.afferent.add(self) self.efferent.add(n) for mod in obj.submodules: for dep in mod.deplist: if dep.hierarchy[0] == obj: continue elif dep.hierarchy[0] in hist: n = hist[dep.hierarchy[0]] else: n = gd.get_node(dep.hierarchy[0],FortranSourceFile,newdict(hist,obj,self)) n.afferent.add(self) self.efferent.add(n) for proc in obj.functions + obj.subroutines: for dep in proc.deplist: if dep.hierarchy[0] == obj: continue elif dep.hierarchy[0] in hist: n = hist[dep.hierarchy[0]] else: n = gd.get_node(dep.hierarchy[0],FortranSourceFile,newdict(hist,obj,self)) n.afferent.add(self) self.efferent.add(n) for prog in obj.programs: for dep in prog.deplist: if dep.hierarchy[0] == obj: continue elif dep.hierarchy[0] in hist: n = hist[dep.hierarchy[0]] else: n = gd.get_node(dep.hierarchy[0],FortranSourceFile,newdict(hist,obj,self)) n.afferent.add(self) self.efferent.add(n) for block in obj.blockdata: for dep in block.deplist: if dep.hierarchy[0] == obj: continue elif dep.hierarchy[0] in hist: n = hist[dep.hierarchy[0]] else: n = gd.get_node(dep.hierarchy[0],FortranSourceFile,newdict(hist,obj,self)) n.afferent.add(self) self.efferent.add(n) class FortranGraph(object): """ Object used to construct the graph for some particular entity in the code. """ data = GraphData() RANKDIR = 'RL' def __init__(self,root,webdir='',ident=None): """ Initialize the graph, root is the object or list of objects, for which the graph is to be constructed. The webdir is the url where the graph should be stored, and ident can be provided to override the default identifacation of the graph that will be used to construct the name of the imagefile. It has to be provided if there are multiple root nodes. """ self.root = [] # root nodes self.hopNodes = [] # nodes of the hop which exceeded the maximum self.hopEdges = [] # edges of the hop which exceeded the maximum self.added = set() # nodes added to the graph self.max_nesting = 0 # maximum numbers of hops allowed self.max_nodes = 1 # maximum numbers of nodes allowed self.warn = False # should warnings be written? self.truncated = -1 # nesting where the graph was truncated try: for r in root: self.root.append(self.data.get_node(r)) self.max_nesting = max(self.max_nesting, int(r.meta['graph_maxdepth'])) self.max_nodes = max(self.max_nodes, int(r.meta['graph_maxnodes'])) self.warn = self.warn or (r.settings['warn'].lower() == 'true') except TypeError: self.root.append(self.data.get_node(root)) self.max_nesting = int(root.meta['graph_maxdepth']) self.max_nodes = max(self.max_nodes, int(root.meta['graph_maxnodes'])) self.warn = root.settings['warn'].lower() == 'true' self.webdir = webdir if ident: self.ident = ident + '~~' + self.__class__.__name__ else: self.ident = root.get_dir() + '~~' + root.ident + '~~' + self.__class__.__name__ self.imgfile = self.ident self.dot = Digraph(self.ident, graph_attr={'size':'8.90625,1000.0', 'rankdir':self.RANKDIR, 'concentrate':'true', 'id':self.ident}, node_attr={'shape':'box', 'height':'0.0', 'margin':'0.08', 'fontname':'Helvetica', 'fontsize':'10.5'}, edge_attr={'fontname':'Helvetica', 'fontsize':'9.5'}, format='svg', engine='dot') # add root nodes to the graph for n in self.root: if len(self.root) == 1: self.dot.node(n.ident, label=n.name) else: self.dot.node(n.ident, **n.attribs) self.added.add(n) # add nodes and edges depending on the root nodes to the graph self.add_nodes(self.root) #~ self.linkmap = self.dot.pipe('cmapx').decode('utf-8') if graphviz_installed: self.svg_src = self.dot.pipe().decode('utf-8') self.svg_src = self.svg_src.replace('<svg ','<svg id="' + re.sub('[^\w]','',self.ident) + '" ') w = int(WIDTH_RE.search(self.svg_src).group(1)) if isinstance(self,(ModuleGraph,CallGraph,TypeGraph)): self.scaled = (w >= 855) else: self.scaled = (w >= 641) else: self.svg_src = '' self.scaled = False def add_to_graph(self, nodes, edges, nesting): """ Adds nodes and edges to the graph as long as the maximum number of nodes is not exceeded. All edges are expected to have a reference to an entry in nodes. If the list of nodes is not added in the first hop due to graph size limitations, they are stored in hopNodes. If the graph was extended the function returns True, otherwise the result will be False. """ if (len(nodes) + len(self.added)) > self.max_nodes: if nesting < 2: self.hopNodes = nodes self.hopEdges = edges self.truncated = nesting return False else: for n in nodes: self.dot.node(n.ident, **n.attribs) for e in edges: if len(e) == 5: self.dot.edge(e[0].ident, e[1].ident, style=e[2], color=e[3], label=e[4]) else: self.dot.edge(e[0].ident, e[1].ident, style=e[2], color=e[3]) self.added.update(nodes) return True def __str__(self): """ The string of the graph is its HTML representation. It will only be created if it is not too large. If the graph is overly large but can represented by a single node with many dependencies it will be shown as a table instead to ease the rendering in browsers. """ graph_as_table = len(self.hopNodes) > 0 and len(self.root) == 1 # Do not render empty graphs if len(self.added) <= 1 and not graph_as_table: return '' # Do not render overly large graphs. if len(self.added) > self.max_nodes: if self.warn: print('Warning: Not showing graph {0} as it would exceed the maximal number of {1} nodes.' .format(self.ident,self.max_nodes)) # Only warn once about this self.warn = False return '' # Do not render incomplete graphs. if len(self.added) < len(self.root): if self.warn: print('Warning: Not showing graph {0} as it would be incomplete.'.format(self.ident)) # Only warn once about this self.warn = False return '' if self.warn and self.truncated > 0: print('Warning: Graph {0} is truncated after {1} hops.'.format(self.ident,self.truncated)) # Only warn once about this self.warn = False zoomName = '' svgGraph = '' rettext = '' if graph_as_table: # generate a table graph if maximum number of nodes gets exceeded in # the first hop and there is only one root node. root = '<td class="root" rowspan="{0}">{1}</td>'.format( len(self.hopNodes) * 2 + 1, self.root[0].attribs['label']) if self.hopEdges[0][0].ident == self.root[0].ident: key = 1 root_on_left = (self.RANKDIR == 'LR') if root_on_left: arrowtemp = ('<td class="{0}{1}">{2}</td><td rowspan="2"' + 'class="triangle-right"></td>') else: arrowtemp = ('<td rowspan="2" class="triangle-left">' + '</td><td class="{0}{1}">{2}</td>') else: key = 0 root_on_left = (self.RANKDIR == 'RL') if root_on_left: arrowtemp = ('<td rowspan="2" class="triangle-left">' + '</td><td class="{0}{1}">{2}</td>') else: arrowtemp = ('<td class="{0}{1}">{2}</td><td rowspan="2"' + 'class="triangle-right"></td>') # sort nodes in alphabetical order self.hopEdges.sort(key=lambda x: x[key].attribs['label'].lower()) rows = '' for i in range(len(self.hopEdges)): e = self.hopEdges[i] n = e[key] if len(e) == 5: arrow = arrowtemp.format(e[2], 'Text', e[4]) else: arrow = arrowtemp.format(e[2], 'Bottom', 'w') node = '<td rowspan="2" class="node" bgcolor="{0}">'.format( n.attribs['color']) try: node += '<a href="{0}">{1}</a></td>'.format( n.attribs['URL'], n.attribs['label']) except: node += n.attribs['label'] + '</td>' if root_on_left: rows += '<tr>' + root + arrow + node + '</tr>\n' else: rows += '<tr>' + node + arrow + root + '</tr>\n' rows += '<tr><td class="{0}Top">w</td></tr>\n'.format(e[2]) root = '' rettext += '<table class="graph">\n' + rows + '</table>\n' # generate svg graph else: rettext += '<div class="depgraph">{0}</div>' svgGraph = self.svg_src # add zoom ability for big graphs if self.scaled: zoomName = re.sub('[^\w]', '', self.ident) rettext += ('<script>var pan{1} = svgPanZoom(\'#{1}\', ' '{{zoomEnabled: true,controlIconsEnabled: true, ' 'fit: true, center: true,}}); </script>') rettext += ('<div><a type="button" class="graph-help" ' 'data-toggle="modal" href="#graph-help-text">Help</a>' '</div><div class="modal fade" id="graph-help-text" ' 'tabindex="-1" role="dialog"><div class="modal-dialog ' 'modal-lg" role="document"><div class="modal-content">' '<div class="modal-header"><button type="button" ' 'class="close" data-dismiss="modal" aria-label="Close">' '<span aria-hidden="true">&times;</span></button><h4 class' '="modal-title" id="-graph-help-label">Graph Key</h4>' '</div><div class="modal-body">{2}</div></div></div>' '</div>') return rettext.format(svgGraph, zoomName, self.get_key()) def __nonzero__(self): return self.__bool__() def __bool__(self): return(bool(self.__str__())) @classmethod def reset(cls): cls.data = GraphData() def create_svg(self, out_location): if len(self.added) > len(self.root): self._create_image_file(os.path.join(out_location, self.imgfile)) def _create_image_file(self,filename): if graphviz_installed: self.dot.render(filename,cleanup=False) shutil.move(filename,os.path.join(os.path.dirname(filename), os.path.basename(filename)+'.gv')) class ModuleGraph(FortranGraph): def get_key(self): colour_notice = COLOURED_NOTICE if _coloured_edges else '' return MOD_GRAPH_KEY.format(colour_notice) def add_nodes(self, nodes, nesting=1): """ Adds nodes and edges for generating the graph showing the relationship between modules and submodules listed in nodes. """ hopNodes = set() # nodes in this hop hopEdges = [] # edges in this hop # get nodes and edges for this hop for i, n in zip(range(len(nodes)), nodes): r, g, b = rainbowcolour(i, len(nodes)) colour = '#%02X%02X%02X' % (r, g, b) for nu in n.uses: if nu not in self.added: hopNodes.add(nu) hopEdges.append((n, nu, 'dashed', colour)) if hasattr(n, 'ancestor'): if n.ancestor not in self.added: hopNodes.add(n.ancestor) hopEdges.append((n, n.ancestor, 'solid', colour)) # add nodes, edges and attributes to the graph if maximum number of # nodes is not exceeded if self.add_to_graph(hopNodes, hopEdges, nesting): self.dot.attr('graph', size='11.875,1000.0') class UsesGraph(FortranGraph): def get_key(self): colour_notice = COLOURED_NOTICE if _coloured_edges else '' return MOD_GRAPH_KEY.format(colour_notice) def add_nodes(self, nodes, nesting=1): """ Adds nodes for the modules used by those listed in nodes. Adds edges between them. Also does this for ancestor (sub)modules. """ hopNodes = set() # nodes in this hop hopEdges = [] # edges in this hop # get nodes and edges for this hop for i, n in zip(range(len(nodes)), nodes): r, g, b = rainbowcolour(i, len(nodes)) colour = '#%02X%02X%02X' % (r, g, b) for nu in n.uses: if nu not in self.added: hopNodes.add(nu) hopEdges.append((n, nu, 'dashed', colour)) if hasattr(n, 'ancestor'): if n.ancestor not in self.added: hopNodes.add(n.ancestor) hopEdges.append((n, n.ancestor, 'solid', colour)) # add nodes and edges for this hop to the graph if maximum number of # nodes is not exceeded if not self.add_to_graph(hopNodes, hopEdges, nesting): return elif len(hopNodes) > 0: if nesting < self.max_nesting: self.add_nodes(hopNodes, nesting=nesting+1) else: self.truncated = nesting class UsedByGraph(FortranGraph): def get_key(self): colour_notice = COLOURED_NOTICE if _coloured_edges else '' return MOD_GRAPH_KEY.format(colour_notice) def add_nodes(self, nodes, nesting=1): """ Adds nodes for modules using or descended from those listed in nodes. Adds appropriate edges between them. """ hopNodes = set() # nodes in this hop hopEdges = [] # edges in this hop # get nodes and edges for this hop for i, n in zip(range(len(nodes)), nodes): r, g, b = rainbowcolour(i, len(nodes)) colour = '#%02X%02X%02X' % (r, g, b) for nu in getattr(n, 'used_by', []): if nu not in self.added: hopNodes.add(nu) hopEdges.append((nu, n, 'dashed', colour)) for c in getattr(n, 'children', []): if c not in self.added: hopNodes.add(c) hopEdges.append((c, n, 'solid', colour)) # add nodes and edges for this hop to the graph if maximum number of # nodes is not exceeded if not self.add_to_graph(hopNodes, hopEdges, nesting): return elif len(hopNodes) > 0: if nesting < self.max_nesting: self.add_nodes(hopNodes, nesting=nesting+1) else: self.truncated = nesting class FileGraph(FortranGraph): def get_key(self): colour_notice = COLOURED_NOTICE if _coloured_edges else '' return FILE_GRAPH_KEY.format(colour_notice) def add_nodes(self, nodes, nesting=1): """ Adds edges showing dependencies between source files listed in the nodes. """ hopNodes = set() # nodes in this hop hopEdges = [] # edges in this hop # get nodes and edges for this hop for i, n in zip(range(len(nodes)), nodes): r, g, b = rainbowcolour(i, len(nodes)) colour = '#%02X%02X%02X' % (r, g, b) for ne in n.efferent: if ne not in self.added: hopNodes.add(ne) hopEdges.append((ne, n, 'solid', colour)) # add nodes and edges to the graph if maximum number of nodes is not # exceeded self.add_to_graph(hopNodes, hopEdges, nesting) class EfferentGraph(FortranGraph): def get_key(self): colour_notice = COLOURED_NOTICE if _coloured_edges else '' return FILE_GRAPH_KEY.format(colour_notice) def add_nodes(self, nodes, nesting=1): """ Adds nodes for the files which this one depends on. Adds edges between them. """ hopNodes = set() # nodes in this hop hopEdges = [] # edges in this hop # get nodes and edges for this hop for i, n in zip(range(len(nodes)), nodes): r, g, b = rainbowcolour(i, len(nodes)) colour = '#%02X%02X%02X' % (r, g, b) for ne in n.efferent: if ne not in self.added: hopNodes.add(ne) hopEdges.append((n, ne, 'dashed', colour)) # add nodes and edges for this hop to the graph if maximum number of # nodes is not exceeded if not self.add_to_graph(hopNodes, hopEdges, nesting): return elif len(hopNodes) > 0: if nesting < self.max_nesting: self.add_nodes(hopNodes, nesting=nesting+1) else: self.truncated = nesting class AfferentGraph(FortranGraph): def get_key(self): colour_notice = COLOURED_NOTICE if _coloured_edges else '' return FILE_GRAPH_KEY.format(colour_notice) def add_nodes(self, nodes, nesting=1): """ Adds nodes for files which depend upon this one. Adds appropriate edges between them. """ hopNodes = set() # nodes in this hop hopEdges = [] # edges in this hop # get nodes and edges for this hop for i, n in zip(range(len(nodes)), nodes): r, g, b = rainbowcolour(i, len(nodes)) colour = '#%02X%02X%02X' % (r, g, b) for na in n.afferent: if na not in self.added: hopNodes.add(na) hopEdges.append((na, n, 'dashed', colour)) # add nodes and edges for this hop to the graph if maximum number of # nodes is not exceeded if not self.add_to_graph(hopNodes, hopEdges, nesting): return elif len(hopNodes) > 0: if nesting < self.max_nesting: self.add_nodes(hopNodes, nesting=nesting+1) else: self.truncated = nesting class TypeGraph(FortranGraph): def get_key(self): colour_notice = COLOURED_NOTICE if _coloured_edges else '' return TYPE_GRAPH_KEY.format(colour_notice) def add_nodes(self, nodes, nesting=1): """ Adds edges showing inheritance and composition relationships between derived types listed in the nodes. """ hopNodes = set() # nodes in this hop hopEdges = [] # edges in this hop # get nodes and edges for this hop for i, n in zip(range(len(nodes)), nodes): r, g, b = rainbowcolour(i, len(nodes)) colour = '#%02X%02X%02X' % (r, g, b) for keys in n.comp_types.keys(): if keys not in self.added: hopNodes.add(keys) for c in n.comp_types: if c not in self.added: hopNodes.add(c) hopEdges.append((n, c, 'dashed', colour, n.comp_types[c])) if n.ancestor: if n.ancestor not in self.added: hopNodes.add(n.ancestor) hopEdges.append((n, n.ancestor, 'solid', colour)) # add nodes, edges and attributes to the graph if maximum number of # nodes is not exceeded if self.add_to_graph(hopNodes, hopEdges, nesting): self.dot.attr('graph', size='11.875,1000.0') class InheritsGraph(FortranGraph): def get_key(self): colour_notice = COLOURED_NOTICE if _coloured_edges else '' return TYPE_GRAPH_KEY.format(colour_notice) def add_nodes(self, nodes, nesting=1): """ Adds nodes for modules using or descended from those listed in nodes. Adds appropriate edges between them. """ hopNodes = set() # nodes in this hop hopEdges = [] # edges in this hop # get nodes and edges for this hop for i, n in zip(range(len(nodes)), nodes): r, g, b = rainbowcolour(i, len(nodes)) colour = '#%02X%02X%02X' % (r, g, b) for c in n.comp_types: if c not in self.added: hopNodes.add(c) hopEdges.append((n, c, 'dashed', colour, n.comp_types[c])) if n.ancestor: if n.ancestor not in self.added: hopNodes.add(n.ancestor) hopEdges.append((n, n.ancestor, 'solid', colour)) # add nodes and edges for this hop to the graph if maximum number of # nodes is not exceeded if not self.add_to_graph(hopNodes, hopEdges, nesting): return elif len(hopNodes) > 0: if nesting < self.max_nesting: self.add_nodes(hopNodes, nesting=nesting+1) else: self.truncated = nesting class InheritedByGraph(FortranGraph): def get_key(self): colour_notice = COLOURED_NOTICE if _coloured_edges else '' return TYPE_GRAPH_KEY.format(colour_notice) def add_nodes(self, nodes, nesting=1): """ Adds nodes for modules using or descended from those listed in nodes. Adds appropriate edges between them. """ hopNodes = set() # nodes in this hop hopEdges = [] # edges in this hop # get nodes and edges for this hop for i, n in zip(range(len(nodes)), nodes): r, g, b = rainbowcolour(i, len(nodes)) colour = '#%02X%02X%02X' % (r, g, b) for c in n.comp_of: if c not in self.added: hopNodes.add(c) hopEdges.append((c, n, 'dashed', colour, n.comp_of[c])) for c in n.children: if c not in self.added: hopNodes.add(c) hopEdges.append((c, n, 'solid', colour)) # add nodes and edges for this hop to the graph if maximum number of # nodes is not exceeded if not self.add_to_graph(hopNodes, hopEdges, nesting): return elif len(hopNodes) > 0: if nesting < self.max_nesting: self.add_nodes(hopNodes, nesting=nesting+1) else: self.truncated = nesting class CallGraph(FortranGraph): RANKDIR = 'LR' def get_key(self): colour_notice = COLOURED_NOTICE if _coloured_edges else '' return CALL_GRAPH_KEY.format(colour_notice) def add_nodes(self, nodes, nesting=1): """ Adds edges indicating the call-tree for the procedures listed in the nodes. """ hopNodes = set() # nodes in this hop hopEdges = [] # edges in this hop # get nodes and edges for this hop for i, n in zip(range(len(nodes)), nodes): r, g, b = rainbowcolour(i, len(nodes)) colour = '#%02X%02X%02X' % (r, g, b) for p in n.calls: if p not in hopNodes: hopNodes.add(p) hopEdges.append((n, p, 'solid', colour)) for p in getattr(n, 'interfaces', []): if p not in hopNodes: hopNodes.add(p) hopEdges.append((n, p, 'dashed', colour)) # add nodes, edges and attributes to the graph if maximum number of # nodes is not exceeded if self.add_to_graph(hopNodes, hopEdges, nesting): self.dot.attr('graph', size='11.875,1000.0') self.dot.attr('graph', concentrate='false') class CallsGraph(FortranGraph): RANKDIR = 'LR' def get_key(self): colour_notice = COLOURED_NOTICE if _coloured_edges else '' return CALL_GRAPH_KEY.format(colour_notice) def add_nodes(self, nodes, nesting=1): """ Adds nodes for modules using or descended from those listed in nodes. Adds appropriate edges between them. """ hopNodes = set() # nodes in this hop hopEdges = [] # edges in this hop # get nodes and edges for this hop for i, n in zip(range(len(nodes)), nodes): r, g, b = rainbowcolour(i, len(nodes)) colour = '#%02X%02X%02X' % (r, g, b) for p in n.calls: if p not in self.added: hopNodes.add(p) hopEdges.append((n, p, 'solid', colour)) for p in getattr(n, 'interfaces', []): if p not in self.added: hopNodes.add(p) hopEdges.append((n, p, 'dashed', colour)) # add nodes, edges and atrributes for this hop to the graph if # maximum number of nodes is not exceeded if not self.add_to_graph(hopNodes, hopEdges, nesting): return elif len(hopNodes) > 0: if nesting < self.max_nesting: self.dot.attr('graph', concentrate='false') self.add_nodes(hopNodes, nesting=nesting+1) else: self.truncated = nesting class CalledByGraph(FortranGraph): RANKDIR = 'LR' def get_key(self): colour_notice = COLOURED_NOTICE if _coloured_edges else '' return CALL_GRAPH_KEY.format(colour_notice) def add_nodes(self, nodes, nesting=1): """ Adds nodes for modules using or descended from those listed in nodes. Adds appropriate edges between them. """ hopNodes = set() # nodes in this hop hopEdges = [] # edges in this hop # get nodes and edges for this hop for i, n in zip(range(len(nodes)), nodes): r, g, b = rainbowcolour(i, len(nodes)) colour = '#%02X%02X%02X' % (r, g, b) if isinstance(n, ProgNode): continue for p in n.called_by: if p not in self.added: hopNodes.add(p) hopEdges.append((p, n, 'solid', colour)) for p in getattr(n, 'interfaced_by', []): if p not in self.added: hopNodes.add(p) hopEdges.append((p, n, 'dashed', colour)) # add nodes, edges and atrributes for this hop to the graph if # maximum number of nodes is not exceeded if not self.add_to_graph(hopNodes, hopEdges, nesting): return elif len(hopNodes) > 0: if nesting < self.max_nesting: self.dot.attr('graph', concentrate='false') self.add_nodes(hopNodes, nesting=nesting+1) else: self.truncated = nesting class BadType(Exception): """ Raised when a type is passed to GraphData.register() which is not accepted. """ def __init__(self,value): self.value = value def __str__(self): return repr(self.value) # Generate graph keys gd = GraphData() class Proc(object): def __init__(self,name,proctype): self.name = name self.proctype = proctype self.ident = '' def get_url(self): return '' def get_dir(self): return '' sub = Proc('Subroutine','Subroutine') func = Proc('Function','Function') intr = Proc('Interface','Interface') gd.register('Module',FortranModule) gd.register('Submodule',FortranSubmodule) gd.register('Type',FortranType) gd.register(sub,FortranSubroutine) gd.register(func,FortranFunction) gd.register(intr,FortranInterface) gd.register('Unknown Procedure Type',FortranSubroutine) gd.register('Program',FortranProgram) gd.register('Source File',FortranSourceFile) try: # Generate key for module graph dot = Digraph('Graph Key',graph_attr={'size':'8.90625,1000.0', 'concentrate':'false'}, node_attr={'shape':'box', 'height':'0.0', 'margin':'0.08', 'fontname':'Helvetica', 'fontsize':'10.5'}, edge_attr={'fontname':'Helvetica', 'fontsize':'9.5'}, format='svg', engine='dot') for n in [('Module',FortranModule),('Submodule',FortranSubmodule),(sub,FortranSubroutine),(func,FortranFunction),('Program', FortranProgram)]: dot.node(getattr(n[0],'name',n[0]),**gd.get_node(n[0],cls=n[1]).attribs) dot.node('This Page\'s Entity') mod_svg = dot.pipe().decode('utf-8') # Generate key for type graph dot = Digraph('Graph Key',graph_attr={'size':'8.90625,1000.0', 'concentrate':'false'}, node_attr={'shape':'box', 'height':'0.0', 'margin':'0.08', 'fontname':'Helvetica', 'fontsize':'10.5'}, edge_attr={'fontname':'Helvetica', 'fontsize':'9.5'}, format='svg', engine='dot') dot.node('Type',**gd.get_node('Type',cls=FortranType).attribs) dot.node('This Page\'s Entity') type_svg = dot.pipe().decode('utf-8') # Generate key for call graph dot = Digraph('Graph Key',graph_attr={'size':'8.90625,1000.0', 'concentrate':'false'}, node_attr={'shape':'box', 'height':'0.0', 'margin':'0.08', 'fontname':'Helvetica', 'fontsize':'10.5'}, edge_attr={'fontname':'Helvetica', 'fontsize':'9.5'}, format='svg', engine='dot') for n in [(sub,FortranSubroutine),(func,FortranFunction),(intr, FortranInterface),('Unknown Procedure Type',FortranFunction),('Program', FortranProgram)]: dot.node(getattr(n[0],'name',n[0]),**gd.get_node(n[0],cls=n[1]).attribs) dot.node('This Page\'s Entity') call_svg = dot.pipe().decode('utf-8') # Generate key for file graph dot = Digraph('Graph Key',graph_attr={'size':'8.90625,1000.0', 'concentrate':'false'}, node_attr={'shape':'box', 'height':'0.0', 'margin':'0.08', 'fontname':'Helvetica', 'fontsize':'10.5'}, edge_attr={'fontname':'Helvetica', 'fontsize':'9.5'}, format='svg', engine='dot') dot.node('Source File',**gd.get_node('Source File',cls=FortranSourceFile).attribs) dot.node('This Page\'s Entity') file_svg = dot.pipe().decode('utf-8') except RuntimeError: graphviz_installed = False if graphviz_installed: NODE_DIAGRAM = """ <p>Nodes of different colours represent the following: </p> {} """ MOD_GRAPH_KEY = (NODE_DIAGRAM + """ <p>Solid arrows point from a submodule to the (sub)module which it is descended from. Dashed arrows point from a module or program unit to modules which it uses.{{}} </p> """).format(mod_svg) TYPE_GRAPH_KEY = (NODE_DIAGRAM + """ <p>Solid arrows point from a derived type to the parent type which it extends. Dashed arrows point from a derived type to the other types it contains as a components, with a label listing the name(s) of said component(s).{{}} </p> """).format(type_svg) CALL_GRAPH_KEY = (NODE_DIAGRAM + """ <p>Solid arrows point from a procedure to one which it calls. Dashed arrows point from an interface to procedures which implement that interface. This could include the module procedures in a generic interface or the implementation in a submodule of an interface in a parent module.{{}} </p> """).format(call_svg) FILE_GRAPH_KEY = (NODE_DIAGRAM + """ <p>Solid arrows point from a file to a file which it depends on. A file is dependent upon another if the latter must be compiled before the former can be.{{}} </p> """).format(file_svg) COLOURED_NOTICE = " Where possible, edges connecting nodes are given " \ "different colours to make them easier to distinguish " \ "in large graphs." del call_svg del file_svg del type_svg del mod_svg del dot del sub del func del intr
gpl-3.0
WillGuan105/django
tests/signed_cookies_tests/tests.py
288
2768
from __future__ import unicode_literals from django.core import signing from django.http import HttpRequest, HttpResponse from django.test import SimpleTestCase, override_settings from django.test.utils import freeze_time class SignedCookieTest(SimpleTestCase): def test_can_set_and_read_signed_cookies(self): response = HttpResponse() response.set_signed_cookie('c', 'hello') self.assertIn('c', response.cookies) self.assertTrue(response.cookies['c'].value.startswith('hello:')) request = HttpRequest() request.COOKIES['c'] = response.cookies['c'].value value = request.get_signed_cookie('c') self.assertEqual(value, 'hello') def test_can_use_salt(self): response = HttpResponse() response.set_signed_cookie('a', 'hello', salt='one') request = HttpRequest() request.COOKIES['a'] = response.cookies['a'].value value = request.get_signed_cookie('a', salt='one') self.assertEqual(value, 'hello') self.assertRaises(signing.BadSignature, request.get_signed_cookie, 'a', salt='two') def test_detects_tampering(self): response = HttpResponse() response.set_signed_cookie('c', 'hello') request = HttpRequest() request.COOKIES['c'] = response.cookies['c'].value[:-2] + '$$' self.assertRaises(signing.BadSignature, request.get_signed_cookie, 'c') def test_default_argument_suppresses_exceptions(self): response = HttpResponse() response.set_signed_cookie('c', 'hello') request = HttpRequest() request.COOKIES['c'] = response.cookies['c'].value[:-2] + '$$' self.assertEqual(request.get_signed_cookie('c', default=None), None) def test_max_age_argument(self): value = 'hello' with freeze_time(123456789): response = HttpResponse() response.set_signed_cookie('c', value) request = HttpRequest() request.COOKIES['c'] = response.cookies['c'].value self.assertEqual(request.get_signed_cookie('c'), value) with freeze_time(123456800): self.assertEqual(request.get_signed_cookie('c', max_age=12), value) self.assertEqual(request.get_signed_cookie('c', max_age=11), value) self.assertRaises(signing.SignatureExpired, request.get_signed_cookie, 'c', max_age=10) @override_settings(SECRET_KEY=b'\xe7') def test_signed_cookies_with_binary_key(self): response = HttpResponse() response.set_signed_cookie('c', 'hello') request = HttpRequest() request.COOKIES['c'] = response.cookies['c'].value self.assertEqual(request.get_signed_cookie('c'), 'hello')
bsd-3-clause
otron/zenodo
zenodo/base/upgrades/zenodo_2015_06_10_fix_alternate_identifiers.py
2
4755
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015 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. import warnings from sqlalchemy import * from invenio.ext.sqlalchemy import db from invenio.modules.upgrader.api import op from invenio.utils.text import wait_for_user depends_on = [u'zenodo_2015_06_10_missing_formats'] def has_two_dois(fields): res = 0 for field, data in fields.items(): if data['0247_2'] == 'DOI': res += 1 return res > 1 def info(): return "Short description of upgrade displayed to end-user" def do_upgrade(): """Implement your upgrades here.""" result = db.engine.execute(""" select b.id, d.tag, d.value, r.field_number from bibrec as b join bibrec_bib02x as r on b.id=r.id_bibrec join bib02x as d on r.id_bibxxx=d.id where b.id in ( select b.id from bibrec as b join bibrec_bib02x as r on b.id=r.id_bibrec join bib02x as d on r.id_bibxxx=d.id where d.tag='0247_2' group by b.id having count(d.tag) > 1 ) order by b.id, r.field_number;""") records = {} for r in result: recid = str(r[0]) tag = r[1] value = r[2] fieldno = str(r[3]) if recid not in records: records[recid] = {} if fieldno not in records[recid]: records[recid][fieldno] = {} if tag not in records[recid][fieldno]: records[recid][fieldno][tag] = value recdata = {} # Determine doi and alternate identifiers. for recid, fields in records.items(): recdata[recid] = dict(doi=None, alt=[]) if not has_two_dois(fields): for field, data in fields.items(): if data['0247_2'] == 'DOI': recdata[recid]['doi'] = data['0247_a'] else: recdata[recid]['alt'].append( {"id": data['0247_a'].strip(), "scheme": data['0247_2']} ) else: dois = [] alt = [] for data in fields.values(): if data['0247_2'].lower() == 'doi': dois.append(data['0247_a'].strip()) else: recdata[recid]['alt'].append( {"id": data['0247_a'].strip(), "scheme": data['0247_2']} ) dois = set(dois) for d in dois: if d.startswith("10.5281"): recdata[recid]['doi'] = d else: recdata[recid]['alt'].append({'id': d, 'scheme': 'doi'}) from invenio.legacy.bibupload.utils import open_temp_file, close_temp_file from invenio.legacy.bibsched.bibtask import task_low_level_submission (fo, fname) = open_temp_file("datafix") fo.write("<collection>\n") for recid, data in recdata.items(): fo.write("<record>\n") fo.write(""" <controlfield tag="001">%s</controlfield>\n""" % recid) fo.write(""" <datafield tag="024" ind1="7" ind2=" "> <subfield code="2">DOI</subfield> <subfield code="a">%s</subfield> </datafield>\n""" % data['doi']) for alt in data['alt']: fo.write(""" <datafield tag="024" ind1="7" ind2=" "> <subfield code="2">%s</subfield> <subfield code="a">%s</subfield> <subfield code="q">alternateIdentifier</subfield> </datafield>\n""" % (alt['scheme'], alt['id'])) fo.write("</record>\n") fo.write("</collection>\n") close_temp_file(fo, fname) task_low_level_submission('bibupload', "datafix", "-c", fname) def estimate(): """Estimate running time of upgrade in seconds (optional).""" return 1 def pre_upgrade(): """Run pre-upgrade checks (optional).""" # Example of raising errors: # raise RuntimeError("Description of error 1", "Description of error 2") def post_upgrade(): """Run post-upgrade checks (optional).""" # Example of issuing warnings: # warnings.warn("A continuable error occurred")
gpl-3.0
popazerty/dvbapp-gui2
lib/python/Components/NetworkTime.py
24
1473
from Components.Console import Console from config import config from enigma import eTimer, eDVBLocalTimeHandler, eEPGCache from Tools.StbHardware import setRTCtime from time import time # _session = None # def AutoNTPSync(session=None, **kwargs): global ntpsyncpoller ntpsyncpoller = NTPSyncPoller() ntpsyncpoller.start() class NTPSyncPoller: """Automatically Poll NTP""" def __init__(self): # Init Timer self.timer = eTimer() self.Console = Console() def start(self): if self.timecheck not in self.timer.callback: self.timer.callback.append(self.timecheck) self.timer.startLongTimer(0) def stop(self): if self.timecheck in self.timer.callback: self.timer.callback.remove(self.timecheck) self.timer.stop() def timecheck(self): if config.misc.SyncTimeUsing.value == "1": print '[NTP]: Updating' self.Console.ePopen('/usr/bin/ntpdate-sync', self.update_schedule) else: self.update_schedule() def update_schedule(self, result = None, retval = None, extra_args = None): nowTime = time() if nowTime > 10000: print '[NTP]: setting E2 time:',nowTime setRTCtime(nowTime) if config.misc.SyncTimeUsing.value == "1": eDVBLocalTimeHandler.getInstance().setUseDVBTime(False) else: eDVBLocalTimeHandler.getInstance().setUseDVBTime(True) eEPGCache.getInstance().timeUpdated() self.timer.startLongTimer(int(config.misc.useNTPminutes.value) * 60) else: print 'NO TIME SET' self.timer.startLongTimer(10)
gpl-2.0