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
lintzc/gpdb
src/test/unit/mock/special.py
20
2211
class SpecialFuncs(object): @classmethod def make_body(cls, func): key = 'make_body_' + func.funcname if key in cls.__dict__: return cls.__dict__[key].__get__(None, SpecialFuncs)(func) @staticmethod def make_body_MemoryContextAllocZeroImpl(func): return """ void *p = malloc(size); memset(p, 0, size); return p; """ @staticmethod def make_body_MemoryContextAllocImpl(func): return """ void *p = malloc(size); return p; """ @staticmethod def make_body_MemoryContextFreeImpl(func): return """ free(pointer); """ @staticmethod def make_body_MemoryContextStrdup(func): return """ return strdup(string); """ @staticmethod def make_body_MemoryContextReallocImpl(func): return """ return realloc(pointer, size); """ @staticmethod def make_body_MemoryContextAllocZeroAlignedImpl(func): return """ void *p = malloc(size); memset(p, 0, size); return p; """ class ByValStructs(object): """These are structs over 32 bit and possibly passed by-value. As our mock framework doesn't accept 64 bit integer in some platform, we have to treat them specially. """ type_names = set([ 'ArrayTuple', 'CdbPathLocus', 'Complex', 'DbDirNode', 'DirectDispatchCalculationInfo', 'FileRepIdentifier_u', 'FileRepOperationDescription_u', 'FileRepRelFileNodeInfo_s', 'FileRepVerifyArguments', 'FileRepVerifyLogControl_s', 'FileRepVerifyRequest_s', 'instr_time', 'Interval', 'ItemPointerData', 'NameData', 'mpp_fd_set', 'PGSemaphoreData', 'PossibleValueSet', 'PrimaryMirrorModeTransitionArguments', 'RelFileNode', 'struct timeval', 'VariableStatData', 'XLogRecPtr' ]) @classmethod def has(cls, argtype): return argtype in cls.type_names
apache-2.0
gusai-francelabs/datafari
windows/python/Lib/encodings/utf_16_le.py
860
1037
""" Python 'utf-16-le' Codec Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. """ import codecs ### Codec APIs encode = codecs.utf_16_le_encode def decode(input, errors='strict'): return codecs.utf_16_le_decode(input, errors, True) class IncrementalEncoder(codecs.IncrementalEncoder): def encode(self, input, final=False): return codecs.utf_16_le_encode(input, self.errors)[0] class IncrementalDecoder(codecs.BufferedIncrementalDecoder): _buffer_decode = codecs.utf_16_le_decode class StreamWriter(codecs.StreamWriter): encode = codecs.utf_16_le_encode class StreamReader(codecs.StreamReader): decode = codecs.utf_16_le_decode ### encodings module API def getregentry(): return codecs.CodecInfo( name='utf-16-le', encode=encode, decode=decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, )
apache-2.0
rouault/Quantum-GIS
tests/src/python/test_qgsserver_wms_getfeatureinfo.py
1
17012
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsServer GetFeatureInfo WMS. From build dir, run: ctest -R PyQgsServerWMSGetFeatureInfo -V .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ __author__ = 'Alessandro Pasotti' __date__ = '11/03/2018' __copyright__ = 'Copyright 2018, The QGIS Project' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' import os # Needed on Qt 5 so that the serialization of XML is consistent among all executions os.environ['QT_HASH_SEED'] = '1' import re import urllib.request import urllib.parse import urllib.error from qgis.testing import unittest from qgis.PyQt.QtCore import QSize import osgeo.gdal # NOQA from test_qgsserver_wms import TestQgsServerWMSTestBase from qgis.core import QgsProject class TestQgsServerWMSGetFeatureInfo(TestQgsServerWMSTestBase): """QGIS Server WMS Tests for GetFeatureInfo request""" def testGetFeatureInfo(self): # Test getfeatureinfo response xml self.wms_request_compare('GetFeatureInfo', '&layers=testlayer%20%C3%A8%C3%A9&styles=&' + 'info_format=text%2Fxml&transparent=true&' + 'width=600&height=400&srs=EPSG%3A3857&bbox=913190.6389747962%2C' + '5606005.488876367%2C913235.426296057%2C5606035.347090538&' + 'query_layers=testlayer%20%C3%A8%C3%A9&X=190&Y=320', 'wms_getfeatureinfo-text-xml') self.wms_request_compare('GetFeatureInfo', '&layers=&styles=&' + 'info_format=text%2Fxml&transparent=true&' + 'width=600&height=400&srs=EPSG%3A3857&bbox=913190.6389747962%2C' + '5606005.488876367%2C913235.426296057%2C5606035.347090538&' + 'query_layers=testlayer%20%C3%A8%C3%A9&X=190&Y=320', 'wms_getfeatureinfo-text-xml') # Test getfeatureinfo response html self.wms_request_compare('GetFeatureInfo', '&layers=testlayer%20%C3%A8%C3%A9&styles=&' + 'info_format=text%2Fhtml&transparent=true&' + 'width=600&height=400&srs=EPSG%3A3857&bbox=913190.6389747962%2C' + '5606005.488876367%2C913235.426296057%2C5606035.347090538&' + 'query_layers=testlayer%20%C3%A8%C3%A9&X=190&Y=320', 'wms_getfeatureinfo-text-html') # Test getfeatureinfo response html with geometry self.wms_request_compare('GetFeatureInfo', '&layers=testlayer%20%C3%A8%C3%A9&styles=&' + 'info_format=text%2Fhtml&transparent=true&' + 'width=600&height=400&srs=EPSG%3A3857&bbox=913190.6389747962%2C' + '5606005.488876367%2C913235.426296057%2C5606035.347090538&' + 'query_layers=testlayer%20%C3%A8%C3%A9&X=190&Y=320&' + 'with_geometry=true', 'wms_getfeatureinfo-text-html-geometry') # Test getfeatureinfo response html with maptip self.wms_request_compare('GetFeatureInfo', '&layers=testlayer%20%C3%A8%C3%A9&styles=&' + 'info_format=text%2Fhtml&transparent=true&' + 'width=600&height=400&srs=EPSG%3A3857&bbox=913190.6389747962%2C' + '5606005.488876367%2C913235.426296057%2C5606035.347090538&' + 'query_layers=testlayer%20%C3%A8%C3%A9&X=190&Y=320&' + 'with_maptip=true', 'wms_getfeatureinfo-text-html-maptip') # Test getfeatureinfo response text self.wms_request_compare('GetFeatureInfo', '&layers=testlayer%20%C3%A8%C3%A9&styles=&' + 'transparent=true&' + 'width=600&height=400&srs=EPSG%3A3857&bbox=913190.6389747962%2C' + '5606005.488876367%2C913235.426296057%2C5606035.347090538&' + 'query_layers=testlayer%20%C3%A8%C3%A9&X=190&Y=320&' + 'info_format=text/plain', 'wms_getfeatureinfo-text-plain') # Test getfeatureinfo default info_format self.wms_request_compare('GetFeatureInfo', '&layers=testlayer%20%C3%A8%C3%A9&styles=&' + 'transparent=true&' + 'width=600&height=400&srs=EPSG%3A3857&bbox=913190.6389747962%2C' + '5606005.488876367%2C913235.426296057%2C5606035.347090538&' + 'query_layers=testlayer%20%C3%A8%C3%A9&X=190&Y=320', 'wms_getfeatureinfo-text-plain') # Test getfeatureinfo invalid info_format self.wms_request_compare('GetFeatureInfo', '&layers=testlayer%20%C3%A8%C3%A9&styles=&' + 'transparent=true&' + 'width=600&height=400&srs=EPSG%3A3857&bbox=913190.6389747962%2C' + '5606005.488876367%2C913235.426296057%2C5606035.347090538&' + 'query_layers=testlayer%20%C3%A8%C3%A9&X=190&Y=320&' + 'info_format=InvalidFormat', 'wms_getfeatureinfo-invalid-format') # Test feature info request with filter geometry self.wms_request_compare('GetFeatureInfo', '&layers=testlayer%20%C3%A8%C3%A9&' + 'INFO_FORMAT=text%2Fxml&' + 'width=600&height=400&srs=EPSG%3A4326&' + 'query_layers=testlayer%20%C3%A8%C3%A9&' + 'FEATURE_COUNT=10&FILTER_GEOM=POLYGON((8.2035381 44.901459,8.2035562 44.901459,8.2035562 44.901418,8.2035381 44.901418,8.2035381 44.901459))', 'wms_getfeatureinfo_geometry_filter') # Test feature info request with filter geometry in non-layer CRS self.wms_request_compare('GetFeatureInfo', '&layers=testlayer%20%C3%A8%C3%A9&' + 'INFO_FORMAT=text%2Fxml&' + 'width=600&height=400&srs=EPSG%3A3857&' + 'query_layers=testlayer%20%C3%A8%C3%A9&' + 'FEATURE_COUNT=10&FILTER_GEOM=POLYGON ((913213.6839952 5606021.5399693, 913215.6988780 5606021.5399693, 913215.6988780 5606015.09643322, 913213.6839952 5606015.0964332, 913213.6839952 5606021.5399693))', 'wms_getfeatureinfo_geometry_filter_3857') # Test feature info request with invalid query_layer self.wms_request_compare('GetFeatureInfo', '&layers=testlayer%20%C3%A8%C3%A9&' + 'INFO_FORMAT=text%2Fxml&' + 'width=600&height=400&srs=EPSG%3A3857&' + 'query_layers=InvalidLayer&' + 'FEATURE_COUNT=10&FILTER_GEOM=POLYGON((8.2035381 44.901459,8.2035562 44.901459,8.2035562 44.901418,8.2035381 44.901418,8.2035381 44.901459))', 'wms_getfeatureinfo_invalid_query_layers') # Test feature info request with '+' instead of ' ' in layers and # query_layers parameters self.wms_request_compare('GetFeatureInfo', '&layers=testlayer+%C3%A8%C3%A9&styles=&' + 'info_format=text%2Fxml&transparent=true&' + 'width=600&height=400&srs=EPSG%3A3857&bbox=913190.6389747962%2C' + '5606005.488876367%2C913235.426296057%2C5606035.347090538&' + 'query_layers=testlayer+%C3%A8%C3%A9&X=190&Y=320', 'wms_getfeatureinfo-text-xml') # layer1 is a clone of layer0 but with a scale visibility. Thus, # GetFeatureInfo response contains only a feature for layer0 and layer1 # is ignored for the required bbox. Without the scale visibility option, # the feature for layer1 would have been in the response too. mypath = self.testdata_path + "test_project_scalevisibility.qgs" self.wms_request_compare('GetFeatureInfo', '&layers=layer0,layer1&styles=&' + 'VERSION=1.1.0&' + 'info_format=text%2Fxml&' + 'width=500&height=500&srs=EPSG%3A4326' + '&bbox=8.1976,44.8998,8.2100,44.9027&' + 'query_layers=layer0,layer1&X=235&Y=243', 'wms_getfeatureinfo_notvisible', 'test_project_scalevisibility.qgs') # Test GetFeatureInfo resolves "value map" widget values mypath = self.testdata_path + "test_project_values.qgs" self.wms_request_compare('GetFeatureInfo', '&layers=layer0&styles=&' + 'VERSION=1.3.0&' + 'info_format=text%2Fxml&' + 'width=926&height=787&srs=EPSG%3A4326' + '&bbox=912217,5605059,914099,5606652' + '&CRS=EPSG:3857' + '&FEATURE_COUNT=10' + '&QUERY_LAYERS=layer0&I=487&J=308', 'wms_getfeatureinfo-values1-text-xml', 'test_project_values.qgs') # TODO fix regression in QGIS 3 as the widget values don't get solved and enable test @unittest.expectedFailure def testGetFeatureInfoValueRelation(self): """Test GetFeatureInfo resolves "value relation" widget values""" mypath = self.testdata_path + "test_project_values.qgs" self.wms_request_compare('GetFeatureInfo', '&layers=layer1&styles=&' + 'VERSION=1.3.0&' + 'info_format=text%2Fxml&' + 'width=926&height=787&srs=EPSG%3A4326' + '&bbox=912217,5605059,914099,5606652' + '&CRS=EPSG:3857' + '&FEATURE_COUNT=10' + '&WITH_GEOMETRY=True' + '&QUERY_LAYERS=layer1&I=487&J=308', 'wms_getfeatureinfo-values1-text-xml', 'test_project_values.qgs') # TODO make GetFeatureInfo show the dictionary values and enable test @unittest.expectedFailure def testGetFeatureInfoValueRelationArray(self): """Test GetFeatureInfo on "value relation" widget with array field (multiple selections)""" mypath = self.testdata_path + "test_project_values.qgs" self.wms_request_compare('GetFeatureInfo', '&layers=layer3&styles=&' + 'VERSION=1.3.0&' + 'info_format=text%2Fxml&' + 'width=926&height=787&srs=EPSG%3A4326' + '&bbox=912217,5605059,914099,5606652' + '&CRS=EPSG:3857' + '&FEATURE_COUNT=10' + '&WITH_GEOMETRY=True' + '&QUERY_LAYERS=layer3&I=487&J=308', 'wms_getfeatureinfo-values3-text-xml', 'test_project_values.qgs') # TODO make GetFeatureInfo show what's in the display expression and enable test @unittest.expectedFailure def testGetFeatureInfoRelationReference(self): """Test GetFeatureInfo solves "relation reference" widget "display expression" values""" mypath = self.testdata_path + "test_project_values.qgs" self.wms_request_compare('GetFeatureInfo', '&layers=layer2&styles=&' + 'VERSION=1.3.0&' + 'info_format=text%2Fxml&' + 'width=926&height=787&srs=EPSG%3A4326' + '&bbox=912217,5605059,914099,5606652' + '&CRS=EPSG:3857' + '&FEATURE_COUNT=10' + '&WITH_GEOMETRY=True' + '&QUERY_LAYERS=layer2&I=487&J=308', 'wms_getfeatureinfo-values2-text-xml', 'test_project_values.qgs') def testGetFeatureInfoFilter(self): # Test getfeatureinfo response xml # Regression for #8656 # Mind the gap! (the space in the FILTER expression) self.wms_request_compare('GetFeatureInfo', '&layers=testlayer%20%C3%A8%C3%A9&' + 'INFO_FORMAT=text%2Fxml&' + 'width=600&height=400&srs=EPSG%3A3857&' + 'query_layers=testlayer%20%C3%A8%C3%A9&' + 'FEATURE_COUNT=10&FILTER=testlayer%20%C3%A8%C3%A9' + urllib.parse.quote(':"NAME" = \'two\''), 'wms_getfeatureinfo_filter') # Test a filter with NO condition results self.wms_request_compare('GetFeatureInfo', '&layers=testlayer%20%C3%A8%C3%A9&' + 'INFO_FORMAT=text%2Fxml&' + 'width=600&height=400&srs=EPSG%3A3857&' + 'query_layers=testlayer%20%C3%A8%C3%A9&' + 'FEATURE_COUNT=10&FILTER=testlayer%20%C3%A8%C3%A9' + urllib.parse.quote(':"NAME" = \'two\' AND "utf8nameè" = \'no-results\''), 'wms_getfeatureinfo_filter_no_results') # Test a filter with OR condition results self.wms_request_compare('GetFeatureInfo', '&layers=testlayer%20%C3%A8%C3%A9&' + 'INFO_FORMAT=text%2Fxml&' + 'width=600&height=400&srs=EPSG%3A3857&' + 'query_layers=testlayer%20%C3%A8%C3%A9&' + 'FEATURE_COUNT=10&FILTER=testlayer%20%C3%A8%C3%A9' + urllib.parse.quote(':"NAME" = \'two\' OR "NAME" = \'three\''), 'wms_getfeatureinfo_filter_or') # Test a filter with OR condition and UTF results # Note that the layer name that contains utf-8 chars cannot be # to upper case. self.wms_request_compare('GetFeatureInfo', '&layers=testlayer%20%C3%A8%C3%A9&' + 'INFO_FORMAT=text%2Fxml&' + 'width=600&height=400&srs=EPSG%3A3857&' + 'query_layers=testlayer%20%C3%A8%C3%A9&' + 'FEATURE_COUNT=10&FILTER=testlayer%20%C3%A8%C3%A9' + urllib.parse.quote(':"NAME" = \'two\' OR "utf8nameè" = \'three èé↓\''), 'wms_getfeatureinfo_filter_or_utf8') # Regression #18292 Server GetFeatureInfo FILTER search fails when WIDTH, HEIGHT are not specified self.wms_request_compare('GetFeatureInfo', '&layers=testlayer%20%C3%A8%C3%A9&' + 'INFO_FORMAT=text%2Fxml&' + 'srs=EPSG%3A3857&' + 'query_layers=testlayer%20%C3%A8%C3%A9&' + 'FEATURE_COUNT=10&FILTER=testlayer%20%C3%A8%C3%A9' + urllib.parse.quote(':"NAME" = \'two\''), 'wms_getfeatureinfo_filter_no_width') if __name__ == '__main__': unittest.main()
gpl-2.0
GdZ/scriptfile
software/googleAppEngine/lib/django_1_2/django/utils/html.py
202
8105
"""HTML utilities suitable for global use.""" import re import string from django.utils.safestring import SafeData, mark_safe from django.utils.encoding import force_unicode from django.utils.functional import allow_lazy from django.utils.http import urlquote # Configuration for urlize() function. LEADING_PUNCTUATION = ['(', '<', '&lt;'] TRAILING_PUNCTUATION = ['.', ',', ')', '>', '\n', '&gt;'] # List of possible strings used for bullets in bulleted lists. DOTS = ['&middot;', '*', '\xe2\x80\xa2', '&#149;', '&bull;', '&#8226;'] unencoded_ampersands_re = re.compile(r'&(?!(\w+|#\d+);)') word_split_re = re.compile(r'(\s+)') punctuation_re = re.compile('^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % \ ('|'.join([re.escape(x) for x in LEADING_PUNCTUATION]), '|'.join([re.escape(x) for x in TRAILING_PUNCTUATION]))) simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$') link_target_attribute_re = re.compile(r'(<a [^>]*?)target=[^\s>]+') html_gunk_re = re.compile(r'(?:<br clear="all">|<i><\/i>|<b><\/b>|<em><\/em>|<strong><\/strong>|<\/?smallcaps>|<\/?uppercase>)', re.IGNORECASE) hard_coded_bullets_re = re.compile(r'((?:<p>(?:%s).*?[a-zA-Z].*?</p>\s*)+)' % '|'.join([re.escape(x) for x in DOTS]), re.DOTALL) trailing_empty_content_re = re.compile(r'(?:<p>(?:&nbsp;|\s|<br \/>)*?</p>\s*)+\Z') del x # Temporary variable def escape(html): """ Returns the given HTML with ampersands, quotes and angle brackets encoded. """ return mark_safe(force_unicode(html).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;')) escape = allow_lazy(escape, unicode) _base_js_escapes = ( ('\\', r'\u005C'), ('\'', r'\u0027'), ('"', r'\u0022'), ('>', r'\u003E'), ('<', r'\u003C'), ('&', r'\u0026'), ('=', r'\u003D'), ('-', r'\u002D'), (';', r'\u003B'), (u'\u2028', r'\u2028'), (u'\u2029', r'\u2029') ) # Escape every ASCII character with a value less than 32. _js_escapes = (_base_js_escapes + tuple([('%c' % z, '\\u%04X' % z) for z in range(32)])) def escapejs(value): """Hex encodes characters for use in JavaScript strings.""" for bad, good in _js_escapes: value = mark_safe(force_unicode(value).replace(bad, good)) return value escapejs = allow_lazy(escapejs, unicode) def conditional_escape(html): """ Similar to escape(), except that it doesn't operate on pre-escaped strings. """ if isinstance(html, SafeData): return html else: return escape(html) def linebreaks(value, autoescape=False): """Converts newlines into <p> and <br />s.""" value = re.sub(r'\r\n|\r|\n', '\n', force_unicode(value)) # normalize newlines paras = re.split('\n{2,}', value) if autoescape: paras = [u'<p>%s</p>' % escape(p).replace('\n', '<br />') for p in paras] else: paras = [u'<p>%s</p>' % p.replace('\n', '<br />') for p in paras] return u'\n\n'.join(paras) linebreaks = allow_lazy(linebreaks, unicode) def strip_tags(value): """Returns the given HTML with all tags stripped.""" return re.sub(r'<[^>]*?>', '', force_unicode(value)) strip_tags = allow_lazy(strip_tags) def strip_spaces_between_tags(value): """Returns the given HTML with spaces between tags removed.""" return re.sub(r'>\s+<', '><', force_unicode(value)) strip_spaces_between_tags = allow_lazy(strip_spaces_between_tags, unicode) def strip_entities(value): """Returns the given HTML with all entities (&something;) stripped.""" return re.sub(r'&(?:\w+|#\d+);', '', force_unicode(value)) strip_entities = allow_lazy(strip_entities, unicode) def fix_ampersands(value): """Returns the given HTML with all unencoded ampersands encoded correctly.""" return unencoded_ampersands_re.sub('&amp;', force_unicode(value)) fix_ampersands = allow_lazy(fix_ampersands, unicode) def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): """ Converts any URLs in text into clickable links. Works on http://, https://, www. links and links ending in .org, .net or .com. Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens) and it'll still do the right thing. If trim_url_limit is not None, the URLs in link text longer than this limit will truncated to trim_url_limit-3 characters and appended with an elipsis. If nofollow is True, the URLs in link text will get a rel="nofollow" attribute. If autoescape is True, the link text and URLs will get autoescaped. """ trim_url = lambda x, limit=trim_url_limit: limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x safe_input = isinstance(text, SafeData) words = word_split_re.split(force_unicode(text)) nofollow_attr = nofollow and ' rel="nofollow"' or '' for i, word in enumerate(words): match = None if '.' in word or '@' in word or ':' in word: match = punctuation_re.match(word) if match: lead, middle, trail = match.groups() # Make URL we want to point to. url = None if middle.startswith('http://') or middle.startswith('https://'): url = urlquote(middle, safe='/&=:;#?+*') elif middle.startswith('www.') or ('@' not in middle and \ middle and middle[0] in string.ascii_letters + string.digits and \ (middle.endswith('.org') or middle.endswith('.net') or middle.endswith('.com'))): url = urlquote('http://%s' % middle, safe='/&=:;#?+*') elif '@' in middle and not ':' in middle and simple_email_re.match(middle): url = 'mailto:%s' % middle nofollow_attr = '' # Make link. if url: trimmed = trim_url(middle) if autoescape and not safe_input: lead, trail = escape(lead), escape(trail) url, trimmed = escape(url), escape(trimmed) middle = '<a href="%s"%s>%s</a>' % (url, nofollow_attr, trimmed) words[i] = mark_safe('%s%s%s' % (lead, middle, trail)) else: if safe_input: words[i] = mark_safe(word) elif autoescape: words[i] = escape(word) elif safe_input: words[i] = mark_safe(word) elif autoescape: words[i] = escape(word) return u''.join(words) urlize = allow_lazy(urlize, unicode) def clean_html(text): """ Clean the given HTML. Specifically, do the following: * Convert <b> and <i> to <strong> and <em>. * Encode all ampersands correctly. * Remove all "target" attributes from <a> tags. * Remove extraneous HTML, such as presentational tags that open and immediately close and <br clear="all">. * Convert hard-coded bullets into HTML unordered lists. * Remove stuff like "<p>&nbsp;&nbsp;</p>", but only if it's at the bottom of the text. """ from django.utils.text import normalize_newlines text = normalize_newlines(force_unicode(text)) text = re.sub(r'<(/?)\s*b\s*>', '<\\1strong>', text) text = re.sub(r'<(/?)\s*i\s*>', '<\\1em>', text) text = fix_ampersands(text) # Remove all target="" attributes from <a> tags. text = link_target_attribute_re.sub('\\1', text) # Trim stupid HTML such as <br clear="all">. text = html_gunk_re.sub('', text) # Convert hard-coded bullets into HTML unordered lists. def replace_p_tags(match): s = match.group().replace('</p>', '</li>') for d in DOTS: s = s.replace('<p>%s' % d, '<li>') return u'<ul>\n%s\n</ul>' % s text = hard_coded_bullets_re.sub(replace_p_tags, text) # Remove stuff like "<p>&nbsp;&nbsp;</p>", but only if it's at the bottom # of the text. text = trailing_empty_content_re.sub('', text) return text clean_html = allow_lazy(clean_html, unicode)
mit
maxdeliso/elevatorSim
Lib/test/test_runpy.py
5
23521
# Test the runpy module import unittest import os import os.path import sys import re import tempfile import importlib import py_compile from test.support import ( forget, make_legacy_pyc, run_unittest, unload, verbose, no_tracing, create_empty_file) from test.script_helper import ( make_pkg, make_script, make_zip_pkg, make_zip_script, temp_dir) import runpy from runpy import _run_code, _run_module_code, run_module, run_path # Note: This module can't safely test _run_module_as_main as it # runs its tests in the current process, which would mess with the # real __main__ module (usually test.regrtest) # See test_cmd_line_script for a test that executes that code path # Set up the test code and expected results example_source = """\ # Check basic code execution result = ['Top level assignment'] def f(): result.append('Lower level reference') f() del f # Check the sys module import sys run_argv0 = sys.argv[0] run_name_in_sys_modules = __name__ in sys.modules module_in_sys_modules = (run_name_in_sys_modules and globals() is sys.modules[__name__].__dict__) # Check nested operation import runpy nested = runpy._run_module_code('x=1\\n', mod_name='<run>') """ implicit_namespace = { "__name__": None, "__file__": None, "__cached__": None, "__package__": None, "__doc__": None, } example_namespace = { "sys": sys, "runpy": runpy, "result": ["Top level assignment", "Lower level reference"], "run_argv0": sys.argv[0], "run_name_in_sys_modules": False, "module_in_sys_modules": False, "nested": dict(implicit_namespace, x=1, __name__="<run>", __loader__=None), } example_namespace.update(implicit_namespace) class CodeExecutionMixin: # Issue #15230 (run_path not handling run_name correctly) highlighted a # problem with the way arguments were being passed from higher level APIs # down to lower level code. This mixin makes it easier to ensure full # testing occurs at those upper layers as well, not just at the utility # layer def assertNamespaceMatches(self, result_ns, expected_ns): """Check two namespaces match. Ignores any unspecified interpreter created names """ # Impls are permitted to add extra names, so filter them out for k in list(result_ns): if k.startswith("__") and k.endswith("__"): if k not in expected_ns: result_ns.pop(k) if k not in expected_ns["nested"]: result_ns["nested"].pop(k) # Don't use direct dict comparison - the diffs are too hard to debug self.assertEqual(set(result_ns), set(expected_ns)) for k in result_ns: actual = (k, result_ns[k]) expected = (k, expected_ns[k]) self.assertEqual(actual, expected) def check_code_execution(self, create_namespace, expected_namespace): """Check that an interface runs the example code correctly First argument is a callable accepting the initial globals and using them to create the actual namespace Second argument is the expected result """ sentinel = object() expected_ns = expected_namespace.copy() run_name = expected_ns["__name__"] saved_argv0 = sys.argv[0] saved_mod = sys.modules.get(run_name, sentinel) # Check without initial globals result_ns = create_namespace(None) self.assertNamespaceMatches(result_ns, expected_ns) self.assertIs(sys.argv[0], saved_argv0) self.assertIs(sys.modules.get(run_name, sentinel), saved_mod) # And then with initial globals initial_ns = {"sentinel": sentinel} expected_ns["sentinel"] = sentinel result_ns = create_namespace(initial_ns) self.assertIsNot(result_ns, initial_ns) self.assertNamespaceMatches(result_ns, expected_ns) self.assertIs(sys.argv[0], saved_argv0) self.assertIs(sys.modules.get(run_name, sentinel), saved_mod) class ExecutionLayerTestCase(unittest.TestCase, CodeExecutionMixin): """Unit tests for runpy._run_code and runpy._run_module_code""" def test_run_code(self): expected_ns = example_namespace.copy() expected_ns.update({ "__loader__": None, }) def create_ns(init_globals): return _run_code(example_source, {}, init_globals) self.check_code_execution(create_ns, expected_ns) def test_run_module_code(self): mod_name = "<Nonsense>" mod_fname = "Some other nonsense" mod_loader = "Now you're just being silly" mod_package = '' # Treat as a top level module expected_ns = example_namespace.copy() expected_ns.update({ "__name__": mod_name, "__file__": mod_fname, "__loader__": mod_loader, "__package__": mod_package, "run_argv0": mod_fname, "run_name_in_sys_modules": True, "module_in_sys_modules": True, }) def create_ns(init_globals): return _run_module_code(example_source, init_globals, mod_name, mod_fname, mod_loader, mod_package) self.check_code_execution(create_ns, expected_ns) # TODO: Use self.addCleanup to get rid of a lot of try-finally blocks class RunModuleTestCase(unittest.TestCase, CodeExecutionMixin): """Unit tests for runpy.run_module""" def expect_import_error(self, mod_name): try: run_module(mod_name) except ImportError: pass else: self.fail("Expected import error for " + mod_name) def test_invalid_names(self): # Builtin module self.expect_import_error("sys") # Non-existent modules self.expect_import_error("sys.imp.eric") self.expect_import_error("os.path.half") self.expect_import_error("a.bee") self.expect_import_error(".howard") self.expect_import_error("..eaten") # Package without __main__.py self.expect_import_error("multiprocessing") def test_library_module(self): self.assertEqual(run_module("runpy")["__name__"], "runpy") def _add_pkg_dir(self, pkg_dir): os.mkdir(pkg_dir) pkg_fname = os.path.join(pkg_dir, "__init__.py") create_empty_file(pkg_fname) return pkg_fname def _make_pkg(self, source, depth, mod_base="runpy_test"): pkg_name = "__runpy_pkg__" test_fname = mod_base+os.extsep+"py" pkg_dir = sub_dir = os.path.realpath(tempfile.mkdtemp()) if verbose > 1: print(" Package tree in:", sub_dir) sys.path.insert(0, pkg_dir) if verbose > 1: print(" Updated sys.path:", sys.path[0]) for i in range(depth): sub_dir = os.path.join(sub_dir, pkg_name) pkg_fname = self._add_pkg_dir(sub_dir) if verbose > 1: print(" Next level in:", sub_dir) if verbose > 1: print(" Created:", pkg_fname) mod_fname = os.path.join(sub_dir, test_fname) mod_file = open(mod_fname, "w") mod_file.write(source) mod_file.close() if verbose > 1: print(" Created:", mod_fname) mod_name = (pkg_name+".")*depth + mod_base return pkg_dir, mod_fname, mod_name def _del_pkg(self, top, depth, mod_name): for entry in list(sys.modules): if entry.startswith("__runpy_pkg__"): del sys.modules[entry] if verbose > 1: print(" Removed sys.modules entries") del sys.path[0] if verbose > 1: print(" Removed sys.path entry") for root, dirs, files in os.walk(top, topdown=False): for name in files: try: os.remove(os.path.join(root, name)) except OSError as ex: if verbose > 1: print(ex) # Persist with cleaning up for name in dirs: fullname = os.path.join(root, name) try: os.rmdir(fullname) except OSError as ex: if verbose > 1: print(ex) # Persist with cleaning up try: os.rmdir(top) if verbose > 1: print(" Removed package tree") except OSError as ex: if verbose > 1: print(ex) # Persist with cleaning up def _fix_ns_for_legacy_pyc(self, ns, alter_sys): char_to_add = "c" if __debug__ else "o" ns["__file__"] += char_to_add if alter_sys: ns["run_argv0"] += char_to_add def _check_module(self, depth, alter_sys=False): pkg_dir, mod_fname, mod_name = ( self._make_pkg(example_source, depth)) forget(mod_name) expected_ns = example_namespace.copy() expected_ns.update({ "__name__": mod_name, "__file__": mod_fname, "__package__": mod_name.rpartition(".")[0], }) if alter_sys: expected_ns.update({ "run_argv0": mod_fname, "run_name_in_sys_modules": True, "module_in_sys_modules": True, }) def create_ns(init_globals): return run_module(mod_name, init_globals, alter_sys=alter_sys) try: if verbose > 1: print("Running from source:", mod_name) self.check_code_execution(create_ns, expected_ns) importlib.invalidate_caches() __import__(mod_name) os.remove(mod_fname) make_legacy_pyc(mod_fname) unload(mod_name) # In case loader caches paths importlib.invalidate_caches() if verbose > 1: print("Running from compiled:", mod_name) self._fix_ns_for_legacy_pyc(expected_ns, alter_sys) self.check_code_execution(create_ns, expected_ns) finally: self._del_pkg(pkg_dir, depth, mod_name) if verbose > 1: print("Module executed successfully") def _check_package(self, depth, alter_sys=False): pkg_dir, mod_fname, mod_name = ( self._make_pkg(example_source, depth, "__main__")) pkg_name = mod_name.rpartition(".")[0] forget(mod_name) expected_ns = example_namespace.copy() expected_ns.update({ "__name__": mod_name, "__file__": mod_fname, "__package__": pkg_name, }) if alter_sys: expected_ns.update({ "run_argv0": mod_fname, "run_name_in_sys_modules": True, "module_in_sys_modules": True, }) def create_ns(init_globals): return run_module(pkg_name, init_globals, alter_sys=alter_sys) try: if verbose > 1: print("Running from source:", pkg_name) self.check_code_execution(create_ns, expected_ns) importlib.invalidate_caches() __import__(mod_name) os.remove(mod_fname) make_legacy_pyc(mod_fname) unload(mod_name) # In case loader caches paths if verbose > 1: print("Running from compiled:", pkg_name) importlib.invalidate_caches() self._fix_ns_for_legacy_pyc(expected_ns, alter_sys) self.check_code_execution(create_ns, expected_ns) finally: self._del_pkg(pkg_dir, depth, pkg_name) if verbose > 1: print("Package executed successfully") def _add_relative_modules(self, base_dir, source, depth): if depth <= 1: raise ValueError("Relative module test needs depth > 1") pkg_name = "__runpy_pkg__" module_dir = base_dir for i in range(depth): parent_dir = module_dir module_dir = os.path.join(module_dir, pkg_name) # Add sibling module sibling_fname = os.path.join(module_dir, "sibling.py") create_empty_file(sibling_fname) if verbose > 1: print(" Added sibling module:", sibling_fname) # Add nephew module uncle_dir = os.path.join(parent_dir, "uncle") self._add_pkg_dir(uncle_dir) if verbose > 1: print(" Added uncle package:", uncle_dir) cousin_dir = os.path.join(uncle_dir, "cousin") self._add_pkg_dir(cousin_dir) if verbose > 1: print(" Added cousin package:", cousin_dir) nephew_fname = os.path.join(cousin_dir, "nephew.py") create_empty_file(nephew_fname) if verbose > 1: print(" Added nephew module:", nephew_fname) def _check_relative_imports(self, depth, run_name=None): contents = r"""\ from __future__ import absolute_import from . import sibling from ..uncle.cousin import nephew """ pkg_dir, mod_fname, mod_name = ( self._make_pkg(contents, depth)) if run_name is None: expected_name = mod_name else: expected_name = run_name try: self._add_relative_modules(pkg_dir, contents, depth) pkg_name = mod_name.rpartition('.')[0] if verbose > 1: print("Running from source:", mod_name) d1 = run_module(mod_name, run_name=run_name) # Read from source self.assertEqual(d1["__name__"], expected_name) self.assertEqual(d1["__package__"], pkg_name) self.assertIn("sibling", d1) self.assertIn("nephew", d1) del d1 # Ensure __loader__ entry doesn't keep file open importlib.invalidate_caches() __import__(mod_name) os.remove(mod_fname) make_legacy_pyc(mod_fname) unload(mod_name) # In case the loader caches paths if verbose > 1: print("Running from compiled:", mod_name) importlib.invalidate_caches() d2 = run_module(mod_name, run_name=run_name) # Read from bytecode self.assertEqual(d2["__name__"], expected_name) self.assertEqual(d2["__package__"], pkg_name) self.assertIn("sibling", d2) self.assertIn("nephew", d2) del d2 # Ensure __loader__ entry doesn't keep file open finally: self._del_pkg(pkg_dir, depth, mod_name) if verbose > 1: print("Module executed successfully") def test_run_module(self): for depth in range(4): if verbose > 1: print("Testing package depth:", depth) self._check_module(depth) def test_run_package(self): for depth in range(1, 4): if verbose > 1: print("Testing package depth:", depth) self._check_package(depth) def test_run_module_alter_sys(self): for depth in range(4): if verbose > 1: print("Testing package depth:", depth) self._check_module(depth, alter_sys=True) def test_run_package_alter_sys(self): for depth in range(1, 4): if verbose > 1: print("Testing package depth:", depth) self._check_package(depth, alter_sys=True) def test_explicit_relative_import(self): for depth in range(2, 5): if verbose > 1: print("Testing relative imports at depth:", depth) self._check_relative_imports(depth) def test_main_relative_import(self): for depth in range(2, 5): if verbose > 1: print("Testing main relative imports at depth:", depth) self._check_relative_imports(depth, "__main__") def test_run_name(self): depth = 1 run_name = "And now for something completely different" pkg_dir, mod_fname, mod_name = ( self._make_pkg(example_source, depth)) forget(mod_name) expected_ns = example_namespace.copy() expected_ns.update({ "__name__": run_name, "__file__": mod_fname, "__package__": mod_name.rpartition(".")[0], }) def create_ns(init_globals): return run_module(mod_name, init_globals, run_name) try: self.check_code_execution(create_ns, expected_ns) finally: self._del_pkg(pkg_dir, depth, mod_name) def test_pkgutil_walk_packages(self): # This is a dodgy hack to use the test_runpy infrastructure to test # issue #15343. Issue #15348 declares this is indeed a dodgy hack ;) import pkgutil max_depth = 4 base_name = "__runpy_pkg__" package_suffixes = ["uncle", "uncle.cousin"] module_suffixes = ["uncle.cousin.nephew", base_name + ".sibling"] expected_packages = set() expected_modules = set() for depth in range(1, max_depth): pkg_name = ".".join([base_name] * depth) expected_packages.add(pkg_name) for name in package_suffixes: expected_packages.add(pkg_name + "." + name) for name in module_suffixes: expected_modules.add(pkg_name + "." + name) pkg_name = ".".join([base_name] * max_depth) expected_packages.add(pkg_name) expected_modules.add(pkg_name + ".runpy_test") pkg_dir, mod_fname, mod_name = ( self._make_pkg("", max_depth)) self.addCleanup(self._del_pkg, pkg_dir, max_depth, mod_name) for depth in range(2, max_depth+1): self._add_relative_modules(pkg_dir, "", depth) for finder, mod_name, ispkg in pkgutil.walk_packages([pkg_dir]): self.assertIsInstance(finder, importlib.machinery.FileFinder) if ispkg: expected_packages.remove(mod_name) else: expected_modules.remove(mod_name) self.assertEqual(len(expected_packages), 0, expected_packages) self.assertEqual(len(expected_modules), 0, expected_modules) class RunPathTestCase(unittest.TestCase, CodeExecutionMixin): """Unit tests for runpy.run_path""" def _make_test_script(self, script_dir, script_basename, source=None): if source is None: source = example_source return make_script(script_dir, script_basename, source) def _check_script(self, script_name, expected_name, expected_file, expected_argv0): # First check is without run_name def create_ns(init_globals): return run_path(script_name, init_globals) expected_ns = example_namespace.copy() expected_ns.update({ "__name__": expected_name, "__file__": expected_file, "__package__": "", "run_argv0": expected_argv0, "run_name_in_sys_modules": True, "module_in_sys_modules": True, }) self.check_code_execution(create_ns, expected_ns) # Second check makes sure run_name works in all cases run_name = "prove.issue15230.is.fixed" def create_ns(init_globals): return run_path(script_name, init_globals, run_name) expected_ns["__name__"] = run_name expected_ns["__package__"] = run_name.rpartition(".")[0] self.check_code_execution(create_ns, expected_ns) def _check_import_error(self, script_name, msg): msg = re.escape(msg) self.assertRaisesRegex(ImportError, msg, run_path, script_name) def test_basic_script(self): with temp_dir() as script_dir: mod_name = 'script' script_name = self._make_test_script(script_dir, mod_name) self._check_script(script_name, "<run_path>", script_name, script_name) def test_script_compiled(self): with temp_dir() as script_dir: mod_name = 'script' script_name = self._make_test_script(script_dir, mod_name) compiled_name = py_compile.compile(script_name, doraise=True) os.remove(script_name) self._check_script(compiled_name, "<run_path>", compiled_name, compiled_name) def test_directory(self): with temp_dir() as script_dir: mod_name = '__main__' script_name = self._make_test_script(script_dir, mod_name) self._check_script(script_dir, "<run_path>", script_name, script_dir) def test_directory_compiled(self): with temp_dir() as script_dir: mod_name = '__main__' script_name = self._make_test_script(script_dir, mod_name) compiled_name = py_compile.compile(script_name, doraise=True) os.remove(script_name) legacy_pyc = make_legacy_pyc(script_name) self._check_script(script_dir, "<run_path>", legacy_pyc, script_dir) def test_directory_error(self): with temp_dir() as script_dir: mod_name = 'not_main' script_name = self._make_test_script(script_dir, mod_name) msg = "can't find '__main__' module in %r" % script_dir self._check_import_error(script_dir, msg) def test_zipfile(self): with temp_dir() as script_dir: mod_name = '__main__' script_name = self._make_test_script(script_dir, mod_name) zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name) self._check_script(zip_name, "<run_path>", fname, zip_name) def test_zipfile_compiled(self): with temp_dir() as script_dir: mod_name = '__main__' script_name = self._make_test_script(script_dir, mod_name) compiled_name = py_compile.compile(script_name, doraise=True) zip_name, fname = make_zip_script(script_dir, 'test_zip', compiled_name) self._check_script(zip_name, "<run_path>", fname, zip_name) def test_zipfile_error(self): with temp_dir() as script_dir: mod_name = 'not_main' script_name = self._make_test_script(script_dir, mod_name) zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name) msg = "can't find '__main__' module in %r" % zip_name self._check_import_error(zip_name, msg) @no_tracing def test_main_recursion_error(self): with temp_dir() as script_dir, temp_dir() as dummy_dir: mod_name = '__main__' source = ("import runpy\n" "runpy.run_path(%r)\n") % dummy_dir script_name = self._make_test_script(script_dir, mod_name, source) zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name) msg = "recursion depth exceeded" self.assertRaisesRegex(RuntimeError, msg, run_path, zip_name) def test_encoding(self): with temp_dir() as script_dir: filename = os.path.join(script_dir, 'script.py') with open(filename, 'w', encoding='latin1') as f: f.write(""" #coding:latin1 "non-ASCII: h\xe9" """) result = run_path(filename) self.assertEqual(result['__doc__'], "non-ASCII: h\xe9") def test_main(): run_unittest( ExecutionLayerTestCase, RunModuleTestCase, RunPathTestCase ) if __name__ == "__main__": test_main()
bsd-2-clause
barrysteyn/pelican-plugins
asciidoc_reader/asciidoc_reader.py
24
1918
# -*- coding: utf-8 -*- """ AsciiDoc Reader =============== This plugin allows you to use AsciiDoc to write your posts. File extension should be ``.asc``, ``.adoc``, or ``asciidoc``. """ from pelican.readers import BaseReader from pelican.utils import pelican_open from pelican import signals try: # asciidocapi won't import on Py3 from .asciidocapi import AsciiDocAPI, AsciiDocError # AsciiDocAPI class checks for asciidoc.py AsciiDocAPI() except: asciidoc_enabled = False else: asciidoc_enabled = True class AsciiDocReader(BaseReader): """Reader for AsciiDoc files""" enabled = asciidoc_enabled file_extensions = ['asc', 'adoc', 'asciidoc'] default_options = ["--no-header-footer", "-a newline=\\n"] default_backend = 'html5' def read(self, source_path): """Parse content and metadata of asciidoc files""" from cStringIO import StringIO with pelican_open(source_path) as source: text = StringIO(source.encode('utf8')) content = StringIO() ad = AsciiDocAPI() options = self.settings.get('ASCIIDOC_OPTIONS', []) options = self.default_options + options for o in options: ad.options(*o.split()) backend = self.settings.get('ASCIIDOC_BACKEND', self.default_backend) ad.execute(text, content, backend=backend) content = content.getvalue().decode('utf8') metadata = {} for name, value in ad.asciidoc.document.attributes.items(): name = name.lower() metadata[name] = self.process_metadata(name, value) if 'doctitle' in metadata: metadata['title'] = metadata['doctitle'] return content, metadata def add_reader(readers): for ext in AsciiDocReader.file_extensions: readers.reader_classes[ext] = AsciiDocReader def register(): signals.readers_init.connect(add_reader)
agpl-3.0
mfalcon/edujango
zinnia/views/quick_entry.py
7
3417
"""Views for Zinnia quick entry""" try: from urllib.parse import urlencode except: # Python 2 from urllib import urlencode from django import forms from django.shortcuts import redirect from django.utils.html import linebreaks from django.views.generic.base import View from django.utils.encoding import smart_str from django.core.urlresolvers import reverse from django.contrib.sites.models import Site from django.template.defaultfilters import slugify from django.utils.decorators import method_decorator from django.contrib.auth.decorators import permission_required from django.utils import timezone from zinnia.models.entry import Entry from zinnia.managers import DRAFT from zinnia.managers import PUBLISHED from zinnia.settings import MARKUP_LANGUAGE class QuickEntryForm(forms.ModelForm): """ Form for posting an entry quickly. """ class Meta: model = Entry exclude = ('comment_count', 'pingback_count', 'trackback_count') class QuickEntry(View): """ View handling the quick post of a short Entry. """ @method_decorator(permission_required('zinnia.add_entry')) def dispatch(self, *args, **kwargs): """ Decorate the view dispatcher with permission_required. """ return super(QuickEntry, self).dispatch(*args, **kwargs) def get(self, request, *args, **kwargs): """ GET only do a redirection to the admin for adding and entry. """ return redirect('admin:zinnia_entry_add') def post(self, request, *args, **kwargs): """ Handle the datas for posting a quick entry, and redirect to the admin in case of error or to the entry's page in case of success. """ data = { 'title': request.POST.get('title'), 'slug': slugify(request.POST.get('title')), 'status': DRAFT if 'save_draft' in request.POST else PUBLISHED, 'sites': [Site.objects.get_current().pk], 'authors': [request.user.pk], 'content_template': 'zinnia/_entry_detail.html', 'detail_template': 'entry_detail.html', 'creation_date': timezone.now(), 'last_update': timezone.now(), 'content': request.POST.get('content'), 'tags': request.POST.get('tags')} form = QuickEntryForm(data) if form.is_valid(): form.instance.content = self.htmlize(form.cleaned_data['content']) entry = form.save() return redirect(entry) data = {'title': smart_str(request.POST.get('title', '')), 'content': smart_str(self.htmlize( request.POST.get('content', ''))), 'tags': smart_str(request.POST.get('tags', '')), 'slug': slugify(request.POST.get('title', '')), 'authors': request.user.pk, 'sites': Site.objects.get_current().pk} return redirect('%s?%s' % (reverse('admin:zinnia_entry_add'), urlencode(data))) def htmlize(self, content): """ Convert to HTML the content if the MARKUP_LANGUAGE is set to HTML to optimize the rendering and avoid ugly effect in WYMEditor. """ if MARKUP_LANGUAGE == 'html': return linebreaks(content) return content
apache-2.0
w1ll1am23/home-assistant
tests/components/gree/test_init.py
6
1322
"""Tests for the Gree Integration.""" from unittest.mock import patch from homeassistant.components.gree.const import DOMAIN as GREE_DOMAIN from homeassistant.config_entries import ENTRY_STATE_LOADED, ENTRY_STATE_NOT_LOADED from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry async def test_setup_simple(hass, discovery, device): """Test gree integration is setup.""" await async_setup_component(hass, GREE_DOMAIN, {}) await hass.async_block_till_done() # No flows started assert len(hass.config_entries.flow.async_progress()) == 0 async def test_unload_config_entry(hass, discovery, device): """Test that the async_unload_entry works.""" # As we have currently no configuration, we just to pass the domain here. entry = MockConfigEntry(domain=GREE_DOMAIN) entry.add_to_hass(hass) with patch( "homeassistant.components.gree.climate.async_setup_entry", return_value=True, ) as climate_setup: assert await async_setup_component(hass, GREE_DOMAIN, {}) await hass.async_block_till_done() assert len(climate_setup.mock_calls) == 1 assert entry.state == ENTRY_STATE_LOADED await hass.config_entries.async_unload(entry.entry_id) assert entry.state == ENTRY_STATE_NOT_LOADED
apache-2.0
flwh/KK_mt6589_iq451
prebuilts/python/darwin-x86/2.7.5/lib/python2.7/plat-mac/lib-scriptpackages/SystemEvents/Text_Suite.py
82
5759
"""Suite Text Suite: A set of basic classes for text processing. Level 1, version 1 Generated from /System/Library/CoreServices/System Events.app AETE/AEUT resource version 1/0, language 0, script 0 """ import aetools import MacOS _code = '????' class Text_Suite_Events: pass class attachment(aetools.ComponentItem): """attachment - Represents an inline text attachment. This class is used mainly for make commands. """ want = 'atts' class _Prop__3c_Inheritance_3e_(aetools.NProperty): """<Inheritance> - All of the properties of the superclass. """ which = 'c@#^' want = 'ctxt' class _Prop_file_name(aetools.NProperty): """file name - The path to the file for the attachment """ which = 'atfn' want = 'utxt' # element 'catr' as ['indx', 'rele', 'rang', 'test'] # element 'cha ' as ['indx', 'rele', 'rang', 'test'] # element 'cpar' as ['indx', 'rele', 'rang', 'test'] # element 'cwor' as ['indx', 'rele', 'rang', 'test'] class attribute_run(aetools.ComponentItem): """attribute run - This subdivides the text into chunks that all have the same attributes. """ want = 'catr' class _Prop_color(aetools.NProperty): """color - The color of the first character. """ which = 'colr' want = 'colr' class _Prop_font(aetools.NProperty): """font - The name of the font of the first character. """ which = 'font' want = 'utxt' class _Prop_size(aetools.NProperty): """size - The size in points of the first character. """ which = 'ptsz' want = 'long' # element 'catr' as ['indx', 'rele', 'rang', 'test'] # element 'cha ' as ['indx', 'rele', 'rang', 'test'] # element 'cpar' as ['indx', 'rele', 'rang', 'test'] # element 'cwor' as ['indx', 'rele', 'rang', 'test'] attribute_runs = attribute_run class character(aetools.ComponentItem): """character - This subdivides the text into characters. """ want = 'cha ' # element 'catr' as ['indx', 'rele', 'rang', 'test'] # element 'cha ' as ['indx', 'rele', 'rang', 'test'] # element 'cpar' as ['indx', 'rele', 'rang', 'test'] # element 'cwor' as ['indx', 'rele', 'rang', 'test'] characters = character class paragraph(aetools.ComponentItem): """paragraph - This subdivides the text into paragraphs. """ want = 'cpar' # element 'catr' as ['indx', 'rele', 'rang', 'test'] # element 'cha ' as ['indx', 'rele', 'rang', 'test'] # element 'cpar' as ['indx', 'rele', 'rang', 'test'] # element 'cwor' as ['indx', 'rele', 'rang', 'test'] paragraphs = paragraph class text(aetools.ComponentItem): """text - Rich (styled) text """ want = 'ctxt' # element 'catr' as ['indx', 'rele', 'rang', 'test'] # element 'cha ' as ['indx', 'rele', 'rang', 'test'] # element 'cpar' as ['indx', 'rele', 'rang', 'test'] # element 'cwor' as ['indx', 'rele', 'rang', 'test'] class word(aetools.ComponentItem): """word - This subdivides the text into words. """ want = 'cwor' # element 'catr' as ['indx', 'rele', 'rang', 'test'] # element 'cha ' as ['indx', 'rele', 'rang', 'test'] # element 'cpar' as ['indx', 'rele', 'rang', 'test'] # element 'cwor' as ['indx', 'rele', 'rang', 'test'] words = word attachment._superclassnames = ['text'] attachment._privpropdict = { '_3c_Inheritance_3e_' : _Prop__3c_Inheritance_3e_, 'file_name' : _Prop_file_name, } attachment._privelemdict = { 'attribute_run' : attribute_run, 'character' : character, 'paragraph' : paragraph, 'word' : word, } import Standard_Suite attribute_run._superclassnames = ['item'] attribute_run._privpropdict = { '_3c_Inheritance_3e_' : _Prop__3c_Inheritance_3e_, 'color' : _Prop_color, 'font' : _Prop_font, 'size' : _Prop_size, } attribute_run._privelemdict = { 'attribute_run' : attribute_run, 'character' : character, 'paragraph' : paragraph, 'word' : word, } character._superclassnames = ['item'] character._privpropdict = { '_3c_Inheritance_3e_' : _Prop__3c_Inheritance_3e_, 'color' : _Prop_color, 'font' : _Prop_font, 'size' : _Prop_size, } character._privelemdict = { 'attribute_run' : attribute_run, 'character' : character, 'paragraph' : paragraph, 'word' : word, } paragraph._superclassnames = ['item'] paragraph._privpropdict = { '_3c_Inheritance_3e_' : _Prop__3c_Inheritance_3e_, 'color' : _Prop_color, 'font' : _Prop_font, 'size' : _Prop_size, } paragraph._privelemdict = { 'attribute_run' : attribute_run, 'character' : character, 'paragraph' : paragraph, 'word' : word, } text._superclassnames = ['item'] text._privpropdict = { '_3c_Inheritance_3e_' : _Prop__3c_Inheritance_3e_, 'color' : _Prop_color, 'font' : _Prop_font, 'size' : _Prop_size, } text._privelemdict = { 'attribute_run' : attribute_run, 'character' : character, 'paragraph' : paragraph, 'word' : word, } word._superclassnames = ['item'] word._privpropdict = { '_3c_Inheritance_3e_' : _Prop__3c_Inheritance_3e_, 'color' : _Prop_color, 'font' : _Prop_font, 'size' : _Prop_size, } word._privelemdict = { 'attribute_run' : attribute_run, 'character' : character, 'paragraph' : paragraph, 'word' : word, } # # Indices of types declared in this module # _classdeclarations = { 'atts' : attachment, 'catr' : attribute_run, 'cha ' : character, 'cpar' : paragraph, 'ctxt' : text, 'cwor' : word, } _propdeclarations = { 'atfn' : _Prop_file_name, 'c@#^' : _Prop__3c_Inheritance_3e_, 'colr' : _Prop_color, 'font' : _Prop_font, 'ptsz' : _Prop_size, } _compdeclarations = { } _enumdeclarations = { }
gpl-2.0
broferek/ansible
lib/ansible/modules/network/onyx/onyx_qos.py
28
9337
#!/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: onyx_qos version_added: "2.9" author: "Anas Badaha (@anasb)" short_description: Configures QoS description: - This module provides declarative management of Onyx QoS configuration on Mellanox ONYX network devices. notes: - Tested on ONYX 3.6.8130 options: interfaces: description: - list of interfaces name. required: true trust: description: - trust type. choices: ['L2', 'L3', 'both'] default: L2 rewrite_pcp: description: - rewrite with type pcp. choices: ['enabled', 'disabled'] default: disabled rewrite_dscp: description: - rewrite with type dscp. choices: ['enabled', 'disabled'] default: disabled """ EXAMPLES = """ - name: configure QoS onyx_QoS: interfaces: - Mpo7 - Mpo7 trust: L3 rewrite_pcp: disabled rewrite_dscp: enabled - name: configure QoS onyx_QoS: interfaces: - Eth1/1 - Eth1/2 trust: both rewrite_pcp: disabled rewrite_dscp: enabled """ RETURN = """ commands: description: The list of configuration mode commands to send to the device. returned: always type: list sample: - interface ethernet 1/16 qos trust L3 - interface mlag-port-channel 7 qos trust L3 - interface port-channel 1 qos trust L3 - interface mlag-port-channel 7 qos trust L2 - interface mlag-port-channel 7 qos rewrite dscp - interface ethernet 1/16 qos rewrite pcp - interface ethernet 1/1 no qos rewrite pcp """ import re from ansible.module_utils.six import iteritems from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.onyx.onyx import show_cmd from ansible.module_utils.network.onyx.onyx import BaseOnyxModule class OnyxQosModule(BaseOnyxModule): TRUST_CMD = "interface {0} {1} qos trust {2}" NO_REWRITE_PCP_CMD = "interface {0} {1} no qos rewrite pcp" NO_REWRITE_DSCP_CMD = "interface {0} {1} no qos rewrite dscp" REWRITE_PCP_CMD = "interface {0} {1} qos rewrite pcp" REWRITE_DSCP_CMD = "interface {0} {1} qos rewrite dscp" REWRITE_PCP = "pcp" REWRITE_DSCP = "dscp" IF_ETH_REGEX = re.compile(r"^Eth(\d+\/\d+|Eth\d+\/\d+\d+)$") IF_PO_REGEX = re.compile(r"^Po(\d+)$") MLAG_NAME_REGEX = re.compile(r"^Mpo(\d+)$") IF_TYPE_ETH = "ethernet" PORT_CHANNEL = "port-channel" MLAG_PORT_CHANNEL = "mlag-port-channel" IF_TYPE_MAP = { IF_TYPE_ETH: IF_ETH_REGEX, PORT_CHANNEL: IF_PO_REGEX, MLAG_PORT_CHANNEL: MLAG_NAME_REGEX } def init_module(self): """ initialize module """ element_spec = dict( interfaces=dict(type='list', required=True), trust=dict(choices=['L2', 'L3', 'both'], default='L2'), rewrite_pcp=dict(choices=['enabled', 'disabled'], default='disabled'), rewrite_dscp=dict(choices=['enabled', 'disabled'], default='disabled') ) argument_spec = dict() argument_spec.update(element_spec) self._module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True) def get_required_config(self): module_params = self._module.params self._required_config = dict(module_params) self.validate_param_values(self._required_config) def _get_interface_type(self, if_name): if_type = None if_id = None for interface_type, interface_regex in iteritems(self.IF_TYPE_MAP): match = interface_regex.match(if_name) if match: if_type = interface_type if_id = match.group(1) break return if_type, if_id def _set_interface_qos_config(self, interface_qos_config, interface, if_type, if_id): interface_qos_config = interface_qos_config[0].get(interface) trust = interface_qos_config[0].get("Trust mode") rewrite_dscp = interface_qos_config[0].get("DSCP rewrite") rewrite_pcp = interface_qos_config[0].get("PCP,DEI rewrite") self._current_config[interface] = dict(trust=trust, rewrite_dscp=rewrite_dscp, rewrite_pcp=rewrite_pcp, if_type=if_type, if_id=if_id) def _show_interface_qos(self, if_type, interface): cmd = "show qos interface {0} {1}".format(if_type, interface) return show_cmd(self._module, cmd, json_fmt=True, fail_on_error=False) def load_current_config(self): self._current_config = dict() for interface in self._required_config.get("interfaces"): if_type, if_id = self._get_interface_type(interface) if not if_id: self._module.fail_json( msg='unsupported interface: {0}'.format(interface)) interface_qos_config = self._show_interface_qos(if_type, if_id) if interface_qos_config is not None: self._set_interface_qos_config(interface_qos_config, interface, if_type, if_id) else: self._module.fail_json( msg='Interface {0} does not exist on switch'.format(interface)) def generate_commands(self): trust = self._required_config.get("trust") rewrite_pcp = self._required_config.get("rewrite_pcp") rewrite_dscp = self._required_config.get("rewrite_dscp") for interface in self._required_config.get("interfaces"): ignored1, ignored2, current_trust, if_type, if_id = self._get_current_rewrite_config(interface) self._add_interface_trust_cmds(if_type, if_id, interface, trust, current_trust) self._add_interface_rewrite_cmds(if_type, if_id, interface, rewrite_pcp, rewrite_dscp) def _get_current_rewrite_config(self, interface): current_interface_qos_config = self._current_config.get(interface) current_rewrite_pcp = current_interface_qos_config.get('rewrite_pcp') current_rewrite_dscp = current_interface_qos_config.get('rewrite_dscp') if_type = current_interface_qos_config.get("if_type") if_id = current_interface_qos_config.get("if_id") current_trust = current_interface_qos_config.get('trust') return current_rewrite_pcp, current_rewrite_dscp, current_trust, if_type, if_id def _add_interface_trust_cmds(self, if_type, if_id, interface, trust, current_trust): current_rewrite_pcp, current_rewrite_dscp, ignored1, ignored2, ignored3 = self._get_current_rewrite_config( interface) if trust == "L3" and trust != current_trust: self._add_no_rewrite_cmd(if_type, if_id, interface, self.REWRITE_DSCP, current_rewrite_dscp) self._commands.append(self.TRUST_CMD.format(if_type, if_id, trust)) elif trust == "L2" and trust != current_trust: self._add_no_rewrite_cmd(if_type, if_id, interface, self.REWRITE_PCP, current_rewrite_pcp) self._commands.append(self.TRUST_CMD.format(if_type, if_id, trust)) elif trust == "both" and trust != current_trust: self._add_no_rewrite_cmd(if_type, if_id, interface, self.REWRITE_DSCP, current_rewrite_dscp) self._add_no_rewrite_cmd(if_type, if_id, interface, self.REWRITE_PCP, current_rewrite_pcp) self._commands.append(self.TRUST_CMD.format(if_type, if_id, trust)) def _add_interface_rewrite_cmds(self, if_type, if_id, interface, rewrite_pcp, rewrite_dscp): current_rewrite_pcp, current_rewrite_dscp, ignored1, ignored2, ignored3 = self._get_current_rewrite_config( interface) if rewrite_pcp == "enabled" and rewrite_pcp != current_rewrite_pcp: self._commands.append(self.REWRITE_PCP_CMD.format(if_type, if_id)) elif rewrite_pcp == "disabled" and rewrite_pcp != current_rewrite_pcp: self._commands.append(self.NO_REWRITE_PCP_CMD.format(if_type, if_id)) if rewrite_dscp == "enabled" and rewrite_dscp != current_rewrite_dscp: self._commands.append(self.REWRITE_DSCP_CMD.format(if_type, if_id)) elif rewrite_dscp == "disabled" and rewrite_dscp != current_rewrite_dscp: self._commands.append(self.NO_REWRITE_DSCP_CMD.format(if_type, if_id)) def _add_no_rewrite_cmd(self, if_type, if_id, interface, rewrite_type, current_rewrite): if rewrite_type == self.REWRITE_PCP and current_rewrite == "enabled": self._commands.append(self.NO_REWRITE_PCP_CMD.format(if_type, if_id)) self._current_config[interface]["rewrite_pcp"] = "disabled" elif rewrite_type == self.REWRITE_DSCP and current_rewrite == "enabled": self._commands.append(self.NO_REWRITE_DSCP_CMD.format(if_type, if_id)) self._current_config[interface]["rewrite_dscp"] = "disabled" def main(): """ main entry point for module execution """ OnyxQosModule.main() if __name__ == '__main__': main()
gpl-3.0
fxfitz/ansible
test/units/module_utils/facts/system/test_lsb.py
118
4485
# unit tests for ansible system lsb fact collectors # -*- coding: utf-8 -*- # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # Make coding more python3-ish from __future__ import (absolute_import, division) __metaclass__ = type from ansible.compat.tests.mock import Mock, patch from .. base import BaseFactsTest from ansible.module_utils.facts.system.lsb import LSBFactCollector lsb_release_a_fedora_output = ''' LSB Version: :core-4.1-amd64:core-4.1-noarch:cxx-4.1-amd64:cxx-4.1-noarch:desktop-4.1-amd64:desktop-4.1-noarch:languages-4.1-amd64:languages-4.1-noarch:printing-4.1-amd64:printing-4.1-noarch Distributor ID: Fedora Description: Fedora release 25 (Twenty Five) Release: 25 Codename: TwentyFive ''' # noqa # FIXME: a etc_lsb_release_ubuntu14 = '''DISTRIB_ID=Ubuntu DISTRIB_RELEASE=14.04 DISTRIB_CODENAME=trusty DISTRIB_DESCRIPTION="Ubuntu 14.04.3 LTS" ''' etc_lsb_release_no_decimal = '''DISTRIB_ID=AwesomeOS DISTRIB_RELEASE=11 DISTRIB_CODENAME=stonehenge DISTRIB_DESCRIPTION="AwesomeÖS 11" ''' class TestLSBFacts(BaseFactsTest): __test__ = True gather_subset = ['!all', 'lsb'] valid_subsets = ['lsb'] fact_namespace = 'ansible_lsb' collector_class = LSBFactCollector def _mock_module(self): mock_module = Mock() mock_module.params = {'gather_subset': self.gather_subset, 'gather_timeout': 10, 'filter': '*'} mock_module.get_bin_path = Mock(return_value='/usr/bin/lsb_release') mock_module.run_command = Mock(return_value=(0, lsb_release_a_fedora_output, '')) return mock_module def test_lsb_release_bin(self): module = self._mock_module() fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module) self.assertIsInstance(facts_dict, dict) self.assertEqual(facts_dict['lsb']['release'], '25') self.assertEqual(facts_dict['lsb']['id'], 'Fedora') self.assertEqual(facts_dict['lsb']['description'], 'Fedora release 25 (Twenty Five)') self.assertEqual(facts_dict['lsb']['codename'], 'TwentyFive') self.assertEqual(facts_dict['lsb']['major_release'], '25') def test_etc_lsb_release(self): module = self._mock_module() module.get_bin_path = Mock(return_value=None) with patch('ansible.module_utils.facts.system.lsb.os.path.exists', return_value=True): with patch('ansible.module_utils.facts.system.lsb.get_file_lines', return_value=etc_lsb_release_ubuntu14.splitlines()): fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module) self.assertIsInstance(facts_dict, dict) self.assertEqual(facts_dict['lsb']['release'], '14.04') self.assertEqual(facts_dict['lsb']['id'], 'Ubuntu') self.assertEqual(facts_dict['lsb']['description'], '"Ubuntu 14.04.3 LTS"') self.assertEqual(facts_dict['lsb']['codename'], 'trusty') def test_etc_lsb_release_no_decimal_release(self): module = self._mock_module() module.get_bin_path = Mock(return_value=None) with patch('ansible.module_utils.facts.system.lsb.os.path.exists', return_value=True): with patch('ansible.module_utils.facts.system.lsb.get_file_lines', return_value=etc_lsb_release_no_decimal.splitlines()): fact_collector = self.collector_class() facts_dict = fact_collector.collect(module=module) self.assertIsInstance(facts_dict, dict) self.assertEqual(facts_dict['lsb']['release'], '11') self.assertEqual(facts_dict['lsb']['id'], 'AwesomeOS') self.assertEqual(facts_dict['lsb']['description'], '"AwesomeÖS 11"') self.assertEqual(facts_dict['lsb']['codename'], 'stonehenge')
gpl-3.0
viaembedded/vab820-kernel-bsp-old
scripts/analyze_suspend.py
1537
120394
#!/usr/bin/python # # Tool for analyzing suspend/resume timing # Copyright (c) 2013, Intel Corporation. # # This program is free software; you can redistribute it and/or modify it # under the terms and conditions of the GNU General Public License, # version 2, as published by the Free Software Foundation. # # This program is distributed in the hope 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 St - Fifth Floor, Boston, MA 02110-1301 USA. # # Authors: # Todd Brandt <todd.e.brandt@linux.intel.com> # # Description: # This tool is designed to assist kernel and OS developers in optimizing # their linux stack's suspend/resume time. Using a kernel image built # with a few extra options enabled, the tool will execute a suspend and # will capture dmesg and ftrace data until resume is complete. This data # is transformed into a device timeline and a callgraph to give a quick # and detailed view of which devices and callbacks are taking the most # time in suspend/resume. The output is a single html file which can be # viewed in firefox or chrome. # # The following kernel build options are required: # CONFIG_PM_DEBUG=y # CONFIG_PM_SLEEP_DEBUG=y # CONFIG_FTRACE=y # CONFIG_FUNCTION_TRACER=y # CONFIG_FUNCTION_GRAPH_TRACER=y # # For kernel versions older than 3.15: # The following additional kernel parameters are required: # (e.g. in file /etc/default/grub) # GRUB_CMDLINE_LINUX_DEFAULT="... initcall_debug log_buf_len=16M ..." # # ----------------- LIBRARIES -------------------- import sys import time import os import string import re import platform from datetime import datetime import struct # ----------------- CLASSES -------------------- # Class: SystemValues # Description: # A global, single-instance container used to # store system values and test parameters class SystemValues: version = 3.0 verbose = False testdir = '.' tpath = '/sys/kernel/debug/tracing/' fpdtpath = '/sys/firmware/acpi/tables/FPDT' epath = '/sys/kernel/debug/tracing/events/power/' traceevents = [ 'suspend_resume', 'device_pm_callback_end', 'device_pm_callback_start' ] modename = { 'freeze': 'Suspend-To-Idle (S0)', 'standby': 'Power-On Suspend (S1)', 'mem': 'Suspend-to-RAM (S3)', 'disk': 'Suspend-to-disk (S4)' } mempath = '/dev/mem' powerfile = '/sys/power/state' suspendmode = 'mem' hostname = 'localhost' prefix = 'test' teststamp = '' dmesgfile = '' ftracefile = '' htmlfile = '' rtcwake = False rtcwaketime = 10 rtcpath = '' android = False adb = 'adb' devicefilter = [] stamp = 0 execcount = 1 x2delay = 0 usecallgraph = False usetraceevents = False usetraceeventsonly = False notestrun = False altdevname = dict() postresumetime = 0 tracertypefmt = '# tracer: (?P<t>.*)' firmwarefmt = '# fwsuspend (?P<s>[0-9]*) fwresume (?P<r>[0-9]*)$' postresumefmt = '# post resume time (?P<t>[0-9]*)$' stampfmt = '# suspend-(?P<m>[0-9]{2})(?P<d>[0-9]{2})(?P<y>[0-9]{2})-'+\ '(?P<H>[0-9]{2})(?P<M>[0-9]{2})(?P<S>[0-9]{2})'+\ ' (?P<host>.*) (?P<mode>.*) (?P<kernel>.*)$' def __init__(self): self.hostname = platform.node() if(self.hostname == ''): self.hostname = 'localhost' rtc = "rtc0" if os.path.exists('/dev/rtc'): rtc = os.readlink('/dev/rtc') rtc = '/sys/class/rtc/'+rtc if os.path.exists(rtc) and os.path.exists(rtc+'/date') and \ os.path.exists(rtc+'/time') and os.path.exists(rtc+'/wakealarm'): self.rtcpath = rtc def setOutputFile(self): if((self.htmlfile == '') and (self.dmesgfile != '')): m = re.match('(?P<name>.*)_dmesg\.txt$', self.dmesgfile) if(m): self.htmlfile = m.group('name')+'.html' if((self.htmlfile == '') and (self.ftracefile != '')): m = re.match('(?P<name>.*)_ftrace\.txt$', self.ftracefile) if(m): self.htmlfile = m.group('name')+'.html' if(self.htmlfile == ''): self.htmlfile = 'output.html' def initTestOutput(self, subdir): if(not self.android): self.prefix = self.hostname v = open('/proc/version', 'r').read().strip() kver = string.split(v)[2] else: self.prefix = 'android' v = os.popen(self.adb+' shell cat /proc/version').read().strip() kver = string.split(v)[2] testtime = datetime.now().strftime('suspend-%m%d%y-%H%M%S') if(subdir != "."): self.testdir = subdir+"/"+testtime else: self.testdir = testtime self.teststamp = \ '# '+testtime+' '+self.prefix+' '+self.suspendmode+' '+kver self.dmesgfile = \ self.testdir+'/'+self.prefix+'_'+self.suspendmode+'_dmesg.txt' self.ftracefile = \ self.testdir+'/'+self.prefix+'_'+self.suspendmode+'_ftrace.txt' self.htmlfile = \ self.testdir+'/'+self.prefix+'_'+self.suspendmode+'.html' os.mkdir(self.testdir) def setDeviceFilter(self, devnames): self.devicefilter = string.split(devnames) def rtcWakeAlarm(self): os.system('echo 0 > '+self.rtcpath+'/wakealarm') outD = open(self.rtcpath+'/date', 'r').read().strip() outT = open(self.rtcpath+'/time', 'r').read().strip() mD = re.match('^(?P<y>[0-9]*)-(?P<m>[0-9]*)-(?P<d>[0-9]*)', outD) mT = re.match('^(?P<h>[0-9]*):(?P<m>[0-9]*):(?P<s>[0-9]*)', outT) if(mD and mT): # get the current time from hardware utcoffset = int((datetime.now() - datetime.utcnow()).total_seconds()) dt = datetime(\ int(mD.group('y')), int(mD.group('m')), int(mD.group('d')), int(mT.group('h')), int(mT.group('m')), int(mT.group('s'))) nowtime = int(dt.strftime('%s')) + utcoffset else: # if hardware time fails, use the software time nowtime = int(datetime.now().strftime('%s')) alarm = nowtime + self.rtcwaketime os.system('echo %d > %s/wakealarm' % (alarm, self.rtcpath)) sysvals = SystemValues() # Class: DeviceNode # Description: # A container used to create a device hierachy, with a single root node # and a tree of child nodes. Used by Data.deviceTopology() class DeviceNode: name = '' children = 0 depth = 0 def __init__(self, nodename, nodedepth): self.name = nodename self.children = [] self.depth = nodedepth # Class: Data # Description: # The primary container for suspend/resume test data. There is one for # each test run. The data is organized into a cronological hierarchy: # Data.dmesg { # root structure, started as dmesg & ftrace, but now only ftrace # contents: times for suspend start/end, resume start/end, fwdata # phases { # 10 sequential, non-overlapping phases of S/R # contents: times for phase start/end, order/color data for html # devlist { # device callback or action list for this phase # device { # a single device callback or generic action # contents: start/stop times, pid/cpu/driver info # parents/children, html id for timeline/callgraph # optionally includes an ftrace callgraph # optionally includes intradev trace events # } # } # } # } # class Data: dmesg = {} # root data structure phases = [] # ordered list of phases start = 0.0 # test start end = 0.0 # test end tSuspended = 0.0 # low-level suspend start tResumed = 0.0 # low-level resume start tLow = 0.0 # time spent in low-level suspend (standby/freeze) fwValid = False # is firmware data available fwSuspend = 0 # time spent in firmware suspend fwResume = 0 # time spent in firmware resume dmesgtext = [] # dmesg text file in memory testnumber = 0 idstr = '' html_device_id = 0 stamp = 0 outfile = '' def __init__(self, num): idchar = 'abcdefghijklmnopqrstuvwxyz' self.testnumber = num self.idstr = idchar[num] self.dmesgtext = [] self.phases = [] self.dmesg = { # fixed list of 10 phases 'suspend_prepare': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': '#CCFFCC', 'order': 0}, 'suspend': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': '#88FF88', 'order': 1}, 'suspend_late': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': '#00AA00', 'order': 2}, 'suspend_noirq': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': '#008888', 'order': 3}, 'suspend_machine': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': '#0000FF', 'order': 4}, 'resume_machine': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': '#FF0000', 'order': 5}, 'resume_noirq': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': '#FF9900', 'order': 6}, 'resume_early': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': '#FFCC00', 'order': 7}, 'resume': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': '#FFFF88', 'order': 8}, 'resume_complete': {'list': dict(), 'start': -1.0, 'end': -1.0, 'row': 0, 'color': '#FFFFCC', 'order': 9} } self.phases = self.sortedPhases() def getStart(self): return self.dmesg[self.phases[0]]['start'] def setStart(self, time): self.start = time self.dmesg[self.phases[0]]['start'] = time def getEnd(self): return self.dmesg[self.phases[-1]]['end'] def setEnd(self, time): self.end = time self.dmesg[self.phases[-1]]['end'] = time def isTraceEventOutsideDeviceCalls(self, pid, time): for phase in self.phases: list = self.dmesg[phase]['list'] for dev in list: d = list[dev] if(d['pid'] == pid and time >= d['start'] and time <= d['end']): return False return True def addIntraDevTraceEvent(self, action, name, pid, time): if(action == 'mutex_lock_try'): color = 'red' elif(action == 'mutex_lock_pass'): color = 'green' elif(action == 'mutex_unlock'): color = 'blue' else: # create separate colors based on the name v1 = len(name)*10 % 256 v2 = string.count(name, 'e')*100 % 256 v3 = ord(name[0])*20 % 256 color = '#%06X' % ((v1*0x10000) + (v2*0x100) + v3) for phase in self.phases: list = self.dmesg[phase]['list'] for dev in list: d = list[dev] if(d['pid'] == pid and time >= d['start'] and time <= d['end']): e = TraceEvent(action, name, color, time) if('traceevents' not in d): d['traceevents'] = [] d['traceevents'].append(e) return d break return 0 def capIntraDevTraceEvent(self, action, name, pid, time): for phase in self.phases: list = self.dmesg[phase]['list'] for dev in list: d = list[dev] if(d['pid'] == pid and time >= d['start'] and time <= d['end']): if('traceevents' not in d): return for e in d['traceevents']: if(e.action == action and e.name == name and not e.ready): e.length = time - e.time e.ready = True break return def trimTimeVal(self, t, t0, dT, left): if left: if(t > t0): if(t - dT < t0): return t0 return t - dT else: return t else: if(t < t0 + dT): if(t > t0): return t0 + dT return t + dT else: return t def trimTime(self, t0, dT, left): self.tSuspended = self.trimTimeVal(self.tSuspended, t0, dT, left) self.tResumed = self.trimTimeVal(self.tResumed, t0, dT, left) self.start = self.trimTimeVal(self.start, t0, dT, left) self.end = self.trimTimeVal(self.end, t0, dT, left) for phase in self.phases: p = self.dmesg[phase] p['start'] = self.trimTimeVal(p['start'], t0, dT, left) p['end'] = self.trimTimeVal(p['end'], t0, dT, left) list = p['list'] for name in list: d = list[name] d['start'] = self.trimTimeVal(d['start'], t0, dT, left) d['end'] = self.trimTimeVal(d['end'], t0, dT, left) if('ftrace' in d): cg = d['ftrace'] cg.start = self.trimTimeVal(cg.start, t0, dT, left) cg.end = self.trimTimeVal(cg.end, t0, dT, left) for line in cg.list: line.time = self.trimTimeVal(line.time, t0, dT, left) if('traceevents' in d): for e in d['traceevents']: e.time = self.trimTimeVal(e.time, t0, dT, left) def normalizeTime(self, tZero): # first trim out any standby or freeze clock time if(self.tSuspended != self.tResumed): if(self.tResumed > tZero): self.trimTime(self.tSuspended, \ self.tResumed-self.tSuspended, True) else: self.trimTime(self.tSuspended, \ self.tResumed-self.tSuspended, False) # shift the timeline so that tZero is the new 0 self.tSuspended -= tZero self.tResumed -= tZero self.start -= tZero self.end -= tZero for phase in self.phases: p = self.dmesg[phase] p['start'] -= tZero p['end'] -= tZero list = p['list'] for name in list: d = list[name] d['start'] -= tZero d['end'] -= tZero if('ftrace' in d): cg = d['ftrace'] cg.start -= tZero cg.end -= tZero for line in cg.list: line.time -= tZero if('traceevents' in d): for e in d['traceevents']: e.time -= tZero def newPhaseWithSingleAction(self, phasename, devname, start, end, color): for phase in self.phases: self.dmesg[phase]['order'] += 1 self.html_device_id += 1 devid = '%s%d' % (self.idstr, self.html_device_id) list = dict() list[devname] = \ {'start': start, 'end': end, 'pid': 0, 'par': '', 'length': (end-start), 'row': 0, 'id': devid, 'drv': '' }; self.dmesg[phasename] = \ {'list': list, 'start': start, 'end': end, 'row': 0, 'color': color, 'order': 0} self.phases = self.sortedPhases() def newPhase(self, phasename, start, end, color, order): if(order < 0): order = len(self.phases) for phase in self.phases[order:]: self.dmesg[phase]['order'] += 1 if(order > 0): p = self.phases[order-1] self.dmesg[p]['end'] = start if(order < len(self.phases)): p = self.phases[order] self.dmesg[p]['start'] = end list = dict() self.dmesg[phasename] = \ {'list': list, 'start': start, 'end': end, 'row': 0, 'color': color, 'order': order} self.phases = self.sortedPhases() def setPhase(self, phase, ktime, isbegin): if(isbegin): self.dmesg[phase]['start'] = ktime else: self.dmesg[phase]['end'] = ktime def dmesgSortVal(self, phase): return self.dmesg[phase]['order'] def sortedPhases(self): return sorted(self.dmesg, key=self.dmesgSortVal) def sortedDevices(self, phase): list = self.dmesg[phase]['list'] slist = [] tmp = dict() for devname in list: dev = list[devname] tmp[dev['start']] = devname for t in sorted(tmp): slist.append(tmp[t]) return slist def fixupInitcalls(self, phase, end): # if any calls never returned, clip them at system resume end phaselist = self.dmesg[phase]['list'] for devname in phaselist: dev = phaselist[devname] if(dev['end'] < 0): dev['end'] = end vprint('%s (%s): callback didnt return' % (devname, phase)) def deviceFilter(self, devicefilter): # remove all by the relatives of the filter devnames filter = [] for phase in self.phases: list = self.dmesg[phase]['list'] for name in devicefilter: dev = name while(dev in list): if(dev not in filter): filter.append(dev) dev = list[dev]['par'] children = self.deviceDescendants(name, phase) for dev in children: if(dev not in filter): filter.append(dev) for phase in self.phases: list = self.dmesg[phase]['list'] rmlist = [] for name in list: pid = list[name]['pid'] if(name not in filter and pid >= 0): rmlist.append(name) for name in rmlist: del list[name] def fixupInitcallsThatDidntReturn(self): # if any calls never returned, clip them at system resume end for phase in self.phases: self.fixupInitcalls(phase, self.getEnd()) def newActionGlobal(self, name, start, end): # which phase is this device callback or action "in" targetphase = "none" overlap = 0.0 for phase in self.phases: pstart = self.dmesg[phase]['start'] pend = self.dmesg[phase]['end'] o = max(0, min(end, pend) - max(start, pstart)) if(o > overlap): targetphase = phase overlap = o if targetphase in self.phases: self.newAction(targetphase, name, -1, '', start, end, '') return True return False def newAction(self, phase, name, pid, parent, start, end, drv): # new device callback for a specific phase self.html_device_id += 1 devid = '%s%d' % (self.idstr, self.html_device_id) list = self.dmesg[phase]['list'] length = -1.0 if(start >= 0 and end >= 0): length = end - start list[name] = {'start': start, 'end': end, 'pid': pid, 'par': parent, 'length': length, 'row': 0, 'id': devid, 'drv': drv } def deviceIDs(self, devlist, phase): idlist = [] list = self.dmesg[phase]['list'] for devname in list: if devname in devlist: idlist.append(list[devname]['id']) return idlist def deviceParentID(self, devname, phase): pdev = '' pdevid = '' list = self.dmesg[phase]['list'] if devname in list: pdev = list[devname]['par'] if pdev in list: return list[pdev]['id'] return pdev def deviceChildren(self, devname, phase): devlist = [] list = self.dmesg[phase]['list'] for child in list: if(list[child]['par'] == devname): devlist.append(child) return devlist def deviceDescendants(self, devname, phase): children = self.deviceChildren(devname, phase) family = children for child in children: family += self.deviceDescendants(child, phase) return family def deviceChildrenIDs(self, devname, phase): devlist = self.deviceChildren(devname, phase) return self.deviceIDs(devlist, phase) def printDetails(self): vprint(' test start: %f' % self.start) for phase in self.phases: dc = len(self.dmesg[phase]['list']) vprint(' %16s: %f - %f (%d devices)' % (phase, \ self.dmesg[phase]['start'], self.dmesg[phase]['end'], dc)) vprint(' test end: %f' % self.end) def masterTopology(self, name, list, depth): node = DeviceNode(name, depth) for cname in list: clist = self.deviceChildren(cname, 'resume') cnode = self.masterTopology(cname, clist, depth+1) node.children.append(cnode) return node def printTopology(self, node): html = '' if node.name: info = '' drv = '' for phase in self.phases: list = self.dmesg[phase]['list'] if node.name in list: s = list[node.name]['start'] e = list[node.name]['end'] if list[node.name]['drv']: drv = ' {'+list[node.name]['drv']+'}' info += ('<li>%s: %.3fms</li>' % (phase, (e-s)*1000)) html += '<li><b>'+node.name+drv+'</b>' if info: html += '<ul>'+info+'</ul>' html += '</li>' if len(node.children) > 0: html += '<ul>' for cnode in node.children: html += self.printTopology(cnode) html += '</ul>' return html def rootDeviceList(self): # list of devices graphed real = [] for phase in self.dmesg: list = self.dmesg[phase]['list'] for dev in list: if list[dev]['pid'] >= 0 and dev not in real: real.append(dev) # list of top-most root devices rootlist = [] for phase in self.dmesg: list = self.dmesg[phase]['list'] for dev in list: pdev = list[dev]['par'] if(re.match('[0-9]*-[0-9]*\.[0-9]*[\.0-9]*\:[\.0-9]*$', pdev)): continue if pdev and pdev not in real and pdev not in rootlist: rootlist.append(pdev) return rootlist def deviceTopology(self): rootlist = self.rootDeviceList() master = self.masterTopology('', rootlist, 0) return self.printTopology(master) # Class: TraceEvent # Description: # A container for trace event data found in the ftrace file class TraceEvent: ready = False name = '' time = 0.0 color = '#FFFFFF' length = 0.0 action = '' def __init__(self, a, n, c, t): self.action = a self.name = n self.color = c self.time = t # Class: FTraceLine # Description: # A container for a single line of ftrace data. There are six basic types: # callgraph line: # call: " dpm_run_callback() {" # return: " }" # leaf: " dpm_run_callback();" # trace event: # tracing_mark_write: SUSPEND START or RESUME COMPLETE # suspend_resume: phase or custom exec block data # device_pm_callback: device callback info class FTraceLine: time = 0.0 length = 0.0 fcall = False freturn = False fevent = False depth = 0 name = '' type = '' def __init__(self, t, m, d): self.time = float(t) # is this a trace event if(d == 'traceevent' or re.match('^ *\/\* *(?P<msg>.*) \*\/ *$', m)): if(d == 'traceevent'): # nop format trace event msg = m else: # function_graph format trace event em = re.match('^ *\/\* *(?P<msg>.*) \*\/ *$', m) msg = em.group('msg') emm = re.match('^(?P<call>.*?): (?P<msg>.*)', msg) if(emm): self.name = emm.group('msg') self.type = emm.group('call') else: self.name = msg self.fevent = True return # convert the duration to seconds if(d): self.length = float(d)/1000000 # the indentation determines the depth match = re.match('^(?P<d> *)(?P<o>.*)$', m) if(not match): return self.depth = self.getDepth(match.group('d')) m = match.group('o') # function return if(m[0] == '}'): self.freturn = True if(len(m) > 1): # includes comment with function name match = re.match('^} *\/\* *(?P<n>.*) *\*\/$', m) if(match): self.name = match.group('n') # function call else: self.fcall = True # function call with children if(m[-1] == '{'): match = re.match('^(?P<n>.*) *\(.*', m) if(match): self.name = match.group('n') # function call with no children (leaf) elif(m[-1] == ';'): self.freturn = True match = re.match('^(?P<n>.*) *\(.*', m) if(match): self.name = match.group('n') # something else (possibly a trace marker) else: self.name = m def getDepth(self, str): return len(str)/2 def debugPrint(self, dev): if(self.freturn and self.fcall): print('%s -- %f (%02d): %s(); (%.3f us)' % (dev, self.time, \ self.depth, self.name, self.length*1000000)) elif(self.freturn): print('%s -- %f (%02d): %s} (%.3f us)' % (dev, self.time, \ self.depth, self.name, self.length*1000000)) else: print('%s -- %f (%02d): %s() { (%.3f us)' % (dev, self.time, \ self.depth, self.name, self.length*1000000)) # Class: FTraceCallGraph # Description: # A container for the ftrace callgraph of a single recursive function. # This can be a dpm_run_callback, dpm_prepare, or dpm_complete callgraph # Each instance is tied to a single device in a single phase, and is # comprised of an ordered list of FTraceLine objects class FTraceCallGraph: start = -1.0 end = -1.0 list = [] invalid = False depth = 0 def __init__(self): self.start = -1.0 self.end = -1.0 self.list = [] self.depth = 0 def setDepth(self, line): if(line.fcall and not line.freturn): line.depth = self.depth self.depth += 1 elif(line.freturn and not line.fcall): self.depth -= 1 line.depth = self.depth else: line.depth = self.depth def addLine(self, line, match): if(not self.invalid): self.setDepth(line) if(line.depth == 0 and line.freturn): if(self.start < 0): self.start = line.time self.end = line.time self.list.append(line) return True if(self.invalid): return False if(len(self.list) >= 1000000 or self.depth < 0): if(len(self.list) > 0): first = self.list[0] self.list = [] self.list.append(first) self.invalid = True if(not match): return False id = 'task %s cpu %s' % (match.group('pid'), match.group('cpu')) window = '(%f - %f)' % (self.start, line.time) if(self.depth < 0): print('Too much data for '+id+\ ' (buffer overflow), ignoring this callback') else: print('Too much data for '+id+\ ' '+window+', ignoring this callback') return False self.list.append(line) if(self.start < 0): self.start = line.time return False def slice(self, t0, tN): minicg = FTraceCallGraph() count = -1 firstdepth = 0 for l in self.list: if(l.time < t0 or l.time > tN): continue if(count < 0): if(not l.fcall or l.name == 'dev_driver_string'): continue firstdepth = l.depth count = 0 l.depth -= firstdepth minicg.addLine(l, 0) if((count == 0 and l.freturn and l.fcall) or (count > 0 and l.depth <= 0)): break count += 1 return minicg def sanityCheck(self): stack = dict() cnt = 0 for l in self.list: if(l.fcall and not l.freturn): stack[l.depth] = l cnt += 1 elif(l.freturn and not l.fcall): if(l.depth not in stack): return False stack[l.depth].length = l.length stack[l.depth] = 0 l.length = 0 cnt -= 1 if(cnt == 0): return True return False def debugPrint(self, filename): if(filename == 'stdout'): print('[%f - %f]') % (self.start, self.end) for l in self.list: if(l.freturn and l.fcall): print('%f (%02d): %s(); (%.3f us)' % (l.time, \ l.depth, l.name, l.length*1000000)) elif(l.freturn): print('%f (%02d): %s} (%.3f us)' % (l.time, \ l.depth, l.name, l.length*1000000)) else: print('%f (%02d): %s() { (%.3f us)' % (l.time, \ l.depth, l.name, l.length*1000000)) print(' ') else: fp = open(filename, 'w') print(filename) for l in self.list: if(l.freturn and l.fcall): fp.write('%f (%02d): %s(); (%.3f us)\n' % (l.time, \ l.depth, l.name, l.length*1000000)) elif(l.freturn): fp.write('%f (%02d): %s} (%.3f us)\n' % (l.time, \ l.depth, l.name, l.length*1000000)) else: fp.write('%f (%02d): %s() { (%.3f us)\n' % (l.time, \ l.depth, l.name, l.length*1000000)) fp.close() # Class: Timeline # Description: # A container for a suspend/resume html timeline. In older versions # of the script there were multiple timelines, but in the latest # there is only one. class Timeline: html = {} scaleH = 0.0 # height of the row as a percent of the timeline height rowH = 0.0 # height of each row in percent of the timeline height row_height_pixels = 30 maxrows = 0 height = 0 def __init__(self): self.html = { 'timeline': '', 'legend': '', 'scale': '' } def setRows(self, rows): self.maxrows = int(rows) self.scaleH = 100.0/float(self.maxrows) self.height = self.maxrows*self.row_height_pixels r = float(self.maxrows - 1) if(r < 1.0): r = 1.0 self.rowH = (100.0 - self.scaleH)/r # Class: TestRun # Description: # A container for a suspend/resume test run. This is necessary as # there could be more than one, and they need to be separate. class TestRun: ftrace_line_fmt_fg = \ '^ *(?P<time>[0-9\.]*) *\| *(?P<cpu>[0-9]*)\)'+\ ' *(?P<proc>.*)-(?P<pid>[0-9]*) *\|'+\ '[ +!]*(?P<dur>[0-9\.]*) .*\| (?P<msg>.*)' ftrace_line_fmt_nop = \ ' *(?P<proc>.*)-(?P<pid>[0-9]*) *\[(?P<cpu>[0-9]*)\] *'+\ '(?P<flags>.{4}) *(?P<time>[0-9\.]*): *'+\ '(?P<msg>.*)' ftrace_line_fmt = ftrace_line_fmt_nop cgformat = False ftemp = dict() ttemp = dict() inthepipe = False tracertype = '' data = 0 def __init__(self, dataobj): self.data = dataobj self.ftemp = dict() self.ttemp = dict() def isReady(self): if(tracertype == '' or not data): return False return True def setTracerType(self, tracer): self.tracertype = tracer if(tracer == 'function_graph'): self.cgformat = True self.ftrace_line_fmt = self.ftrace_line_fmt_fg elif(tracer == 'nop'): self.ftrace_line_fmt = self.ftrace_line_fmt_nop else: doError('Invalid tracer format: [%s]' % tracer, False) # ----------------- FUNCTIONS -------------------- # Function: vprint # Description: # verbose print (prints only with -verbose option) # Arguments: # msg: the debug/log message to print def vprint(msg): global sysvals if(sysvals.verbose): print(msg) # Function: initFtrace # Description: # Configure ftrace to use trace events and/or a callgraph def initFtrace(): global sysvals tp = sysvals.tpath cf = 'dpm_run_callback' if(sysvals.usetraceeventsonly): cf = '-e dpm_prepare -e dpm_complete -e dpm_run_callback' if(sysvals.usecallgraph or sysvals.usetraceevents): print('INITIALIZING FTRACE...') # turn trace off os.system('echo 0 > '+tp+'tracing_on') # set the trace clock to global os.system('echo global > '+tp+'trace_clock') # set trace buffer to a huge value os.system('echo nop > '+tp+'current_tracer') os.system('echo 100000 > '+tp+'buffer_size_kb') # initialize the callgraph trace, unless this is an x2 run if(sysvals.usecallgraph and sysvals.execcount == 1): # set trace type os.system('echo function_graph > '+tp+'current_tracer') os.system('echo "" > '+tp+'set_ftrace_filter') # set trace format options os.system('echo funcgraph-abstime > '+tp+'trace_options') os.system('echo funcgraph-proc > '+tp+'trace_options') # focus only on device suspend and resume os.system('cat '+tp+'available_filter_functions | grep '+\ cf+' > '+tp+'set_graph_function') if(sysvals.usetraceevents): # turn trace events on events = iter(sysvals.traceevents) for e in events: os.system('echo 1 > '+sysvals.epath+e+'/enable') # clear the trace buffer os.system('echo "" > '+tp+'trace') # Function: initFtraceAndroid # Description: # Configure ftrace to capture trace events def initFtraceAndroid(): global sysvals tp = sysvals.tpath if(sysvals.usetraceevents): print('INITIALIZING FTRACE...') # turn trace off os.system(sysvals.adb+" shell 'echo 0 > "+tp+"tracing_on'") # set the trace clock to global os.system(sysvals.adb+" shell 'echo global > "+tp+"trace_clock'") # set trace buffer to a huge value os.system(sysvals.adb+" shell 'echo nop > "+tp+"current_tracer'") os.system(sysvals.adb+" shell 'echo 10000 > "+tp+"buffer_size_kb'") # turn trace events on events = iter(sysvals.traceevents) for e in events: os.system(sysvals.adb+" shell 'echo 1 > "+\ sysvals.epath+e+"/enable'") # clear the trace buffer os.system(sysvals.adb+" shell 'echo \"\" > "+tp+"trace'") # Function: verifyFtrace # Description: # Check that ftrace is working on the system # Output: # True or False def verifyFtrace(): global sysvals # files needed for any trace data files = ['buffer_size_kb', 'current_tracer', 'trace', 'trace_clock', 'trace_marker', 'trace_options', 'tracing_on'] # files needed for callgraph trace data tp = sysvals.tpath if(sysvals.usecallgraph): files += [ 'available_filter_functions', 'set_ftrace_filter', 'set_graph_function' ] for f in files: if(sysvals.android): out = os.popen(sysvals.adb+' shell ls '+tp+f).read().strip() if(out != tp+f): return False else: if(os.path.exists(tp+f) == False): return False return True # Function: parseStamp # Description: # Pull in the stamp comment line from the data file(s), # create the stamp, and add it to the global sysvals object # Arguments: # m: the valid re.match output for the stamp line def parseStamp(m, data): global sysvals data.stamp = {'time': '', 'host': '', 'mode': ''} dt = datetime(int(m.group('y'))+2000, int(m.group('m')), int(m.group('d')), int(m.group('H')), int(m.group('M')), int(m.group('S'))) data.stamp['time'] = dt.strftime('%B %d %Y, %I:%M:%S %p') data.stamp['host'] = m.group('host') data.stamp['mode'] = m.group('mode') data.stamp['kernel'] = m.group('kernel') sysvals.suspendmode = data.stamp['mode'] if not sysvals.stamp: sysvals.stamp = data.stamp # Function: diffStamp # Description: # compare the host, kernel, and mode fields in 3 stamps # Arguments: # stamp1: string array with mode, kernel, and host # stamp2: string array with mode, kernel, and host # Return: # True if stamps differ, False if they're the same def diffStamp(stamp1, stamp2): if 'host' in stamp1 and 'host' in stamp2: if stamp1['host'] != stamp2['host']: return True if 'kernel' in stamp1 and 'kernel' in stamp2: if stamp1['kernel'] != stamp2['kernel']: return True if 'mode' in stamp1 and 'mode' in stamp2: if stamp1['mode'] != stamp2['mode']: return True return False # Function: doesTraceLogHaveTraceEvents # Description: # Quickly determine if the ftrace log has some or all of the trace events # required for primary parsing. Set the usetraceevents and/or # usetraceeventsonly flags in the global sysvals object def doesTraceLogHaveTraceEvents(): global sysvals sysvals.usetraceeventsonly = True sysvals.usetraceevents = False for e in sysvals.traceevents: out = os.popen('cat '+sysvals.ftracefile+' | grep "'+e+': "').read() if(not out): sysvals.usetraceeventsonly = False if(e == 'suspend_resume' and out): sysvals.usetraceevents = True # Function: appendIncompleteTraceLog # Description: # [deprecated for kernel 3.15 or newer] # Legacy support of ftrace outputs that lack the device_pm_callback # and/or suspend_resume trace events. The primary data should be # taken from dmesg, and this ftrace is used only for callgraph data # or custom actions in the timeline. The data is appended to the Data # objects provided. # Arguments: # testruns: the array of Data objects obtained from parseKernelLog def appendIncompleteTraceLog(testruns): global sysvals # create TestRun vessels for ftrace parsing testcnt = len(testruns) testidx = -1 testrun = [] for data in testruns: testrun.append(TestRun(data)) # extract the callgraph and traceevent data vprint('Analyzing the ftrace data...') tf = open(sysvals.ftracefile, 'r') for line in tf: # remove any latent carriage returns line = line.replace('\r\n', '') # grab the time stamp first (signifies the start of the test run) m = re.match(sysvals.stampfmt, line) if(m): testidx += 1 parseStamp(m, testrun[testidx].data) continue # pull out any firmware data if(re.match(sysvals.firmwarefmt, line)): continue # if we havent found a test time stamp yet keep spinning til we do if(testidx < 0): continue # determine the trace data type (required for further parsing) m = re.match(sysvals.tracertypefmt, line) if(m): tracer = m.group('t') testrun[testidx].setTracerType(tracer) continue # parse only valid lines, if this isnt one move on m = re.match(testrun[testidx].ftrace_line_fmt, line) if(not m): continue # gather the basic message data from the line m_time = m.group('time') m_pid = m.group('pid') m_msg = m.group('msg') if(testrun[testidx].cgformat): m_param3 = m.group('dur') else: m_param3 = 'traceevent' if(m_time and m_pid and m_msg): t = FTraceLine(m_time, m_msg, m_param3) pid = int(m_pid) else: continue # the line should be a call, return, or event if(not t.fcall and not t.freturn and not t.fevent): continue # only parse the ftrace data during suspend/resume data = testrun[testidx].data if(not testrun[testidx].inthepipe): # look for the suspend start marker if(t.fevent): if(t.name == 'SUSPEND START'): testrun[testidx].inthepipe = True data.setStart(t.time) continue else: # trace event processing if(t.fevent): if(t.name == 'RESUME COMPLETE'): testrun[testidx].inthepipe = False data.setEnd(t.time) if(testidx == testcnt - 1): break continue # general trace events have two types, begin and end if(re.match('(?P<name>.*) begin$', t.name)): isbegin = True elif(re.match('(?P<name>.*) end$', t.name)): isbegin = False else: continue m = re.match('(?P<name>.*)\[(?P<val>[0-9]*)\] .*', t.name) if(m): val = m.group('val') if val == '0': name = m.group('name') else: name = m.group('name')+'['+val+']' else: m = re.match('(?P<name>.*) .*', t.name) name = m.group('name') # special processing for trace events if re.match('dpm_prepare\[.*', name): continue elif re.match('machine_suspend.*', name): continue elif re.match('suspend_enter\[.*', name): if(not isbegin): data.dmesg['suspend_prepare']['end'] = t.time continue elif re.match('dpm_suspend\[.*', name): if(not isbegin): data.dmesg['suspend']['end'] = t.time continue elif re.match('dpm_suspend_late\[.*', name): if(isbegin): data.dmesg['suspend_late']['start'] = t.time else: data.dmesg['suspend_late']['end'] = t.time continue elif re.match('dpm_suspend_noirq\[.*', name): if(isbegin): data.dmesg['suspend_noirq']['start'] = t.time else: data.dmesg['suspend_noirq']['end'] = t.time continue elif re.match('dpm_resume_noirq\[.*', name): if(isbegin): data.dmesg['resume_machine']['end'] = t.time data.dmesg['resume_noirq']['start'] = t.time else: data.dmesg['resume_noirq']['end'] = t.time continue elif re.match('dpm_resume_early\[.*', name): if(isbegin): data.dmesg['resume_early']['start'] = t.time else: data.dmesg['resume_early']['end'] = t.time continue elif re.match('dpm_resume\[.*', name): if(isbegin): data.dmesg['resume']['start'] = t.time else: data.dmesg['resume']['end'] = t.time continue elif re.match('dpm_complete\[.*', name): if(isbegin): data.dmesg['resume_complete']['start'] = t.time else: data.dmesg['resume_complete']['end'] = t.time continue # is this trace event outside of the devices calls if(data.isTraceEventOutsideDeviceCalls(pid, t.time)): # global events (outside device calls) are simply graphed if(isbegin): # store each trace event in ttemp if(name not in testrun[testidx].ttemp): testrun[testidx].ttemp[name] = [] testrun[testidx].ttemp[name].append(\ {'begin': t.time, 'end': t.time}) else: # finish off matching trace event in ttemp if(name in testrun[testidx].ttemp): testrun[testidx].ttemp[name][-1]['end'] = t.time else: if(isbegin): data.addIntraDevTraceEvent('', name, pid, t.time) else: data.capIntraDevTraceEvent('', name, pid, t.time) # call/return processing elif sysvals.usecallgraph: # create a callgraph object for the data if(pid not in testrun[testidx].ftemp): testrun[testidx].ftemp[pid] = [] testrun[testidx].ftemp[pid].append(FTraceCallGraph()) # when the call is finished, see which device matches it cg = testrun[testidx].ftemp[pid][-1] if(cg.addLine(t, m)): testrun[testidx].ftemp[pid].append(FTraceCallGraph()) tf.close() for test in testrun: # add the traceevent data to the device hierarchy if(sysvals.usetraceevents): for name in test.ttemp: for event in test.ttemp[name]: begin = event['begin'] end = event['end'] # if event starts before timeline start, expand timeline if(begin < test.data.start): test.data.setStart(begin) # if event ends after timeline end, expand the timeline if(end > test.data.end): test.data.setEnd(end) test.data.newActionGlobal(name, begin, end) # add the callgraph data to the device hierarchy for pid in test.ftemp: for cg in test.ftemp[pid]: if(not cg.sanityCheck()): id = 'task %s cpu %s' % (pid, m.group('cpu')) vprint('Sanity check failed for '+\ id+', ignoring this callback') continue callstart = cg.start callend = cg.end for p in test.data.phases: if(test.data.dmesg[p]['start'] <= callstart and callstart <= test.data.dmesg[p]['end']): list = test.data.dmesg[p]['list'] for devname in list: dev = list[devname] if(pid == dev['pid'] and callstart <= dev['start'] and callend >= dev['end']): dev['ftrace'] = cg break if(sysvals.verbose): test.data.printDetails() # add the time in between the tests as a new phase so we can see it if(len(testruns) > 1): t1e = testruns[0].getEnd() t2s = testruns[-1].getStart() testruns[-1].newPhaseWithSingleAction('user mode', \ 'user mode', t1e, t2s, '#FF9966') # Function: parseTraceLog # Description: # Analyze an ftrace log output file generated from this app during # the execution phase. Used when the ftrace log is the primary data source # and includes the suspend_resume and device_pm_callback trace events # The ftrace filename is taken from sysvals # Output: # An array of Data objects def parseTraceLog(): global sysvals vprint('Analyzing the ftrace data...') if(os.path.exists(sysvals.ftracefile) == False): doError('%s doesnt exist' % sysvals.ftracefile, False) # extract the callgraph and traceevent data testruns = [] testdata = [] testrun = 0 data = 0 tf = open(sysvals.ftracefile, 'r') phase = 'suspend_prepare' for line in tf: # remove any latent carriage returns line = line.replace('\r\n', '') # stamp line: each stamp means a new test run m = re.match(sysvals.stampfmt, line) if(m): data = Data(len(testdata)) testdata.append(data) testrun = TestRun(data) testruns.append(testrun) parseStamp(m, data) continue if(not data): continue # firmware line: pull out any firmware data m = re.match(sysvals.firmwarefmt, line) if(m): data.fwSuspend = int(m.group('s')) data.fwResume = int(m.group('r')) if(data.fwSuspend > 0 or data.fwResume > 0): data.fwValid = True continue # tracer type line: determine the trace data type m = re.match(sysvals.tracertypefmt, line) if(m): tracer = m.group('t') testrun.setTracerType(tracer) continue # post resume time line: did this test run include post-resume data m = re.match(sysvals.postresumefmt, line) if(m): t = int(m.group('t')) if(t > 0): sysvals.postresumetime = t continue # ftrace line: parse only valid lines m = re.match(testrun.ftrace_line_fmt, line) if(not m): continue # gather the basic message data from the line m_time = m.group('time') m_pid = m.group('pid') m_msg = m.group('msg') if(testrun.cgformat): m_param3 = m.group('dur') else: m_param3 = 'traceevent' if(m_time and m_pid and m_msg): t = FTraceLine(m_time, m_msg, m_param3) pid = int(m_pid) else: continue # the line should be a call, return, or event if(not t.fcall and not t.freturn and not t.fevent): continue # only parse the ftrace data during suspend/resume if(not testrun.inthepipe): # look for the suspend start marker if(t.fevent): if(t.name == 'SUSPEND START'): testrun.inthepipe = True data.setStart(t.time) continue # trace event processing if(t.fevent): if(t.name == 'RESUME COMPLETE'): if(sysvals.postresumetime > 0): phase = 'post_resume' data.newPhase(phase, t.time, t.time, '#FF9966', -1) else: testrun.inthepipe = False data.setEnd(t.time) continue if(phase == 'post_resume'): data.setEnd(t.time) if(t.type == 'suspend_resume'): # suspend_resume trace events have two types, begin and end if(re.match('(?P<name>.*) begin$', t.name)): isbegin = True elif(re.match('(?P<name>.*) end$', t.name)): isbegin = False else: continue m = re.match('(?P<name>.*)\[(?P<val>[0-9]*)\] .*', t.name) if(m): val = m.group('val') if val == '0': name = m.group('name') else: name = m.group('name')+'['+val+']' else: m = re.match('(?P<name>.*) .*', t.name) name = m.group('name') # ignore these events if(re.match('acpi_suspend\[.*', t.name) or re.match('suspend_enter\[.*', name)): continue # -- phase changes -- # suspend_prepare start if(re.match('dpm_prepare\[.*', t.name)): phase = 'suspend_prepare' if(not isbegin): data.dmesg[phase]['end'] = t.time continue # suspend start elif(re.match('dpm_suspend\[.*', t.name)): phase = 'suspend' data.setPhase(phase, t.time, isbegin) continue # suspend_late start elif(re.match('dpm_suspend_late\[.*', t.name)): phase = 'suspend_late' data.setPhase(phase, t.time, isbegin) continue # suspend_noirq start elif(re.match('dpm_suspend_noirq\[.*', t.name)): phase = 'suspend_noirq' data.setPhase(phase, t.time, isbegin) if(not isbegin): phase = 'suspend_machine' data.dmesg[phase]['start'] = t.time continue # suspend_machine/resume_machine elif(re.match('machine_suspend\[.*', t.name)): if(isbegin): phase = 'suspend_machine' data.dmesg[phase]['end'] = t.time data.tSuspended = t.time else: if(sysvals.suspendmode in ['mem', 'disk']): data.dmesg['suspend_machine']['end'] = t.time data.tSuspended = t.time phase = 'resume_machine' data.dmesg[phase]['start'] = t.time data.tResumed = t.time data.tLow = data.tResumed - data.tSuspended continue # resume_noirq start elif(re.match('dpm_resume_noirq\[.*', t.name)): phase = 'resume_noirq' data.setPhase(phase, t.time, isbegin) if(isbegin): data.dmesg['resume_machine']['end'] = t.time continue # resume_early start elif(re.match('dpm_resume_early\[.*', t.name)): phase = 'resume_early' data.setPhase(phase, t.time, isbegin) continue # resume start elif(re.match('dpm_resume\[.*', t.name)): phase = 'resume' data.setPhase(phase, t.time, isbegin) continue # resume complete start elif(re.match('dpm_complete\[.*', t.name)): phase = 'resume_complete' if(isbegin): data.dmesg[phase]['start'] = t.time continue # is this trace event outside of the devices calls if(data.isTraceEventOutsideDeviceCalls(pid, t.time)): # global events (outside device calls) are simply graphed if(name not in testrun.ttemp): testrun.ttemp[name] = [] if(isbegin): # create a new list entry testrun.ttemp[name].append(\ {'begin': t.time, 'end': t.time}) else: if(len(testrun.ttemp[name]) > 0): # if an antry exists, assume this is its end testrun.ttemp[name][-1]['end'] = t.time elif(phase == 'post_resume'): # post resume events can just have ends testrun.ttemp[name].append({ 'begin': data.dmesg[phase]['start'], 'end': t.time}) else: if(isbegin): data.addIntraDevTraceEvent('', name, pid, t.time) else: data.capIntraDevTraceEvent('', name, pid, t.time) # device callback start elif(t.type == 'device_pm_callback_start'): m = re.match('(?P<drv>.*) (?P<d>.*), parent: *(?P<p>.*), .*',\ t.name); if(not m): continue drv = m.group('drv') n = m.group('d') p = m.group('p') if(n and p): data.newAction(phase, n, pid, p, t.time, -1, drv) # device callback finish elif(t.type == 'device_pm_callback_end'): m = re.match('(?P<drv>.*) (?P<d>.*), err.*', t.name); if(not m): continue n = m.group('d') list = data.dmesg[phase]['list'] if(n in list): dev = list[n] dev['length'] = t.time - dev['start'] dev['end'] = t.time # callgraph processing elif sysvals.usecallgraph: # this shouldn't happen, but JIC, ignore callgraph data post-res if(phase == 'post_resume'): continue # create a callgraph object for the data if(pid not in testrun.ftemp): testrun.ftemp[pid] = [] testrun.ftemp[pid].append(FTraceCallGraph()) # when the call is finished, see which device matches it cg = testrun.ftemp[pid][-1] if(cg.addLine(t, m)): testrun.ftemp[pid].append(FTraceCallGraph()) tf.close() for test in testruns: # add the traceevent data to the device hierarchy if(sysvals.usetraceevents): for name in test.ttemp: for event in test.ttemp[name]: begin = event['begin'] end = event['end'] # if event starts before timeline start, expand timeline if(begin < test.data.start): test.data.setStart(begin) # if event ends after timeline end, expand the timeline if(end > test.data.end): test.data.setEnd(end) test.data.newActionGlobal(name, begin, end) # add the callgraph data to the device hierarchy borderphase = { 'dpm_prepare': 'suspend_prepare', 'dpm_complete': 'resume_complete' } for pid in test.ftemp: for cg in test.ftemp[pid]: if len(cg.list) < 2: continue if(not cg.sanityCheck()): id = 'task %s cpu %s' % (pid, m.group('cpu')) vprint('Sanity check failed for '+\ id+', ignoring this callback') continue callstart = cg.start callend = cg.end if(cg.list[0].name in borderphase): p = borderphase[cg.list[0].name] list = test.data.dmesg[p]['list'] for devname in list: dev = list[devname] if(pid == dev['pid'] and callstart <= dev['start'] and callend >= dev['end']): dev['ftrace'] = cg.slice(dev['start'], dev['end']) continue if(cg.list[0].name != 'dpm_run_callback'): continue for p in test.data.phases: if(test.data.dmesg[p]['start'] <= callstart and callstart <= test.data.dmesg[p]['end']): list = test.data.dmesg[p]['list'] for devname in list: dev = list[devname] if(pid == dev['pid'] and callstart <= dev['start'] and callend >= dev['end']): dev['ftrace'] = cg break # fill in any missing phases for data in testdata: lp = data.phases[0] for p in data.phases: if(data.dmesg[p]['start'] < 0 and data.dmesg[p]['end'] < 0): print('WARNING: phase "%s" is missing!' % p) if(data.dmesg[p]['start'] < 0): data.dmesg[p]['start'] = data.dmesg[lp]['end'] if(p == 'resume_machine'): data.tSuspended = data.dmesg[lp]['end'] data.tResumed = data.dmesg[lp]['end'] data.tLow = 0 if(data.dmesg[p]['end'] < 0): data.dmesg[p]['end'] = data.dmesg[p]['start'] lp = p if(len(sysvals.devicefilter) > 0): data.deviceFilter(sysvals.devicefilter) data.fixupInitcallsThatDidntReturn() if(sysvals.verbose): data.printDetails() # add the time in between the tests as a new phase so we can see it if(len(testdata) > 1): t1e = testdata[0].getEnd() t2s = testdata[-1].getStart() testdata[-1].newPhaseWithSingleAction('user mode', \ 'user mode', t1e, t2s, '#FF9966') return testdata # Function: loadKernelLog # Description: # [deprecated for kernel 3.15.0 or newer] # load the dmesg file into memory and fix up any ordering issues # The dmesg filename is taken from sysvals # Output: # An array of empty Data objects with only their dmesgtext attributes set def loadKernelLog(): global sysvals vprint('Analyzing the dmesg data...') if(os.path.exists(sysvals.dmesgfile) == False): doError('%s doesnt exist' % sysvals.dmesgfile, False) # there can be multiple test runs in a single file delineated by stamps testruns = [] data = 0 lf = open(sysvals.dmesgfile, 'r') for line in lf: line = line.replace('\r\n', '') idx = line.find('[') if idx > 1: line = line[idx:] m = re.match(sysvals.stampfmt, line) if(m): if(data): testruns.append(data) data = Data(len(testruns)) parseStamp(m, data) continue if(not data): continue m = re.match(sysvals.firmwarefmt, line) if(m): data.fwSuspend = int(m.group('s')) data.fwResume = int(m.group('r')) if(data.fwSuspend > 0 or data.fwResume > 0): data.fwValid = True continue m = re.match('[ \t]*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)', line) if(m): data.dmesgtext.append(line) if(re.match('ACPI: resume from mwait', m.group('msg'))): print('NOTE: This suspend appears to be freeze rather than'+\ ' %s, it will be treated as such' % sysvals.suspendmode) sysvals.suspendmode = 'freeze' else: vprint('ignoring dmesg line: %s' % line.replace('\n', '')) testruns.append(data) lf.close() if(not data): print('ERROR: analyze_suspend header missing from dmesg log') sys.exit() # fix lines with same timestamp/function with the call and return swapped for data in testruns: last = '' for line in data.dmesgtext: mc = re.match('.*(\[ *)(?P<t>[0-9\.]*)(\]) calling '+\ '(?P<f>.*)\+ @ .*, parent: .*', line) mr = re.match('.*(\[ *)(?P<t>[0-9\.]*)(\]) call '+\ '(?P<f>.*)\+ returned .* after (?P<dt>.*) usecs', last) if(mc and mr and (mc.group('t') == mr.group('t')) and (mc.group('f') == mr.group('f'))): i = data.dmesgtext.index(last) j = data.dmesgtext.index(line) data.dmesgtext[i] = line data.dmesgtext[j] = last last = line return testruns # Function: parseKernelLog # Description: # [deprecated for kernel 3.15.0 or newer] # Analyse a dmesg log output file generated from this app during # the execution phase. Create a set of device structures in memory # for subsequent formatting in the html output file # This call is only for legacy support on kernels where the ftrace # data lacks the suspend_resume or device_pm_callbacks trace events. # Arguments: # data: an empty Data object (with dmesgtext) obtained from loadKernelLog # Output: # The filled Data object def parseKernelLog(data): global sysvals phase = 'suspend_runtime' if(data.fwValid): vprint('Firmware Suspend = %u ns, Firmware Resume = %u ns' % \ (data.fwSuspend, data.fwResume)) # dmesg phase match table dm = { 'suspend_prepare': 'PM: Syncing filesystems.*', 'suspend': 'PM: Entering [a-z]* sleep.*', 'suspend_late': 'PM: suspend of devices complete after.*', 'suspend_noirq': 'PM: late suspend of devices complete after.*', 'suspend_machine': 'PM: noirq suspend of devices complete after.*', 'resume_machine': 'ACPI: Low-level resume complete.*', 'resume_noirq': 'ACPI: Waking up from system sleep state.*', 'resume_early': 'PM: noirq resume of devices complete after.*', 'resume': 'PM: early resume of devices complete after.*', 'resume_complete': 'PM: resume of devices complete after.*', 'post_resume': '.*Restarting tasks \.\.\..*', } if(sysvals.suspendmode == 'standby'): dm['resume_machine'] = 'PM: Restoring platform NVS memory' elif(sysvals.suspendmode == 'disk'): dm['suspend_late'] = 'PM: freeze of devices complete after.*' dm['suspend_noirq'] = 'PM: late freeze of devices complete after.*' dm['suspend_machine'] = 'PM: noirq freeze of devices complete after.*' dm['resume_machine'] = 'PM: Restoring platform NVS memory' dm['resume_early'] = 'PM: noirq restore of devices complete after.*' dm['resume'] = 'PM: early restore of devices complete after.*' dm['resume_complete'] = 'PM: restore of devices complete after.*' elif(sysvals.suspendmode == 'freeze'): dm['resume_machine'] = 'ACPI: resume from mwait' # action table (expected events that occur and show up in dmesg) at = { 'sync_filesystems': { 'smsg': 'PM: Syncing filesystems.*', 'emsg': 'PM: Preparing system for mem sleep.*' }, 'freeze_user_processes': { 'smsg': 'Freezing user space processes .*', 'emsg': 'Freezing remaining freezable tasks.*' }, 'freeze_tasks': { 'smsg': 'Freezing remaining freezable tasks.*', 'emsg': 'PM: Entering (?P<mode>[a-z,A-Z]*) sleep.*' }, 'ACPI prepare': { 'smsg': 'ACPI: Preparing to enter system sleep state.*', 'emsg': 'PM: Saving platform NVS memory.*' }, 'PM vns': { 'smsg': 'PM: Saving platform NVS memory.*', 'emsg': 'Disabling non-boot CPUs .*' }, } t0 = -1.0 cpu_start = -1.0 prevktime = -1.0 actions = dict() for line in data.dmesgtext: # -- preprocessing -- # parse each dmesg line into the time and message m = re.match('[ \t]*(\[ *)(?P<ktime>[0-9\.]*)(\]) (?P<msg>.*)', line) if(m): val = m.group('ktime') try: ktime = float(val) except: doWarning('INVALID DMESG LINE: '+\ line.replace('\n', ''), 'dmesg') continue msg = m.group('msg') # initialize data start to first line time if t0 < 0: data.setStart(ktime) t0 = ktime else: continue # hack for determining resume_machine end for freeze if(not sysvals.usetraceevents and sysvals.suspendmode == 'freeze' \ and phase == 'resume_machine' and \ re.match('calling (?P<f>.*)\+ @ .*, parent: .*', msg)): data.dmesg['resume_machine']['end'] = ktime phase = 'resume_noirq' data.dmesg[phase]['start'] = ktime # -- phase changes -- # suspend start if(re.match(dm['suspend_prepare'], msg)): phase = 'suspend_prepare' data.dmesg[phase]['start'] = ktime data.setStart(ktime) # suspend start elif(re.match(dm['suspend'], msg)): data.dmesg['suspend_prepare']['end'] = ktime phase = 'suspend' data.dmesg[phase]['start'] = ktime # suspend_late start elif(re.match(dm['suspend_late'], msg)): data.dmesg['suspend']['end'] = ktime phase = 'suspend_late' data.dmesg[phase]['start'] = ktime # suspend_noirq start elif(re.match(dm['suspend_noirq'], msg)): data.dmesg['suspend_late']['end'] = ktime phase = 'suspend_noirq' data.dmesg[phase]['start'] = ktime # suspend_machine start elif(re.match(dm['suspend_machine'], msg)): data.dmesg['suspend_noirq']['end'] = ktime phase = 'suspend_machine' data.dmesg[phase]['start'] = ktime # resume_machine start elif(re.match(dm['resume_machine'], msg)): if(sysvals.suspendmode in ['freeze', 'standby']): data.tSuspended = prevktime data.dmesg['suspend_machine']['end'] = prevktime else: data.tSuspended = ktime data.dmesg['suspend_machine']['end'] = ktime phase = 'resume_machine' data.tResumed = ktime data.tLow = data.tResumed - data.tSuspended data.dmesg[phase]['start'] = ktime # resume_noirq start elif(re.match(dm['resume_noirq'], msg)): data.dmesg['resume_machine']['end'] = ktime phase = 'resume_noirq' data.dmesg[phase]['start'] = ktime # resume_early start elif(re.match(dm['resume_early'], msg)): data.dmesg['resume_noirq']['end'] = ktime phase = 'resume_early' data.dmesg[phase]['start'] = ktime # resume start elif(re.match(dm['resume'], msg)): data.dmesg['resume_early']['end'] = ktime phase = 'resume' data.dmesg[phase]['start'] = ktime # resume complete start elif(re.match(dm['resume_complete'], msg)): data.dmesg['resume']['end'] = ktime phase = 'resume_complete' data.dmesg[phase]['start'] = ktime # post resume start elif(re.match(dm['post_resume'], msg)): data.dmesg['resume_complete']['end'] = ktime data.setEnd(ktime) phase = 'post_resume' break # -- device callbacks -- if(phase in data.phases): # device init call if(re.match('calling (?P<f>.*)\+ @ .*, parent: .*', msg)): sm = re.match('calling (?P<f>.*)\+ @ '+\ '(?P<n>.*), parent: (?P<p>.*)', msg); f = sm.group('f') n = sm.group('n') p = sm.group('p') if(f and n and p): data.newAction(phase, f, int(n), p, ktime, -1, '') # device init return elif(re.match('call (?P<f>.*)\+ returned .* after '+\ '(?P<t>.*) usecs', msg)): sm = re.match('call (?P<f>.*)\+ returned .* after '+\ '(?P<t>.*) usecs(?P<a>.*)', msg); f = sm.group('f') t = sm.group('t') list = data.dmesg[phase]['list'] if(f in list): dev = list[f] dev['length'] = int(t) dev['end'] = ktime # -- non-devicecallback actions -- # if trace events are not available, these are better than nothing if(not sysvals.usetraceevents): # look for known actions for a in at: if(re.match(at[a]['smsg'], msg)): if(a not in actions): actions[a] = [] actions[a].append({'begin': ktime, 'end': ktime}) if(re.match(at[a]['emsg'], msg)): actions[a][-1]['end'] = ktime # now look for CPU on/off events if(re.match('Disabling non-boot CPUs .*', msg)): # start of first cpu suspend cpu_start = ktime elif(re.match('Enabling non-boot CPUs .*', msg)): # start of first cpu resume cpu_start = ktime elif(re.match('smpboot: CPU (?P<cpu>[0-9]*) is now offline', msg)): # end of a cpu suspend, start of the next m = re.match('smpboot: CPU (?P<cpu>[0-9]*) is now offline', msg) cpu = 'CPU'+m.group('cpu') if(cpu not in actions): actions[cpu] = [] actions[cpu].append({'begin': cpu_start, 'end': ktime}) cpu_start = ktime elif(re.match('CPU(?P<cpu>[0-9]*) is up', msg)): # end of a cpu resume, start of the next m = re.match('CPU(?P<cpu>[0-9]*) is up', msg) cpu = 'CPU'+m.group('cpu') if(cpu not in actions): actions[cpu] = [] actions[cpu].append({'begin': cpu_start, 'end': ktime}) cpu_start = ktime prevktime = ktime # fill in any missing phases lp = data.phases[0] for p in data.phases: if(data.dmesg[p]['start'] < 0 and data.dmesg[p]['end'] < 0): print('WARNING: phase "%s" is missing, something went wrong!' % p) print(' In %s, this dmesg line denotes the start of %s:' % \ (sysvals.suspendmode, p)) print(' "%s"' % dm[p]) if(data.dmesg[p]['start'] < 0): data.dmesg[p]['start'] = data.dmesg[lp]['end'] if(p == 'resume_machine'): data.tSuspended = data.dmesg[lp]['end'] data.tResumed = data.dmesg[lp]['end'] data.tLow = 0 if(data.dmesg[p]['end'] < 0): data.dmesg[p]['end'] = data.dmesg[p]['start'] lp = p # fill in any actions we've found for name in actions: for event in actions[name]: begin = event['begin'] end = event['end'] # if event starts before timeline start, expand timeline if(begin < data.start): data.setStart(begin) # if event ends after timeline end, expand the timeline if(end > data.end): data.setEnd(end) data.newActionGlobal(name, begin, end) if(sysvals.verbose): data.printDetails() if(len(sysvals.devicefilter) > 0): data.deviceFilter(sysvals.devicefilter) data.fixupInitcallsThatDidntReturn() return True # Function: setTimelineRows # Description: # Organize the timeline entries into the smallest # number of rows possible, with no entry overlapping # Arguments: # list: the list of devices/actions for a single phase # sortedkeys: cronologically sorted key list to use # Output: # The total number of rows needed to display this phase of the timeline def setTimelineRows(list, sortedkeys): # clear all rows and set them to undefined remaining = len(list) rowdata = dict() row = 0 for item in list: list[item]['row'] = -1 # try to pack each row with as many ranges as possible while(remaining > 0): if(row not in rowdata): rowdata[row] = [] for item in sortedkeys: if(list[item]['row'] < 0): s = list[item]['start'] e = list[item]['end'] valid = True for ritem in rowdata[row]: rs = ritem['start'] re = ritem['end'] if(not (((s <= rs) and (e <= rs)) or ((s >= re) and (e >= re)))): valid = False break if(valid): rowdata[row].append(list[item]) list[item]['row'] = row remaining -= 1 row += 1 return row # Function: createTimeScale # Description: # Create the timescale header for the html timeline # Arguments: # t0: start time (suspend begin) # tMax: end time (resume end) # tSuspend: time when suspend occurs, i.e. the zero time # Output: # The html code needed to display the time scale def createTimeScale(t0, tMax, tSuspended): timescale = '<div class="t" style="right:{0}%">{1}</div>\n' output = '<div id="timescale">\n' # set scale for timeline tTotal = tMax - t0 tS = 0.1 if(tTotal <= 0): return output if(tTotal > 4): tS = 1 if(tSuspended < 0): for i in range(int(tTotal/tS)+1): pos = '%0.3f' % (100 - ((float(i)*tS*100)/tTotal)) if(i > 0): val = '%0.fms' % (float(i)*tS*1000) else: val = '' output += timescale.format(pos, val) else: tSuspend = tSuspended - t0 divTotal = int(tTotal/tS) + 1 divSuspend = int(tSuspend/tS) s0 = (tSuspend - tS*divSuspend)*100/tTotal for i in range(divTotal): pos = '%0.3f' % (100 - ((float(i)*tS*100)/tTotal) - s0) if((i == 0) and (s0 < 3)): val = '' elif(i == divSuspend): val = 'S/R' else: val = '%0.fms' % (float(i-divSuspend)*tS*1000) output += timescale.format(pos, val) output += '</div>\n' return output # Function: createHTMLSummarySimple # Description: # Create summary html file for a series of tests # Arguments: # testruns: array of Data objects from parseTraceLog def createHTMLSummarySimple(testruns, htmlfile): global sysvals # print out the basic summary of all the tests hf = open(htmlfile, 'w') # write the html header first (html head, css code, up to body start) html = '<!DOCTYPE html>\n<html>\n<head>\n\ <meta http-equiv="content-type" content="text/html; charset=UTF-8">\n\ <title>AnalyzeSuspend Summary</title>\n\ <style type=\'text/css\'>\n\ body {overflow-y: scroll;}\n\ .stamp {width: 100%;text-align:center;background-color:#495E09;line-height:30px;color:white;font: 25px Arial;}\n\ table {width:100%;border-collapse: collapse;}\n\ .summary {font: 22px Arial;border:1px solid;}\n\ th {border: 1px solid black;background-color:#A7C942;color:white;}\n\ td {text-align: center;}\n\ tr.alt td {background-color:#EAF2D3;}\n\ tr.avg td {background-color:#BDE34C;}\n\ a:link {color: #90B521;}\n\ a:visited {color: #495E09;}\n\ a:hover {color: #B1DF28;}\n\ a:active {color: #FFFFFF;}\n\ </style>\n</head>\n<body>\n' # group test header count = len(testruns) headline_stamp = '<div class="stamp">{0} {1} {2} {3} ({4} tests)</div>\n' html += headline_stamp.format(sysvals.stamp['host'], sysvals.stamp['kernel'], sysvals.stamp['mode'], sysvals.stamp['time'], count) # check to see if all the tests have the same value stampcolumns = False for data in testruns: if diffStamp(sysvals.stamp, data.stamp): stampcolumns = True break th = '\t<th>{0}</th>\n' td = '\t<td>{0}</td>\n' tdlink = '\t<td><a href="{0}">Click Here</a></td>\n' # table header html += '<table class="summary">\n<tr>\n' html += th.format("Test #") if stampcolumns: html += th.format("Hostname") html += th.format("Kernel Version") html += th.format("Suspend Mode") html += th.format("Test Time") html += th.format("Suspend Time") html += th.format("Resume Time") html += th.format("Detail") html += '</tr>\n' # test data, 1 row per test sTimeAvg = 0.0 rTimeAvg = 0.0 num = 1 for data in testruns: # data.end is the end of post_resume resumeEnd = data.dmesg['resume_complete']['end'] if num % 2 == 1: html += '<tr class="alt">\n' else: html += '<tr>\n' # test num html += td.format("test %d" % num) num += 1 if stampcolumns: # host name val = "unknown" if('host' in data.stamp): val = data.stamp['host'] html += td.format(val) # host kernel val = "unknown" if('kernel' in data.stamp): val = data.stamp['kernel'] html += td.format(val) # suspend mode val = "unknown" if('mode' in data.stamp): val = data.stamp['mode'] html += td.format(val) # test time val = "unknown" if('time' in data.stamp): val = data.stamp['time'] html += td.format(val) # suspend time sTime = (data.tSuspended - data.start)*1000 sTimeAvg += sTime html += td.format("%3.3f ms" % sTime) # resume time rTime = (resumeEnd - data.tResumed)*1000 rTimeAvg += rTime html += td.format("%3.3f ms" % rTime) # link to the output html html += tdlink.format(data.outfile) html += '</tr>\n' # last line: test average if(count > 0): sTimeAvg /= count rTimeAvg /= count html += '<tr class="avg">\n' html += td.format('Average') # name if stampcolumns: html += td.format('') # host html += td.format('') # kernel html += td.format('') # mode html += td.format('') # time html += td.format("%3.3f ms" % sTimeAvg) # suspend time html += td.format("%3.3f ms" % rTimeAvg) # resume time html += td.format('') # output link html += '</tr>\n' # flush the data to file hf.write(html+'</table>\n') hf.write('</body>\n</html>\n') hf.close() # Function: createHTML # Description: # Create the output html file from the resident test data # Arguments: # testruns: array of Data objects from parseKernelLog or parseTraceLog # Output: # True if the html file was created, false if it failed def createHTML(testruns): global sysvals for data in testruns: data.normalizeTime(testruns[-1].tSuspended) x2changes = ['', 'absolute'] if len(testruns) > 1: x2changes = ['1', 'relative'] # html function templates headline_stamp = '<div class="stamp">{0} {1} {2} {3}</div>\n' html_devlist1 = '<button id="devlist1" class="devlist" style="float:left;">Device Detail%s</button>' % x2changes[0] html_zoombox = '<center><button id="zoomin">ZOOM IN</button><button id="zoomout">ZOOM OUT</button><button id="zoomdef">ZOOM 1:1</button></center>\n' html_devlist2 = '<button id="devlist2" class="devlist" style="float:right;">Device Detail2</button>\n' html_timeline = '<div id="dmesgzoombox" class="zoombox">\n<div id="{0}" class="timeline" style="height:{1}px">\n' html_device = '<div id="{0}" title="{1}" class="thread" style="left:{2}%;top:{3}%;height:{4}%;width:{5}%;">{6}</div>\n' html_traceevent = '<div title="{0}" class="traceevent" style="left:{1}%;top:{2}%;height:{3}%;width:{4}%;border:1px solid {5};background-color:{5}">{6}</div>\n' html_phase = '<div class="phase" style="left:{0}%;width:{1}%;top:{2}%;height:{3}%;background-color:{4}">{5}</div>\n' html_phaselet = '<div id="{0}" class="phaselet" style="left:{1}%;width:{2}%;background-color:{3}"></div>\n' html_legend = '<div class="square" style="left:{0}%;background-color:{1}">&nbsp;{2}</div>\n' html_timetotal = '<table class="time1">\n<tr>'\ '<td class="green">{2} Suspend Time: <b>{0} ms</b></td>'\ '<td class="yellow">{2} Resume Time: <b>{1} ms</b></td>'\ '</tr>\n</table>\n' html_timetotal2 = '<table class="time1">\n<tr>'\ '<td class="green">{3} Suspend Time: <b>{0} ms</b></td>'\ '<td class="gray">'+sysvals.suspendmode+' time: <b>{1} ms</b></td>'\ '<td class="yellow">{3} Resume Time: <b>{2} ms</b></td>'\ '</tr>\n</table>\n' html_timegroups = '<table class="time2">\n<tr>'\ '<td class="green">{4}Kernel Suspend: {0} ms</td>'\ '<td class="purple">{4}Firmware Suspend: {1} ms</td>'\ '<td class="purple">{4}Firmware Resume: {2} ms</td>'\ '<td class="yellow">{4}Kernel Resume: {3} ms</td>'\ '</tr>\n</table>\n' # device timeline vprint('Creating Device Timeline...') devtl = Timeline() # Generate the header for this timeline textnum = ['First', 'Second'] for data in testruns: tTotal = data.end - data.start tEnd = data.dmesg['resume_complete']['end'] if(tTotal == 0): print('ERROR: No timeline data') sys.exit() if(data.tLow > 0): low_time = '%.0f'%(data.tLow*1000) if data.fwValid: suspend_time = '%.0f'%((data.tSuspended-data.start)*1000 + \ (data.fwSuspend/1000000.0)) resume_time = '%.0f'%((tEnd-data.tSuspended)*1000 + \ (data.fwResume/1000000.0)) testdesc1 = 'Total' testdesc2 = '' if(len(testruns) > 1): testdesc1 = testdesc2 = textnum[data.testnumber] testdesc2 += ' ' if(data.tLow == 0): thtml = html_timetotal.format(suspend_time, \ resume_time, testdesc1) else: thtml = html_timetotal2.format(suspend_time, low_time, \ resume_time, testdesc1) devtl.html['timeline'] += thtml sktime = '%.3f'%((data.dmesg['suspend_machine']['end'] - \ data.getStart())*1000) sftime = '%.3f'%(data.fwSuspend / 1000000.0) rftime = '%.3f'%(data.fwResume / 1000000.0) rktime = '%.3f'%((data.getEnd() - \ data.dmesg['resume_machine']['start'])*1000) devtl.html['timeline'] += html_timegroups.format(sktime, \ sftime, rftime, rktime, testdesc2) else: suspend_time = '%.0f'%((data.tSuspended-data.start)*1000) resume_time = '%.0f'%((tEnd-data.tSuspended)*1000) testdesc = 'Kernel' if(len(testruns) > 1): testdesc = textnum[data.testnumber]+' '+testdesc if(data.tLow == 0): thtml = html_timetotal.format(suspend_time, \ resume_time, testdesc) else: thtml = html_timetotal2.format(suspend_time, low_time, \ resume_time, testdesc) devtl.html['timeline'] += thtml # time scale for potentially multiple datasets t0 = testruns[0].start tMax = testruns[-1].end tSuspended = testruns[-1].tSuspended tTotal = tMax - t0 # determine the maximum number of rows we need to draw timelinerows = 0 for data in testruns: for phase in data.dmesg: list = data.dmesg[phase]['list'] rows = setTimelineRows(list, list) data.dmesg[phase]['row'] = rows if(rows > timelinerows): timelinerows = rows # calculate the timeline height and create bounding box, add buttons devtl.setRows(timelinerows + 1) devtl.html['timeline'] += html_devlist1 if len(testruns) > 1: devtl.html['timeline'] += html_devlist2 devtl.html['timeline'] += html_zoombox devtl.html['timeline'] += html_timeline.format('dmesg', devtl.height) # draw the colored boxes for each of the phases for data in testruns: for b in data.dmesg: phase = data.dmesg[b] length = phase['end']-phase['start'] left = '%.3f' % (((phase['start']-t0)*100.0)/tTotal) width = '%.3f' % ((length*100.0)/tTotal) devtl.html['timeline'] += html_phase.format(left, width, \ '%.3f'%devtl.scaleH, '%.3f'%(100-devtl.scaleH), \ data.dmesg[b]['color'], '') # draw the time scale, try to make the number of labels readable devtl.html['scale'] = createTimeScale(t0, tMax, tSuspended) devtl.html['timeline'] += devtl.html['scale'] for data in testruns: for b in data.dmesg: phaselist = data.dmesg[b]['list'] for d in phaselist: name = d drv = '' dev = phaselist[d] if(d in sysvals.altdevname): name = sysvals.altdevname[d] if('drv' in dev and dev['drv']): drv = ' {%s}' % dev['drv'] height = (100.0 - devtl.scaleH)/data.dmesg[b]['row'] top = '%.3f' % ((dev['row']*height) + devtl.scaleH) left = '%.3f' % (((dev['start']-t0)*100)/tTotal) width = '%.3f' % (((dev['end']-dev['start'])*100)/tTotal) length = ' (%0.3f ms) ' % ((dev['end']-dev['start'])*1000) color = 'rgba(204,204,204,0.5)' devtl.html['timeline'] += html_device.format(dev['id'], \ d+drv+length+b, left, top, '%.3f'%height, width, name+drv) # draw any trace events found for data in testruns: for b in data.dmesg: phaselist = data.dmesg[b]['list'] for name in phaselist: dev = phaselist[name] if('traceevents' in dev): vprint('Debug trace events found for device %s' % name) vprint('%20s %20s %10s %8s' % ('action', \ 'name', 'time(ms)', 'length(ms)')) for e in dev['traceevents']: vprint('%20s %20s %10.3f %8.3f' % (e.action, \ e.name, e.time*1000, e.length*1000)) height = (100.0 - devtl.scaleH)/data.dmesg[b]['row'] top = '%.3f' % ((dev['row']*height) + devtl.scaleH) left = '%.3f' % (((e.time-t0)*100)/tTotal) width = '%.3f' % (e.length*100/tTotal) color = 'rgba(204,204,204,0.5)' devtl.html['timeline'] += \ html_traceevent.format(e.action+' '+e.name, \ left, top, '%.3f'%height, \ width, e.color, '') # timeline is finished devtl.html['timeline'] += '</div>\n</div>\n' # draw a legend which describes the phases by color data = testruns[-1] devtl.html['legend'] = '<div class="legend">\n' pdelta = 100.0/len(data.phases) pmargin = pdelta / 4.0 for phase in data.phases: order = '%.2f' % ((data.dmesg[phase]['order'] * pdelta) + pmargin) name = string.replace(phase, '_', ' &nbsp;') devtl.html['legend'] += html_legend.format(order, \ data.dmesg[phase]['color'], name) devtl.html['legend'] += '</div>\n' hf = open(sysvals.htmlfile, 'w') thread_height = 0 # write the html header first (html head, css code, up to body start) html_header = '<!DOCTYPE html>\n<html>\n<head>\n\ <meta http-equiv="content-type" content="text/html; charset=UTF-8">\n\ <title>AnalyzeSuspend</title>\n\ <style type=\'text/css\'>\n\ body {overflow-y: scroll;}\n\ .stamp {width: 100%;text-align:center;background-color:gray;line-height:30px;color:white;font: 25px Arial;}\n\ .callgraph {margin-top: 30px;box-shadow: 5px 5px 20px black;}\n\ .callgraph article * {padding-left: 28px;}\n\ h1 {color:black;font: bold 30px Times;}\n\ t0 {color:black;font: bold 30px Times;}\n\ t1 {color:black;font: 30px Times;}\n\ t2 {color:black;font: 25px Times;}\n\ t3 {color:black;font: 20px Times;white-space:nowrap;}\n\ t4 {color:black;font: bold 30px Times;line-height:60px;white-space:nowrap;}\n\ table {width:100%;}\n\ .gray {background-color:rgba(80,80,80,0.1);}\n\ .green {background-color:rgba(204,255,204,0.4);}\n\ .purple {background-color:rgba(128,0,128,0.2);}\n\ .yellow {background-color:rgba(255,255,204,0.4);}\n\ .time1 {font: 22px Arial;border:1px solid;}\n\ .time2 {font: 15px Arial;border-bottom:1px solid;border-left:1px solid;border-right:1px solid;}\n\ td {text-align: center;}\n\ r {color:#500000;font:15px Tahoma;}\n\ n {color:#505050;font:15px Tahoma;}\n\ .tdhl {color: red;}\n\ .hide {display: none;}\n\ .pf {display: none;}\n\ .pf:checked + label {background: url(\'data:image/svg+xml;utf,<?xml version="1.0" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" height="18" width="18" version="1.1"><circle cx="9" cy="9" r="8" stroke="black" stroke-width="1" fill="white"/><rect x="4" y="8" width="10" height="2" style="fill:black;stroke-width:0"/><rect x="8" y="4" width="2" height="10" style="fill:black;stroke-width:0"/></svg>\') no-repeat left center;}\n\ .pf:not(:checked) ~ label {background: url(\'data:image/svg+xml;utf,<?xml version="1.0" standalone="no"?><svg xmlns="http://www.w3.org/2000/svg" height="18" width="18" version="1.1"><circle cx="9" cy="9" r="8" stroke="black" stroke-width="1" fill="white"/><rect x="4" y="8" width="10" height="2" style="fill:black;stroke-width:0"/></svg>\') no-repeat left center;}\n\ .pf:checked ~ *:not(:nth-child(2)) {display: none;}\n\ .zoombox {position: relative; width: 100%; overflow-x: scroll;}\n\ .timeline {position: relative; font-size: 14px;cursor: pointer;width: 100%; overflow: hidden; background-color:#dddddd;}\n\ .thread {position: absolute; height: '+'%.3f'%thread_height+'%; overflow: hidden; line-height: 30px; border:1px solid;text-align:center;white-space:nowrap;background-color:rgba(204,204,204,0.5);}\n\ .thread:hover {background-color:white;border:1px solid red;z-index:10;}\n\ .hover {background-color:white;border:1px solid red;z-index:10;}\n\ .traceevent {position: absolute;opacity: 0.3;height: '+'%.3f'%thread_height+'%;width:0;overflow:hidden;line-height:30px;text-align:center;white-space:nowrap;}\n\ .phase {position: absolute;overflow: hidden;border:0px;text-align:center;}\n\ .phaselet {position:absolute;overflow:hidden;border:0px;text-align:center;height:100px;font-size:24px;}\n\ .t {position:absolute;top:0%;height:100%;border-right:1px solid black;}\n\ .legend {position: relative; width: 100%; height: 40px; text-align: center;margin-bottom:20px}\n\ .legend .square {position:absolute;top:10px; width: 0px;height: 20px;border:1px solid;padding-left:20px;}\n\ button {height:40px;width:200px;margin-bottom:20px;margin-top:20px;font-size:24px;}\n\ .devlist {position:'+x2changes[1]+';width:190px;}\n\ #devicedetail {height:100px;box-shadow: 5px 5px 20px black;}\n\ </style>\n</head>\n<body>\n' hf.write(html_header) # write the test title and general info header if(sysvals.stamp['time'] != ""): hf.write(headline_stamp.format(sysvals.stamp['host'], sysvals.stamp['kernel'], sysvals.stamp['mode'], \ sysvals.stamp['time'])) # write the device timeline hf.write(devtl.html['timeline']) hf.write(devtl.html['legend']) hf.write('<div id="devicedetailtitle"></div>\n') hf.write('<div id="devicedetail" style="display:none;">\n') # draw the colored boxes for the device detail section for data in testruns: hf.write('<div id="devicedetail%d">\n' % data.testnumber) for b in data.phases: phase = data.dmesg[b] length = phase['end']-phase['start'] left = '%.3f' % (((phase['start']-t0)*100.0)/tTotal) width = '%.3f' % ((length*100.0)/tTotal) hf.write(html_phaselet.format(b, left, width, \ data.dmesg[b]['color'])) hf.write('</div>\n') hf.write('</div>\n') # write the ftrace data (callgraph) data = testruns[-1] if(sysvals.usecallgraph): hf.write('<section id="callgraphs" class="callgraph">\n') # write out the ftrace data converted to html html_func_top = '<article id="{0}" class="atop" style="background-color:{1}">\n<input type="checkbox" class="pf" id="f{2}" checked/><label for="f{2}">{3} {4}</label>\n' html_func_start = '<article>\n<input type="checkbox" class="pf" id="f{0}" checked/><label for="f{0}">{1} {2}</label>\n' html_func_end = '</article>\n' html_func_leaf = '<article>{0} {1}</article>\n' num = 0 for p in data.phases: list = data.dmesg[p]['list'] for devname in data.sortedDevices(p): if('ftrace' not in list[devname]): continue name = devname if(devname in sysvals.altdevname): name = sysvals.altdevname[devname] devid = list[devname]['id'] cg = list[devname]['ftrace'] flen = '<r>(%.3f ms @ %.3f to %.3f)</r>' % \ ((cg.end - cg.start)*1000, cg.start*1000, cg.end*1000) hf.write(html_func_top.format(devid, data.dmesg[p]['color'], \ num, name+' '+p, flen)) num += 1 for line in cg.list: if(line.length < 0.000000001): flen = '' else: flen = '<n>(%.3f ms @ %.3f)</n>' % (line.length*1000, \ line.time*1000) if(line.freturn and line.fcall): hf.write(html_func_leaf.format(line.name, flen)) elif(line.freturn): hf.write(html_func_end) else: hf.write(html_func_start.format(num, line.name, flen)) num += 1 hf.write(html_func_end) hf.write('\n\n </section>\n') # write the footer and close addScriptCode(hf, testruns) hf.write('</body>\n</html>\n') hf.close() return True # Function: addScriptCode # Description: # Adds the javascript code to the output html # Arguments: # hf: the open html file pointer # testruns: array of Data objects from parseKernelLog or parseTraceLog def addScriptCode(hf, testruns): t0 = (testruns[0].start - testruns[-1].tSuspended) * 1000 tMax = (testruns[-1].end - testruns[-1].tSuspended) * 1000 # create an array in javascript memory with the device details detail = ' var devtable = [];\n' for data in testruns: topo = data.deviceTopology() detail += ' devtable[%d] = "%s";\n' % (data.testnumber, topo) detail += ' var bounds = [%f,%f];\n' % (t0, tMax) # add the code which will manipulate the data in the browser script_code = \ '<script type="text/javascript">\n'+detail+\ ' function zoomTimeline() {\n'\ ' var timescale = document.getElementById("timescale");\n'\ ' var dmesg = document.getElementById("dmesg");\n'\ ' var zoombox = document.getElementById("dmesgzoombox");\n'\ ' var val = parseFloat(dmesg.style.width);\n'\ ' var newval = 100;\n'\ ' var sh = window.outerWidth / 2;\n'\ ' if(this.id == "zoomin") {\n'\ ' newval = val * 1.2;\n'\ ' if(newval > 40000) newval = 40000;\n'\ ' dmesg.style.width = newval+"%";\n'\ ' zoombox.scrollLeft = ((zoombox.scrollLeft + sh) * newval / val) - sh;\n'\ ' } else if (this.id == "zoomout") {\n'\ ' newval = val / 1.2;\n'\ ' if(newval < 100) newval = 100;\n'\ ' dmesg.style.width = newval+"%";\n'\ ' zoombox.scrollLeft = ((zoombox.scrollLeft + sh) * newval / val) - sh;\n'\ ' } else {\n'\ ' zoombox.scrollLeft = 0;\n'\ ' dmesg.style.width = "100%";\n'\ ' }\n'\ ' var html = "";\n'\ ' var t0 = bounds[0];\n'\ ' var tMax = bounds[1];\n'\ ' var tTotal = tMax - t0;\n'\ ' var wTotal = tTotal * 100.0 / newval;\n'\ ' for(var tS = 1000; (wTotal / tS) < 3; tS /= 10);\n'\ ' if(tS < 1) tS = 1;\n'\ ' for(var s = ((t0 / tS)|0) * tS; s < tMax; s += tS) {\n'\ ' var pos = (tMax - s) * 100.0 / tTotal;\n'\ ' var name = (s == 0)?"S/R":(s+"ms");\n'\ ' html += "<div class=\\"t\\" style=\\"right:"+pos+"%\\">"+name+"</div>";\n'\ ' }\n'\ ' timescale.innerHTML = html;\n'\ ' }\n'\ ' function deviceHover() {\n'\ ' var name = this.title.slice(0, this.title.indexOf(" ("));\n'\ ' var dmesg = document.getElementById("dmesg");\n'\ ' var dev = dmesg.getElementsByClassName("thread");\n'\ ' var cpu = -1;\n'\ ' if(name.match("CPU_ON\[[0-9]*\]"))\n'\ ' cpu = parseInt(name.slice(7));\n'\ ' else if(name.match("CPU_OFF\[[0-9]*\]"))\n'\ ' cpu = parseInt(name.slice(8));\n'\ ' for (var i = 0; i < dev.length; i++) {\n'\ ' dname = dev[i].title.slice(0, dev[i].title.indexOf(" ("));\n'\ ' if((cpu >= 0 && dname.match("CPU_O[NF]*\\\[*"+cpu+"\\\]")) ||\n'\ ' (name == dname))\n'\ ' {\n'\ ' dev[i].className = "thread hover";\n'\ ' } else {\n'\ ' dev[i].className = "thread";\n'\ ' }\n'\ ' }\n'\ ' }\n'\ ' function deviceUnhover() {\n'\ ' var dmesg = document.getElementById("dmesg");\n'\ ' var dev = dmesg.getElementsByClassName("thread");\n'\ ' for (var i = 0; i < dev.length; i++) {\n'\ ' dev[i].className = "thread";\n'\ ' }\n'\ ' }\n'\ ' function deviceTitle(title, total, cpu) {\n'\ ' var prefix = "Total";\n'\ ' if(total.length > 3) {\n'\ ' prefix = "Average";\n'\ ' total[1] = (total[1]+total[3])/2;\n'\ ' total[2] = (total[2]+total[4])/2;\n'\ ' }\n'\ ' var devtitle = document.getElementById("devicedetailtitle");\n'\ ' var name = title.slice(0, title.indexOf(" "));\n'\ ' if(cpu >= 0) name = "CPU"+cpu;\n'\ ' var driver = "";\n'\ ' var tS = "<t2>(</t2>";\n'\ ' var tR = "<t2>)</t2>";\n'\ ' if(total[1] > 0)\n'\ ' tS = "<t2>("+prefix+" Suspend:</t2><t0> "+total[1].toFixed(3)+" ms</t0> ";\n'\ ' if(total[2] > 0)\n'\ ' tR = " <t2>"+prefix+" Resume:</t2><t0> "+total[2].toFixed(3)+" ms<t2>)</t2></t0>";\n'\ ' var s = title.indexOf("{");\n'\ ' var e = title.indexOf("}");\n'\ ' if((s >= 0) && (e >= 0))\n'\ ' driver = title.slice(s+1, e) + " <t1>@</t1> ";\n'\ ' if(total[1] > 0 && total[2] > 0)\n'\ ' devtitle.innerHTML = "<t0>"+driver+name+"</t0> "+tS+tR;\n'\ ' else\n'\ ' devtitle.innerHTML = "<t0>"+title+"</t0>";\n'\ ' return name;\n'\ ' }\n'\ ' function deviceDetail() {\n'\ ' var devinfo = document.getElementById("devicedetail");\n'\ ' devinfo.style.display = "block";\n'\ ' var name = this.title.slice(0, this.title.indexOf(" ("));\n'\ ' var cpu = -1;\n'\ ' if(name.match("CPU_ON\[[0-9]*\]"))\n'\ ' cpu = parseInt(name.slice(7));\n'\ ' else if(name.match("CPU_OFF\[[0-9]*\]"))\n'\ ' cpu = parseInt(name.slice(8));\n'\ ' var dmesg = document.getElementById("dmesg");\n'\ ' var dev = dmesg.getElementsByClassName("thread");\n'\ ' var idlist = [];\n'\ ' var pdata = [[]];\n'\ ' var pd = pdata[0];\n'\ ' var total = [0.0, 0.0, 0.0];\n'\ ' for (var i = 0; i < dev.length; i++) {\n'\ ' dname = dev[i].title.slice(0, dev[i].title.indexOf(" ("));\n'\ ' if((cpu >= 0 && dname.match("CPU_O[NF]*\\\[*"+cpu+"\\\]")) ||\n'\ ' (name == dname))\n'\ ' {\n'\ ' idlist[idlist.length] = dev[i].id;\n'\ ' var tidx = 1;\n'\ ' if(dev[i].id[0] == "a") {\n'\ ' pd = pdata[0];\n'\ ' } else {\n'\ ' if(pdata.length == 1) pdata[1] = [];\n'\ ' if(total.length == 3) total[3]=total[4]=0.0;\n'\ ' pd = pdata[1];\n'\ ' tidx = 3;\n'\ ' }\n'\ ' var info = dev[i].title.split(" ");\n'\ ' var pname = info[info.length-1];\n'\ ' pd[pname] = parseFloat(info[info.length-3].slice(1));\n'\ ' total[0] += pd[pname];\n'\ ' if(pname.indexOf("suspend") >= 0)\n'\ ' total[tidx] += pd[pname];\n'\ ' else\n'\ ' total[tidx+1] += pd[pname];\n'\ ' }\n'\ ' }\n'\ ' var devname = deviceTitle(this.title, total, cpu);\n'\ ' var left = 0.0;\n'\ ' for (var t = 0; t < pdata.length; t++) {\n'\ ' pd = pdata[t];\n'\ ' devinfo = document.getElementById("devicedetail"+t);\n'\ ' var phases = devinfo.getElementsByClassName("phaselet");\n'\ ' for (var i = 0; i < phases.length; i++) {\n'\ ' if(phases[i].id in pd) {\n'\ ' var w = 100.0*pd[phases[i].id]/total[0];\n'\ ' var fs = 32;\n'\ ' if(w < 8) fs = 4*w | 0;\n'\ ' var fs2 = fs*3/4;\n'\ ' phases[i].style.width = w+"%";\n'\ ' phases[i].style.left = left+"%";\n'\ ' phases[i].title = phases[i].id+" "+pd[phases[i].id]+" ms";\n'\ ' left += w;\n'\ ' var time = "<t4 style=\\"font-size:"+fs+"px\\">"+pd[phases[i].id]+" ms<br></t4>";\n'\ ' var pname = "<t3 style=\\"font-size:"+fs2+"px\\">"+phases[i].id.replace("_", " ")+"</t3>";\n'\ ' phases[i].innerHTML = time+pname;\n'\ ' } else {\n'\ ' phases[i].style.width = "0%";\n'\ ' phases[i].style.left = left+"%";\n'\ ' }\n'\ ' }\n'\ ' }\n'\ ' var cglist = document.getElementById("callgraphs");\n'\ ' if(!cglist) return;\n'\ ' var cg = cglist.getElementsByClassName("atop");\n'\ ' for (var i = 0; i < cg.length; i++) {\n'\ ' if(idlist.indexOf(cg[i].id) >= 0) {\n'\ ' cg[i].style.display = "block";\n'\ ' } else {\n'\ ' cg[i].style.display = "none";\n'\ ' }\n'\ ' }\n'\ ' }\n'\ ' function devListWindow(e) {\n'\ ' var sx = e.clientX;\n'\ ' if(sx > window.innerWidth - 440)\n'\ ' sx = window.innerWidth - 440;\n'\ ' var cfg="top="+e.screenY+", left="+sx+", width=440, height=720, scrollbars=yes";\n'\ ' var win = window.open("", "_blank", cfg);\n'\ ' if(window.chrome) win.moveBy(sx, 0);\n'\ ' var html = "<title>"+e.target.innerHTML+"</title>"+\n'\ ' "<style type=\\"text/css\\">"+\n'\ ' " ul {list-style-type:circle;padding-left:10px;margin-left:10px;}"+\n'\ ' "</style>"\n'\ ' var dt = devtable[0];\n'\ ' if(e.target.id != "devlist1")\n'\ ' dt = devtable[1];\n'\ ' win.document.write(html+dt);\n'\ ' }\n'\ ' window.addEventListener("load", function () {\n'\ ' var dmesg = document.getElementById("dmesg");\n'\ ' dmesg.style.width = "100%"\n'\ ' document.getElementById("zoomin").onclick = zoomTimeline;\n'\ ' document.getElementById("zoomout").onclick = zoomTimeline;\n'\ ' document.getElementById("zoomdef").onclick = zoomTimeline;\n'\ ' var devlist = document.getElementsByClassName("devlist");\n'\ ' for (var i = 0; i < devlist.length; i++)\n'\ ' devlist[i].onclick = devListWindow;\n'\ ' var dev = dmesg.getElementsByClassName("thread");\n'\ ' for (var i = 0; i < dev.length; i++) {\n'\ ' dev[i].onclick = deviceDetail;\n'\ ' dev[i].onmouseover = deviceHover;\n'\ ' dev[i].onmouseout = deviceUnhover;\n'\ ' }\n'\ ' zoomTimeline();\n'\ ' });\n'\ '</script>\n' hf.write(script_code); # Function: executeSuspend # Description: # Execute system suspend through the sysfs interface, then copy the output # dmesg and ftrace files to the test output directory. def executeSuspend(): global sysvals detectUSB(False) t0 = time.time()*1000 tp = sysvals.tpath # execute however many s/r runs requested for count in range(1,sysvals.execcount+1): # clear the kernel ring buffer just as we start os.system('dmesg -C') # enable callgraph ftrace only for the second run if(sysvals.usecallgraph and count == 2): # set trace type os.system('echo function_graph > '+tp+'current_tracer') os.system('echo "" > '+tp+'set_ftrace_filter') # set trace format options os.system('echo funcgraph-abstime > '+tp+'trace_options') os.system('echo funcgraph-proc > '+tp+'trace_options') # focus only on device suspend and resume os.system('cat '+tp+'available_filter_functions | '+\ 'grep dpm_run_callback > '+tp+'set_graph_function') # if this is test2 and there's a delay, start here if(count > 1 and sysvals.x2delay > 0): tN = time.time()*1000 while (tN - t0) < sysvals.x2delay: tN = time.time()*1000 time.sleep(0.001) # start ftrace if(sysvals.usecallgraph or sysvals.usetraceevents): print('START TRACING') os.system('echo 1 > '+tp+'tracing_on') # initiate suspend if(sysvals.usecallgraph or sysvals.usetraceevents): os.system('echo SUSPEND START > '+tp+'trace_marker') if(sysvals.rtcwake): print('SUSPEND START') print('will autoresume in %d seconds' % sysvals.rtcwaketime) sysvals.rtcWakeAlarm() else: print('SUSPEND START (press a key to resume)') pf = open(sysvals.powerfile, 'w') pf.write(sysvals.suspendmode) # execution will pause here pf.close() t0 = time.time()*1000 # return from suspend print('RESUME COMPLETE') if(sysvals.usecallgraph or sysvals.usetraceevents): os.system('echo RESUME COMPLETE > '+tp+'trace_marker') # see if there's firmware timing data to be had t = sysvals.postresumetime if(t > 0): print('Waiting %d seconds for POST-RESUME trace events...' % t) time.sleep(t) # stop ftrace if(sysvals.usecallgraph or sysvals.usetraceevents): os.system('echo 0 > '+tp+'tracing_on') print('CAPTURING TRACE') writeDatafileHeader(sysvals.ftracefile) os.system('cat '+tp+'trace >> '+sysvals.ftracefile) os.system('echo "" > '+tp+'trace') # grab a copy of the dmesg output print('CAPTURING DMESG') writeDatafileHeader(sysvals.dmesgfile) os.system('dmesg -c >> '+sysvals.dmesgfile) def writeDatafileHeader(filename): global sysvals fw = getFPDT(False) prt = sysvals.postresumetime fp = open(filename, 'a') fp.write(sysvals.teststamp+'\n') if(fw): fp.write('# fwsuspend %u fwresume %u\n' % (fw[0], fw[1])) if(prt > 0): fp.write('# post resume time %u\n' % prt) fp.close() # Function: executeAndroidSuspend # Description: # Execute system suspend through the sysfs interface # on a remote android device, then transfer the output # dmesg and ftrace files to the local output directory. def executeAndroidSuspend(): global sysvals # check to see if the display is currently off tp = sysvals.tpath out = os.popen(sysvals.adb+\ ' shell dumpsys power | grep mScreenOn').read().strip() # if so we need to turn it on so we can issue a new suspend if(out.endswith('false')): print('Waking the device up for the test...') # send the KEYPAD_POWER keyevent to wake it up os.system(sysvals.adb+' shell input keyevent 26') # wait a few seconds so the user can see the device wake up time.sleep(3) # execute however many s/r runs requested for count in range(1,sysvals.execcount+1): # clear the kernel ring buffer just as we start os.system(sysvals.adb+' shell dmesg -c > /dev/null 2>&1') # start ftrace if(sysvals.usetraceevents): print('START TRACING') os.system(sysvals.adb+" shell 'echo 1 > "+tp+"tracing_on'") # initiate suspend for count in range(1,sysvals.execcount+1): if(sysvals.usetraceevents): os.system(sysvals.adb+\ " shell 'echo SUSPEND START > "+tp+"trace_marker'") print('SUSPEND START (press a key on the device to resume)') os.system(sysvals.adb+" shell 'echo "+sysvals.suspendmode+\ " > "+sysvals.powerfile+"'") # execution will pause here, then adb will exit while(True): check = os.popen(sysvals.adb+\ ' shell pwd 2>/dev/null').read().strip() if(len(check) > 0): break time.sleep(1) if(sysvals.usetraceevents): os.system(sysvals.adb+" shell 'echo RESUME COMPLETE > "+tp+\ "trace_marker'") # return from suspend print('RESUME COMPLETE') # stop ftrace if(sysvals.usetraceevents): os.system(sysvals.adb+" shell 'echo 0 > "+tp+"tracing_on'") print('CAPTURING TRACE') os.system('echo "'+sysvals.teststamp+'" > '+sysvals.ftracefile) os.system(sysvals.adb+' shell cat '+tp+\ 'trace >> '+sysvals.ftracefile) # grab a copy of the dmesg output print('CAPTURING DMESG') os.system('echo "'+sysvals.teststamp+'" > '+sysvals.dmesgfile) os.system(sysvals.adb+' shell dmesg >> '+sysvals.dmesgfile) # Function: setUSBDevicesAuto # Description: # Set the autosuspend control parameter of all USB devices to auto # This can be dangerous, so use at your own risk, most devices are set # to always-on since the kernel cant determine if the device can # properly autosuspend def setUSBDevicesAuto(): global sysvals rootCheck() for dirname, dirnames, filenames in os.walk('/sys/devices'): if(re.match('.*/usb[0-9]*.*', dirname) and 'idVendor' in filenames and 'idProduct' in filenames): os.system('echo auto > %s/power/control' % dirname) name = dirname.split('/')[-1] desc = os.popen('cat %s/product 2>/dev/null' % \ dirname).read().replace('\n', '') ctrl = os.popen('cat %s/power/control 2>/dev/null' % \ dirname).read().replace('\n', '') print('control is %s for %6s: %s' % (ctrl, name, desc)) # Function: yesno # Description: # Print out an equivalent Y or N for a set of known parameter values # Output: # 'Y', 'N', or ' ' if the value is unknown def yesno(val): yesvals = ['auto', 'enabled', 'active', '1'] novals = ['on', 'disabled', 'suspended', 'forbidden', 'unsupported'] if val in yesvals: return 'Y' elif val in novals: return 'N' return ' ' # Function: ms2nice # Description: # Print out a very concise time string in minutes and seconds # Output: # The time string, e.g. "1901m16s" def ms2nice(val): ms = 0 try: ms = int(val) except: return 0.0 m = ms / 60000 s = (ms / 1000) - (m * 60) return '%3dm%2ds' % (m, s) # Function: detectUSB # Description: # Detect all the USB hosts and devices currently connected and add # a list of USB device names to sysvals for better timeline readability # Arguments: # output: True to output the info to stdout, False otherwise def detectUSB(output): global sysvals field = {'idVendor':'', 'idProduct':'', 'product':'', 'speed':''} power = {'async':'', 'autosuspend':'', 'autosuspend_delay_ms':'', 'control':'', 'persist':'', 'runtime_enabled':'', 'runtime_status':'', 'runtime_usage':'', 'runtime_active_time':'', 'runtime_suspended_time':'', 'active_duration':'', 'connected_duration':''} if(output): print('LEGEND') print('---------------------------------------------------------------------------------------------') print(' A = async/sync PM queue Y/N D = autosuspend delay (seconds)') print(' S = autosuspend Y/N rACTIVE = runtime active (min/sec)') print(' P = persist across suspend Y/N rSUSPEN = runtime suspend (min/sec)') print(' E = runtime suspend enabled/forbidden Y/N ACTIVE = active duration (min/sec)') print(' R = runtime status active/suspended Y/N CONNECT = connected duration (min/sec)') print(' U = runtime usage count') print('---------------------------------------------------------------------------------------------') print(' NAME ID DESCRIPTION SPEED A S P E R U D rACTIVE rSUSPEN ACTIVE CONNECT') print('---------------------------------------------------------------------------------------------') for dirname, dirnames, filenames in os.walk('/sys/devices'): if(re.match('.*/usb[0-9]*.*', dirname) and 'idVendor' in filenames and 'idProduct' in filenames): for i in field: field[i] = os.popen('cat %s/%s 2>/dev/null' % \ (dirname, i)).read().replace('\n', '') name = dirname.split('/')[-1] if(len(field['product']) > 0): sysvals.altdevname[name] = \ '%s [%s]' % (field['product'], name) else: sysvals.altdevname[name] = \ '%s:%s [%s]' % (field['idVendor'], \ field['idProduct'], name) if(output): for i in power: power[i] = os.popen('cat %s/power/%s 2>/dev/null' % \ (dirname, i)).read().replace('\n', '') if(re.match('usb[0-9]*', name)): first = '%-8s' % name else: first = '%8s' % name print('%s [%s:%s] %-20s %-4s %1s %1s %1s %1s %1s %1s %1s %s %s %s %s' % \ (first, field['idVendor'], field['idProduct'], \ field['product'][0:20], field['speed'], \ yesno(power['async']), \ yesno(power['control']), \ yesno(power['persist']), \ yesno(power['runtime_enabled']), \ yesno(power['runtime_status']), \ power['runtime_usage'], \ power['autosuspend'], \ ms2nice(power['runtime_active_time']), \ ms2nice(power['runtime_suspended_time']), \ ms2nice(power['active_duration']), \ ms2nice(power['connected_duration']))) # Function: getModes # Description: # Determine the supported power modes on this system # Output: # A string list of the available modes def getModes(): global sysvals modes = '' if(not sysvals.android): if(os.path.exists(sysvals.powerfile)): fp = open(sysvals.powerfile, 'r') modes = string.split(fp.read()) fp.close() else: line = os.popen(sysvals.adb+' shell cat '+\ sysvals.powerfile).read().strip() modes = string.split(line) return modes # Function: getFPDT # Description: # Read the acpi bios tables and pull out FPDT, the firmware data # Arguments: # output: True to output the info to stdout, False otherwise def getFPDT(output): global sysvals rectype = {} rectype[0] = 'Firmware Basic Boot Performance Record' rectype[1] = 'S3 Performance Table Record' prectype = {} prectype[0] = 'Basic S3 Resume Performance Record' prectype[1] = 'Basic S3 Suspend Performance Record' rootCheck() if(not os.path.exists(sysvals.fpdtpath)): if(output): doError('file doesnt exist: %s' % sysvals.fpdtpath, False) return False if(not os.access(sysvals.fpdtpath, os.R_OK)): if(output): doError('file isnt readable: %s' % sysvals.fpdtpath, False) return False if(not os.path.exists(sysvals.mempath)): if(output): doError('file doesnt exist: %s' % sysvals.mempath, False) return False if(not os.access(sysvals.mempath, os.R_OK)): if(output): doError('file isnt readable: %s' % sysvals.mempath, False) return False fp = open(sysvals.fpdtpath, 'rb') buf = fp.read() fp.close() if(len(buf) < 36): if(output): doError('Invalid FPDT table data, should '+\ 'be at least 36 bytes', False) return False table = struct.unpack('4sIBB6s8sI4sI', buf[0:36]) if(output): print('') print('Firmware Performance Data Table (%s)' % table[0]) print(' Signature : %s' % table[0]) print(' Table Length : %u' % table[1]) print(' Revision : %u' % table[2]) print(' Checksum : 0x%x' % table[3]) print(' OEM ID : %s' % table[4]) print(' OEM Table ID : %s' % table[5]) print(' OEM Revision : %u' % table[6]) print(' Creator ID : %s' % table[7]) print(' Creator Revision : 0x%x' % table[8]) print('') if(table[0] != 'FPDT'): if(output): doError('Invalid FPDT table') return False if(len(buf) <= 36): return False i = 0 fwData = [0, 0] records = buf[36:] fp = open(sysvals.mempath, 'rb') while(i < len(records)): header = struct.unpack('HBB', records[i:i+4]) if(header[0] not in rectype): continue if(header[1] != 16): continue addr = struct.unpack('Q', records[i+8:i+16])[0] try: fp.seek(addr) first = fp.read(8) except: doError('Bad address 0x%x in %s' % (addr, sysvals.mempath), False) rechead = struct.unpack('4sI', first) recdata = fp.read(rechead[1]-8) if(rechead[0] == 'FBPT'): record = struct.unpack('HBBIQQQQQ', recdata) if(output): print('%s (%s)' % (rectype[header[0]], rechead[0])) print(' Reset END : %u ns' % record[4]) print(' OS Loader LoadImage Start : %u ns' % record[5]) print(' OS Loader StartImage Start : %u ns' % record[6]) print(' ExitBootServices Entry : %u ns' % record[7]) print(' ExitBootServices Exit : %u ns' % record[8]) elif(rechead[0] == 'S3PT'): if(output): print('%s (%s)' % (rectype[header[0]], rechead[0])) j = 0 while(j < len(recdata)): prechead = struct.unpack('HBB', recdata[j:j+4]) if(prechead[0] not in prectype): continue if(prechead[0] == 0): record = struct.unpack('IIQQ', recdata[j:j+prechead[1]]) fwData[1] = record[2] if(output): print(' %s' % prectype[prechead[0]]) print(' Resume Count : %u' % \ record[1]) print(' FullResume : %u ns' % \ record[2]) print(' AverageResume : %u ns' % \ record[3]) elif(prechead[0] == 1): record = struct.unpack('QQ', recdata[j+4:j+prechead[1]]) fwData[0] = record[1] - record[0] if(output): print(' %s' % prectype[prechead[0]]) print(' SuspendStart : %u ns' % \ record[0]) print(' SuspendEnd : %u ns' % \ record[1]) print(' SuspendTime : %u ns' % \ fwData[0]) j += prechead[1] if(output): print('') i += header[1] fp.close() return fwData # Function: statusCheck # Description: # Verify that the requested command and options will work, and # print the results to the terminal # Output: # True if the test will work, False if not def statusCheck(): global sysvals status = True if(sysvals.android): print('Checking the android system ...') else: print('Checking this system (%s)...' % platform.node()) # check if adb is connected to a device if(sysvals.android): res = 'NO' out = os.popen(sysvals.adb+' get-state').read().strip() if(out == 'device'): res = 'YES' print(' is android device connected: %s' % res) if(res != 'YES'): print(' Please connect the device before using this tool') return False # check we have root access res = 'NO (No features of this tool will work!)' if(sysvals.android): out = os.popen(sysvals.adb+' shell id').read().strip() if('root' in out): res = 'YES' else: if(os.environ['USER'] == 'root'): res = 'YES' print(' have root access: %s' % res) if(res != 'YES'): if(sysvals.android): print(' Try running "adb root" to restart the daemon as root') else: print(' Try running this script with sudo') return False # check sysfs is mounted res = 'NO (No features of this tool will work!)' if(sysvals.android): out = os.popen(sysvals.adb+' shell ls '+\ sysvals.powerfile).read().strip() if(out == sysvals.powerfile): res = 'YES' else: if(os.path.exists(sysvals.powerfile)): res = 'YES' print(' is sysfs mounted: %s' % res) if(res != 'YES'): return False # check target mode is a valid mode res = 'NO' modes = getModes() if(sysvals.suspendmode in modes): res = 'YES' else: status = False print(' is "%s" a valid power mode: %s' % (sysvals.suspendmode, res)) if(res == 'NO'): print(' valid power modes are: %s' % modes) print(' please choose one with -m') # check if the tool can unlock the device if(sysvals.android): res = 'YES' out1 = os.popen(sysvals.adb+\ ' shell dumpsys power | grep mScreenOn').read().strip() out2 = os.popen(sysvals.adb+\ ' shell input').read().strip() if(not out1.startswith('mScreenOn') or not out2.startswith('usage')): res = 'NO (wake the android device up before running the test)' print(' can I unlock the screen: %s' % res) # check if ftrace is available res = 'NO' ftgood = verifyFtrace() if(ftgood): res = 'YES' elif(sysvals.usecallgraph): status = False print(' is ftrace supported: %s' % res) # what data source are we using res = 'DMESG' if(ftgood): sysvals.usetraceeventsonly = True sysvals.usetraceevents = False for e in sysvals.traceevents: check = False if(sysvals.android): out = os.popen(sysvals.adb+' shell ls -d '+\ sysvals.epath+e).read().strip() if(out == sysvals.epath+e): check = True else: if(os.path.exists(sysvals.epath+e)): check = True if(not check): sysvals.usetraceeventsonly = False if(e == 'suspend_resume' and check): sysvals.usetraceevents = True if(sysvals.usetraceevents and sysvals.usetraceeventsonly): res = 'FTRACE (all trace events found)' elif(sysvals.usetraceevents): res = 'DMESG and FTRACE (suspend_resume trace event found)' print(' timeline data source: %s' % res) # check if rtcwake res = 'NO' if(sysvals.rtcpath != ''): res = 'YES' elif(sysvals.rtcwake): status = False print(' is rtcwake supported: %s' % res) return status # Function: doError # Description: # generic error function for catastrphic failures # Arguments: # msg: the error message to print # help: True if printHelp should be called after, False otherwise def doError(msg, help): if(help == True): printHelp() print('ERROR: %s\n') % msg sys.exit() # Function: doWarning # Description: # generic warning function for non-catastrophic anomalies # Arguments: # msg: the warning message to print # file: If not empty, a filename to request be sent to the owner for debug def doWarning(msg, file): print('/* %s */') % msg if(file): print('/* For a fix, please send this'+\ ' %s file to <todd.e.brandt@intel.com> */' % file) # Function: rootCheck # Description: # quick check to see if we have root access def rootCheck(): if(os.environ['USER'] != 'root'): doError('This script must be run as root', False) # Function: getArgInt # Description: # pull out an integer argument from the command line with checks def getArgInt(name, args, min, max): try: arg = args.next() except: doError(name+': no argument supplied', True) try: val = int(arg) except: doError(name+': non-integer value given', True) if(val < min or val > max): doError(name+': value should be between %d and %d' % (min, max), True) return val # Function: rerunTest # Description: # generate an output from an existing set of ftrace/dmesg logs def rerunTest(): global sysvals if(sysvals.ftracefile != ''): doesTraceLogHaveTraceEvents() if(sysvals.dmesgfile == '' and not sysvals.usetraceeventsonly): doError('recreating this html output '+\ 'requires a dmesg file', False) sysvals.setOutputFile() vprint('Output file: %s' % sysvals.htmlfile) print('PROCESSING DATA') if(sysvals.usetraceeventsonly): testruns = parseTraceLog() else: testruns = loadKernelLog() for data in testruns: parseKernelLog(data) if(sysvals.ftracefile != ''): appendIncompleteTraceLog(testruns) createHTML(testruns) # Function: runTest # Description: # execute a suspend/resume, gather the logs, and generate the output def runTest(subdir): global sysvals # prepare for the test if(not sysvals.android): initFtrace() else: initFtraceAndroid() sysvals.initTestOutput(subdir) vprint('Output files:\n %s' % sysvals.dmesgfile) if(sysvals.usecallgraph or sysvals.usetraceevents or sysvals.usetraceeventsonly): vprint(' %s' % sysvals.ftracefile) vprint(' %s' % sysvals.htmlfile) # execute the test if(not sysvals.android): executeSuspend() else: executeAndroidSuspend() # analyze the data and create the html output print('PROCESSING DATA') if(sysvals.usetraceeventsonly): # data for kernels 3.15 or newer is entirely in ftrace testruns = parseTraceLog() else: # data for kernels older than 3.15 is primarily in dmesg testruns = loadKernelLog() for data in testruns: parseKernelLog(data) if(sysvals.usecallgraph or sysvals.usetraceevents): appendIncompleteTraceLog(testruns) createHTML(testruns) # Function: runSummary # Description: # create a summary of tests in a sub-directory def runSummary(subdir, output): global sysvals # get a list of ftrace output files files = [] for dirname, dirnames, filenames in os.walk(subdir): for filename in filenames: if(re.match('.*_ftrace.txt', filename)): files.append("%s/%s" % (dirname, filename)) # process the files in order and get an array of data objects testruns = [] for file in sorted(files): if output: print("Test found in %s" % os.path.dirname(file)) sysvals.ftracefile = file sysvals.dmesgfile = file.replace('_ftrace.txt', '_dmesg.txt') doesTraceLogHaveTraceEvents() sysvals.usecallgraph = False if not sysvals.usetraceeventsonly: if(not os.path.exists(sysvals.dmesgfile)): print("Skipping %s: not a valid test input" % file) continue else: if output: f = os.path.basename(sysvals.ftracefile) d = os.path.basename(sysvals.dmesgfile) print("\tInput files: %s and %s" % (f, d)) testdata = loadKernelLog() data = testdata[0] parseKernelLog(data) testdata = [data] appendIncompleteTraceLog(testdata) else: if output: print("\tInput file: %s" % os.path.basename(sysvals.ftracefile)) testdata = parseTraceLog() data = testdata[0] data.normalizeTime(data.tSuspended) link = file.replace(subdir+'/', '').replace('_ftrace.txt', '.html') data.outfile = link testruns.append(data) createHTMLSummarySimple(testruns, subdir+'/summary.html') # Function: printHelp # Description: # print out the help text def printHelp(): global sysvals modes = getModes() print('') print('AnalyzeSuspend v%.1f' % sysvals.version) print('Usage: sudo analyze_suspend.py <options>') print('') print('Description:') print(' This tool is designed to assist kernel and OS developers in optimizing') print(' their linux stack\'s suspend/resume time. Using a kernel image built') print(' with a few extra options enabled, the tool will execute a suspend and') print(' capture dmesg and ftrace data until resume is complete. This data is') print(' transformed into a device timeline and an optional callgraph to give') print(' a detailed view of which devices/subsystems are taking the most') print(' time in suspend/resume.') print('') print(' Generates output files in subdirectory: suspend-mmddyy-HHMMSS') print(' HTML output: <hostname>_<mode>.html') print(' raw dmesg output: <hostname>_<mode>_dmesg.txt') print(' raw ftrace output: <hostname>_<mode>_ftrace.txt') print('') print('Options:') print(' [general]') print(' -h Print this help text') print(' -v Print the current tool version') print(' -verbose Print extra information during execution and analysis') print(' -status Test to see if the system is enabled to run this tool') print(' -modes List available suspend modes') print(' -m mode Mode to initiate for suspend %s (default: %s)') % (modes, sysvals.suspendmode) print(' -rtcwake t Use rtcwake to autoresume after <t> seconds (default: disabled)') print(' [advanced]') print(' -f Use ftrace to create device callgraphs (default: disabled)') print(' -filter "d1 d2 ..." Filter out all but this list of dev names') print(' -x2 Run two suspend/resumes back to back (default: disabled)') print(' -x2delay t Minimum millisecond delay <t> between the two test runs (default: 0 ms)') print(' -postres t Time after resume completion to wait for post-resume events (default: 0 S)') print(' -multi n d Execute <n> consecutive tests at <d> seconds intervals. The outputs will') print(' be created in a new subdirectory with a summary page.') print(' [utilities]') print(' -fpdt Print out the contents of the ACPI Firmware Performance Data Table') print(' -usbtopo Print out the current USB topology with power info') print(' -usbauto Enable autosuspend for all connected USB devices') print(' [android testing]') print(' -adb binary Use the given adb binary to run the test on an android device.') print(' The device should already be connected and with root access.') print(' Commands will be executed on the device using "adb shell"') print(' [re-analyze data from previous runs]') print(' -ftrace ftracefile Create HTML output using ftrace input') print(' -dmesg dmesgfile Create HTML output using dmesg (not needed for kernel >= 3.15)') print(' -summary directory Create a summary of all test in this dir') print('') return True # ----------------- MAIN -------------------- # exec start (skipped if script is loaded as library) if __name__ == '__main__': cmd = '' cmdarg = '' multitest = {'run': False, 'count': 0, 'delay': 0} # loop through the command line arguments args = iter(sys.argv[1:]) for arg in args: if(arg == '-m'): try: val = args.next() except: doError('No mode supplied', True) sysvals.suspendmode = val elif(arg == '-adb'): try: val = args.next() except: doError('No adb binary supplied', True) if(not os.path.exists(val)): doError('file doesnt exist: %s' % val, False) if(not os.access(val, os.X_OK)): doError('file isnt executable: %s' % val, False) try: check = os.popen(val+' version').read().strip() except: doError('adb version failed to execute', False) if(not re.match('Android Debug Bridge .*', check)): doError('adb version failed to execute', False) sysvals.adb = val sysvals.android = True elif(arg == '-x2'): if(sysvals.postresumetime > 0): doError('-x2 is not compatible with -postres', False) sysvals.execcount = 2 elif(arg == '-x2delay'): sysvals.x2delay = getArgInt('-x2delay', args, 0, 60000) elif(arg == '-postres'): if(sysvals.execcount != 1): doError('-x2 is not compatible with -postres', False) sysvals.postresumetime = getArgInt('-postres', args, 0, 3600) elif(arg == '-f'): sysvals.usecallgraph = True elif(arg == '-modes'): cmd = 'modes' elif(arg == '-fpdt'): cmd = 'fpdt' elif(arg == '-usbtopo'): cmd = 'usbtopo' elif(arg == '-usbauto'): cmd = 'usbauto' elif(arg == '-status'): cmd = 'status' elif(arg == '-verbose'): sysvals.verbose = True elif(arg == '-v'): print("Version %.1f" % sysvals.version) sys.exit() elif(arg == '-rtcwake'): sysvals.rtcwake = True sysvals.rtcwaketime = getArgInt('-rtcwake', args, 0, 3600) elif(arg == '-multi'): multitest['run'] = True multitest['count'] = getArgInt('-multi n (exec count)', args, 2, 1000000) multitest['delay'] = getArgInt('-multi d (delay between tests)', args, 0, 3600) elif(arg == '-dmesg'): try: val = args.next() except: doError('No dmesg file supplied', True) sysvals.notestrun = True sysvals.dmesgfile = val if(os.path.exists(sysvals.dmesgfile) == False): doError('%s doesnt exist' % sysvals.dmesgfile, False) elif(arg == '-ftrace'): try: val = args.next() except: doError('No ftrace file supplied', True) sysvals.notestrun = True sysvals.usecallgraph = True sysvals.ftracefile = val if(os.path.exists(sysvals.ftracefile) == False): doError('%s doesnt exist' % sysvals.ftracefile, False) elif(arg == '-summary'): try: val = args.next() except: doError('No directory supplied', True) cmd = 'summary' cmdarg = val sysvals.notestrun = True if(os.path.isdir(val) == False): doError('%s isnt accesible' % val, False) elif(arg == '-filter'): try: val = args.next() except: doError('No devnames supplied', True) sysvals.setDeviceFilter(val) elif(arg == '-h'): printHelp() sys.exit() else: doError('Invalid argument: '+arg, True) # just run a utility command and exit if(cmd != ''): if(cmd == 'status'): statusCheck() elif(cmd == 'fpdt'): if(sysvals.android): doError('cannot read FPDT on android device', False) getFPDT(True) elif(cmd == 'usbtopo'): if(sysvals.android): doError('cannot read USB topology '+\ 'on an android device', False) detectUSB(True) elif(cmd == 'modes'): modes = getModes() print modes elif(cmd == 'usbauto'): setUSBDevicesAuto() elif(cmd == 'summary'): print("Generating a summary of folder \"%s\"" % cmdarg) runSummary(cmdarg, True) sys.exit() # run test on android device if(sysvals.android): if(sysvals.usecallgraph): doError('ftrace (-f) is not yet supported '+\ 'in the android kernel', False) if(sysvals.notestrun): doError('cannot analyze test files on the '+\ 'android device', False) # if instructed, re-analyze existing data files if(sysvals.notestrun): rerunTest() sys.exit() # verify that we can run a test if(not statusCheck()): print('Check FAILED, aborting the test run!') sys.exit() if multitest['run']: # run multiple tests in a separte subdirectory s = 'x%d' % multitest['count'] subdir = datetime.now().strftime('suspend-'+s+'-%m%d%y-%H%M%S') os.mkdir(subdir) for i in range(multitest['count']): if(i != 0): print('Waiting %d seconds...' % (multitest['delay'])) time.sleep(multitest['delay']) print('TEST (%d/%d) START' % (i+1, multitest['count'])) runTest(subdir) print('TEST (%d/%d) COMPLETE' % (i+1, multitest['count'])) runSummary(subdir, False) else: # run the test in the current directory runTest(".")
gpl-2.0
Designist/sympy
sympy/plotting/intervalmath/interval_arithmetic.py
98
16450
""" Interval Arithmetic for plotting. This module does not implement interval arithmetic accurately and hence cannot be used for purposes other than plotting. If you want to use interval arithmetic, use mpmath's interval arithmetic. The module implements interval arithmetic using numpy and python floating points. The rounding up and down is not handled and hence this is not an accurate implementation of interval arithmetic. The module uses numpy for speed which cannot be achieved with mpmath. """ # Q: Why use numpy? Why not simply use mpmath's interval arithmetic? # A: mpmath's interval arithmetic simulates a floating point unit # and hence is slow, while numpy evaluations are orders of magnitude # faster. # Q: Why create a separate class for intervals? Why not use sympy's # Interval Sets? # A: The functionalities that will be required for plotting is quite # different from what Interval Sets implement. # Q: Why is rounding up and down according to IEEE754 not handled? # A: It is not possible to do it in both numpy and python. An external # library has to used, which defeats the whole purpose i.e., speed. Also # rounding is handled for very few functions in those libraries. # Q Will my plots be affected? # A It will not affect most of the plots. The interval arithmetic # module based suffers the same problems as that of floating point # arithmetic. from __future__ import print_function, division from sympy.simplify.simplify import nsimplify class interval(object): """ Represents an interval containing floating points as start and end of the interval The is_valid variable tracks whether the interval obtained as the result of the function is in the domain and is continuous. - True: Represents the interval result of a function is continuous and in the domain of the function. - False: The interval argument of the function was not in the domain of the function, hence the is_valid of the result interval is False - None: The function was not continuous over the interval or the function's argument interval is partly in the domain of the function The comparison of two intervals returns a tuple of two 3-valued logic values. The first value determines the comparison as follows: - True: If the comparison is True throughout the intervals. - False: If the comparison is False throughout the intervals. - None: If the comparison is True for some part of the intervals. The second value is determined as follows: - True: If both the intervals in comparison are valid. - False: If at least one of the intervals is False, else - None """ def __init__(self, *args, **kwargs): self.is_valid = kwargs.pop('is_valid', True) if len(args) == 1: if isinstance(args[0], interval): self.start, self.end = args[0].start, args[0].end else: self.start = float(args[0]) self.end = float(args[0]) elif len(args) == 2: if args[0] < args[1]: self.start = float(args[0]) self.end = float(args[1]) else: self.start = float(args[1]) self.end = float(args[0]) else: raise ValueError("interval takes a maximum of two float values " "as arguments") @property def mid(self): return (self.start + self.end) / 2.0 @property def width(self): return self.end - self.start def __repr__(self): return "interval(%f, %f)" % (self.start, self.end) def __str__(self): return "[%f, %f]" % (self.start, self.end) def __lt__(self, other): if isinstance(other, (int, float)): if self.end < other: return (True, self.is_valid) elif self.start > other: return (False, self.is_valid) else: return (None, self.is_valid) elif isinstance(other, interval): if self.is_valid is False or other.is_valid is False: valid = False elif self.is_valid is None or other.is_valid is None: valid = None else: valid = True if self.end < other. start: return (True, valid) if self.start > other.end: return (False, valid) return (None, valid) else: return NotImplemented def __gt__(self, other): if isinstance(other, (int, float)): if self.start > other: return (True, self.is_valid) elif self.end < other: return (False, self.is_valid) else: return (None, self.is_valid) elif isinstance(other, interval): return other.__lt__(self) else: return NotImplemented def __eq__(self, other): if isinstance(other, (int, float)): if self.start == other and self.end == other: return (True, self.is_valid) if other in self: return (None, self.is_valid) else: return (False, self.is_valid) if isinstance(other, interval): if self.is_valid is False or other.is_valid is False: valid = False elif self.is_valid is None or other.is_valid is None: valid = None else: valid = True if self.start == other.start and self.end == other.end: return (True, valid) elif self.__lt__(other)[0] is not None: return (False, valid) else: return (None, valid) else: return NotImplemented def __ne__(self, other): if isinstance(other, (int, float)): if self.start == other and self.end == other: return (False, self.is_valid) if other in self: return (None, self.is_valid) else: return (True, self.is_valid) if isinstance(other, interval): if self.is_valid is False or other.is_valid is False: valid = False elif self.is_valid is None or other.is_valid is None: valid = None else: valid = True if self.start == other.start and self.end == other.end: return (False, valid) if not self.__lt__(other)[0] is None: return (True, valid) return (None, valid) else: return NotImplemented def __le__(self, other): if isinstance(other, (int, float)): if self.end <= other: return (True, self.is_valid) if self.start > other: return (False, self.is_valid) else: return (None, self.is_valid) if isinstance(other, interval): if self.is_valid is False or other.is_valid is False: valid = False elif self.is_valid is None or other.is_valid is None: valid = None else: valid = True if self.end <= other.start: return (True, valid) if self.start > other.end: return (False, valid) return (None, valid) else: return NotImplemented def __ge__(self, other): if isinstance(other, (int, float)): if self.start >= other: return (True, self.is_valid) elif self.end < other: return (False, self.is_valid) else: return (None, self.is_valid) elif isinstance(other, interval): return other.__le__(self) def __add__(self, other): if isinstance(other, (int, float)): if self.is_valid: return interval(self.start + other, self.end + other) else: start = self.start + other end = self.end + other return interval(start, end, is_valid=self.is_valid) elif isinstance(other, interval): start = self.start + other.start end = self.end + other.end if self.is_valid and other.is_valid: return interval(start, end) elif self.is_valid is False or other.is_valid is False: return interval(start, end, is_valid=False) else: return interval(start, end, is_valid=None) else: return NotImplemented __radd__ = __add__ def __sub__(self, other): if isinstance(other, (int, float)): start = self.start - other end = self.end - other return interval(start, end, is_valid=self.is_valid) elif isinstance(other, interval): start = self.start - other.end end = self.end - other.start if self.is_valid and other.is_valid: return interval(self.start - other.end, self.end - other.start) elif self.is_valid is False or other.is_valid is False: return interval(start, end, is_valid=False) else: return interval(start, end, is_valid=None) else: return NotImplemented def __rsub__(self, other): if isinstance(other, (int, float)): start = other - self.end end = other - self.start return interval(start, end, is_valid=self.is_valid) elif isinstance(other, interval): return other.__sub__(self) else: return NotImplemented def __neg__(self): if self.is_valid: return interval(-self.end, -self.start) else: return interval(-self.end, -self.start, is_valid=self.is_valid) def __mul__(self, other): if isinstance(other, interval): if self.is_valid is False or other.is_valid is False: return interval(-float('inf'), float('inf'), is_valid=False) elif self.is_valid is None or other.is_valid is None: return interval(-float('inf'), float('inf'), is_valid=None) else: inters = [] inters.append(self.start * other.start) inters.append(self.end * other.start) inters.append(self.start * other.end) inters.append(self.end * other.end) start = min(inters) end = max(inters) return interval(start, end) elif isinstance(other, (int, float)): return interval(self.start*other, self.end*other, is_valid=self.is_valid) else: return NotImplemented __rmul__ = __mul__ def __contains__(self, other): if isinstance(other, (int, float)): return self.start <= other and self.end >= other else: return self.start <= other.start and other.end <= self.end def __rdiv__(self, other): if isinstance(other, (int, float)): other = interval(other) return other.__div__(self) elif isinstance(other, interval): return other.__div__(self) else: return NotImplemented def __div__(self, other): # Both None and False are handled if not self.is_valid: # Don't divide as the value is not valid return interval(-float('inf'), float('inf'), is_valid=self.is_valid) if isinstance(other, (int, float)): if other == 0: # Divide by zero encountered. valid nowhere return interval(-float('inf'), float('inf'), is_valid=False) else: return interval(self.start / other, self.end / other) elif isinstance(other, interval): if other.is_valid is False or self.is_valid is False: return interval(-float('inf'), float('inf'), is_valid=False) elif other.is_valid is None or self.is_valid is None: return interval(-float('inf'), float('inf'), is_valid=None) else: # denominator contains both signs, i.e. being divided by zero # return the whole real line with is_valid = None if 0 in other: return interval(-float('inf'), float('inf'), is_valid=None) # denominator negative this = self if other.end < 0: this = -this other = -other # denominator positive inters = [] inters.append(this.start / other.start) inters.append(this.end / other.start) inters.append(this.start / other.end) inters.append(this.end / other.end) start = max(inters) end = min(inters) return interval(start, end) else: return NotImplemented __truediv__ = __div__ __rtruediv__ = __rdiv__ def __pow__(self, other): # Implements only power to an integer. from .lib_interval import exp, log if not self.is_valid: return self if isinstance(other, interval): return exp(other * log(self)) elif isinstance(other, (float, int)): if other < 0: return 1 / self.__pow__(abs(other)) else: if int(other) == other: return _pow_int(self, other) else: return _pow_float(self, other) else: return NotImplemented def __rpow__(self, other): if isinstance(other, (float, int)): if not self.is_valid: #Don't do anything return self elif other < 0: if self.width > 0: return interval(-float('inf'), float('inf'), is_valid=False) else: power_rational = nsimplify(self.start) num, denom = power_rational.as_numer_denom() if denom % 2 == 0: return interval(-float('inf'), float('inf'), is_valid=False) else: start = -abs(other)**self.start end = start return interval(start, end) else: return interval(other**self.start, other**self.end) elif isinstance(other, interval): return other.__pow__(self) else: return NotImplemented def __hash__(self): return hash((self.is_valid, self.start, self.end)) def _pow_float(inter, power): """Evaluates an interval raised to a floating point.""" power_rational = nsimplify(power) num, denom = power_rational.as_numer_denom() if num % 2 == 0: start = abs(inter.start)**power end = abs(inter.end)**power if start < 0: ret = interval(0, max(start, end)) else: ret = interval(start, end) return ret elif denom % 2 == 0: if inter.end < 0: return interval(-float('inf'), float('inf'), is_valid=False) elif inter.start < 0: return interval(0, inter.end**power, is_valid=None) else: return interval(inter.start**power, inter.end**power) else: if inter.start < 0: start = -abs(inter.start)**power else: start = inter.start**power if inter.end < 0: end = -abs(inter.end)**power else: end = inter.end**power return interval(start, end, is_valid=inter.is_valid) def _pow_int(inter, power): """Evaluates an interval raised to an integer power""" power = int(power) if power & 1: return interval(inter.start**power, inter.end**power) else: if inter.start < 0 and inter.end > 0: start = 0 end = max(inter.start**power, inter.end**power) return interval(start, end) else: return interval(inter.start**power, inter.end**power)
bsd-3-clause
freeJim/monserver
examples/python/mongrel2/request.py
72
1140
try: import json except: import simplejson as json from mongrel2 import tnetstrings class Request(object): def __init__(self, sender, conn_id, path, headers, body): self.sender = sender self.path = path self.conn_id = conn_id self.headers = headers self.body = body if self.headers['METHOD'] == 'JSON': self.data = json.loads(body) else: self.data = {} @staticmethod def parse(msg): sender, conn_id, path, rest = msg.split(' ', 3) headers, rest = tnetstrings.parse(rest) body, _ = tnetstrings.parse(rest) if type(headers) is str: headers = json.loads(headers) return Request(sender, conn_id, path, headers, body) def is_disconnect(self): if self.headers.get('METHOD') == 'JSON': return self.data['type'] == 'disconnect' def should_close(self): if self.headers.get('connection') == 'close': return True elif self.headers.get('VERSION') == 'HTTP/1.0': return True else: return False
bsd-3-clause
oppia/oppia-ml
core/domain/remote_access_services.py
1
4226
# coding: utf-8 # # Copyright 2017 The Oppia 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. """This module provides interface to communicate with Oppia remotely.""" import base64 import hashlib import hmac import json import requests from core.domain.proto import training_job_response_payload_pb2 from core.platform import platform_services import utils import vmconf metadata_services = platform_services.Registry.import_metadata_services() def _get_url(): if vmconf.DEV_MODE: return vmconf.DEFAULT_COMMUNICATION_URL return vmconf.SERVER_COMMUNICATION_URL def _get_port(): if vmconf.DEV_MODE: return vmconf.DEFAULT_COMMUNICATION_PORT return vmconf.SERVER_COMMUNICATION_PORT def _get_vm_id(): if vmconf.DEV_MODE: return vmconf.DEFAULT_VM_ID # Get VMID dynamically from metadata. HMAC module does not # support unicode string. Hence we need to cast them to str. return str(metadata_services.get_metadata_param( vmconf.METADATA_VM_ID_PARAM_NAME)) def _get_shared_secret(): if vmconf.DEV_MODE: return vmconf.DEFAULT_VM_SHARED_SECRET # Get shared secret dynamically from metadata. HMAC module does not # support unicode string. Hence we need to cast them to str. return str(metadata_services.get_metadata_param( vmconf.METADATA_SHARED_SECRET_PARAM_NAME)) def generate_signature(message, vm_id): """Generates digital signature for given message combined with vm_id. Args: message: bytes. Message string. vm_id: str. ID of the VM that trained the job. Returns: str. The digital signature generated from request data. """ encoded_vm_id = vm_id.encode(encoding='utf-8') msg = b'%s|%s' % (base64.b64encode(message), encoded_vm_id) key = _get_shared_secret().encode(encoding='utf-8') # Generate signature and return it. return hmac.new(key, msg, digestmod=hashlib.sha256).hexdigest() def fetch_next_job_request(): """Returns the next job request to be processed. Returns: dict. A dict retrieved remotely from database containing job request data. """ request_url = "%s:%s/%s" % ( _get_url(), _get_port(), vmconf.FETCH_NEXT_JOB_REQUEST_HANDLER) payload = { 'vm_id': _get_vm_id().encode(encoding='utf-8'), 'message': _get_vm_id().encode(encoding='utf-8'), } signature = generate_signature(payload['message'], payload['vm_id']) payload['signature'] = signature data = { 'payload': json.dumps(payload) } response = requests.post(request_url, data=data) return utils.parse_data_received_from_server(response.text) def store_trained_classifier_model(job_result): """Stores the result of processed job request. Args: job_result: TrainingJobResult. Domain object containing result of training of classifier along with job_id and algorithm_id. Returns: int. Status code of the response. """ job_result.validate() payload = training_job_response_payload_pb2.TrainingJobResponsePayload() payload.job_result.CopyFrom(job_result.to_proto()) payload.vm_id = _get_vm_id().encode(encoding='utf-8') message = payload.job_result.SerializeToString().encode(encoding='utf-8') signature = generate_signature(message, payload.vm_id) payload.signature = signature data = payload.SerializeToString() request_url = "%s:%s/%s" % ( _get_url(), _get_port(), vmconf.STORE_TRAINED_CLASSIFIER_MODEL_HANDLER) response = requests.post( request_url, data=data, headers={'Content-Type': 'application/octet-stream'}) return response.status_code
apache-2.0
Bitergia/redhat-rdo-dashboard
templates/apply_template.py
35
1833
#! /usr/bin/env python # Copyright (C) 2014 Bitergia # 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/>. import argparse def get_arguments(): parser = argparse.ArgumentParser(description='Parse HTML generator arguments') parser.add_argument('--template', dest='template_file', help='Template file name') parser.add_argument('--content', dest='content_file', help='Content file name') args = parser.parse_args() #print args.accumulate(args.integers) return args def include_webstats(html_body): """ Replace string "REPLACE_WEBSTATS" in html_body with JS code from file webstats.tmpl if present. If not, it just include and empty string """ text = "REPLACE_WEBSTATS" try: fd = open("webstats.tmpl","r") jscode = fd.read() fd.close() except: jscode = "" html_body = html_body.replace(text, jscode) return html_body if __name__ == "__main__": text = "REPLACE_HERE" arg = get_arguments() fd = open(arg.template_file, "r") template = fd.read() fd.close() fd2 = open(arg.content_file, "r") body = fd2.read() fd2.close() template = include_webstats(template) template = template.replace(text, body) print template
gpl-3.0
Lab603/PicEncyclopedias
jni-build/jni/include/tensorflow/contrib/distributions/python/ops/mvn.py
3
30904
# 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. # ============================================================================== """Multivariate Normal distribution classes.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math from tensorflow.contrib.distributions.python.ops import distribution from tensorflow.contrib.distributions.python.ops import kullback_leibler from tensorflow.contrib.distributions.python.ops import operator_pd_cholesky from tensorflow.contrib.distributions.python.ops import operator_pd_diag from tensorflow.contrib.distributions.python.ops import operator_pd_full from tensorflow.contrib.distributions.python.ops import operator_pd_vdvt_update from tensorflow.contrib.framework.python.framework import tensor_util as contrib_tensor_util from tensorflow.python.framework import constant_op from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import random_ops __all__ = [ "MultivariateNormalDiag", "MultivariateNormalCholesky", "MultivariateNormalFull", "MultivariateNormalDiagPlusVDVT", ] class MultivariateNormalOperatorPD(distribution.Distribution): """The multivariate normal distribution on `R^k`. This distribution is defined by a 1-D mean `mu` and an instance of `OperatorPDBase`, which provides access to a symmetric positive definite operator, which defines the covariance. #### Mathematical details With `C` the covariance matrix represented by the operator, the PDF of this distribution is: ``` f(x) = (2 pi)^(-k/2) |det(C)|^(-1/2) exp(-1/2 (x - mu)^T C^{-1} (x - mu)) ``` #### Examples A single multi-variate Gaussian distribution is defined by a vector of means of length `k`, and a covariance matrix of shape `k x k`. Extra leading dimensions, if provided, allow for batches. ```python # Initialize a single 3-variate Gaussian. mu = [1, 2, 3] chol = [[1, 0, 0.], [1, 3, 0], [1, 2, 3]] cov = tf.contrib.distributions.OperatorPDCholesky(chol) dist = tf.contrib.distributions.MultivariateNormalOperatorPD(mu, cov) # Evaluate this on an observation in R^3, returning a scalar. dist.pdf([-1, 0, 1.]) # Initialize a batch of two 3-variate Gaussians. mu = [[1, 2, 3], [11, 22, 33.]] chol = ... # shape 2 x 3 x 3, lower triangular, positive diagonal. cov = tf.contrib.distributions.OperatorPDCholesky(chol) dist = tf.contrib.distributions.MultivariateNormalOperatorPD(mu, cov) # Evaluate this on a two observations, each in R^3, returning a length two # tensor. x = [[-1, 0, 1], [-11, 0, 11.]] # Shape 2 x 3. dist.pdf(x) ``` """ def __init__(self, mu, cov, validate_args=True, allow_nan_stats=False, name="MultivariateNormalCov"): """Multivariate Normal distributions on `R^k`. User must provide means `mu`, and an instance of `OperatorPDBase`, `cov`, which determines the covariance. Args: mu: Floating point tensor with shape `[N1,...,Nb, k]`, `b >= 0`. cov: Instance of `OperatorPDBase` with same `dtype` as `mu` and shape `[N1,...,Nb, k, k]`. validate_args: Whether to validate input with asserts. If `validate_args` is `False`, and the inputs are invalid, correct behavior is not guaranteed. allow_nan_stats: `Boolean`, default `False`. If `False`, raise an exception if a statistic (e.g. mean/mode/etc...) is undefined for any batch member If `True`, batch members with valid parameters leading to undefined statistics will return NaN for this statistic. name: The name to give Ops created by the initializer. Raises: TypeError: If `mu` and `cov` are different dtypes. """ self._allow_nan_stats = allow_nan_stats self._validate_args = validate_args with ops.name_scope(name): with ops.op_scope([mu] + cov.inputs, "init"): self._cov = cov self._mu = self._check_mu(mu) self._name = name def _check_mu(self, mu): """Return `mu` after validity checks and possibly with assertations.""" mu = ops.convert_to_tensor(mu) cov = self._cov if mu.dtype != cov.dtype: raise TypeError( "mu and cov must have the same dtype. Found mu.dtype = %s, " "cov.dtype = %s" % (mu.dtype, cov.dtype)) # Try to validate with static checks. mu_shape = mu.get_shape() cov_shape = cov.get_shape() if mu_shape.is_fully_defined() and cov_shape.is_fully_defined(): if mu_shape != cov_shape[:-1]: raise ValueError( "mu.shape and cov.shape[:-1] should match. Found: mu.shape=%s, " "cov.shape=%s" % (mu_shape, cov_shape)) else: return mu # Static checks could not be run, so possibly do dynamic checks. if not self.validate_args: return mu else: assert_same_rank = check_ops.assert_equal( array_ops.rank(mu) + 1, cov.rank(), data=["mu should have rank 1 less than cov. Found: rank(mu) = ", array_ops.rank(mu), " rank(cov) = ", cov.rank()], ) with ops.control_dependencies([assert_same_rank]): assert_same_shape = check_ops.assert_equal( array_ops.shape(mu), cov.vector_shape(), data=["mu.shape and cov.shape[:-1] should match. " "Found: shape(mu) = " , array_ops.shape(mu), " shape(cov) = ", cov.shape()], ) return control_flow_ops.with_dependencies([assert_same_shape], mu) @property def validate_args(self): """`Boolean` describing behavior on invalid input.""" return self._validate_args @property def allow_nan_stats(self): """`Boolean` describing behavior when stats are undefined.""" return self._allow_nan_stats @property def dtype(self): return self._mu.dtype def get_event_shape(self): """`TensorShape` available at graph construction time.""" # Recall _check_mu ensures mu and self._cov have same batch shape. return self._cov.get_shape()[-1:] def event_shape(self, name="event_shape"): """Shape of a sample from a single distribution as a 1-D int32 `Tensor`.""" # Recall _check_mu ensures mu and self._cov have same batch shape. with ops.name_scope(self.name): with ops.op_scope(self._cov.inputs, name): return array_ops.pack([self._cov.vector_space_dimension()]) def batch_shape(self, name="batch_shape"): """Batch dimensions of this instance as a 1-D int32 `Tensor`.""" # Recall _check_mu ensures mu and self._cov have same batch shape. with ops.name_scope(self.name): with ops.op_scope(self._cov.inputs, name): return self._cov.batch_shape() def get_batch_shape(self): """`TensorShape` available at graph construction time.""" # Recall _check_mu ensures mu and self._cov have same batch shape. return self._cov.get_batch_shape() @property def mu(self): return self._mu @property def sigma(self): """Dense (batch) covariance matrix, if available.""" with ops.name_scope(self.name): return self._cov.to_dense() def mean(self, name="mean"): """Mean of each batch member.""" with ops.name_scope(self.name): with ops.op_scope([self._mu], name): return array_ops.identity(self._mu) def mode(self, name="mode"): """Mode of each batch member.""" with ops.name_scope(self.name): with ops.op_scope([self._mu], name): return array_ops.identity(self._mu) def variance(self, name="variance"): """Variance of each batch member.""" with ops.name_scope(self.name): return self.sigma def log_sigma_det(self, name="log_sigma_det"): """Log of determinant of covariance matrix.""" with ops.name_scope(self.name): with ops.op_scope(self._cov.inputs, name): return self._cov.log_det() def sigma_det(self, name="sigma_det"): """Determinant of covariance matrix.""" with ops.name_scope(self.name): with ops.op_scope(self._cov.inputs, name): return math_ops.exp(self._cov.log_det()) def log_prob(self, x, name="log_prob"): """Log prob of observations `x` given these Multivariate Normals. `x` is a batch vector with compatible shape if `x` is a `Tensor` whose shape can be broadcast up to either: ```` self.batch_shape + self.event_shape OR [M1,...,Mm] + self.batch_shape + self.event_shape ``` Args: x: Compatible batch vector with same `dtype` as this distribution. name: The name to give this op. Returns: log_prob: tensor of dtype `dtype`, the log-PDFs of `x`. """ # Q: Why are shape requirements as stated above? # A: The compatible shapes are precisely the ones that will broadcast to # a shape compatible with self._cov. # See Operator base class for notes about shapes compatible with self._cov. with ops.name_scope(self.name): with ops.op_scope([self._mu, x] + self._cov.inputs, name): x = ops.convert_to_tensor(x) contrib_tensor_util.assert_same_float_dtype((self._mu, x)) # _check_mu asserts that self.mu has same batch shape as self.cov. # so batch shape of self.mu = that of self._cov and self, and the # batch shape of x_centered is a broadcast version of these. If this # broadcast results in a shape like # [M1,...,Mm] + self.batch_shape + self.event_shape # OR # self.batch_shape + self.event_shape # then subsequent operator calls are guaranteed to work. x_centered = x - self.mu # Compute the term x^{-1} sigma^{-1} x which appears in the exponent of # the pdf. x_whitened_norm = self._cov.inv_quadratic_form_on_vectors(x_centered) log_sigma_det = self.log_sigma_det() log_two_pi = constant_op.constant( math.log(2 * math.pi), dtype=self.dtype) k = math_ops.cast(self._cov.vector_space_dimension(), self.dtype) log_prob_value = -(log_sigma_det + k * log_two_pi + x_whitened_norm) / 2 output_static_shape = x_centered.get_shape()[:-1] log_prob_value.set_shape(output_static_shape) return log_prob_value def prob(self, x, name="prob"): """The PDF of observations `x` under these Multivariate Normals. `x` is a batch vector with compatible shape if `x` is a `Tensor` whose shape can be broadcast up to either: ```` self.batch_shape + self.event_shape OR [M1,...,Mm] + self.batch_shape + self.event_shape ``` Args: x: Compatible batch vector with same `dtype` as this distribution. name: The name to give this op. Returns: prob: tensor of dtype `dtype`, the prob values of `x`. """ with ops.name_scope(self.name): with ops.op_scope([self._mu, x] + self._cov.inputs, name): return math_ops.exp(self.log_prob(x)) def entropy(self, name="entropy"): """The entropies of these Multivariate Normals. Args: name: The name to give this op. Returns: entropy: tensor of dtype `dtype`, the entropies. """ with ops.name_scope(self.name): with ops.op_scope([self._mu] + self._cov.inputs, name): log_sigma_det = self.log_sigma_det() one_plus_log_two_pi = constant_op.constant(1 + math.log(2 * math.pi), dtype=self.dtype) # Use broadcasting rules to calculate the full broadcast sigma. k = math_ops.cast(self._cov.vector_space_dimension(), dtype=self.dtype) entropy_value = (k * one_plus_log_two_pi + log_sigma_det) / 2 entropy_value.set_shape(log_sigma_det.get_shape()) return entropy_value def sample_n(self, n, seed=None, name="sample_n"): """Sample `n` observations from the Multivariate Normal Distributions. Args: n: `Scalar`, type int32, the number of observations to sample. seed: Python integer, the random seed. name: The name to give this op. Returns: samples: `[n, ...]`, a `Tensor` of `n` samples for each of the distributions determined by broadcasting the hyperparameters. """ with ops.name_scope(self.name): with ops.op_scope([self._mu, n] + self._cov.inputs, name): # Recall _check_mu ensures mu and self._cov have same batch shape. broadcast_shape = self.mu.get_shape() n = ops.convert_to_tensor(n) shape = array_ops.concat(0, [self._cov.vector_shape(), [n]]) white_samples = random_ops.random_normal(shape=shape, mean=0, stddev=1, dtype=self.dtype, seed=seed) correlated_samples = self._cov.sqrt_matmul(white_samples) # Move the last dimension to the front perm = array_ops.concat(0, ( array_ops.pack([array_ops.rank(correlated_samples) - 1]), math_ops.range(0, array_ops.rank(correlated_samples) - 1))) # TODO(ebrevdo): Once we get a proper tensor contraction op, # perform the inner product using that instead of batch_matmul # and this slow transpose can go away! correlated_samples = array_ops.transpose(correlated_samples, perm) samples = correlated_samples + self.mu # Provide some hints to shape inference n_val = tensor_util.constant_value(n) final_shape = tensor_shape.vector(n_val).concatenate(broadcast_shape) samples.set_shape(final_shape) return samples @property def is_reparameterized(self): return True @property def name(self): return self._name @property def is_continuous(self): return True class MultivariateNormalDiag(MultivariateNormalOperatorPD): """The multivariate normal distribution on `R^k`. This distribution is defined by a 1-D mean `mu` and a 1-D diagonal `diag_stdev`, representing the standard deviations. This distribution assumes the random variables, `(X_1,...,X_k)` are independent, thus no non-diagonal terms of the covariance matrix are needed. This allows for `O(k)` pdf evaluation, sampling, and storage. #### Mathematical details The PDF of this distribution is defined in terms of the diagonal covariance determined by `diag_stdev`: `C_{ii} = diag_stdev[i]**2`. ``` f(x) = (2 pi)^(-k/2) |det(C)|^(-1/2) exp(-1/2 (x - mu)^T C^{-1} (x - mu)) ``` #### Examples A single multi-variate Gaussian distribution is defined by a vector of means of length `k`, and the square roots of the (independent) random variables. Extra leading dimensions, if provided, allow for batches. ```python # Initialize a single 3-variate Gaussian with diagonal standard deviation. mu = [1, 2, 3.] diag_stdev = [4, 5, 6.] dist = tf.contrib.distributions.MultivariateNormalDiag(mu, diag_stdev) # Evaluate this on an observation in R^3, returning a scalar. dist.pdf([-1, 0, 1]) # Initialize a batch of two 3-variate Gaussians. mu = [[1, 2, 3], [11, 22, 33]] # shape 2 x 3 diag_stdev = ... # shape 2 x 3, positive. dist = tf.contrib.distributions.MultivariateNormalDiag(mu, diag_stdev) # Evaluate this on a two observations, each in R^3, returning a length two # tensor. x = [[-1, 0, 1], [-11, 0, 11]] # Shape 2 x 3. dist.pdf(x) ``` """ def __init__( self, mu, diag_stdev, validate_args=True, allow_nan_stats=False, name="MultivariateNormalDiag"): """Multivariate Normal distributions on `R^k`. User must provide means `mu` and standard deviations `diag_stdev`. Each batch member represents a random vector `(X_1,...,X_k)` of independent random normals. The mean of `X_i` is `mu[i]`, and the standard deviation is `diag_stdev[i]`. Args: mu: Rank `N + 1` floating point tensor with shape `[N1,...,Nb, k]`, `b >= 0`. diag_stdev: Rank `N + 1` `Tensor` with same `dtype` and shape as `mu`, representing the standard deviations. Must be positive. validate_args: Whether to validate input with asserts. If `validate_args` is `False`, and the inputs are invalid, correct behavior is not guaranteed. allow_nan_stats: `Boolean`, default `False`. If `False`, raise an exception if a statistic (e.g. mean/mode/etc...) is undefined for any batch member If `True`, batch members with valid parameters leading to undefined statistics will return NaN for this statistic. name: The name to give Ops created by the initializer. Raises: TypeError: If `mu` and `diag_stdev` are different dtypes. """ cov = operator_pd_diag.OperatorPDSqrtDiag( diag_stdev, verify_pd=validate_args) super(MultivariateNormalDiag, self).__init__( mu, cov, allow_nan_stats=allow_nan_stats, validate_args=validate_args, name=name) class MultivariateNormalDiagPlusVDVT(MultivariateNormalOperatorPD): """The multivariate normal distribution on `R^k`. Every batch member of this distribution is defined by a mean and a lightweight covariance matrix `C`. #### Mathematical details The PDF of this distribution in terms of the mean `mu` and covariance `C` is: ``` f(x) = (2 pi)^(-k/2) |det(C)|^(-1/2) exp(-1/2 (x - mu)^T C^{-1} (x - mu)) ``` For every batch member, this distribution represents `k` random variables `(X_1,...,X_k)`, with mean `E[X_i] = mu[i]`, and covariance matrix `C_{ij} := E[(X_i - mu[i])(X_j - mu[j])]` The user initializes this class by providing the mean `mu`, and a lightweight definition of `C`: ``` C = SS^T = SS = (M + V D V^T) (M + V D V^T) M is diagonal (k x k) V = is shape (k x r), typically r << k D = is diagonal (r x r), optional (defaults to identity). ``` This allows for `O(kr + r^3)` pdf evaluation and determinant, and `O(kr)` sampling and storage (per batch member). #### Examples A single multi-variate Gaussian distribution is defined by a vector of means of length `k`, and square root of the covariance `S = M + V D V^T`. Extra leading dimensions, if provided, allow for batches. ```python # Initialize a single 3-variate Gaussian with covariance square root # S = M + V D V^T, where V D V^T is a matrix-rank 2 update. mu = [1, 2, 3.] diag_large = [1.1, 2.2, 3.3] v = ... # shape 3 x 2 diag_small = [4., 5.] dist = tf.contrib.distributions.MultivariateNormalDiagPlusVDVT( mu, diag_large, v, diag_small=diag_small) # Evaluate this on an observation in R^3, returning a scalar. dist.pdf([-1, 0, 1]) # Initialize a batch of two 3-variate Gaussians. This time, don't provide # diag_small. This means S = M + V V^T. mu = [[1, 2, 3], [11, 22, 33]] # shape 2 x 3 diag_large = ... # shape 2 x 3 v = ... # shape 2 x 3 x 1, a matrix-rank 1 update. dist = tf.contrib.distributions.MultivariateNormalDiagPlusVDVT( mu, diag_large, v) # Evaluate this on a two observations, each in R^3, returning a length two # tensor. x = [[-1, 0, 1], [-11, 0, 11]] # Shape 2 x 3. dist.pdf(x) ``` """ def __init__( self, mu, diag_large, v, diag_small=None, validate_args=True, allow_nan_stats=False, name="MultivariateNormalDiagPlusVDVT"): """Multivariate Normal distributions on `R^k`. For every batch member, this distribution represents `k` random variables `(X_1,...,X_k)`, with mean `E[X_i] = mu[i]`, and covariance matrix `C_{ij} := E[(X_i - mu[i])(X_j - mu[j])]` The user initializes this class by providing the mean `mu`, and a lightweight definition of `C`: ``` C = SS^T = SS = (M + V D V^T) (M + V D V^T) M is diagonal (k x k) V = is shape (k x r), typically r << k D = is diagonal (r x r), optional (defaults to identity). ``` Args: mu: Rank `n + 1` floating point tensor with shape `[N1,...,Nn, k]`, `n >= 0`. The means. diag_large: Optional rank `n + 1` floating point tensor, shape `[N1,...,Nn, k]` `n >= 0`. Defines the diagonal matrix `M`. v: Rank `n + 1` floating point tensor, shape `[N1,...,Nn, k, r]` `n >= 0`. Defines the matrix `V`. diag_small: Rank `n + 1` floating point tensor, shape `[N1,...,Nn, k]` `n >= 0`. Defines the diagonal matrix `D`. Default is `None`, which means `D` will be the identity matrix. validate_args: Whether to validate input with asserts. If `validate_args` is `False`, and the inputs are invalid, correct behavior is not guaranteed. allow_nan_stats: `Boolean`, default `False`. If `False`, raise an exception if a statistic (e.g. mean/mode/etc...) is undefined for any batch member If `True`, batch members with valid parameters leading to undefined statistics will return NaN for this statistic. name: The name to give Ops created by the initializer. """ m = operator_pd_diag.OperatorPDDiag(diag_large, verify_pd=validate_args) cov = operator_pd_vdvt_update.OperatorPDSqrtVDVTUpdate( m, v, diag=diag_small, verify_pd=validate_args, verify_shapes=validate_args) super(MultivariateNormalDiagPlusVDVT, self).__init__( mu, cov, allow_nan_stats=allow_nan_stats, validate_args=validate_args, name=name) class MultivariateNormalCholesky(MultivariateNormalOperatorPD): """The multivariate normal distribution on `R^k`. This distribution is defined by a 1-D mean `mu` and a Cholesky factor `chol`. Providing the Cholesky factor allows for `O(k^2)` pdf evaluation and sampling, and requires `O(k^2)` storage. #### Mathematical details The Cholesky factor `chol` defines the covariance matrix: `C = chol chol^T`. The PDF of this distribution is then: ``` f(x) = (2 pi)^(-k/2) |det(C)|^(-1/2) exp(-1/2 (x - mu)^T C^{-1} (x - mu)) ``` #### Examples A single multi-variate Gaussian distribution is defined by a vector of means of length `k`, and a covariance matrix of shape `k x k`. Extra leading dimensions, if provided, allow for batches. ```python # Initialize a single 3-variate Gaussian with diagonal covariance. # Note, this would be more efficient with MultivariateNormalDiag. mu = [1, 2, 3.] chol = [[1, 0, 0], [0, 3, 0], [0, 0, 2]] dist = tf.contrib.distributions.MultivariateNormalCholesky(mu, chol) # Evaluate this on an observation in R^3, returning a scalar. dist.pdf([-1, 0, 1]) # Initialize a batch of two 3-variate Gaussians. mu = [[1, 2, 3], [11, 22, 33]] chol = ... # shape 2 x 3 x 3, lower triangular, positive diagonal. dist = tf.contrib.distributions.MultivariateNormalCholesky(mu, chol) # Evaluate this on a two observations, each in R^3, returning a length two # tensor. x = [[-1, 0, 1], [-11, 0, 11]] # Shape 2 x 3. dist.pdf(x) ``` Trainable (batch) Choesky matrices can be created with `tf.contrib.distributions.batch_matrix_diag_transform()` """ def __init__(self, mu, chol, validate_args=True, allow_nan_stats=False, name="MultivariateNormalCholesky"): """Multivariate Normal distributions on `R^k`. User must provide means `mu` and `chol` which holds the (batch) Cholesky factors, such that the covariance of each batch member is `chol chol^T`. Args: mu: `(N+1)-D` floating point tensor with shape `[N1,...,Nb, k]`, `b >= 0`. chol: `(N+2)-D` `Tensor` with same `dtype` as `mu` and shape `[N1,...,Nb, k, k]`. The upper triangular part is ignored (treated as though it is zero), and the diagonal must be positive. validate_args: Whether to validate input with asserts. If `validate_args` is `False`, and the inputs are invalid, correct behavior is not guaranteed. allow_nan_stats: `Boolean`, default `False`. If `False`, raise an exception if a statistic (e.g. mean/mode/etc...) is undefined for any batch member If `True`, batch members with valid parameters leading to undefined statistics will return NaN for this statistic. name: The name to give Ops created by the initializer. Raises: TypeError: If `mu` and `chol` are different dtypes. """ cov = operator_pd_cholesky.OperatorPDCholesky(chol, verify_pd=validate_args) super(MultivariateNormalCholesky, self).__init__( mu, cov, allow_nan_stats=allow_nan_stats, validate_args=validate_args, name=name) class MultivariateNormalFull(MultivariateNormalOperatorPD): """The multivariate normal distribution on `R^k`. This distribution is defined by a 1-D mean `mu` and covariance matrix `sigma`. Evaluation of the pdf, determinant, and sampling are all `O(k^3)` operations. #### Mathematical details With `C = sigma`, the PDF of this distribution is: ``` f(x) = (2 pi)^(-k/2) |det(C)|^(-1/2) exp(-1/2 (x - mu)^T C^{-1} (x - mu)) ``` #### Examples A single multi-variate Gaussian distribution is defined by a vector of means of length `k`, and a covariance matrix of shape `k x k`. Extra leading dimensions, if provided, allow for batches. ```python # Initialize a single 3-variate Gaussian with diagonal covariance. mu = [1, 2, 3.] sigma = [[1, 0, 0], [0, 3, 0], [0, 0, 2.]] dist = tf.contrib.distributions.MultivariateNormalFull(mu, chol) # Evaluate this on an observation in R^3, returning a scalar. dist.pdf([-1, 0, 1]) # Initialize a batch of two 3-variate Gaussians. mu = [[1, 2, 3], [11, 22, 33.]] sigma = ... # shape 2 x 3 x 3, positive definite. dist = tf.contrib.distributions.MultivariateNormalFull(mu, sigma) # Evaluate this on a two observations, each in R^3, returning a length two # tensor. x = [[-1, 0, 1], [-11, 0, 11.]] # Shape 2 x 3. dist.pdf(x) ``` """ def __init__(self, mu, sigma, validate_args=True, allow_nan_stats=False, name="MultivariateNormalFull"): """Multivariate Normal distributions on `R^k`. User must provide means `mu` and `sigma`, the mean and covariance. Args: mu: `(N+1)-D` floating point tensor with shape `[N1,...,Nb, k]`, `b >= 0`. sigma: `(N+2)-D` `Tensor` with same `dtype` as `mu` and shape `[N1,...,Nb, k, k]`. Each batch member must be positive definite. validate_args: Whether to validate input with asserts. If `validate_args` is `False`, and the inputs are invalid, correct behavior is not guaranteed. allow_nan_stats: `Boolean`, default `False`. If `False`, raise an exception if a statistic (e.g. mean/mode/etc...) is undefined for any batch member If `True`, batch members with valid parameters leading to undefined statistics will return NaN for this statistic. name: The name to give Ops created by the initializer. Raises: TypeError: If `mu` and `sigma` are different dtypes. """ cov = operator_pd_full.OperatorPDFull(sigma, verify_pd=validate_args) super(MultivariateNormalFull, self).__init__( mu, cov, allow_nan_stats=allow_nan_stats, validate_args=validate_args, name=name) def _kl_mvn_mvn_brute_force(mvn_a, mvn_b, name=None): """Batched KL divergence `KL(mvn_a || mvn_b)` for multivariate normals. With `X`, `Y` both multivariate normals in `R^k` with means `mu_x`, `mu_y` and covariance `C_x`, `C_y` respectively, ``` KL(X || Y) = 0.5 * ( T + Q + - k + L ), T := trace(C_b^{-1} C_a), Q := (mu_b - mu_a)^T C_b^{-1} (mu_b - mu_a), L := Log[Det(C_b)] - Log[Det(C_a)] ``` This `Op` computes the trace by solving `C_b^{-1} C_a`. Although efficient methods for solving systems with `C_b` may be available, a dense version of (the square root of) `C_a` is used, so performance is `O(B s k^2)` where `B` is the batch size, and `s` is the cost of solving `C_b x = y` for vectors `x` and `y`. Args: mvn_a: Instance of subclass of `MultivariateNormalOperatorPD`. mvn_b: Instance of subclass of `MultivariateNormalOperatorPD`. name: (optional) name to use for created ops. Default "kl_mvn_mvn". Returns: Batchwise `KL(mvn_a || mvn_b)`. """ # Access the "private" OperatorPD that each mvn is built from. cov_a = mvn_a._cov # pylint: disable=protected-access cov_b = mvn_b._cov # pylint: disable=protected-access mu_a = mvn_a.mu mu_b = mvn_b.mu inputs = [mu_a, mu_b] + cov_a.inputs + cov_b.inputs with ops.op_scope(inputs, name, "kl_mvn_mvn"): # If Ca = AA', Cb = BB', then # tr[inv(Cb) Ca] = tr[inv(B)' inv(B) A A'] # = tr[inv(B) A A' inv(B)'] # = tr[(inv(B) A) (inv(B) A)'] # = sum_{ik} (inv(B) A)_{ik}^2 # The second equality follows from the cyclic permutation property. b_inv_a = cov_b.sqrt_solve(cov_a.sqrt_to_dense()) t = math_ops.reduce_sum( math_ops.square(b_inv_a), reduction_indices=[-1, -2]) q = cov_b.inv_quadratic_form_on_vectors(mu_b - mu_a) k = math_ops.cast(cov_a.vector_space_dimension(), mvn_a.dtype) one_half_l = cov_b.sqrt_log_det() - cov_a.sqrt_log_det() return 0.5 * (t + q - k) + one_half_l # Register KL divergences. kl_classes = [ MultivariateNormalFull, MultivariateNormalCholesky, MultivariateNormalDiag, MultivariateNormalDiagPlusVDVT, ] for mvn_aa in kl_classes: # Register when they are the same here, and do not register when they are the # same below because that would result in a repeated registration. kullback_leibler.RegisterKL(mvn_aa, mvn_aa)(_kl_mvn_mvn_brute_force) for mvn_bb in kl_classes: if mvn_bb != mvn_aa: kullback_leibler.RegisterKL(mvn_aa, mvn_bb)(_kl_mvn_mvn_brute_force)
mit
jcpowermac/ansible-modules-extras
clustering/consul_acl.py
13
10484
#!/usr/bin/python # # (c) 2015, Steve Gargan <steve.gargan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. DOCUMENTATION = """ module: consul_acl short_description: "manipulate consul acl keys and rules" description: - allows the addition, modification and deletion of ACL keys and associated rules in a consul cluster via the agent. For more details on using and configuring ACLs, see https://www.consul.io/docs/internals/acl.html. requirements: - "python >= 2.6" - python-consul - pyhcl - requests version_added: "2.0" author: "Steve Gargan (@sgargan)" options: mgmt_token: description: - a management token is required to manipulate the acl lists state: description: - whether the ACL pair should be present or absent, defaults to present required: false choices: ['present', 'absent'] type: description: - the type of token that should be created, either management or client, defaults to client choices: ['client', 'management'] name: description: - the name that should be associated with the acl key, this is opaque to Consul required: false token: description: - the token key indentifying an ACL rule set. If generated by consul this will be a UUID. required: false rules: description: - an list of the rules that should be associated with a given token. required: false host: description: - host of the consul agent defaults to localhost required: false default: localhost port: description: - the port on which the consul agent is running required: false default: 8500 """ EXAMPLES = ''' - name: create an acl token with rules consul_acl: mgmt_token: 'some_management_acl' host: 'consul1.mycluster.io' name: 'Foo access' rules: - key: 'foo' policy: read - key: 'private/foo' policy: deny - name: create an acl with specific token with both key and serivce rules consul_acl: mgmt_token: 'some_management_acl' name: 'Foo access' token: 'some_client_token' rules: - key: 'foo' policy: read - service: '' policy: write - service: 'secret-' policy: deny - name: remove a token consul_acl: mgmt_token: 'some_management_acl' host: 'consul1.mycluster.io' token: '172bd5c8-9fe9-11e4-b1b0-3c15c2c9fd5e' state: absent ''' import sys try: import consul from requests.exceptions import ConnectionError python_consul_installed = True except ImportError, e: python_consul_installed = False try: import hcl pyhcl_installed = True except ImportError: pyhcl_installed = False from requests.exceptions import ConnectionError def execute(module): state = module.params.get('state') if state == 'present': update_acl(module) else: remove_acl(module) def update_acl(module): rules = module.params.get('rules') state = module.params.get('state') token = module.params.get('token') token_type = module.params.get('token_type') mgmt = module.params.get('mgmt_token') name = module.params.get('name') consul = get_consul_api(module, mgmt) changed = False try: if token: existing_rules = load_rules_for_token(module, consul, token) supplied_rules = yml_to_rules(module, rules) changed = not existing_rules == supplied_rules if changed: y = supplied_rules.to_hcl() token = consul.acl.update( token, name=name, type=token_type, rules=supplied_rules.to_hcl()) else: try: rules = yml_to_rules(module, rules) if rules.are_rules(): rules = rules.to_hcl() else: rules = None token = consul.acl.create( name=name, type=token_type, rules=rules) changed = True except Exception, e: module.fail_json( msg="No token returned, check your managment key and that \ the host is in the acl datacenter %s" % e) except Exception, e: module.fail_json(msg="Could not create/update acl %s" % e) module.exit_json(changed=changed, token=token, rules=rules, name=name, type=token_type) def remove_acl(module): state = module.params.get('state') token = module.params.get('token') mgmt = module.params.get('mgmt_token') consul = get_consul_api(module, token=mgmt) changed = token and consul.acl.info(token) if changed: token = consul.acl.destroy(token) module.exit_json(changed=changed, token=token) def load_rules_for_token(module, consul_api, token): try: rules = Rules() info = consul_api.acl.info(token) if info and info['Rules']: rule_set = hcl.loads(to_ascii(info['Rules'])) for rule_type in rule_set: for pattern, policy in rule_set[rule_type].iteritems(): rules.add_rule(rule_type, Rule(pattern, policy['policy'])) return rules except Exception, e: module.fail_json( msg="Could not load rule list from retrieved rule data %s, %s" % ( token, e)) return json_to_rules(module, loaded) def to_ascii(unicode_string): if isinstance(unicode_string, unicode): return unicode_string.encode('ascii', 'ignore') return unicode_string def yml_to_rules(module, yml_rules): rules = Rules() if yml_rules: for rule in yml_rules: if ('key' in rule and 'policy' in rule): rules.add_rule('key', Rule(rule['key'], rule['policy'])) elif ('service' in rule and 'policy' in rule): rules.add_rule('service', Rule(rule['service'], rule['policy'])) else: module.fail_json(msg="a rule requires a key/service and a policy.") return rules template = '''%s "%s" { policy = "%s" } ''' RULE_TYPES = ['key', 'service'] class Rules: def __init__(self): self.rules = {} for rule_type in RULE_TYPES: self.rules[rule_type] = {} def add_rule(self, rule_type, rule): self.rules[rule_type][rule.pattern] = rule def are_rules(self): return len(self) > 0 def to_hcl(self): rules = "" for rule_type in RULE_TYPES: for pattern, rule in self.rules[rule_type].iteritems(): rules += template % (rule_type, pattern, rule.policy) return to_ascii(rules) def __len__(self): count = 0 for rule_type in RULE_TYPES: count += len(self.rules[rule_type]) return count def __eq__(self, other): if not (other or isinstance(other, self.__class__) or len(other) == len(self)): return False for rule_type in RULE_TYPES: for name, other_rule in other.rules[rule_type].iteritems(): if not name in self.rules[rule_type]: return False rule = self.rules[rule_type][name] if not (rule and rule == other_rule): return False return True def __str__(self): return self.to_hcl() class Rule: def __init__(self, pattern, policy): self.pattern = pattern self.policy = policy def __eq__(self, other): return (isinstance(other, self.__class__) and self.pattern == other.pattern and self.policy == other.policy) def __hash__(self): return hash(self.pattern) ^ hash(self.policy) def __str__(self): return '%s %s' % (self.pattern, self.policy) def get_consul_api(module, token=None): if not token: token = module.params.get('token') return consul.Consul(host=module.params.get('host'), port=module.params.get('port'), token=token) def test_dependencies(module): if not python_consul_installed: module.fail_json(msg="python-consul required for this module. "\ "see http://python-consul.readthedocs.org/en/latest/#installation") if not pyhcl_installed: module.fail_json( msg="pyhcl required for this module."\ " see https://pypi.python.org/pypi/pyhcl") def main(): argument_spec = dict( mgmt_token=dict(required=True, no_log=True), host=dict(default='localhost'), name=dict(required=False), port=dict(default=8500, type='int'), rules=dict(default=None, required=False, type='list'), state=dict(default='present', choices=['present', 'absent']), token=dict(required=False, no_log=True), token_type=dict( required=False, choices=['client', 'management'], default='client') ) module = AnsibleModule(argument_spec, supports_check_mode=False) test_dependencies(module) try: execute(module) except ConnectionError, e: module.fail_json(msg='Could not connect to consul agent at %s:%s, error was %s' % ( module.params.get('host'), module.params.get('port'), str(e))) except Exception, e: module.fail_json(msg=str(e)) # import module snippets from ansible.module_utils.basic import * if __name__ == '__main__': main()
gpl-3.0
DreamerKing/LightweightHtmlWidgets
LightweightHtmlWidgets/bin/Release/Ipy.Lib/wsgiref/simple_server.py
177
4743
"""BaseHTTPServer that implements the Python WSGI protocol (PEP 333, rev 1.21) This is both an example of how WSGI can be implemented, and a basis for running simple web applications on a local machine, such as might be done when testing or debugging an application. It has not been reviewed for security issues, however, and we strongly recommend that you use a "real" web server for production use. For example usage, see the 'if __name__=="__main__"' block at the end of the module. See also the BaseHTTPServer module docs for other API information. """ from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer import urllib, sys from wsgiref.handlers import SimpleHandler __version__ = "0.1" __all__ = ['WSGIServer', 'WSGIRequestHandler', 'demo_app', 'make_server'] server_version = "WSGIServer/" + __version__ sys_version = "Python/" + sys.version.split()[0] software_version = server_version + ' ' + sys_version class ServerHandler(SimpleHandler): server_software = software_version def close(self): try: self.request_handler.log_request( self.status.split(' ',1)[0], self.bytes_sent ) finally: SimpleHandler.close(self) class WSGIServer(HTTPServer): """BaseHTTPServer that implements the Python WSGI protocol""" application = None def server_bind(self): """Override server_bind to store the server name.""" HTTPServer.server_bind(self) self.setup_environ() def setup_environ(self): # Set up base environment env = self.base_environ = {} env['SERVER_NAME'] = self.server_name env['GATEWAY_INTERFACE'] = 'CGI/1.1' env['SERVER_PORT'] = str(self.server_port) env['REMOTE_HOST']='' env['CONTENT_LENGTH']='' env['SCRIPT_NAME'] = '' def get_app(self): return self.application def set_app(self,application): self.application = application class WSGIRequestHandler(BaseHTTPRequestHandler): server_version = "WSGIServer/" + __version__ def get_environ(self): env = self.server.base_environ.copy() env['SERVER_PROTOCOL'] = self.request_version env['REQUEST_METHOD'] = self.command if '?' in self.path: path,query = self.path.split('?',1) else: path,query = self.path,'' env['PATH_INFO'] = urllib.unquote(path) env['QUERY_STRING'] = query host = self.address_string() if host != self.client_address[0]: env['REMOTE_HOST'] = host env['REMOTE_ADDR'] = self.client_address[0] if self.headers.typeheader is None: env['CONTENT_TYPE'] = self.headers.type else: env['CONTENT_TYPE'] = self.headers.typeheader length = self.headers.getheader('content-length') if length: env['CONTENT_LENGTH'] = length for h in self.headers.headers: k,v = h.split(':',1) k=k.replace('-','_').upper(); v=v.strip() if k in env: continue # skip content length, type,etc. if 'HTTP_'+k in env: env['HTTP_'+k] += ','+v # comma-separate multiple headers else: env['HTTP_'+k] = v return env def get_stderr(self): return sys.stderr def handle(self): """Handle a single HTTP request""" self.raw_requestline = self.rfile.readline() if not self.parse_request(): # An error code has been sent, just exit return handler = ServerHandler( self.rfile, self.wfile, self.get_stderr(), self.get_environ() ) handler.request_handler = self # backpointer for logging handler.run(self.server.get_app()) def demo_app(environ,start_response): from StringIO import StringIO stdout = StringIO() print >>stdout, "Hello world!" print >>stdout h = environ.items(); h.sort() for k,v in h: print >>stdout, k,'=', repr(v) start_response("200 OK", [('Content-Type','text/plain')]) return [stdout.getvalue()] def make_server( host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler ): """Create a new WSGI server listening on `host` and `port` for `app`""" server = server_class((host, port), handler_class) server.set_app(app) return server if __name__ == '__main__': httpd = make_server('', 8000, demo_app) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." import webbrowser webbrowser.open('http://localhost:8000/xyz?abc') httpd.handle_request() # serve one request, then exit
gpl-3.0
google/clif
examples/wrapfunc/python/default_args_test.py
1
1214
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tests for clif.examples.wrapfunc.python.default_args.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import unittest from wrapfunc.python import default_args class DefaultArgTest(unittest.TestCase): def testDefaultArgTest(self): self.assertTrue(default_args.Inc(5), 6) self.assertTrue(default_args.Inc(5, 2), 7) self.assertTrue(default_args.Scale(5), 10) self.assertTrue(default_args.Scale(5, offset=10), 30) with self.assertRaises(ValueError): default_args.ScaleWithRatios(5, offset=10) if __name__ == '__main__': unittest.main()
apache-2.0
openstack/manila
manila/scheduler/weighers/pool.py
5
1955
# Copyright 2015 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_config import cfg from manila import context from manila.db import api as db_api from manila.scheduler.weighers import base_host from manila.share import utils pool_weight_opts = [ cfg.FloatOpt('pool_weight_multiplier', default=1.0, help='Multiplier used for weighing pools which have ' 'existing share servers. Negative numbers mean to spread' ' vs stack.'), ] CONF = cfg.CONF CONF.register_opts(pool_weight_opts) class PoolWeigher(base_host.BaseHostWeigher): def weight_multiplier(self): """Override the weight multiplier.""" return CONF.pool_weight_multiplier def _weigh_object(self, host_state, weight_properties): """Pools with existing share server win.""" pool_mapping = weight_properties.get('server_pools_mapping', {}) if not pool_mapping: return 0 ctx = context.get_admin_context() host = utils.extract_host(host_state.host, 'backend') servers = db_api.share_server_get_all_by_host(ctx, host) pool = utils.extract_host(host_state.host, 'pool') for server in servers: if any(pool == p['pool_name'] for p in pool_mapping.get( server['id'], [])): return 1 return 0
apache-2.0
Garrett-R/scikit-learn
sklearn/linear_model/randomized_l1.py
11
23088
""" Randomized Lasso/Logistic: feature selection based on Lasso and sparse Logistic Regression """ # Author: Gael Varoquaux, Alexandre Gramfort # # License: BSD 3 clause import itertools from abc import ABCMeta, abstractmethod import warnings import numpy as np from scipy.sparse import issparse from scipy import sparse from scipy.interpolate import interp1d from .base import center_data from ..base import BaseEstimator, TransformerMixin from ..externals import six from ..externals.joblib import Memory, Parallel, delayed from ..utils import (as_float_array, check_random_state, check_X_y, check_array, safe_mask, ConvergenceWarning) from .least_angle import lars_path, LassoLarsIC from .logistic import LogisticRegression ############################################################################### # Randomized linear model: feature selection def _resample_model(estimator_func, X, y, scaling=.5, n_resampling=200, n_jobs=1, verbose=False, pre_dispatch='3*n_jobs', random_state=None, sample_fraction=.75, **params): random_state = check_random_state(random_state) # We are generating 1 - weights, and not weights n_samples, n_features = X.shape if not (0 < scaling < 1): raise ValueError( "'scaling' should be between 0 and 1. Got %r instead." % scaling) scaling = 1. - scaling scores_ = 0.0 for active_set in Parallel(n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch)( delayed(estimator_func)( X, y, weights=scaling * random_state.random_integers( 0, 1, size=(n_features,)), mask=(random_state.rand(n_samples) < sample_fraction), verbose=max(0, verbose - 1), **params) for _ in range(n_resampling)): scores_ += active_set scores_ /= n_resampling return scores_ class BaseRandomizedLinearModel(six.with_metaclass(ABCMeta, BaseEstimator, TransformerMixin)): """Base class to implement randomized linear models for feature selection This implements the strategy by Meinshausen and Buhlman: stability selection with randomized sampling, and random re-weighting of the penalty. """ @abstractmethod def __init__(self): pass _center_data = staticmethod(center_data) def fit(self, X, y): """Fit the model using X, y as training data. Parameters ---------- X : array-like, sparse matrix shape = [n_samples, n_features] Training data. y : array-like, shape = [n_samples] Target values. Returns ------- self : object Returns an instance of self. """ X, y = check_X_y(X, y, ['csr', 'csc', 'coo']) X = as_float_array(X, copy=False) n_samples, n_features = X.shape X, y, X_mean, y_mean, X_std = self._center_data(X, y, self.fit_intercept, self.normalize) estimator_func, params = self._make_estimator_and_params(X, y) memory = self.memory if isinstance(memory, six.string_types): memory = Memory(cachedir=memory) scores_ = memory.cache( _resample_model, ignore=['verbose', 'n_jobs', 'pre_dispatch'] )( estimator_func, X, y, scaling=self.scaling, n_resampling=self.n_resampling, n_jobs=self.n_jobs, verbose=self.verbose, pre_dispatch=self.pre_dispatch, random_state=self.random_state, sample_fraction=self.sample_fraction, **params) if scores_.ndim == 1: scores_ = scores_[:, np.newaxis] self.all_scores_ = scores_ self.scores_ = np.max(self.all_scores_, axis=1) return self def _make_estimator_and_params(self, X, y): """Return the parameters passed to the estimator""" raise NotImplementedError def get_support(self, indices=False): """Return a mask, or list, of the features/indices selected.""" mask = self.scores_ > self.selection_threshold return mask if not indices else np.where(mask)[0] # XXX: the two function below are copy/pasted from feature_selection, # Should we add an intermediate base class? def transform(self, X): """Transform a new matrix using the selected features""" mask = self.get_support() X = check_array(X) if len(mask) != X.shape[1]: raise ValueError("X has a different shape than during fitting.") return check_array(X)[:, safe_mask(X, mask)] def inverse_transform(self, X): """Transform a new matrix using the selected features""" support = self.get_support() if X.ndim == 1: X = X[None, :] Xt = np.zeros((X.shape[0], support.size)) Xt[:, support] = X return Xt ############################################################################### # Randomized lasso: regression settings def _randomized_lasso(X, y, weights, mask, alpha=1., verbose=False, precompute=False, eps=np.finfo(np.float).eps, max_iter=500): X = X[safe_mask(X, mask)] y = y[mask] # Center X and y to avoid fit the intercept X -= X.mean(axis=0) y -= y.mean() alpha = np.atleast_1d(np.asarray(alpha, dtype=np.float)) X = (1 - weights) * X with warnings.catch_warnings(): warnings.simplefilter('ignore', ConvergenceWarning) alphas_, _, coef_ = lars_path(X, y, Gram=precompute, copy_X=False, copy_Gram=False, alpha_min=np.min(alpha), method='lasso', verbose=verbose, max_iter=max_iter, eps=eps) if len(alpha) > 1: if len(alphas_) > 1: # np.min(alpha) < alpha_min interpolator = interp1d(alphas_[::-1], coef_[:, ::-1], bounds_error=False, fill_value=0.) scores = (interpolator(alpha) != 0.0) else: scores = np.zeros((X.shape[1], len(alpha)), dtype=np.bool) else: scores = coef_[:, -1] != 0.0 return scores class RandomizedLasso(BaseRandomizedLinearModel): """Randomized Lasso. Randomized Lasso works by resampling the train data and computing a Lasso on each resampling. In short, the features selected more often are good features. It is also known as stability selection. Parameters ---------- alpha : float, 'aic', or 'bic', optional The regularization parameter alpha parameter in the Lasso. Warning: this is not the alpha parameter in the stability selection article which is scaling. scaling : float, optional The alpha parameter in the stability selection article used to randomly scale the features. Should be between 0 and 1. sample_fraction : float, optional The fraction of samples to be used in each randomized design. Should be between 0 and 1. If 1, all samples are used. n_resampling : int, optional Number of randomized models. selection_threshold: float, optional The score above which features should be selected. fit_intercept : boolean, optional whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). verbose : boolean or integer, optional Sets the verbosity amount normalize : boolean, optional, default True If True, the regressors X will be normalized before regression. precompute : True | False | 'auto' Whether to use a precomputed Gram matrix to speed up calculations. If set to 'auto' let us decide. The Gram matrix can also be passed as argument. max_iter : integer, optional Maximum number of iterations to perform in the Lars algorithm. eps : float, optional The machine-precision regularization in the computation of the Cholesky diagonal factors. Increase this for very ill-conditioned systems. Unlike the 'tol' parameter in some iterative optimization-based algorithms, this parameter does not control the tolerance of the optimization. n_jobs : integer, optional Number of CPUs to use during the resampling. If '-1', use all the CPUs random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. pre_dispatch : int, or string, optional Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be: - None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs - An int, giving the exact number of total jobs that are spawned - A string, giving an expression as a function of n_jobs, as in '2*n_jobs' memory : Instance of joblib.Memory or string Used for internal caching. By default, no caching is done. If a string is given, it is the path to the caching directory. Attributes ---------- scores_ : array, shape = [n_features] Feature scores between 0 and 1. all_scores_ : array, shape = [n_features, n_reg_parameter] Feature scores between 0 and 1 for all values of the regularization \ parameter. The reference article suggests ``scores_`` is the max of \ ``all_scores_``. Examples -------- >>> from sklearn.linear_model import RandomizedLasso >>> randomized_lasso = RandomizedLasso() Notes ----- See examples/linear_model/plot_sparse_recovery.py for an example. References ---------- Stability selection Nicolai Meinshausen, Peter Buhlmann Journal of the Royal Statistical Society: Series B Volume 72, Issue 4, pages 417-473, September 2010 DOI: 10.1111/j.1467-9868.2010.00740.x See also -------- RandomizedLogisticRegression, LogisticRegression """ def __init__(self, alpha='aic', scaling=.5, sample_fraction=.75, n_resampling=200, selection_threshold=.25, fit_intercept=True, verbose=False, normalize=True, precompute='auto', max_iter=500, eps=np.finfo(np.float).eps, random_state=None, n_jobs=1, pre_dispatch='3*n_jobs', memory=Memory(cachedir=None, verbose=0)): self.alpha = alpha self.scaling = scaling self.sample_fraction = sample_fraction self.n_resampling = n_resampling self.fit_intercept = fit_intercept self.max_iter = max_iter self.verbose = verbose self.normalize = normalize self.precompute = precompute self.eps = eps self.random_state = random_state self.n_jobs = n_jobs self.selection_threshold = selection_threshold self.pre_dispatch = pre_dispatch self.memory = memory def _make_estimator_and_params(self, X, y): assert self.precompute in (True, False, None, 'auto') alpha = self.alpha if alpha in ('aic', 'bic'): model = LassoLarsIC(precompute=self.precompute, criterion=self.alpha, max_iter=self.max_iter, eps=self.eps) model.fit(X, y) self.alpha_ = alpha = model.alpha_ return _randomized_lasso, dict(alpha=alpha, max_iter=self.max_iter, eps=self.eps, precompute=self.precompute) ############################################################################### # Randomized logistic: classification settings def _randomized_logistic(X, y, weights, mask, C=1., verbose=False, fit_intercept=True, tol=1e-3): X = X[safe_mask(X, mask)] y = y[mask] if issparse(X): size = len(weights) weight_dia = sparse.dia_matrix((1 - weights, 0), (size, size)) X = X * weight_dia else: X *= (1 - weights) C = np.atleast_1d(np.asarray(C, dtype=np.float)) scores = np.zeros((X.shape[1], len(C)), dtype=np.bool) for this_C, this_scores in zip(C, scores.T): # XXX : would be great to do it with a warm_start ... clf = LogisticRegression(C=this_C, tol=tol, penalty='l1', dual=False, fit_intercept=fit_intercept) clf.fit(X, y) this_scores[:] = np.any( np.abs(clf.coef_) > 10 * np.finfo(np.float).eps, axis=0) return scores class RandomizedLogisticRegression(BaseRandomizedLinearModel): """Randomized Logistic Regression Randomized Regression works by resampling the train data and computing a LogisticRegression on each resampling. In short, the features selected more often are good features. It is also known as stability selection. Parameters ---------- C : float, optional, default=1 The regularization parameter C in the LogisticRegression. scaling : float, optional, default=0.5 The alpha parameter in the stability selection article used to randomly scale the features. Should be between 0 and 1. sample_fraction : float, optional, default=0.75 The fraction of samples to be used in each randomized design. Should be between 0 and 1. If 1, all samples are used. n_resampling : int, optional, default=200 Number of randomized models. selection_threshold: float, optional, default=0.25 The score above which features should be selected. fit_intercept : boolean, optional, default=True whether to calculate the intercept for this model. If set to false, no intercept will be used in calculations (e.g. data is expected to be already centered). verbose : boolean or integer, optional Sets the verbosity amount normalize : boolean, optional, default=True If True, the regressors X will be normalized before regression. tol : float, optional, default=1e-3 tolerance for stopping criteria of LogisticRegression n_jobs : integer, optional Number of CPUs to use during the resampling. If '-1', use all the CPUs random_state : int, RandomState instance or None, optional (default=None) If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. pre_dispatch : int, or string, optional Controls the number of jobs that get dispatched during parallel execution. Reducing this number can be useful to avoid an explosion of memory consumption when more jobs get dispatched than CPUs can process. This parameter can be: - None, in which case all the jobs are immediately created and spawned. Use this for lightweight and fast-running jobs, to avoid delays due to on-demand spawning of the jobs - An int, giving the exact number of total jobs that are spawned - A string, giving an expression as a function of n_jobs, as in '2*n_jobs' memory : Instance of joblib.Memory or string Used for internal caching. By default, no caching is done. If a string is given, it is the path to the caching directory. Attributes ---------- scores_ : array, shape = [n_features] Feature scores between 0 and 1. all_scores_ : array, shape = [n_features, n_reg_parameter] Feature scores between 0 and 1 for all values of the regularization \ parameter. The reference article suggests ``scores_`` is the max \ of ``all_scores_``. Examples -------- >>> from sklearn.linear_model import RandomizedLogisticRegression >>> randomized_logistic = RandomizedLogisticRegression() Notes ----- See examples/linear_model/plot_sparse_recovery.py for an example. References ---------- Stability selection Nicolai Meinshausen, Peter Buhlmann Journal of the Royal Statistical Society: Series B Volume 72, Issue 4, pages 417-473, September 2010 DOI: 10.1111/j.1467-9868.2010.00740.x See also -------- RandomizedLasso, Lasso, ElasticNet """ def __init__(self, C=1, scaling=.5, sample_fraction=.75, n_resampling=200, selection_threshold=.25, tol=1e-3, fit_intercept=True, verbose=False, normalize=True, random_state=None, n_jobs=1, pre_dispatch='3*n_jobs', memory=Memory(cachedir=None, verbose=0)): self.C = C self.scaling = scaling self.sample_fraction = sample_fraction self.n_resampling = n_resampling self.fit_intercept = fit_intercept self.verbose = verbose self.normalize = normalize self.tol = tol self.random_state = random_state self.n_jobs = n_jobs self.selection_threshold = selection_threshold self.pre_dispatch = pre_dispatch self.memory = memory def _make_estimator_and_params(self, X, y): params = dict(C=self.C, tol=self.tol, fit_intercept=self.fit_intercept) return _randomized_logistic, params def _center_data(self, X, y, fit_intercept, normalize=False): """Center the data in X but not in y""" X, _, Xmean, _, X_std = center_data(X, y, fit_intercept, normalize=normalize) return X, y, Xmean, y, X_std ############################################################################### # Stability paths def _lasso_stability_path(X, y, mask, weights, eps): "Inner loop of lasso_stability_path" X = X * weights[np.newaxis, :] X = X[safe_mask(X, mask), :] y = y[mask] alpha_max = np.max(np.abs(np.dot(X.T, y))) / X.shape[0] alpha_min = eps * alpha_max # set for early stopping in path with warnings.catch_warnings(): warnings.simplefilter('ignore', ConvergenceWarning) alphas, _, coefs = lars_path(X, y, method='lasso', verbose=False, alpha_min=alpha_min) # Scale alpha by alpha_max alphas /= alphas[0] # Sort alphas in assending order alphas = alphas[::-1] coefs = coefs[:, ::-1] # Get rid of the alphas that are too small mask = alphas >= eps # We also want to keep the first one: it should be close to the OLS # solution mask[0] = True alphas = alphas[mask] coefs = coefs[:, mask] return alphas, coefs def lasso_stability_path(X, y, scaling=0.5, random_state=None, n_resampling=200, n_grid=100, sample_fraction=0.75, eps=4 * np.finfo(np.float).eps, n_jobs=1, verbose=False): """Stabiliy path based on randomized Lasso estimates Parameters ---------- X : array-like, shape = [n_samples, n_features] training data. y : array-like, shape = [n_samples] target values. scaling : float, optional, default=0.5 The alpha parameter in the stability selection article used to randomly scale the features. Should be between 0 and 1. random_state : integer or numpy.random.RandomState, optional The generator used to randomize the design. n_resampling : int, optional, default=200 Number of randomized models. n_grid : int, optional, default=100 Number of grid points. The path is linearly reinterpolated on a grid between 0 and 1 before computing the scores. sample_fraction : float, optional, default=0.75 The fraction of samples to be used in each randomized design. Should be between 0 and 1. If 1, all samples are used. eps : float, optional Smallest value of alpha / alpha_max considered n_jobs : integer, optional Number of CPUs to use during the resampling. If '-1', use all the CPUs verbose : boolean or integer, optional Sets the verbosity amount Returns ------- alphas_grid : array, shape ~ [n_grid] The grid points between 0 and 1: alpha/alpha_max scores_path : array, shape = [n_features, n_grid] The scores for each feature along the path. Notes ----- See examples/linear_model/plot_sparse_recovery.py for an example. """ rng = check_random_state(random_state) if not (0 < scaling < 1): raise ValueError("Parameter 'scaling' should be between 0 and 1." " Got %r instead." % scaling) n_samples, n_features = X.shape paths = Parallel(n_jobs=n_jobs, verbose=verbose)( delayed(_lasso_stability_path)( X, y, mask=rng.rand(n_samples) < sample_fraction, weights=1. - scaling * rng.random_integers(0, 1, size=(n_features,)), eps=eps) for k in range(n_resampling)) all_alphas = sorted(list(set(itertools.chain(*[p[0] for p in paths])))) # Take approximately n_grid values stride = int(max(1, int(len(all_alphas) / float(n_grid)))) all_alphas = all_alphas[::stride] if not all_alphas[-1] == 1: all_alphas.append(1.) all_alphas = np.array(all_alphas) scores_path = np.zeros((n_features, len(all_alphas))) for alphas, coefs in paths: if alphas[0] != 0: alphas = np.r_[0, alphas] coefs = np.c_[np.ones((n_features, 1)), coefs] if alphas[-1] != all_alphas[-1]: alphas = np.r_[alphas, all_alphas[-1]] coefs = np.c_[coefs, np.zeros((n_features, 1))] scores_path += (interp1d(alphas, coefs, kind='nearest', bounds_error=False, fill_value=0, axis=-1)(all_alphas) != 0) scores_path /= n_resampling return all_alphas, scores_path
bsd-3-clause
onitake/ansible
lib/ansible/modules/network/cnos/cnos_reload.py
17
3423
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) __metaclass__ = type # # Copyright (C) 2017 Lenovo, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # # Module to reload Lenovo Switches # Lenovo Networking # ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: cnos_reload author: "Anil Kumar Muraleedharan (@amuraleedhar)" short_description: Perform switch restart on devices running Lenovo CNOS description: - This module allows you to restart the switch using the current startup configuration. The module is usually invoked after the running configuration has been saved over the startup configuration. This module uses SSH to manage network device configuration. The results of the operation can be viewed in results directory. version_added: "2.3" extends_documentation_fragment: cnos options: {} ''' EXAMPLES = ''' Tasks : The following are examples of using the module cnos_reload. These are written in the main.yml file of the tasks directory. --- - name: Test Reload cnos_reload: deviceType: "{{ hostvars[inventory_hostname]['deviceType'] }}" outputfile: "./results/test_reload_{{ inventory_hostname }}_output.txt" ''' RETURN = ''' msg: description: Success or failure message returned: always type: string sample: "Device is Reloading. Please wait..." ''' import sys import time import socket import array import json import time import re try: from ansible.module_utils.network.cnos import cnos HAS_LIB = True except: HAS_LIB = False from ansible.module_utils.basic import AnsibleModule from collections import defaultdict def main(): module = AnsibleModule( argument_spec=dict( outputfile=dict(required=True), host=dict(required=False), username=dict(required=False), password=dict(required=False, no_log=True), enablePassword=dict(required=False, no_log=True), deviceType=dict(required=True),), supports_check_mode=False) command = 'reload' outputfile = module.params['outputfile'] output = '' cmd = [{'command': command, 'prompt': 'reboot system? (y/n): ', 'answer': 'y'}] output = output + str(cnos.run_cnos_commands(module, cmd)) # Save it into the file file = open(outputfile, "a") file.write(output) file.close() errorMsg = cnos.checkOutputForError(output) if(errorMsg in "Device Response Timed out"): module.exit_json(changed=True, msg="Device is Reloading. Please wait...") else: module.fail_json(msg=errorMsg) if __name__ == '__main__': main()
gpl-3.0
carolFrohlich/nipype
nipype/interfaces/mrtrix3/preprocess.py
2
7501
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # -*- coding: utf-8 -*- """ Change directory to provide relative paths for doctests >>> import os >>> filepath = os.path.dirname(os.path.realpath(__file__ )) >>> datadir = os.path.realpath(os.path.join(filepath, ... '../../testing/data')) >>> os.chdir(datadir) """ from __future__ import print_function, division, unicode_literals, absolute_import import os.path as op from ..traits_extension import isdefined from ..base import (CommandLineInputSpec, CommandLine, traits, TraitedSpec, File) from .base import MRTrix3BaseInputSpec, MRTrix3Base class ResponseSDInputSpec(MRTrix3BaseInputSpec): in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, desc='input diffusion weighted images') out_file = File( 'response.txt', argstr='%s', mandatory=True, position=-1, usedefault=True, desc='output file containing SH coefficients') # DW Shell selection options shell = traits.List(traits.Float, sep=',', argstr='-shell %s', desc='specify one or more dw gradient shells') in_mask = File(exists=True, argstr='-mask %s', desc='provide initial mask image') max_sh = traits.Int(8, argstr='-lmax %d', desc='maximum harmonic degree of response function') out_sf = File('sf_mask.nii.gz', argstr='-sf %s', desc='write a mask containing single-fibre voxels') test_all = traits.Bool(False, argstr='-test_all', desc='re-test all voxels at every iteration') # Optimization iterations = traits.Int(0, argstr='-max_iters %d', desc='maximum number of iterations per pass') max_change = traits.Float( argstr='-max_change %f', desc=('maximum percentile change in any response function coefficient;' ' if no individual coefficient changes by more than this ' 'fraction, the algorithm is terminated.')) # Thresholds vol_ratio = traits.Float( .15, argstr='-volume_ratio %f', desc=('maximal volume ratio between the sum of all other positive' ' lobes in the voxel and the largest FOD lobe')) disp_mult = traits.Float( 1., argstr='-dispersion_multiplier %f', desc=('dispersion of FOD lobe must not exceed some threshold as ' 'determined by this multiplier and the FOD dispersion in other ' 'single-fibre voxels. The threshold is: (mean + (multiplier * ' '(mean - min))); default = 1.0. Criterion is only applied in ' 'second pass of RF estimation.')) int_mult = traits.Float( 2., argstr='-integral_multiplier %f', desc=('integral of FOD lobe must not be outside some range as ' 'determined by this multiplier and FOD lobe integral in other' ' single-fibre voxels. The range is: (mean +- (multiplier * ' 'stdev)); default = 2.0. Criterion is only applied in second ' 'pass of RF estimation.')) class ResponseSDOutputSpec(TraitedSpec): out_file = File(exists=True, desc='the output response file') out_sf = File(desc=('mask containing single-fibre voxels')) class ResponseSD(MRTrix3Base): """ Generate an appropriate response function from the image data for spherical deconvolution. .. [1] Tax, C. M.; Jeurissen, B.; Vos, S. B.; Viergever, M. A. and Leemans, A., Recursive calibration of the fiber response function for spherical deconvolution of diffusion MRI data. NeuroImage, 2014, 86, 67-80 Example ------- >>> import nipype.interfaces.mrtrix3 as mrt >>> resp = mrt.ResponseSD() >>> resp.inputs.in_file = 'dwi.mif' >>> resp.inputs.in_mask = 'mask.nii.gz' >>> resp.inputs.grad_fsl = ('bvecs', 'bvals') >>> resp.cmdline # doctest: +ELLIPSIS +IGNORE_UNICODE 'dwi2response -fslgrad bvecs bvals -mask mask.nii.gz dwi.mif response.txt' >>> resp.run() # doctest: +SKIP """ _cmd = 'dwi2response' input_spec = ResponseSDInputSpec output_spec = ResponseSDOutputSpec def _list_outputs(self): outputs = self.output_spec().get() outputs['out_file'] = op.abspath(self.inputs.out_file) if isdefined(self.inputs.out_sf): outputs['out_sf'] = op.abspath(self.inputs.out_sf) return outputs class ACTPrepareFSLInputSpec(CommandLineInputSpec): in_file = File(exists=True, argstr='%s', mandatory=True, position=-2, desc='input anatomical image') out_file = File( 'act_5tt.mif', argstr='%s', mandatory=True, position=-1, usedefault=True, desc='output file after processing') class ACTPrepareFSLOutputSpec(TraitedSpec): out_file = File(exists=True, desc='the output response file') class ACTPrepareFSL(CommandLine): """ Generate anatomical information necessary for Anatomically Constrained Tractography (ACT). Example ------- >>> import nipype.interfaces.mrtrix3 as mrt >>> prep = mrt.ACTPrepareFSL() >>> prep.inputs.in_file = 'T1.nii.gz' >>> prep.cmdline # doctest: +ELLIPSIS +IGNORE_UNICODE 'act_anat_prepare_fsl T1.nii.gz act_5tt.mif' >>> prep.run() # doctest: +SKIP """ _cmd = 'act_anat_prepare_fsl' input_spec = ACTPrepareFSLInputSpec output_spec = ACTPrepareFSLOutputSpec def _list_outputs(self): outputs = self.output_spec().get() outputs['out_file'] = op.abspath(self.inputs.out_file) return outputs class ReplaceFSwithFIRSTInputSpec(CommandLineInputSpec): in_file = File(exists=True, argstr='%s', mandatory=True, position=-4, desc='input anatomical image') in_t1w = File(exists=True, argstr='%s', mandatory=True, position=-3, desc='input T1 image') in_config = File(exists=True, argstr='%s', position=-2, desc='connectome configuration file') out_file = File( 'aparc+first.mif', argstr='%s', mandatory=True, position=-1, usedefault=True, desc='output file after processing') class ReplaceFSwithFIRSTOutputSpec(TraitedSpec): out_file = File(exists=True, desc='the output response file') class ReplaceFSwithFIRST(CommandLine): """ Replace deep gray matter structures segmented with FSL FIRST in a FreeSurfer parcellation. Example ------- >>> import nipype.interfaces.mrtrix3 as mrt >>> prep = mrt.ReplaceFSwithFIRST() >>> prep.inputs.in_file = 'aparc+aseg.nii' >>> prep.inputs.in_t1w = 'T1.nii.gz' >>> prep.inputs.in_config = 'mrtrix3_labelconfig.txt' >>> prep.cmdline # doctest: +ELLIPSIS +IGNORE_UNICODE 'fs_parc_replace_sgm_first aparc+aseg.nii T1.nii.gz \ mrtrix3_labelconfig.txt aparc+first.mif' >>> prep.run() # doctest: +SKIP """ _cmd = 'fs_parc_replace_sgm_first' input_spec = ReplaceFSwithFIRSTInputSpec output_spec = ReplaceFSwithFIRSTOutputSpec def _list_outputs(self): outputs = self.output_spec().get() outputs['out_file'] = op.abspath(self.inputs.out_file) return outputs
bsd-3-clause
sam-m888/gramps
gramps/plugins/drawreport/ancestortree.py
1
42337
# Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2007 Donald N. Allingham # Copyright (C) 2007-2012 Brian G. Matherly # Copyright (C) 2010 Jakim Friant # Copyright (C) 2014 Paul Franklin # Copyright (C) 2010-2015 Craig J. Anderson # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # """Reports/Graphical Reports/Ancestor Tree""" #------------------------------------------------------------------------ # # Python modules # #------------------------------------------------------------------------ #------------------------------------------------------------------------ # # Gramps modules # #------------------------------------------------------------------------ from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.sgettext from gramps.gen.errors import ReportError from gramps.gen.plug.menu import (TextOption, NumberOption, BooleanOption, EnumeratedListOption, StringOption, PersonOption) from gramps.gen.plug.report import Report, MenuReportOptions, stdoptions from gramps.gen.plug.docgen import (FontStyle, ParagraphStyle, GraphicsStyle, FONT_SANS_SERIF, PARA_ALIGN_CENTER) from gramps.plugins.lib.libtreebase import * from gramps.plugins.lib.librecurse import AscendPerson from gramps.gen.proxy import CacheProxyDb from gramps.gen.display.name import displayer as _nd PT2CM = utils.pt2cm #cm2pt = utils.cm2pt #------------------------------------------------------------------------ # # Constants # #------------------------------------------------------------------------ _BORN = _("birth abbreviation|b."), _DIED = _("death abbreviation|d."), _MARR = _("marriage abbreviation|m."), LVL_GEN, LVL_INDX, LVL_Y = range(3) #------------------------------------------------------------------------ # # Box classes # #------------------------------------------------------------------------ class PersonBox(BoxBase): """ Calculates information about the box that will print on a page """ def __init__(self, level): BoxBase.__init__(self) self.boxstr = "AC2-box" #self.level = (level[0]-1, level[1]) self.level = level def __lt__(self, other): return self.level[LVL_Y] < other.level[LVL_Y] class FamilyBox(BoxBase): """ Calculates information about the box that will print on a page """ def __init__(self, level): BoxBase.__init__(self) self.boxstr = "AC2-fam-box" #self.level = (level[0]-1, level[1]) self.level = level def __lt__(self, other): return self.level[LVL_Y] < other.level[LVL_Y] #------------------------------------------------------------------------ # # Titles Class(es) # #------------------------------------------------------------------------ class TitleN(TitleNoDisplay): """No Title class for the report """ def __init__(self, doc, locale): TitleNoDisplay.__init__(self, doc, "AC2-Title-box") self._ = locale.translation.sgettext def calc_title(self, center): """Calculate the title of the report""" #we want no text, but need a text for the TOC in a book! self.mark_text = self._("Ancestor Graph") self.text = '' class TitleA(TitleBox): """Title class for the report """ def __init__(self, doc, locale, name_displayer): self._nd = name_displayer TitleBox.__init__(self, doc, "AC2-Title-box") self._ = locale.translation.sgettext def calc_title(self, center): """Calculate the title of the report""" name = "" if center is not None: name = self._nd.display(center) # feature request 2356: avoid genitive form self.text = self._("Ancestor Graph for %s") % name self.set_box_height_width() #------------------------------------------------------------------------ # # CalcItems (helper class to calculate text) # make_ancestor_tree (main recursive functions) # #------------------------------------------------------------------------ class CalcItems: """ A helper class to calculate the default box text and text for each person / marriage """ def __init__(self, dbase): _gui = GUIConnect() self._gui = _gui #calculate the printed lines for each box #str = "" #if self.get_val('miss_val'): # str = "_____" display_repl = _gui.get_val("replace_list") self.__calc_l = CalcLines(dbase, display_repl, _gui.locale, _gui.n_d) self.__blank_father = None self.__blank_mother = None self.__blank_father = \ self.__calc_l.calc_lines(None, None, _gui.get_val("father_disp")) self.__blank_mother = \ self.__calc_l.calc_lines(None, None, _gui.get_val("mother_disp")) self.center_use = _gui.get_val("center_uses") self.disp_father = _gui.get_val("father_disp") self.disp_mother = _gui.get_val("mother_disp") self.disp_marr = [_gui.get_val("marr_disp")] self.__blank_marriage = \ self.__calc_l.calc_lines(None, None, self.disp_marr) def calc_person(self, index, indi_handle, fams_handle): working_lines = "" if index[1] % 2 == 0 or (index[1] == 1 and self.center_use == 0): if indi_handle == fams_handle is None: working_lines = self.__calc_l.calc_lines( None, None, self._gui.get_val("father_disp")) else: working_lines = self.disp_father else: if indi_handle == fams_handle is None: working_lines = self.__calc_l.calc_lines( None, None, self._gui.get_val("mother_disp")) else: working_lines = self.disp_mother if indi_handle == fams_handle is None: return working_lines else: return self.__calc_l.calc_lines(indi_handle, fams_handle, working_lines) def calc_marriage(self, indi_handle, fams_handle): if indi_handle == fams_handle is None: return self.__blank_marriage else: return self.__calc_l.calc_lines(indi_handle, fams_handle, self.disp_marr) class MakeAncestorTree(AscendPerson): """ The main procedure to use recursion to make the tree based off of a person. order of people inserted into Persons is important. makes sure that order is done correctly. """ def __init__(self, dbase, canvas): _gui = GUIConnect() AscendPerson.__init__(self, dbase, _gui.maxgen(), _gui.fill_out()) self.database = dbase self.canvas = canvas self.inlc_marr = _gui.inc_marr() self.inc_sib = _gui.inc_sib() self.compress_tree = _gui.compress_tree() self.center_family = None self.lines = [None] * (_gui.maxgen() + 1) self.max_generation = 0 self.calc_items = CalcItems(self.database) def add_person(self, index, indi_handle, fams_handle): """ Makes a person box and add that person into the Canvas. """ #print str(index) + " add_person " + str(indi_handle) myself = PersonBox((index[0] - 1,) + index[1:]) if index[LVL_GEN] == 1: # Center Person self.center_family = fams_handle if index[LVL_GEN] > self.max_generation: self.max_generation = index[LVL_GEN] myself.text = self.calc_items.calc_person(index, indi_handle, fams_handle) # myself.text[0] = myself.text[0] + ' ' + repr(index) # for debugging if indi_handle is not None: # None is legal for an empty box myself.add_mark(self.database, self.database.get_person_from_handle(indi_handle)) self.canvas.add_box(myself) #make the lines indx = index[LVL_GEN] self.lines[indx] = myself if indx > 1: if self.lines[indx - 1].line_to is None: line = LineBase(self.lines[indx - 1]) self.lines[indx - 1].line_to = line self.canvas.add_line(line) else: line = self.lines[indx - 1].line_to line.add_to(myself) return myself def add_person_again(self, index, indi_handle, fams_handle): self.add_person(index, indi_handle, fams_handle) def add_marriage(self, index, indi_handle, fams_handle): """ Makes a marriage box and add that person into the Canvas. """ if not self.inlc_marr: return myself = FamilyBox((index[0] - 1,) + index[1:]) #calculate the text. myself.text = self.calc_items.calc_marriage(indi_handle, fams_handle) self.canvas.add_box(myself) def y_index(self, x_level, index): """ Calculate the column or generation that this person is in. x_level -> 0 to max_gen-1 index -> 1 to (self.max_generation**2)-1 """ #Calculate which row in the column of people. tmp_y = index - (2**x_level) #Calculate which row in the table (yes table) of people. delta = (2**self.max_generation) // (2**(x_level)) return int((delta / 2) + (tmp_y * delta)) - 1 def do_y_indx(self): ''' Make the y_index for all boxes first off of a forumula, then remove blank areas around the edges, then compress the tree if desired ''' min_y = self.y_index(self.canvas.boxes[0].level[LVL_GEN], self.canvas.boxes[0].level[LVL_INDX]) for box in self.canvas.boxes: if "fam" in box.boxstr: box.level = box.level + \ (self.y_index(box.level[LVL_GEN] - 1, int(box.level[LVL_INDX] / 2)),) else: box.level = box.level + \ (self.y_index(box.level[LVL_GEN], box.level[LVL_INDX]),) min_y = min(min_y, box.level[LVL_Y]) #print (str(box.level)) #if a last father (of fathers) does not have a father/parents #Then there could be a gap. Remove this gap if min_y > 0: for box in self.canvas.boxes: box.level = box.level[:LVL_Y] + (box.level[LVL_Y] - min_y,) #Now that we have y_index, lets see if we need to squish the tree self.canvas.boxes.sort() # Sort them on the y_index if not self.compress_tree: return #boxes are already in top down [LVL_Y] form so lets #set the box in the correct y level depending on compress_tree y_level = 0 current_y = self.canvas.boxes[0].level[LVL_Y] for box in self.canvas.boxes: y_index = box.level[LVL_Y] if y_index > current_y: current_y = y_index y_level += 1 box.level = box.level[:LVL_Y] + (y_level,) def do_sibs(self): if not self.inc_sib or self.center_family is None: return family = self.database.get_family_from_handle(self.center_family) mykids = [kid.ref for kid in family.get_child_ref_list()] if len(mykids) == 1: # No other siblings. Don't do anything. return # The first person is the center person had he/she has our information center = self.canvas.boxes.pop(self.canvas.boxes.index(self.lines[1])) line = center.line_to level = center.level[LVL_Y] move = level - (len(mykids) // 2) + ((len(mykids) + 1) % 2) if move < 0: # more kids than parents. ran off the page. Move them all down for box in self.canvas.boxes: box.level = (box.level[0], box.level[1], box.level[2] - move) move = 0 line.start = [] rrr = -1 # if len(mykids)%2 == 1 else 0 for kid in mykids: rrr += 1 mee = self.add_person((1, 1, move + rrr), kid, self.center_family) line.add_from(mee) #mee.level = (0, 1, level - (len(mykids)//2)+rrr) mee.line_to = line def start(self, person_id): """ go ahead and make it happen """ center = self.database.get_person_from_gramps_id(person_id) if center is None: raise ReportError( _("Person %s is not in the Database") % person_id) center_h = center.get_handle() #Step 1. Get the people self.recurse(center_h) #Step 2. Calculate the y_index for everyone self.do_y_indx() #Step 3. Siblings of the center person self.do_sibs() #------------------------------------------------------------------------ # # Transform Classes # #------------------------------------------------------------------------ #------------------------------------------------------------------------ # Class lr_Transform #------------------------------------------------------------------------ class LRTransform: """ setup all of the boxes on the canvas in for a left/right report """ def __init__(self, canvas, max_generations): self.canvas = canvas self.rept_opts = canvas.report_opts self.y_offset = (self.rept_opts.littleoffset * 2 + self.canvas.title.height) def _place(self, box): """ put the box in it's correct spot """ #1. cm_x box.x_cm = self.rept_opts.littleoffset box.x_cm += (box.level[LVL_GEN] * (self.rept_opts.col_width + self.rept_opts.max_box_width)) #2. cm_y box.y_cm = self.rept_opts.max_box_height + self.rept_opts.box_pgap box.y_cm *= box.level[LVL_Y] box.y_cm += self.y_offset #if box.height < self.rept_opts.max_box_height: # box.y_cm += ((self.rept_opts.max_box_height - box.height) /2) def place(self): """ Step through boxes so they can be put in the right spot """ #prime the pump self.__last_y_level = self.canvas.boxes[0].level[LVL_Y] #go for box in self.canvas.boxes: self._place(box) #------------------------------------------------------------------------ # # class make_report # #------------------------------------------------------------------------ class MakeReport: def __init__(self, dbase, doc, canvas, font_normal): self.database = dbase self.doc = doc self.canvas = canvas self.font_normal = font_normal _gui = GUIConnect() self.inlc_marr = _gui.inc_marr() self.compress_tree = _gui.compress_tree() self.mother_ht = self.father_ht = 0 self.max_generations = 0 def get_height_width(self, box): """ obtain width information for each level (x) obtain height information for each item """ self.canvas.set_box_height_width(box) if box.width > self.canvas.report_opts.max_box_width: self.canvas.report_opts.max_box_width = box.width # + box.shadow if box.level[LVL_Y] > 0: if box.level[LVL_INDX] % 2 == 0 and box.height > self.father_ht: self.father_ht = box.height elif box.level[LVL_INDX] % 2 == 1 and box.height > self.mother_ht: self.mother_ht = box.height if box.level[LVL_GEN] > self.max_generations: self.max_generations = box.level[LVL_GEN] def get_generations(self): return self.max_generations def start(self): # __gui = GUIConnect() # 1. #set the sizes for each box and get the max_generations. self.father_ht = 0.0 self.mother_ht = 0.0 for box in self.canvas.boxes: self.get_height_width(box) if self.compress_tree and not self.inlc_marr: self.canvas.report_opts.max_box_height = \ min(self.father_ht, self.mother_ht) else: self.canvas.report_opts.max_box_height = \ max(self.father_ht, self.mother_ht) #At this point we know everything we need to make the report. #Size of each column of people - self.rept_opt.box_width #size of each column (or row) of lines - self.rept_opt.col_width #size of each row - self.rept_opt.box_height #go ahead and set it now. for box in self.canvas.boxes: box.width = self.canvas.report_opts.max_box_width # 2. #setup the transform class to move around the boxes on the canvas transform = LRTransform(self.canvas, self.max_generations) transform.place() class GUIConnect: """ This is a BORG object. There is ONLY one. This give some common routines that EVERYONE can use like get the value from a GUI variable """ __shared_state = {} def __init__(self): # We are BORG! self.__dict__ = self.__shared_state def set__opts(self, options, locale, name_displayer): """ Set only once as we are BORG. """ self.__opts = options self.locale = locale self.n_d = name_displayer def get_val(self, val): """ Get a GUI value. """ value = self.__opts.get_option_by_name(val) if value: return value.get_value() else: False def title_class(self, doc): """ Return a class that holds the proper title based off of the GUI options """ title_type = self.get_val('report_title') if title_type: return TitleA(doc, self.locale, self.n_d) else: return TitleN(doc, self.locale) def inc_marr(self): return self.get_val("inc_marr") def inc_sib(self): return self.get_val("inc_siblings") def maxgen(self): return self.get_val("maxgen") def fill_out(self): return self.get_val("fill_out") def compress_tree(self): return self.get_val("compress_tree") #------------------------------------------------------------------------ # # AncestorTree # #------------------------------------------------------------------------ class AncestorTree(Report): """ AncestorTree Report """ def __init__(self, database, options, user): """ Create AncestorTree object that produces the report. The arguments are: database - the Gramps database instance options - instance of the Options class for this report user - a gen.user.User() instance """ Report.__init__(self, database, options, user) self.options = options self._user = user self.set_locale(options.menu.get_option_by_name('trans').get_value()) stdoptions.run_date_format_option(self, options.menu) stdoptions.run_private_data_option(self, options.menu) stdoptions.run_living_people_option(self, options.menu, self._locale) self.database = CacheProxyDb(self.database) stdoptions.run_name_format_option(self, options.menu) self._nd = self._name_display def begin_report(self): """ This report needs the following parameters (class variables) that come in the options class. max_generations - Maximum number of generations to include. pagebbg - Whether to include page breaks between generations. dispf - Display format for the output box. scale_report - Whether to scale the report to fit the width or all. indblank - Whether to include blank pages. compress - Whether to compress chart. incl_private - Whether to include private data living_people - How to handle living people years_past_death - Consider as living this many years after death We will 1. a canvas in its full one-page size 2. a page that we wish to print on scale up/down either or both of the above as needed/desired. almost all of this should be moved into Canvas! """ database = self.database self.connect = GUIConnect() self.connect.set__opts(self.options.menu, self._locale, self._nd) #Set up the canvas that we will print on. style_sheet = self.doc.get_style_sheet() font_normal = style_sheet.get_paragraph_style("AC2-Normal").get_font() #The canvas that we will put our report on and print off of self.canvas = Canvas(self.doc, ReportOptions(self.doc, font_normal, 'AC2-line')) self.canvas.report_opts.box_shadow *= \ self.connect.get_val('shadowscale') self.canvas.report_opts.box_pgap *= self.connect.get_val('box_Yscale') self.canvas.report_opts.box_mgap *= self.connect.get_val('box_Yscale') with self._user.progress(_('Ancestor Tree'), _('Making the Tree...'), 4) as step: #make the tree onto the canvas # inlc_marr = self.connect.get_val("inc_marr") self.max_generations = self.connect.get_val('maxgen') tree = MakeAncestorTree(database, self.canvas) tree.start(self.connect.get_val('pid')) tree = None step() #Title title = self.connect.title_class(self.doc) center = self.database.get_person_from_gramps_id( self.connect.get_val('pid')) title.calc_title(center) self.canvas.add_title(title) #make the report as big as it wants to be. report = MakeReport(database, self.doc, self.canvas, font_normal) report.start() self.max_generations = report.get_generations() # already know report = None step() #Note? if self.connect.get_val("inc_note"): note_box = NoteBox(self.doc, "AC2-note-box", self.connect.get_val("note_place")) subst = SubstKeywords(self.database, self._locale, self._nd, None, None) note_box.text = subst.replace_and_clean( self.connect.get_val('note_disp')) self.canvas.add_note(note_box) #Now we have the report in its full size. #Do we want to scale the report? one_page = self.connect.get_val("resize_page") scale_report = self.connect.get_val("scale_tree") scale = self.canvas.scale_report(one_page, scale_report != 0, scale_report == 2) step() if scale != 1 or self.connect.get_val('shadowscale') != 1.0: self.scale_styles(scale) def write_report(self): one_page = self.connect.get_val("resize_page") #scale_report = self.connect.get_val("scale_tree") #inlc_marr = self.connect.get_val("inc_marr") inc_border = self.connect.get_val('inc_border') incblank = self.connect.get_val("inc_blank") prnnum = self.connect.get_val("inc_pagenum") ##################### #Setup page information colsperpage = self.doc.get_usable_width() colsperpage += self.canvas.report_opts.col_width colsperpage = int( colsperpage / (self.canvas.report_opts.max_box_width + self.canvas.report_opts.col_width)) colsperpage = colsperpage or 1 ##################### #Vars if prnnum: page_num_box = PageNumberBox(self.doc, 'AC2-box', self._locale) #TODO - Here ##################### #ok, everyone is now ready to print on the canvas. Paginate? self.canvas.paginate(colsperpage, one_page) ##################### #Yeah!!! #lets finally make some pages!!! ##################### pages = self.canvas.page_count(incblank) with self._user.progress(_('Ancestor Tree'), _('Printing the Tree...'), pages) as step: for page in self.canvas.page_iter_gen(incblank): self.doc.start_page() #do we need to print a border? if inc_border: page.draw_border('AC2-line') #Do we need to print the page number? if prnnum: page_num_box.display(page) #Print the individual people and lines page.display() step() self.doc.end_page() def scale_styles(self, scale): """ Scale the styles for this report. """ style_sheet = self.doc.get_style_sheet() graph_style = style_sheet.get_draw_style("AC2-box") graph_style.set_shadow(graph_style.get_shadow(), self.canvas.report_opts.box_shadow * scale) graph_style.set_line_width(graph_style.get_line_width() * scale) style_sheet.add_draw_style("AC2-box", graph_style) graph_style = style_sheet.get_draw_style("AC2-fam-box") graph_style.set_shadow(graph_style.get_shadow(), self.canvas.report_opts.box_shadow * scale) graph_style.set_line_width(graph_style.get_line_width() * scale) style_sheet.add_draw_style("AC2-fam-box", graph_style) graph_style = style_sheet.get_draw_style("AC2-note-box") #graph_style.set_shadow(graph_style.get_shadow(), # self.canvas.report_opts.box_shadow * scale) graph_style.set_line_width(graph_style.get_line_width() * scale) style_sheet.add_draw_style("AC2-note-box", graph_style) para_style = style_sheet.get_paragraph_style("AC2-Normal") font = para_style.get_font() font.set_size(font.get_size() * scale) para_style.set_font(font) style_sheet.add_paragraph_style("AC2-Normal", para_style) para_style = style_sheet.get_paragraph_style("AC2-Note") font = para_style.get_font() font.set_size(font.get_size() * scale) para_style.set_font(font) style_sheet.add_paragraph_style("AC2-Note", para_style) para_style = style_sheet.get_paragraph_style("AC2-Title") font = para_style.get_font() font.set_size(font.get_size() * scale) para_style.set_font(font) style_sheet.add_paragraph_style("AC2-Title", para_style) graph_style = GraphicsStyle() width = graph_style.get_line_width() width = width * scale graph_style.set_line_width(width) style_sheet.add_draw_style("AC2-line", graph_style) self.doc.set_style_sheet(style_sheet) #------------------------------------------------------------------------ # # AncestorTreeOptions # #------------------------------------------------------------------------ class AncestorTreeOptions(MenuReportOptions): """ Defines options and provides handling interface. """ def __init__(self, name, dbase): self.__db = dbase self.__pid = None self.box_Y_sf = None self.box_shadow_sf = None MenuReportOptions.__init__(self, name, dbase) def get_subject(self): """ Return a string that describes the subject of the report. """ gid = self.__pid.get_value() person = self.__db.get_person_from_gramps_id(gid) return _nd.display(person) def add_menu_options(self, menu): ################## category_name = _("Tree Options") self.__pid = PersonOption(_("Center Person")) self.__pid.set_help(_("The center person for the tree")) menu.add_option(category_name, "pid", self.__pid) siblings = BooleanOption( _('Include siblings of the center person'), False) siblings.set_help( _("Whether to only display the center person or all " "of his/her siblings too")) menu.add_option(category_name, "inc_siblings", siblings) self.max_gen = NumberOption(_("Generations"), 10, 1, 50) self.max_gen.set_help(_("The number of generations to include " "in the tree")) menu.add_option(category_name, "maxgen", self.max_gen) self.fillout = EnumeratedListOption(_("Display unknown\ngenerations"), 0) self.fillout.set_help(_("The number of generations of empty " "boxes that will be displayed")) menu.add_option(category_name, "fill_out", self.fillout) self.max_gen.connect('value-changed', self.__fillout_vals) self.__fillout_vals() compress = BooleanOption(_('Compress tree'), True) compress.set_help( _("Whether to remove any extra blank spaces set " "aside for people that are unknown")) menu.add_option(category_name, "compress_tree", compress) #better to 'Show siblings of\nthe center person #Spouse_disp = EnumeratedListOption(_("Show spouses of\nthe center " # "person"), 0) #Spouse_disp.add_item(0, _("No. Do not show Spouses")) #Spouse_disp.add_item(1, _("Yes, and use the Main Display Format")) #Spouse_disp.add_item(2, _("Yes, and use the Secondary " # "Display Format")) #Spouse_disp.set_help(_("Show spouses of the center person?")) #menu.add_option(category_name, "Spouse_disp", Spouse_disp) ################## category_name = _("Report Options") self.title = EnumeratedListOption(_("Report Title"), 0) self.title.add_item(0, _("Do not include a title")) self.title.add_item(1, _("Include Report Title")) self.title.set_help(_("Choose a title for the report")) menu.add_option(category_name, "report_title", self.title) border = BooleanOption(_('Include a border'), False) border.set_help(_("Whether to make a border around the report.")) menu.add_option(category_name, "inc_border", border) prnnum = BooleanOption(_('Include Page Numbers'), False) prnnum.set_help(_("Whether to print page numbers on each page.")) menu.add_option(category_name, "inc_pagenum", prnnum) self.scale = EnumeratedListOption(_("Scale tree to fit"), 0) self.scale.add_item(0, _("Do not scale tree")) self.scale.add_item(1, _("Scale tree to fit page width only")) self.scale.add_item(2, _("Scale tree to fit the size of the page")) self.scale.set_help( _("Whether to scale the tree to fit a specific paper size")) menu.add_option(category_name, "scale_tree", self.scale) self.scale.connect('value-changed', self.__check_blank) if "BKI" not in self.name.split(","): self.__onepage = BooleanOption( _("Resize Page to Fit Tree size\n" "\n" "Note: Overrides options in the 'Paper Option' tab" ), False) self.__onepage.set_help( _("Whether to resize the page to fit the size \n" "of the tree. Note: the page will have a \n" "non standard size.\n" "\n" "With this option selected, the following will happen:\n" "\n" "With the 'Do not scale tree' option the page\n" " is resized to the height/width of the tree\n" "\n" "With 'Scale tree to fit page width only' the height of\n" " the page is resized to the height of the tree\n" "\n" "With 'Scale tree to fit the size of the page' the page\n" " is resized to remove any gap in either height or width" )) menu.add_option(category_name, "resize_page", self.__onepage) self.__onepage.connect('value-changed', self.__check_blank) else: self.__onepage = None self.__blank = BooleanOption(_('Include Blank Pages'), True) self.__blank.set_help(_("Whether to include pages that are blank.")) menu.add_option(category_name, "inc_blank", self.__blank) self.__check_blank() ################## category_name = _("Report Options (2)") stdoptions.add_name_format_option(menu, category_name) stdoptions.add_living_people_option(menu, category_name) stdoptions.add_private_data_option(menu, category_name) locale_opt = stdoptions.add_localization_option(menu, category_name) stdoptions.add_date_format_option(menu, category_name, locale_opt) ################## category_name = _("Display") disp = TextOption(_("Father\nDisplay Format"), ["$n", "%s $b" % _BORN, "-{%s $d}" % _DIED]) disp.set_help(_("Display format for the fathers box.")) menu.add_option(category_name, "father_disp", disp) #Will add when libsubstkeyword supports it. #missing = EnumeratedListOption(_("Replace missing\nplaces\\dates \ # with"), 0) #missing.add_item(0, _("Does not display anything")) #missing.add_item(1, _("Displays '_____'")) #missing.set_help(_("What will print when information is not known")) #menu.add_option(category_name, "miss_val", missing) disp_mom = TextOption(_("Mother\nDisplay Format"), ["$n", "%s $b" % _BORN, "%s $m" % _MARR, "-{%s $d}" % _DIED]) disp_mom.set_help(_("Display format for the mothers box.")) menu.add_option(category_name, "mother_disp", disp_mom) center_disp = EnumeratedListOption(_("Center person uses\n" "which format"), 0) center_disp.add_item(0, _("Use Fathers Display format")) center_disp.add_item(1, _("Use Mothers display format")) center_disp.set_help(_("The display format for the center person")) menu.add_option(category_name, "center_uses", center_disp) self.incmarr = BooleanOption(_('Include Marriage box'), False) self.incmarr.set_help( _("Whether to include a separate marital box in the report")) menu.add_option(category_name, "inc_marr", self.incmarr) self.incmarr.connect('value-changed', self._incmarr_changed) self.marrdisp = StringOption(_("Marriage\nDisplay Format"), "%s $m" % _MARR) self.marrdisp.set_help(_("Display format for the marital box.")) menu.add_option(category_name, "marr_disp", self.marrdisp) self._incmarr_changed() ################## category_name = _("Advanced") repldisp = TextOption( _("Replace Display Format:\n'Replace this'/' with this'"), []) repldisp.set_help(_("i.e.\nUnited States of America/U.S.A")) menu.add_option(category_name, "replace_list", repldisp) # TODO this code is never used and so I conclude it is for future use # self.__include_images = BooleanOption( # _('Include thumbnail images of people'), False) # self.__include_images.set_help( # _("Whether to include thumbnails of people.")) # menu.add_option(category_name, "includeImages", # self.__include_images) self.usenote = BooleanOption(_('Include a note'), False) self.usenote.set_help(_("Whether to include a note on the report.")) menu.add_option(category_name, "inc_note", self.usenote) self.usenote.connect('value-changed', self._usenote_changed) self.notedisp = TextOption(_("Note"), []) self.notedisp.set_help(_("Add a note\n\n" "$T inserts today's date")) menu.add_option(category_name, "note_disp", self.notedisp) locales = NoteType(0, 1) self.notelocal = EnumeratedListOption(_("Note Location"), 0) for num, text in locales.note_locals(): self.notelocal.add_item(num, text) self.notelocal.set_help(_("Where to place the note.")) menu.add_option(category_name, "note_place", self.notelocal) self._usenote_changed() self.box_Y_sf = NumberOption(_("inter-box scale factor"), 1.00, 0.10, 2.00, 0.01) self.box_Y_sf.set_help( _("Make the inter-box spacing bigger or smaller")) menu.add_option(category_name, "box_Yscale", self.box_Y_sf) self.box_shadow_sf = NumberOption(_("box shadow scale factor"), 1.00, 0.00, 2.00, 0.01) # down to 0 self.box_shadow_sf.set_help(_("Make the box shadow bigger or smaller")) menu.add_option(category_name, "shadowscale", self.box_shadow_sf) def _incmarr_changed(self): """ If Marriage box is not enabled, disable Marriage Display Format box """ value = self.incmarr.get_value() self.marrdisp.set_available(value) def _usenote_changed(self): """ If Note box is not enabled, disable Note Location box """ value = self.usenote.get_value() self.notelocal.set_available(value) def __check_blank(self): if self.__onepage: value = not self.__onepage.get_value() else: value = True off = value and (self.scale.get_value() != 2) self.__blank.set_available(off) def __fillout_vals(self): max_gen = self.max_gen.get_value() old_val = self.fillout.get_value() item_list = [] item_list.append([0, _("No generations of empty boxes " "for unknown ancestors")]) if max_gen > 1: item_list.append([1, _("One Generation of empty boxes " "for unknown ancestors")]) item_list.extend( [itr, str(itr) + _(" Generations of empty boxes for unknown ancestors")] for itr in range(2, max_gen)) self.fillout.set_items(item_list) if old_val + 2 > len(item_list): self.fillout.set_value(len(item_list) - 2) def make_default_style(self, default_style): """Make the default output style for the Ancestor Tree.""" # Paragraph Styles: font = FontStyle() font.set_size(9) font.set_type_face(FONT_SANS_SERIF) para_style = ParagraphStyle() para_style.set_font(font) para_style.set_description( _('The basic style used for the text display.')) default_style.add_paragraph_style("AC2-Normal", para_style) box_shadow = PT2CM(font.get_size()) * .6 font = FontStyle() font.set_size(9) font.set_type_face(FONT_SANS_SERIF) para_style = ParagraphStyle() para_style.set_font(font) para_style.set_description( _('The basic style used for the note display.')) default_style.add_paragraph_style("AC2-Note", para_style) font = FontStyle() font.set_size(16) font.set_type_face(FONT_SANS_SERIF) para_style = ParagraphStyle() para_style.set_font(font) para_style.set_alignment(PARA_ALIGN_CENTER) para_style.set_description(_('The style used for the title.')) default_style.add_paragraph_style("AC2-Title", para_style) # Draw styles graph_style = GraphicsStyle() graph_style.set_paragraph_style("AC2-Normal") graph_style.set_shadow(1, box_shadow) # shadow set by text size graph_style.set_fill_color((255, 255, 255)) default_style.add_draw_style("AC2-box", graph_style) graph_style = GraphicsStyle() graph_style.set_paragraph_style("AC2-Normal") #graph_style.set_shadow(0, PT2CM(9)) # shadow set by text size graph_style.set_fill_color((255, 255, 255)) default_style.add_draw_style("AC2-fam-box", graph_style) graph_style = GraphicsStyle() graph_style.set_paragraph_style("AC2-Note") graph_style.set_fill_color((255, 255, 255)) default_style.add_draw_style("AC2-note-box", graph_style) # TODO this seems meaningless, as only the text is displayed graph_style = GraphicsStyle() graph_style.set_paragraph_style("AC2-Title") graph_style.set_color((0, 0, 0)) graph_style.set_fill_color((255, 255, 255)) graph_style.set_line_width(0) graph_style.set_description(_("Cannot edit this reference")) default_style.add_draw_style("AC2-Title-box", graph_style) graph_style = GraphicsStyle() default_style.add_draw_style("AC2-line", graph_style) #===================================== #But even if you should suffer for what is right, you are blessed. #"Do not fear what they fear ; do not be frightened." #Take Courage #1 Peter 3:14
gpl-2.0
Moriadry/tensorflow
tensorflow/python/ops/control_flow_ops.py
2
124140
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Control Flow Operations. See the @{$python/control_flow_ops} guide. @@identity @@tuple @@group @@no_op @@count_up_to @@cond @@case @@while_loop @@logical_and @@logical_not @@logical_or @@logical_xor @@equal @@not_equal @@less @@less_equal @@greater @@greater_equal @@where @@is_finite @@is_inf @@is_nan @@verify_tensor_all_finite @@check_numerics @@add_check_numerics_ops @@Assert @@Print """ # pylint: disable=g-bad-name from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import six from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.core.protobuf import control_flow_pb2 from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import sparse_tensor from tensorflow.python.framework import tensor_shape from tensorflow.python.ops import array_ops from tensorflow.python.ops import gen_array_ops from tensorflow.python.ops import gen_control_flow_ops from tensorflow.python.ops import gen_data_flow_ops from tensorflow.python.ops import gen_logging_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import tensor_array_ops # go/tf-wildcard-import # pylint: disable=wildcard-import,undefined-variable from tensorflow.python.ops.gen_control_flow_ops import * # pylint: enable=wildcard-import from tensorflow.python.platform import tf_logging as logging from tensorflow.python.util import deprecation from tensorflow.python.util import nest from tensorflow.python.util import tf_should_use # We override the 'tuple' for a control flow op, so we keep python's # existing 'tuple' for later use in this module. _basetuple = tuple # pylint: disable=protected-access # Assert and Print are special symbols in python, so we must # use an upper-case version of them. @tf_should_use.should_use_result def Assert(condition, data, summarize=None, name=None): """Asserts that the given condition is true. If `condition` evaluates to false, print the list of tensors in `data`. `summarize` determines how many entries of the tensors to print. NOTE: To ensure that Assert executes, one usually attaches a dependency: ```python # Ensure maximum element of x is smaller or equal to 1 assert_op = tf.Assert(tf.less_equal(tf.reduce_max(x), 1.), [x]) with tf.control_dependencies([assert_op]): ... code using x ... ``` Args: condition: The condition to evaluate. data: The tensors to print out when condition is false. summarize: Print this many entries of each tensor. name: A name for this operation (optional). Returns: assert_op: An `Operation` that, when executed, raises a `tf.errors.InvalidArgumentError` if `condition` is not true. """ with ops.name_scope(name, "Assert", [condition, data]) as name: xs = ops.convert_n_to_tensor(data) if all([x.dtype in {dtypes.string, dtypes.int32} for x in xs]): # As a simple heuristic, we assume that string and int32 are # on host to avoid the need to use cond. If it is not case, # we will pay the price copying the tensor to host memory. return gen_logging_ops._assert( condition, data, summarize, name="Assert") else: condition = ops.convert_to_tensor(condition, name="Condition") def true_assert(): return gen_logging_ops._assert( condition, data, summarize, name="Assert") guarded_assert = cond( condition, no_op, true_assert, name="AssertGuard") return guarded_assert.op def _Identity(data, name=None): """Return a tensor with the same shape and contents as the input tensor. Args: data: A Tensor. name: A name for this operation (optional). Returns: A Tensor with the same type and value as the input Tensor. """ data = ops.internal_convert_to_tensor_or_indexed_slices(data, as_ref=True) if isinstance(data, ops.Tensor): if data.dtype._is_ref_dtype: # pylint: disable=protected-access return gen_array_ops._ref_identity(data, name=name) else: return array_ops.identity(data, name=name) else: if not isinstance(data, (ops.IndexedSlices, sparse_tensor.SparseTensor)): raise TypeError("Type %s not supported" % type(data)) values = _Identity(data.values, name=name) indices = array_ops.identity(data.indices, name="indices") if isinstance(data, ops.IndexedSlices): dense_shape = data.dense_shape if dense_shape is not None: dense_shape = array_ops.identity(dense_shape, name="dense_shape") return ops.IndexedSlices(values, indices, dense_shape) else: dense_shape = array_ops.identity(data.dense_shape, name="dense_shape") return sparse_tensor.SparseTensor(indices, values, dense_shape) def _NextIteration(data, name=None): data = ops.internal_convert_to_tensor_or_indexed_slices(data, as_ref=True) if isinstance(data, ops.Tensor): if data.dtype._is_ref_dtype: # pylint: disable=protected-access return ref_next_iteration(data, name=name) else: return next_iteration(data, name=name) else: if not isinstance(data, (ops.IndexedSlices, sparse_tensor.SparseTensor)): raise TypeError("Type %s not supported" % type(data)) values = _NextIteration(data.values, name=name) indices = next_iteration(data.indices, name="indices") if isinstance(data, ops.IndexedSlices): dense_shape = data.dense_shape if dense_shape is not None: dense_shape = next_iteration(dense_shape, name="dense_shape") return ops.IndexedSlices(values, indices, dense_shape) else: dense_shape = next_iteration(data.dense_shape, name="dense_shape") return sparse_tensor.SparseTensor(indices, values, dense_shape) def _Enter(data, frame_name, is_constant=False, parallel_iterations=10, use_ref=True, use_input_shape=True, name=None): """Creates or finds a child frame, and makes `data` available to it. The unique `frame_name` is used by the `Executor` to identify frames. If `is_constant` is true, `data` is a constant in the child frame; otherwise it may be changed in the child frame. At most `parallel_iterations` iterations are run in parallel in the child frame. Args: data: The tensor to be made available to the child frame. frame_name: The name of the child frame. is_constant: If true, the output is constant within the child frame. parallel_iterations: The number of iterations allowed to run in parallel. use_ref: If true, use ref_enter if data is of ref type. name: A name for this operation (optional). Returns: The same tensor as `data`. """ data = ops.internal_convert_to_tensor_or_indexed_slices(data, as_ref=True) if isinstance(data, ops.Tensor): if data.dtype._is_ref_dtype and use_ref: # pylint: disable=protected-access result = ref_enter(data, frame_name, is_constant, parallel_iterations, name=name) else: result = enter(data, frame_name, is_constant, parallel_iterations, name=name) if use_input_shape: result.set_shape(data.get_shape()) return result else: if not isinstance(data, (ops.IndexedSlices, sparse_tensor.SparseTensor)): raise TypeError("Type %s not supported" % type(data)) values = _Enter(data.values, frame_name, is_constant, parallel_iterations=parallel_iterations, use_input_shape=use_input_shape, name=name) indices = enter(data.indices, frame_name, is_constant, parallel_iterations, name="indices") if use_input_shape: indices.set_shape(data.indices.get_shape()) if isinstance(data, ops.IndexedSlices): dense_shape = data.dense_shape if dense_shape is not None: dense_shape = enter(dense_shape, frame_name, is_constant, parallel_iterations, name="dense_shape") if use_input_shape: dense_shape.set_shape(data.dense_shape.get_shape()) return ops.IndexedSlices(values, indices, dense_shape) else: dense_shape = enter(data.dense_shape, frame_name, is_constant, parallel_iterations, name="dense_shape") if use_input_shape: dense_shape.set_shape(data.dense_shape.get_shape()) return sparse_tensor.SparseTensor(indices, values, dense_shape) def exit(data, name=None): """Exits the current frame to its parent frame. Exit makes its input `data` available to the parent frame. Args: data: The tensor to be made available to the parent frame. name: A name for this operation (optional). Returns: The same tensor as `data`. """ data = ops.internal_convert_to_tensor_or_indexed_slices(data, as_ref=True) if isinstance(data, ops.Tensor): if data.dtype._is_ref_dtype: # pylint: disable=protected-access return gen_control_flow_ops._ref_exit(data, name) else: return gen_control_flow_ops._exit(data, name) else: if not isinstance(data, (ops.IndexedSlices, sparse_tensor.SparseTensor)): raise TypeError("Type %s not supported" % type(data)) values = exit(data.values, name=name) indices = gen_control_flow_ops._exit(data.indices, name="indices") if isinstance(data, ops.IndexedSlices): dense_shape = data.dense_shape if dense_shape is not None: dense_shape = gen_control_flow_ops._exit(dense_shape, name) return ops.IndexedSlices(values, indices, dense_shape) else: dense_shape = gen_control_flow_ops._exit(data.dense_shape, name) return sparse_tensor.SparseTensor(indices, values, dense_shape) def switch(data, pred, dtype=None, name=None): """Forwards `data` to an output determined by `pred`. If `pred` is false, the `data` input is forwarded to the first output. Otherwise, the data goes to the second output. This op handles `Tensor`s and `IndexedSlices`. Args: data: The tensor to be forwarded to the appropriate output. pred: A scalar that specifies which output port will receive data. dtype: Optional element type for the returned tensor. If missing, the type is inferred from the type of `value`. name: A name for this operation (optional). Returns: `(output_false, output_true)`: If `pred` is true, data will be forwarded to `output_true`, otherwise it goes to `output_false`. """ with ops.name_scope(name, "Switch", [data, pred]) as name: data = ops.internal_convert_to_tensor_or_indexed_slices( data, dtype=dtype, name="data", as_ref=True) pred = ops.convert_to_tensor(pred, name="pred") if isinstance(data, ops.Tensor): return gen_control_flow_ops._switch(data, pred, name=name) else: if not isinstance(data, (ops.IndexedSlices, sparse_tensor.SparseTensor)): raise TypeError("Type %s not supported" % type(data)) val, ind = data.values, data.indices val_f, val_t = gen_control_flow_ops._switch(val, pred, name=name) ind_f, ind_t = gen_control_flow_ops._switch(ind, pred, name="indices") if isinstance(data, ops.IndexedSlices): dense_shape = data.dense_shape if dense_shape is not None: dense_shape_f, dense_shape_t = gen_control_flow_ops._switch( dense_shape, pred, name="dense_shape") else: dense_shape_f, dense_shape_t = None, None return (ops.IndexedSlices(val_f, ind_f, dense_shape_f), ops.IndexedSlices(val_t, ind_t, dense_shape_t)) else: dense_shape = data.dense_shape dense_shape_f, dense_shape_t = gen_control_flow_ops._switch( data.dense_shape, pred, name="dense_shape") return (sparse_tensor.SparseTensor(ind_f, val_f, dense_shape_f), sparse_tensor.SparseTensor(ind_t, val_t, dense_shape_t)) def _SwitchRefOrTensor(data, pred, name="Switch"): """Forwards `data` to an output determined by `pred`. If `pred` is false, the `data` input is forwarded to the first output. Otherwise, the data goes to the second output. This op handles `Tensor`s and `IndexedSlices`. Args: data: The tensor to be forwarded to the appropriate output. pred: A scalar that specifies which output port will receive data. name: A name for this operation (optional). Returns: `(output_false, output_true)`: If `pred` is true, data will be forwarded to `output_true`, otherwise it goes to `output_false`. Raises: TypeError: if data is not a Tensor or IndexedSlices """ data = ops.convert_to_tensor_or_indexed_slices(data, name="data") # NOTE(vrv): ops.colocate_with(data, ignore_existing=True) below # addresses the following scenario. # # Assume you execute Optimizer.apply_gradients() in a branch of a cond(). # # 1. The update op is created inside a `with ops.colocate(var):` block # # 2. Some tensor `data` is captured and a switch is created in a # `with ops.colocate_with(data):` block. # # with ops.colocate_with(var): # with ops.colocate_with(data): # op = ... # # var and data may be pinned to different devices, so we want to ops # created within ops.colocate_with(data) to ignore the existing stack. with ops.colocate_with(data, ignore_existing=True): if isinstance(data, ops.Tensor): if data.dtype._is_ref_dtype: # pylint: disable=protected-access return ref_switch(data, pred, name=name) return switch(data, pred, name=name) def merge(inputs, name=None): """Returns the value of an available element of `inputs`. This op tests each of the tensors in `inputs` in turn to determine if any of them is available. If it finds an available tensor, it returns it and its index in `inputs`. It is an error if more than one tensor in `inputs` is available. If no tensor in `inputs` is available, the returned tensor and index are not set. This op handles both `Tensor`s and `IndexedSlices`. If inputs has a mix of `Tensor`s and `IndexedSlices`, all inputs are converted to IndexedSlices before merging. Args: inputs: The input tensors, at most one of which is available. name: A name for this operation (optional). Returns: A tuple containing the chosen input tensor and its index in `inputs`. Raises: ValueError: If any of the inputs is None, or inputs are IndexedSlices and some but not all have a dense_shape property. """ if any([inp is None for inp in inputs]): raise ValueError("At least one of the merge inputs is None: %s" % inputs) with ops.name_scope(name, "Merge", inputs) as name: inputs = [ops.internal_convert_to_tensor_or_indexed_slices(inp, as_ref=True) for inp in inputs] if all([isinstance(v, ops.Tensor) for v in inputs]): if all([v.dtype._is_ref_dtype for v in inputs]): # pylint: disable=protected-access return gen_control_flow_ops._ref_merge(inputs, name) else: return gen_control_flow_ops._merge(inputs, name) elif all([isinstance(v, sparse_tensor.SparseTensor) for v in inputs]): # Only handle the case when all inputs are SparseTensor. values, _ = merge([inp.values for inp in inputs], name=name) indices, chosen_index = gen_control_flow_ops._merge( [inp.indices for inp in inputs], name="indices") dense_shape, _ = gen_control_flow_ops._merge( [inp.dense_shape for inp in inputs], name="dense_shape") return (sparse_tensor.SparseTensor(indices, values, dense_shape), chosen_index) else: # For now convert all the inputs as IndexedSlices. inputs = math_ops._as_indexed_slices_list(inputs, optimize=False) values, _ = merge([inp.values for inp in inputs], name=name) indices, chosen_index = gen_control_flow_ops._merge( [inp.indices for inp in inputs], name="indices") if any(inp.dense_shape is not None for inp in inputs): if any(inp.dense_shape is None for inp in inputs): raise ValueError("Either all merged IndexedSlices must have a " "dense_shape, or none must have a dense_shape.") dense_shape, _ = gen_control_flow_ops._merge( [inp.dense_shape for inp in inputs], name="dense_shape") else: dense_shape = None return ops.IndexedSlices(values, indices, dense_shape), chosen_index # pylint: enable=protected-access def _convert_tensorarray_to_flow(tensor_or_tensor_array): if isinstance(tensor_or_tensor_array, tensor_array_ops.TensorArray): return tensor_or_tensor_array.flow else: return tensor_or_tensor_array def _make_tensor_array(ta, t_or_flow): # pylint: disable=protected-access new_ta = tensor_array_ops.TensorArray( dtype=ta.dtype, handle=ta.handle, flow=t_or_flow, infer_shape=ta._infer_shape, colocate_with_first_write_call=ta._colocate_with_first_write_call) new_ta._colocate_with = ta._colocate_with new_ta._element_shape = ta._element_shape # pylint: enable=protected-access return new_ta def _convert_flows_to_tensorarrays(tensors_or_tensorarrays, tensors_or_flows): if len(tensors_or_tensorarrays) != len(tensors_or_flows): raise ValueError( "Lengths of original Tensor list and new list do not match: %d vs. %d" % (len(tensors_or_tensorarrays), len(tensors_or_flows))) return [ _make_tensor_array(ta, t_or_flow) if isinstance(ta, tensor_array_ops.TensorArray) else t_or_flow for (ta, t_or_flow) in zip(tensors_or_tensorarrays, tensors_or_flows)] def _IsLoopConstantEnter(op): """Return true iff op is a loop invariant.""" is_enter = (op.type == "Enter" or op.type == "RefEnter") return is_enter and op.get_attr("is_constant") def _GetLoopConstantEnter(value): """Return the enter op if we can infer `value` to be a loop invariant.""" id_ops = {"Switch", "RefSwitch", "Identity", "RefIdentity"} op = value.op while op.type in id_ops: op = op.inputs[0].op return op if _IsLoopConstantEnter(op) else None def _GetOutputContext(op): """Return the control flow context for the output of an op.""" ctxt = op._get_control_flow_context() if IsLoopExit(op): ctxt = ctxt.outer_context return ctxt def _ShapeLessThanOrEqual(shape1, shape2): if shape2.dims is None: return True if shape1.ndims != shape2.ndims: return False for dim1, dim2 in zip(shape1.dims, shape2.dims): if dim2.value is not None and dim1.value != dim2.value: return False return True def _SetShapeInvariants(input_vars, enter_vars, shapes): """Set the shapes of the tensors in `enter_vars` to `shapes`. Args: input_vars: A list of tensors that are inputs to `enter_vars`. enter_vars: A list of tensors whose shapes will be set. shapes: A (possibly nested) list of shapes. Raises: ValueError: If any tensor in `enter_vars` has a less specific shape than its corresponding shape in `shapes`. """ if shapes is None: return flat_shapes = nest.flatten(shapes) if not all([isinstance(s, tensor_shape.TensorShape) for s in flat_shapes]): raise ValueError("`shapes` must be a (possibly nested) list of shapes.") # Check that the shapes of the inputs are less than the shape invariants, # and set the shapes of `enter_vars` to the shape invariants. for inp, var, shape in zip(input_vars, enter_vars, flat_shapes): if isinstance(var, ops.Tensor): if not _ShapeLessThanOrEqual(inp.get_shape(), shape): raise ValueError( "The shape invariant specified for %s is not compatible with " "the initial shape of the loop variable. It enters the loop " "with shape %s, but the specified shape invariant is %s." % (inp.name, inp.get_shape(), shape)) var.set_shape(shape) else: if not isinstance(var, (ops.IndexedSlices, sparse_tensor.SparseTensor)): raise TypeError("Type %s not supported" % type(var)) if isinstance(var, ops.IndexedSlices): if not _ShapeLessThanOrEqual(inp.values.get_shape(), shape): raise ValueError( "The shape invariant specified for %s is not compatible with " "the initial shape of the values tensor of this IndexedSlices. " "It enters the loop with shape %s, but the specified shape " "invariant is %s." % (inp.values.name, inp.values.get_shape(), shape)) var.values.set_shape(shape) var.indices.set_shape(tensor_shape.TensorShape([shape[0]])) if var.dense_shape is not None: var.dense_shape.set_shape(tensor_shape.TensorShape([shape.ndims])) else: if not _ShapeLessThanOrEqual(inp.dense_shape.get_shape(), shape): raise ValueError( "The shape invariant specified for %s is not compatible with " "the initial shape of the shape tensor of this SparseTensor. " "It enters the loop with shape %s, but the specified shape " "invariant is %s." % (inp.dense_shape.name, inp.dense_shape.get_shape(), shape)) var.values.set_shape(tensor_shape.TensorShape([None])) var.indices.set_shape(tensor_shape.TensorShape([None, shape.ndims])) var.dense_shape.set_shape(shape) def _EnforceShapeInvariant(merge_var, next_var): """Check if the shapes of the loops variables are invariants. Args: merge_vars: The list of tensors representing the initial values of the loop variables. next_vars: The list of tensors representing the values of the loop variables after one loop iteration. Raises: ValueError: If any tensor in `merge_vars` has a more specific shape than its correspnding tensor in `next_var`. """ if isinstance(merge_var, ops.Tensor): m_shape = merge_var.get_shape() n_shape = next_var.get_shape() if not _ShapeLessThanOrEqual(n_shape, m_shape): raise ValueError( "The shape for %s is not an invariant for the loop. It enters " "the loop with shape %s, but has shape %s after one iteration. " "Provide shape invariants using either the `shape_invariants` " "argument of tf.while_loop or set_shape() on the loop variables." % (merge_var.name, m_shape, n_shape)) else: if not isinstance(var, (ops.IndexedSlices, sparse_tensor.SparseTensor)): raise TypeError("Type %s not supported" % type(var)) if isinstance(var, ops.IndexedSlices): m_values_shape = merge_var.values.get_shape() m_indices_shape = merge_var.indices.get_shape() m_shape_shape = tensor_shape.TensorShape(None) if merge_var.dense_shape is not None: m_shape_shape = merge_var.dense_shape.get_shape() n_values_shape = next_var.values.get_shape() n_indices_shape = next_var.indices.get_shape() n_shape_shape = tensor_shape.TensorShape(None) if next_var.dense_shape is not None: n_shape_shape = next_var.dense_shape.get_shape() if (not _ShapeLessThanOrEqual(n_values_shape, m_values_shape) or not _ShapeLessThanOrEqual(n_indices_shape, m_indices_shape)): if not _ShapeLessThanOrEqual(n_values_shape, m_values_shape): raise ValueError( "The shape for %s is not an invariant for the loop. It enters " "the loop with shape (%s, %s, %s), but has shape (%s, %s, %s) " "after one iteration. Provide shape invariants using either the " "`shape_invariants` argument of tf.while_loop or set_shape() " "on the loop variables." % (merge_var.name, m_values_shape, m_indices_shape, m_shape_shape, n_values_shape, n_indices_shape, n_shape_shape)) else: m_values_shape = merge_var.values.get_shape() m_indices_shape = merge_var.indices.get_shape() m_shape_shape = merge_var.dense_shape.get_shape() n_values_shape = next_var.values.get_shape() n_indices_shape = next_var.indices.get_shape() n_shape_shape = next_var.dense_shape.get_shape() if (not _ShapeLessThanOrEqual(n_values_shape, m_values_shape) or not _ShapeLessThanOrEqual(n_indices_shape, m_indices_shape) or not _ShapeLessThanOrEqual(n_shape_shape, m_shape_shape)): raise ValueError( "The shape for %s is not an invariant for the loop. It enters " "the loop with shape (%s, %s, %s), but has shape (%s, %s, %s) " "after one iteration. Provide shape invariants using either " "the `shape_invariants` argument of tf.while_loop or set_shape() " "on the loop variables." % (merge_var.name, m_values_shape, m_indices_shape, m_shape_shape, n_values_shape, n_indices_shape, n_shape_shape)) def _AddNextAndBackEdge(m, v): """Add NextIteration and back edge from v to m.""" if isinstance(m, ops.Tensor): v = ops.convert_to_tensor(v) v = _NextIteration(v) m.op._update_input(1, v) # pylint: disable=protected-access elif isinstance(m, ops.IndexedSlices): # pylint: disable=protected-access v = math_ops._as_indexed_slices(v, optimize=False) v = _NextIteration(v) m.values.op._update_input(1, v.values) m.indices.op._update_input(1, v.indices) # pylint: enable=protected-access if m.dense_shape is not None: if v.dense_shape is None: raise ValueError("Must have dense shape: %s" % v.name) m.dense_shape.op._update_input(1, v.dense_shape) elif isinstance(m, sparse_tensor.SparseTensor): if not isinstance(v, sparse_tensor.SparseTensor): raise ValueError("Must be a sparse tensor: %s" % v.name) v = _NextIteration(v) # pylint: disable=protected-access m.values.op._update_input(1, v.values) m.indices.op._update_input(1, v.indices) m.dense_shape.op._update_input(1, v.dense_shape) # pylint: enable=protected-access else: raise TypeError("Type %s not supported" % type(m)) return v class GradLoopState(object): """The state used for constructing the gradient graph for a while loop. We create a GradLoopState for each while loop in forward and its corresponding while loop in backprop. This gives us access to both the forward and the backprop WhileContexts. During the construction of gradient graph, any time when we detect a forward value that is needed for backprop, we create a history accumulator and add it to `history_map`. Any time when we backprop a loop switch op (in _SwitchGrad), we add the grad merge op in `switch_map`. """ def __init__(self, forward_ctxt, outer_grad_state): # The grad loop state for the outer while loop. self._outer_grad_state = None # The while loop context for forward. self._forward_context = None # The loop counter added by AddForwardLoopCounter. It is the value # of the loop counter for the next iteration. self._forward_index = None # A sync op for forward. self._forward_sync = None # The while loop context for backprop. self._grad_context = None # The loop counter added by AddBackPropLoopCounter. It is the value # of the loop counter for the current iteration. self._grad_index = None # A sync op for backprop. self._grad_sync = None # Information needed by backprop. self._history_map = {} self._switch_map = {} self._unused_exits = [] self._deferred_exits = [] self._forward_loop_exits = list(forward_ctxt.loop_exits) self._pending_exits_count = len(forward_ctxt.loop_exits) self._outer_grad_state = outer_grad_state if outer_grad_state: outer_forward_ctxt = outer_grad_state.forward_context else: outer_forward_ctxt = forward_ctxt.outer_context # Add the forward loop counter. if outer_forward_ctxt: outer_forward_ctxt.Enter() cnt, forward_index = forward_ctxt.AddForwardLoopCounter(outer_grad_state) if outer_forward_ctxt: outer_forward_ctxt.Exit() self._forward_context = forward_ctxt self._forward_index = forward_index # Add the backprop WhileContext, and the backprop loop counter. if outer_grad_state: # This is a nested loop. Remember the iteration counts for each # execution of this inner loop. outer_forward_ctxt.AddName(cnt.name) history_cnt = outer_grad_state.AddForwardAccumulator(cnt) outer_grad_ctxt = outer_grad_state.grad_context outer_grad_ctxt.Enter() self._grad_context = WhileContext(forward_ctxt.parallel_iterations, forward_ctxt.back_prop, forward_ctxt.swap_memory, forward_ctxt.name, self) real_cnt = outer_grad_state.AddBackPropAccumulatedValue(history_cnt, cnt) self._grad_index = self._grad_context.AddBackPropLoopCounter( real_cnt, outer_grad_state) outer_grad_ctxt.Exit() else: if outer_forward_ctxt: outer_forward_ctxt.Enter() self._grad_context = WhileContext(forward_ctxt.parallel_iterations, forward_ctxt.back_prop, forward_ctxt.swap_memory, forward_ctxt.name, self) self._grad_index = self._grad_context.AddBackPropLoopCounter( cnt, outer_grad_state) if outer_forward_ctxt: outer_forward_ctxt.Exit() @property def outer_grad_state(self): """The grad loop state for outer loop.""" return self._outer_grad_state @property def forward_context(self): """The while loop context for forward.""" return self._forward_context @property def forward_index(self): """The loop index of forward loop.""" return self._forward_index @property def forward_sync(self): """A control trigger node for synchronization in the forward loop. One main use is to keep the push ops of a stack executed in the iteration order. """ if self._forward_sync is None: with ops.control_dependencies(None): self._forward_sync = control_trigger(name="f_sync") self._forward_sync._set_control_flow_context(self._forward_context) self._forward_index.op._add_control_input(self._forward_sync) return self._forward_sync @property def grad_context(self): """The corresponding WhileContext for gradient.""" return self._grad_context @property def grad_index(self): """The loop index of backprop loop.""" return self._grad_index @property def grad_sync(self): """A control trigger node for synchronization in the grad loop. One main use is to keep the pop ops of a stack executed in the iteration order. """ if self._grad_sync is None: with ops.control_dependencies(None): self._grad_sync = control_trigger(name="b_sync") self._grad_sync._set_control_flow_context(self._grad_context) self._grad_index.op._add_control_input(self._grad_sync) return self._grad_sync @property def history_map(self): """The map that records all the tensors needed for backprop.""" return self._history_map @property def switch_map(self): """The map that records all the Switch ops for the while loop.""" return self._switch_map @property def unused_exits(self): """The list of "unused" exits.""" return self._unused_exits @property def deferred_exits(self): """The list of "deferred" exits.""" return self._deferred_exits @property def forward_loop_exits(self): """The list of exits of the forward loop.""" return self._forward_loop_exits @property def pending_exits_count(self): """The number of exits we expect to see but haven't.""" return self._pending_exits_count @pending_exits_count.setter def pending_exits_count(self, cnt): """Set the pending count to cnt.""" self._pending_exits_count = cnt def AddForwardAccumulator(self, value, dead_branch=False): """Add an accumulator for each forward tensor that is needed in backprop. This is added to the forward loop at the first time when a tensor in the forward loop is used by backprop gradient computation loop. We create an accumulator that accumulates the value of tensor at each iteration. Called in the control flow context where gradients() is called. The pseudocode is: ``` acc = stack(); while (_pivot) { acc = stack_push(acc, value); } ``` We make sure that the stack push op in one iteration is executed before next iteration. This is achieved by adding a control edge from `forward_index.op.inputs[0].op` to the push op, and another control edge from the push op to either `forward_index.op` or `forward_sync`. Args: value: The source tensor in forward that is to be accumulated. dead_branch: True iff the tensor is on a dead branch of a cond. Returns: The stack that contains the accumulated history of the tensor. Raises: TypeError: For internal errors involving the value condition context. """ curr_ctxt = ops.get_default_graph()._get_control_flow_context() with ops.control_dependencies(None): if curr_ctxt: curr_ctxt.Enter() with ops.colocate_with(value): # pylint: disable=protected-access acc = gen_data_flow_ops._stack(value.dtype.base_dtype, name="f_acc") # pylint: enable=protected-access if curr_ctxt: curr_ctxt.Exit() # Make acc available in the forward context. enter_acc = self.forward_context.AddValue(acc) # Add the stack_push op in the context of value.op. swap_enabled = self.forward_context.swap_memory value_ctxt = _GetOutputContext(value.op) if value_ctxt == self.forward_context: # value is not nested in the forward context. self.forward_context.Enter() push = gen_data_flow_ops._stack_push( enter_acc, value, swap_memory=swap_enabled) self.forward_context.Exit() # Protect stack push and order it before forward_index. self.forward_index.op._add_control_input(push.op) else: # value is in a cond context within the forward context. if not isinstance(value_ctxt, CondContext): raise TypeError( "value_ctxt is not a CondContext: %s" % value_ctxt) if dead_branch: # The special case for creating a zero tensor for a dead # branch of a switch. See ControlFlowState.ZerosLike(). value_ctxt.outer_context.Enter() push = gen_data_flow_ops._stack_push( enter_acc, value, swap_memory=swap_enabled) value_ctxt.outer_context.Exit() push.op._set_control_flow_context(value_ctxt) else: value_ctxt.Enter() push = gen_data_flow_ops._stack_push( enter_acc, value, swap_memory=swap_enabled) value_ctxt.Exit() # Protect stack push and order it before forward_sync. self.forward_sync._add_control_input(push.op) # Order stack push after the successor of forward_index add_op = self.forward_index.op.inputs[0].op push.op._add_control_input(add_op) return acc def AddBackPropAccumulatedValue(self, history_value, value, dead_branch=False): """Add the getter for an accumulated value in the grad context. This is added to the backprop loop. Called in the grad context to get the value of an accumulated value. The stack pop op must be guarded by the pred of the controlling cond. Args: history_value: The history (a stack) of a value. value: The value that is pushed onto the stack. dead_branch: True iff the tensor is on a dead branch of a cond. Returns: The current value (the top of the stack). """ history_ctxt = history_value.op._get_control_flow_context() # Find the cond context that controls history_value if any. cond_ctxt = None value_ctxt = value.op._get_control_flow_context() while value_ctxt and value_ctxt != history_ctxt: if isinstance(value_ctxt, CondContext): cond_ctxt = value_ctxt break value_ctxt = value_ctxt.outer_context with ops.control_dependencies(None): self.grad_context.Enter() if cond_ctxt: # Guard stack pop with a switch if it is controlled by a cond. grad_state = self pred = None while pred is None and grad_state: pred = grad_state.history_map.get(cond_ctxt.pred.name) grad_state = grad_state.outer_grad_state if pred is None: pred = cond_ctxt.pred branch = (1 - cond_ctxt.branch) if dead_branch else cond_ctxt.branch history_value = _SwitchRefOrTensor(history_value, pred)[branch] pop = gen_data_flow_ops._stack_pop(history_value, value.dtype.base_dtype) pop.set_shape(value.get_shape()) self.grad_context.Exit() parallel_iterations = self.grad_context.parallel_iterations if parallel_iterations > 1: # All pops are ordered after pivot_for_body and before grad_sync. self.grad_sync._add_control_input(pop.op) return pop def GetRealValue(self, value): """Get the real value of `value`. If backprop "uses" a value produced by forward inference, an accumulator is added in the forward loop to accumulate its values. We use the accumulated value. This method must be called in the grad loop context. `value` must be in forward and needed for backprop. Args: value: A tensor to be captured. Returns: The same tensor obtained from the saved history. """ assert value.op.type not in ["Variable", "VariableV2"] real_value = self._history_map.get(value.name) if real_value is None: cur_value = value cur_grad_state = self while True: enter_op = _GetLoopConstantEnter(cur_value) if enter_op: # Special case: cur_value comes from a constant Enter node. cur_value = enter_op.inputs[0] cur_grad_state = cur_grad_state.outer_grad_state if cur_grad_state is None: # We are now outside all nested loops for this gradient(), # so `value` is a loop invariant and there is no need to # save the history of value. Just make cur_value to enter # the right control flow context. real_value = self._grad_context.AddValue(cur_value) break else: # Record the history of this value in forward_ctxt. # TODO(yuanbyu): Avoid recording constants. self._grad_context.Exit() history_value = cur_grad_state.AddForwardAccumulator(cur_value) self._grad_context.Enter() break if real_value is None: # Add the stack pop op in the grad context. real_value = cur_grad_state.AddBackPropAccumulatedValue(history_value, cur_value) if cur_grad_state != self: real_value = self._grad_context.AddValue(real_value) self._history_map[value.name] = real_value return real_value def _GetWhileContext(op): """Get the WhileContext to which this op belongs.""" ctxt = op._get_control_flow_context() if ctxt: ctxt = ctxt.GetWhileContext() return ctxt class ControlFlowState(object): """Maintain the mapping from the loops to their grad states.""" def __init__(self): self._map = {} # maps forward loop context to GradLoopState def GetGradState(self, op, before): """Return the grad state for this op if it's in a forward loop context.""" if before and IsLoopExit(op): forward_ctxt = op._get_control_flow_context() forward_ctxt = forward_ctxt.outer_context if forward_ctxt: forward_ctxt = forward_ctxt.GetWhileContext() else: forward_ctxt = _GetWhileContext(op) if forward_ctxt: return self._map.get(forward_ctxt) return None def ProcessUnusedLoopExits(self, pending_count, to_ops_set): """Process all the "unused" loop exits. The "unused" exits of the loops are added to `unused_exits`. An exit is unused if its pending_count is 0. If there is an exit with real gradient, all these deferred exits will enter the backprop loop with zero gradient. Otherwise, they will enter the backprop loop with None. As an example, people often write: ``` v1, _ = tf.while_loop(p, b, [x1, x2]) result = gradients(v1, x1) ``` The exit node for x2 is not included by the betweenness analysis. But we need to backprop x2 if x2 is involved in computing v1. Args: pending_count: The number of backprop inputs for every op. to_ops_set: The set of ops for ys in gradients(ys, xs) Returns: The set of unused loop exits that we know at this point we need to backprop. """ loop_exits = [] for _, grad_state in self._map.items(): # pylint: disable=protected-access for y in grad_state.forward_loop_exits: if pending_count[y.op._id] == 0: grad_state.pending_exits_count -= 1 if y.op._id not in to_ops_set: grad_state.unused_exits.append(y) if grad_state.pending_exits_count == 0: loop_exits.extend(grad_state.unused_exits) # Need to include Enters in backprop for higher-order gradients. for y in grad_state.forward_context.loop_enters: if pending_count[y.op._id] == 0: pending_count[y.op._id] = 1 # pylint: enable=protected-access return loop_exits def EnterGradWhileContext(self, op, before): """Enter the WhileContext for gradient computation.""" grad_state = self.GetGradState(op, before) if grad_state: grad_state.grad_context.Enter() def ExitGradWhileContext(self, op, before): """Exit the WhileContext for gradient computation.""" grad_state = self.GetGradState(op, before) if grad_state: grad_state.grad_context.Exit() def AddWhileContext(self, op, between_op_list, between_ops): """Add the grad state for the while loop that op belongs to. Note that op is an Exit, and this method must be called in the control flow context where gradients() is called. Note that this method modifies `between_op_list` and `between_ops`. """ forward_ctxt = _GetWhileContext(op) grad_state = self._map.get(forward_ctxt) if grad_state is None: # This is a new while loop so create a grad state for it. outer_forward_ctxt = forward_ctxt.outer_context if outer_forward_ctxt: outer_forward_ctxt = outer_forward_ctxt.GetWhileContext() outer_grad_state = None if outer_forward_ctxt: outer_grad_state = self._map.get(outer_forward_ctxt) grad_state = GradLoopState(forward_ctxt, outer_grad_state) self._map[forward_ctxt] = grad_state # We need to include all exits of a loop for backprop. for loop_exit in grad_state.forward_loop_exits: if not between_ops[loop_exit.op._id]: between_ops[loop_exit.op._id] = True between_op_list.append(loop_exit.op) def ZerosLikeForExit(self, val): """Create zeros_like gradient for a loop exit. If the result of a loop variable is not used but is involved in computing the result of some needed loop variable, we create a zero-valued tensor that is fed as gradient for the Exit node of that loop variable. Note that val.op is an Exit, and this method must be called in the control flow context where gradients() is called. Args: val: The output tensor of an Exit op. Returns: A zero tensor of the same shape of val. """ val_shape = val.get_shape() forward_ctxt = val.op._get_control_flow_context() outer_forward_ctxt = forward_ctxt.outer_context if outer_forward_ctxt: outer_forward_ctxt = outer_forward_ctxt.GetWhileContext() outer_grad_state = None if outer_forward_ctxt: outer_grad_state = self._map.get(outer_forward_ctxt) if outer_grad_state: # This is a nested loop. if val_shape.is_fully_defined(): # If the shape is known statically, just create a zero tensor # with the right shape in the right context. outer_grad_state.grad_context.Enter() result = array_ops.zeros(val_shape.dims, val.dtype) outer_grad_state.grad_context.Exit() else: # Only the shape of value is needed for backprop. forward_ctxt.outer_context.Enter() shape = array_ops.shape_internal(val, optimize=False) forward_ctxt.outer_context.Exit() # Save the shape to a stack. history_shape = outer_grad_state.AddForwardAccumulator(shape) # Get the shape back from the stack. outer_grad_ctxt = outer_grad_state.grad_context outer_grad_ctxt.Enter() real_shape = outer_grad_state.AddBackPropAccumulatedValue( history_shape, shape) result = array_ops.zeros(real_shape, val.dtype) outer_grad_ctxt.Exit() else: # This is not a nested loop. if val_shape.is_fully_defined(): # If the shape is known statically, just create a zero tensor # with the right shape. result = array_ops.zeros(val_shape.dims, val.dtype) else: result = array_ops.zeros_like(val, optimize=False) return result def ZerosLike(self, op, index): """Create zeros_like for the specified output of an op. If op is in a while loop that is part of gradients(), this method must be called in its grad loop context. Args: op: A tensorflow operation. index: the index for a specific output of the op. Returns: A zero tensor of the same shape of op.outputs[index]. """ if IsLoopSwitch(op): return None dead_branch = IsSwitch(op) forward_ctxt = _GetWhileContext(op) grad_state = self._map.get(forward_ctxt) if grad_state is None: # op is not in a while loop that is part of gradients(). return ZerosLikeOutsideLoop(op, index) op_ctxt = op._get_control_flow_context() val = ops.convert_to_tensor(op.outputs[index], name="tensor") shape = val.get_shape() if shape.is_fully_defined(): # If the shape is known statically, just create a zero tensor with # the right shape in the grad loop context. result = constant_op.constant(0, shape=shape.dims, dtype=val.dtype) if dead_branch: # op is a cond switch. Guard the zero tensor with a switch. pred = grad_state.history_map.get(op_ctxt.pred.name) branch = op_ctxt.branch result = _SwitchRefOrTensor(result, pred)[1 - branch] else: # Unknown shape so keep a history of the shape at runtime. if dead_branch: # Need to add a special switch to guard the value. pred = op_ctxt.pred branch = op_ctxt.branch op_ctxt.outer_context.Enter() val = _SwitchRefOrTensor(op.inputs[0], pred)[1 - branch] zeros_shape = array_ops.shape_internal(val, optimize=False) op_ctxt.outer_context.Exit() val.op._set_control_flow_context(op_ctxt) zeros_shape.op._set_control_flow_context(op_ctxt) else: op_ctxt.Enter() zeros_shape = array_ops.shape_internal(val, optimize=False) op_ctxt.Exit() # Add forward accumulator for shape. grad_state.grad_context.Exit() history_zeros_shape = grad_state.AddForwardAccumulator( zeros_shape, dead_branch=dead_branch) grad_state.grad_context.Enter() # Create a zero tensor with the right shape. shape = grad_state.AddBackPropAccumulatedValue( history_zeros_shape, zeros_shape, dead_branch) result = array_ops.zeros(shape, val.dtype) return result def PostProcessing(self): """Perform postprocessing at the end of gradients(). We have created the gradient graph at this point. So this function can be used to perform any postprocessing on the gradient graph. We currently perform the following postprocessing: 1. Patch the gradient graph if the output of a loop variable doesn't depend on its input. """ for _, grad_state in self._map.items(): for _, b_merge in grad_state.switch_map.items(): if b_merge.op.inputs[0] == b_merge.op.inputs[1]: # The value of this loop variable at iteration i+1 doesn't # depend on its value at iteration i. So use zeros as the # gradients for all iterations > 0. dtype = b_merge.op.inputs[0].dtype shape = b_merge.op.inputs[0].get_shape() # pylint: disable=protected-access if shape.is_fully_defined(): grad_state.grad_context.Enter() # Create a zeros and use it for iterations > 0. grad_val = constant_op.constant(0, dtype=dtype, shape=shape) next_grad_val = _NextIteration(grad_val) grad_state.grad_context.Exit() else: # Create a zeros in the outer grad context. outer_grad_ctxt = grad_state.grad_context.outer_context if outer_grad_ctxt: outer_grad_ctxt.Enter() enter_grad_op = b_merge.op.inputs[0].op enter_grad = enter_grad_op.inputs[0] grad_shape = array_ops.shape_internal(enter_grad, optimize=False) grad_val = array_ops.zeros(grad_shape) if outer_grad_ctxt: outer_grad_ctxt.Exit() # Use the zeros for iterations > 0. grad_state.grad_context.Enter() next_grad_val = _NextIteration(grad_val) grad_state.grad_context.Exit() b_merge.op._update_input(1, next_grad_val) # pylint: enable=protected-access def MaybeCreateControlFlowState(between_op_list, between_ops, colocate_gradients_with_ops): """Create the state for all the while loops involved in one gradients(). We create a ControlFlowState when there are while loops involved in gradients(). In gradients(), control flow logic is only invoked when the ControlFlowState is not None. Note that this method modifies `between_op_list` and `between_ops`. """ loop_state = None for op in between_op_list: if IsLoopExit(op): if loop_state is None: loop_state = ControlFlowState() if colocate_gradients_with_ops: with ops.colocate_with(op): loop_state.AddWhileContext(op, between_op_list, between_ops) else: loop_state.AddWhileContext(op, between_op_list, between_ops) return loop_state def IsSwitch(op): """Return true if `op` is a Switch.""" return op.type == "Switch" or op.type == "RefSwitch" def IsLoopExit(op): """Return true if `op` is an Exit.""" return op.type == "Exit" or op.type == "RefExit" def IsLoopSwitch(op): """Return true if `op` is the Switch for a while loop.""" if IsSwitch(op): ctxt = op._get_control_flow_context() return ctxt and isinstance(ctxt, WhileContext) return False def ZerosLikeOutsideLoop(op, index): """Create zeros_like for the specified output of an op.""" val = op.outputs[index] if not IsSwitch(op): return array_ops.zeros_like(val, optimize=False) else: op_ctxt = op._get_control_flow_context() if op_ctxt: # We are in a cond context. Use a switch to create zeros only when needed. pred = op_ctxt.pred branch = op_ctxt.branch switch_val = switch(op.inputs[0], pred)[1 - branch] zeros_shape = array_ops.shape_internal(switch_val, optimize=False) return array_ops.zeros(zeros_shape, dtype=val.dtype) else: return array_ops.zeros_like(val, optimize=False) class ControlFlowContext(object): """The base class for control flow context. The usage pattern is a sequence of (Enter, Exit) followed by a final ExitResult. We maintain the following state for control flow contexts during graph construction: 1. graph has _control_flow_context: the current context used to construct new nodes. Changed by ctxt.Enter() and ctxt.Exit() 2. op has _control_flow_context: the context to which the op belongs. Set at the time the op is created. Immutable. 3. A ControlFlowContext has _outer_context: the context in which this context is created. Set at the time a context is created. Immutable. 4. A ControlFlowContext has _context_stack. Pushed and popped by ctxt.Enter() and ctxt.Exit() """ def __init__(self, values_def=None, import_scope=None): self._outer_context = ops.get_default_graph()._get_control_flow_context() self._context_stack = [] if values_def: self._init_values_from_proto(values_def, import_scope=import_scope) else: # Values that have been already seen in this context. self._values = set() # Values referenced by but external to this context. self._external_values = {} def _init_values_from_proto(self, values_def, import_scope=None): """Initializes values and external_values from `ValuesDef` protocol buffer. Args: values_def: `ValuesDef` protocol buffer. import_scope: Optional `string`. Name scope to add. """ assert isinstance(values_def, control_flow_pb2.ValuesDef) self._values = set( ops.prepend_name_scope(value, import_scope) for value in values_def.values) g = ops.get_default_graph() self._external_values = {} for k, v in values_def.external_values.items(): k = ops.prepend_name_scope(k, import_scope) self._external_values[k] = g.as_graph_element( ops.prepend_name_scope(v, import_scope)) op_names = set([ op.split(":")[0] for op in self._values - set(self._external_values.keys()) ]) for op in op_names: # pylint: disable=protected-access g.as_graph_element(op)._set_control_flow_context(self) # pylint: enable=protected-access @property def outer_context(self): """Return the context containing this context.""" return self._outer_context @property def grad_state(self): raise NotImplementedError("Abstract method") @property def back_prop(self): raise NotImplementedError("Abstract method") def _to_proto(self, export_scope=None): """Converts the values to a `ValuesDef` protocol buffer. Args: export_scope: Optional `string`. Name scope to remove. Returns: A `ValuesDef` protocol buffer. """ values_def = control_flow_pb2.ValuesDef() values_def.values.extend( [ops.strip_name_scope(v, export_scope) for v in sorted(self._values)]) for k, v in self._external_values.items(): k = ops.strip_name_scope(k, export_scope) values_def.external_values[k] = ops.strip_name_scope( v.name, export_scope) return values_def @staticmethod def _from_proto(values_def, import_scope=None): """Returns a `ControlFlowContext` created from `values_def`.""" return ControlFlowContext(values_def=values_def, import_scope=import_scope) def AddName(self, name): self._values.add(name) # pylint: disable=protected-access def Enter(self): """Enter this control flow context.""" graph = ops.get_default_graph() self._context_stack.append(graph._get_control_flow_context()) graph._set_control_flow_context(self) def Exit(self): """Exit this control flow context.""" graph = ops.get_default_graph() last_context = self._context_stack.pop() graph._set_control_flow_context(last_context) def ExitResult(self, result): """Make a list of tensors available in the outer context.""" if self._outer_context: nest.map_structure(lambda x: self._outer_context.AddName(x.name), result) def GetWhileContext(self): """Return the while context containing this context.""" if self._outer_context: return self._outer_context.GetWhileContext() return None def _IsInOuterContext(self, op): op_ctxt = _GetOutputContext(op) outer_ctxt = self.outer_context while outer_ctxt != op_ctxt: if outer_ctxt is None: return False outer_ctxt = outer_ctxt.outer_context return True def _RemoveExternalControlEdges(self, op): """Remove any external control dependency on this op.""" while_ctxt = self.GetWhileContext() # A control input of `op` is internal if it is in the same while # loop context as the enclosing while loop context of self. if while_ctxt is None: internal_control_inputs = op.control_inputs else: internal_control_inputs = [] for x in op.control_inputs: ctxt = _GetOutputContext(x) if ctxt is not None and ctxt.GetWhileContext() == while_ctxt: internal_control_inputs.append(x) if len(internal_control_inputs) != len(op.control_inputs): del op.control_inputs[:] op._add_control_inputs(internal_control_inputs) return internal_control_inputs # pylint: enable=protected-access def AddInnerOp(self, op): """Notifies a scope about an operator added to an inner scope.""" pass def GetControlPivot(self): """Returns the pivot node for this context, or None.""" return None class CondContext(ControlFlowContext): """The context for the conditional construct.""" def __init__(self, pred=None, pivot=None, branch=None, name="cond_text", context_def=None, import_scope=None): """Creates a `CondContext`. Args: pred: The `boolean` tensor for the conditional predicate. pivot: The predicate tensor in this branch. branch: 0 or 1 representing this branch. name: Name of the `CondContext` python object. context_def: Optional `ContextDef` protocol buffer to initialize the `CondContext` object from. import_scope: Optional `string`. Name scope to add. Only used when initialing from protocol buffer. """ self._name = ops.get_default_graph().unique_name(name) if context_def: self._init_from_proto(context_def, import_scope=import_scope) else: # Initializes the default fields. ControlFlowContext.__init__(self) self._pred = pred # The boolean tensor for the cond predicate self._pivot = pivot # The predicate tensor in this branch self._branch = branch # 0 or 1 representing this branch # Values considered to have been already seen in this context. self._values.add(pred.name) self._values.add(pivot.name) def _init_from_proto(self, context_def, import_scope=None): """Creates a new `CondContext` from protocol buffer. Args: context_def: `CondContextDef` protocol buffer. import_scope: Optional `string`. Name scope to add. """ assert isinstance(context_def, control_flow_pb2.CondContextDef) # Create from context_def. g = ops.get_default_graph() self._name = ops.prepend_name_scope( context_def.context_name, import_scope) self._pred = g.as_graph_element(ops.prepend_name_scope( context_def.pred_name, import_scope)) self._pivot = g.as_graph_element(ops.prepend_name_scope( context_def.pivot_name, import_scope)) self._branch = context_def.branch super(CondContext, self).__init__(values_def=context_def.values_def, import_scope=import_scope) @property def name(self): return self._name @property def pred(self): return self._pred @property def pivot(self): return self._pivot @property def branch(self): return self._branch @property def grad_state(self): if self.GetWhileContext(): return self.GetWhileContext().grad_state return None @property def back_prop(self): if self.GetWhileContext(): self.GetWhileContext().back_prop return False def GetControlPivot(self): return self._pivot def to_proto(self, export_scope=None): """Converts a `CondContext` to a `CondContextDef` protocol buffer. Args: export_scope: Optional `string`. Name scope to remove. Returns: A `CondContextDef` protocol buffer. """ if (export_scope is None or self.name.startswith(export_scope)): context_def = control_flow_pb2.CondContextDef() context_def.context_name = ops.strip_name_scope( self.name, export_scope) context_def.pred_name = ops.strip_name_scope( self._pred.name, export_scope) context_def.pivot_name = ops.strip_name_scope( self._pivot.name, export_scope) context_def.branch = self._branch context_def.values_def.MergeFrom(super(CondContext, self)._to_proto( export_scope)) return context_def else: return None @staticmethod def from_proto(context_def, import_scope=None): """Returns a `CondContext` object created from `context_def`.""" return CondContext(context_def=context_def, import_scope=import_scope) def AddValue(self, val): """Add `val` to the current context and its outer context recursively.""" if val.name in self._values: # Use the real value if it comes from outer context. This is needed in # particular for nested conds. result = self._external_values.get(val.name) result = val if result is None else result else: result = val self._values.add(val.name) if self._outer_context: result = self._outer_context.AddValue(val) self._values.add(result.name) with ops.control_dependencies(None): result = _SwitchRefOrTensor(result, self._pred)[self._branch] result.op.graph.prevent_fetching(result.op) # pylint: disable=protected-access result.op._set_control_flow_context(self) # pylint: enable=protected-access self._values.add(result.name) self._external_values[val.name] = result return result def AddOp(self, op): self._AddOpInternal(op) def _AddOpInternal(self, op): """Add `op` to the current context.""" if not op.inputs: # Remove any external control dependency on this op self._RemoveExternalControlEdges(op) # pylint: disable=protected-access op._add_control_input(self._pivot.op) # pylint: enable=protected-access for x in op.outputs: self._values.add(x.name) else: for index in range(len(op.inputs)): x = op.inputs[index] real_x = self.AddValue(x) if real_x != x: # pylint: disable=protected-access op._update_input(index, real_x) # pylint: enable=protected-access # Remove any external control dependency on this op. self._RemoveExternalControlEdges(op) for x in op.outputs: self._values.add(x.name) # pylint: disable=protected-access if op.graph._is_function(op.type) or op.type == "SymbolicGradient": op._add_control_input(self._pivot.op) # pylint: enable=protected-access if self._outer_context or not IsLoopExit(op): op.graph.prevent_fetching(op) def _ProcessOutputTensor(self, val): """Process an output tensor of a conditional branch.""" real_val = val if val.name not in self._values: # Handle the special case of lambda: x self._values.add(val.name) if self._outer_context: real_val = self._outer_context.AddValue(val) self._values.add(real_val.name) real_val = _SwitchRefOrTensor(real_val, self._pred)[self._branch] self._external_values[val.name] = real_val else: external_val = self._external_values.get(val.name) if external_val is not None: real_val = external_val return real_val def _BuildCondTensor(self, v): if isinstance(v, ops.Operation): # Use pivot as the proxy for this op. return with_dependencies([v], self._pivot) elif isinstance(v, (ops.IndexedSlices, sparse_tensor.SparseTensor)): values = self._ProcessOutputTensor(v.values) indices = self._ProcessOutputTensor(v.indices) if isinstance(v, ops.IndexedSlices): dense_shape = v.dense_shape if dense_shape is not None: dense_shape = self._ProcessOutputTensor(dense_shape) return ops.IndexedSlices(values, indices, dense_shape) else: dense_shape = self._ProcessOutputTensor(v.dense_shape) return sparse_tensor.SparseTensor(indices, values, dense_shape) else: v = nest.map_structure(_convert_tensorarray_to_flow, v) return self._ProcessOutputTensor(ops.convert_to_tensor(v)) def BuildCondBranch(self, fn): """Add the subgraph defined by fn() to the graph.""" original_result = fn() if original_result is None: return None, None result = nest.map_structure(self._BuildCondTensor, original_result) if not isinstance(result, (list, _basetuple)): result = [result] return original_result, result def _UnpackIfSingleton(res): if isinstance(res, (list, _basetuple)) and len(res) == 1: return res[0] else: return res # pylint: disable=g-doc-args @deprecation.deprecated_args( None, "fn1/fn2 are deprecated in favor of the true_fn/false_fn arguments.", "fn1", "fn2") def cond(pred, true_fn=None, false_fn=None, strict=False, name=None, fn1=None, fn2=None): """Return `true_fn()` if the predicate `pred` is true else `false_fn()`. `true_fn` and `false_fn` both return lists of output tensors. `true_fn` and `false_fn` must have the same non-zero number and type of outputs. Note that the conditional execution applies only to the operations defined in `true_fn` and `false_fn`. Consider the following simple program: ```python z = tf.multiply(a, b) result = tf.cond(x < y, lambda: tf.add(x, z), lambda: tf.square(y)) ``` If `x < y`, the `tf.add` operation will be executed and `tf.square` operation will not be executed. Since `z` is needed for at least one branch of the `cond`, the `tf.multiply` operation is always executed, unconditionally. Although this behavior is consistent with the dataflow model of TensorFlow, it has occasionally surprised some users who expected a lazier semantics. Note that `cond` calls `true_fn` and `false_fn` *exactly once* (inside the call to `cond`, and not at all during `Session.run()`). `cond` stitches together the graph fragments created during the `true_fn` and `false_fn` calls with some additional graph nodes to ensure that the right branch gets executed depending on the value of `pred`. `tf.cond` supports nested structures as implemented in `tensorflow.python.util.nest`. Both `true_fn` and `false_fn` must return the same (possibly nested) value structure of lists, tuples, and/or named tuples. Singleton lists and tuples form the only exceptions to this: when returned by `true_fn` and/or `false_fn`, they are implicitly unpacked to single values. This behavior is disabled by passing `strict=True`. Args: pred: A scalar determining whether to return the result of `true_fn` or `false_fn`. true_fn: The callable to be performed if pred is true. false_fn: The callable to be performed if pred is false. strict: A boolean that enables/disables 'strict' mode; see above. name: Optional name prefix for the returned tensors. Returns: Tensors returned by the call to either `true_fn` or `false_fn`. If the callables return a singleton list, the element is extracted from the list. Raises: TypeError: if `true_fn` or `false_fn` is not callable. ValueError: if `true_fn` and `false_fn` do not return the same number of tensors, or return tensors of different types. Example: ```python x = tf.constant(2) y = tf.constant(5) def f1(): return tf.multiply(x, 17) def f2(): return tf.add(y, 23) r = tf.cond(tf.less(x, y), f1, f2) # r is set to f1(). # Operations in f2 (e.g., tf.add) are not executed. ``` """ # We needed to make true_fn/false_fn keyword arguments for # backwards-compatibility. This check exists so that we can convert back to # having them be positional arguments. # TODO(josh11b): Make `true_fn` and `false_fn` positional arguments after # `fn1` and `fn2` are deleted. if fn1 is not None: if true_fn is not None: raise TypeError("cond(): true_fn and fn1 may not be set simultaneously.") true_fn = fn1 elif true_fn is None: raise TypeError("cond(): true_fn argument required") if fn2 is not None: if false_fn is not None: raise TypeError("cond(): false_fn and fn2 may not be set simultaneously.") false_fn = fn2 elif false_fn is None: raise TypeError("cond(): false_fn argument required") if not callable(true_fn): raise TypeError("true_fn must be callable.") if not callable(false_fn): raise TypeError("false_fn must be callable.") with ops.name_scope(name, "cond", [pred]): # Add the Switch to the graph. if isinstance(pred, bool): raise TypeError("pred must not be a Python bool") p_2, p_1 = switch(pred, pred) pivot_1 = array_ops.identity(p_1, name="switch_t") pivot_2 = array_ops.identity(p_2, name="switch_f") pred = array_ops.identity(pred, name="pred_id") # Disable the fetching of tensors that are only on one branch of cond. for tensor in [p_1, p_2, pivot_1, pivot_2, pred]: tensor.op.graph.prevent_fetching(tensor.op) # Build the graph for the true branch in a new context. context_t = CondContext(pred, pivot_1, branch=1) context_t.Enter() orig_res_t, res_t = context_t.BuildCondBranch(true_fn) if orig_res_t is None: raise ValueError("true_fn must have a return value.") context_t.ExitResult(res_t) context_t.Exit() # Build the graph for the false branch in a new context. context_f = CondContext(pred, pivot_2, branch=0) context_f.Enter() orig_res_f, res_f = context_f.BuildCondBranch(false_fn) if orig_res_f is None: raise ValueError("false_fn must have a return value.") context_f.ExitResult(res_f) context_f.Exit() if not strict: orig_res_t = _UnpackIfSingleton(orig_res_t) orig_res_f = _UnpackIfSingleton(orig_res_f) # Check that the return values of the two branches have the same structure. try: nest.assert_same_structure(orig_res_t, orig_res_f) except TypeError as e: raise TypeError( "Incompatible return types of true_fn and false_fn: {}".format(e)) except ValueError as e: raise ValueError( "Incompatible return values of true_fn and false_fn: {}".format(e)) # Add the final merge to the graph. if not res_t: raise ValueError("true_fn and false_fn must return at least one result.") res_t_flat = nest.flatten(res_t) res_f_flat = nest.flatten(res_f) for x, y in zip(res_t_flat, res_f_flat): assert ((isinstance(x, ops.IndexedSlices) and isinstance(y, ops.IndexedSlices)) or (isinstance(x, sparse_tensor.SparseTensor) and isinstance(y, sparse_tensor.SparseTensor)) or (isinstance(x, ops.Tensor) and isinstance(y, ops.Tensor))) val_x = x if isinstance(x, ops.Tensor) else x.values val_y = y if isinstance(y, ops.Tensor) else y.values if val_x.dtype.base_dtype != val_y.dtype.base_dtype: raise ValueError( "Outputs of true_fn and false_fn must have the same type: %s, %s" % (val_x.dtype.name, val_y.dtype.name)) merges = [merge(pair)[0] for pair in zip(res_f_flat, res_t_flat)] merges = _convert_flows_to_tensorarrays(nest.flatten(orig_res_t), merges) # Add to collections ops.add_to_collection(ops.GraphKeys.COND_CONTEXT, context_t) ops.add_to_collection(ops.GraphKeys.COND_CONTEXT, context_f) merges = nest.pack_sequence_as(structure=orig_res_t, flat_sequence=merges) # Singleton lists and tuples are automatically unpacked if strict == False. if not strict: merges = _UnpackIfSingleton(merges) return merges # pylint: enable=g-doc-args def _resource_safe_shape(t): """Returns the shape of t or the variable it points to.""" if t.dtype == dtypes.resource: while t.op.inputs: t = t.op.inputs[0] return tensor_shape.TensorShape(t.op.get_attr("shape")) return array_ops.shape_internal(t, optimize=False) # TODO(yuanbyu): Consider having a unified notion of context for # not only conditionals and loops but also control dependency and # subgraphs. class WhileContext(ControlFlowContext): """The context for the loop construct.""" def __init__(self, parallel_iterations=10, back_prop=True, swap_memory=False, name="while_context", grad_state=None, context_def=None, import_scope=None): """"Creates a `WhileContext`. Args: parallel_iterations: The number of iterations allowed to run in parallel. back_prop: Whether backprop is enabled for this while loop. swap_memory: Whether GPU-CPU memory swap is enabled for this loop. name: Optional name prefix for the returned tensors. grad_state: The gradient loop state. context_def: Optional `WhileContextDef` protocol buffer to initialize the `Whilecontext` python object from. import_scope: Optional `string`. Name scope to add. Only used when initialing from protocol buffer. """ if context_def: self._init_from_proto(context_def, import_scope=import_scope) else: ControlFlowContext.__init__(self) self._init_from_args(parallel_iterations, back_prop, swap_memory, name) # The gradient loop state. self._grad_state = grad_state def _init_from_args(self, parallel_iterations, back_prop, swap_memory, name): """Creates a new `WhileContext` from arguments. Args: parallel_iterations: The number of iterations allowed to run in parallel. back_prop: Whether backprop is enabled for this while loop. swap_memory: Whether GPU-CPU memory swap is enabled for this loop. name: Optional name prefix for the returned tensors. Raises: ValueError: If `parallel_iterations` has invalid value. """ if not isinstance(parallel_iterations, int) or (parallel_iterations <= 0): raise ValueError("`parallel_iterations` must be a positive integer: " "%s" % parallel_iterations) self._name = ops.get_default_graph().unique_name(name) self._parallel_iterations = parallel_iterations self._back_prop = back_prop self._swap_memory = swap_memory # We use this node to control constants created by the pred lambda. self._pivot_for_pred = None # We use this node to control constants created by the body lambda. self._pivot_for_body = None # The boolean tensor for loop termination condition. Used in code # generation for gradient computation self._pivot = None # The list of exit tensors for loop variables. self._loop_exits = [] # The list of enter tensors for loop variables. self._loop_enters = [] def _init_from_proto(self, context_def, import_scope=None): """Creates a new `WhileContext` from protocol buffer. Args: context_def: `WhileContextDef` protocol buffer. import_scope: Optional `string`. Name scope to add. """ assert isinstance(context_def, control_flow_pb2.WhileContextDef) # Create from context_def. g = ops.get_default_graph() self._name = ops.prepend_name_scope( context_def.context_name, import_scope) self._parallel_iterations = context_def.parallel_iterations self._back_prop = context_def.back_prop self._swap_memory = context_def.swap_memory self._pivot_for_pred = g.as_graph_element(ops.prepend_name_scope( context_def.pivot_for_pred_name, import_scope)) # We use this node to control constants created by the body lambda. self._pivot_for_body = g.as_graph_element(ops.prepend_name_scope( context_def.pivot_for_body_name, import_scope)) # The boolean tensor for loop termination condition. Used in code # generation for gradient computation. self._pivot = g.as_graph_element( ops.prepend_name_scope(context_def.pivot_name, import_scope)) # The list of exit tensors for loop variables. self._loop_exits = [g.as_graph_element( ops.prepend_name_scope(exit_name, import_scope)) for exit_name in context_def.loop_exit_names] # The list of enter tensors for loop variables. self._loop_enters = [g.as_graph_element( ops.prepend_name_scope(enter_name, import_scope)) for enter_name in context_def.loop_enter_names] super(WhileContext, self).__init__(values_def=context_def.values_def, import_scope=import_scope) @property def name(self): return self._name @property def parallel_iterations(self): """The number of iterations allowed to run in parallel.""" return self._parallel_iterations @property def back_prop(self): """True iff backprop is enabled for this while loop.""" return self._back_prop @property def swap_memory(self): """True iff GPU-CPU memory swap is enabled for this while loop.""" return self._swap_memory @property def pivot(self): """The boolean tensor representing the loop termination condition.""" return self._pivot @property def loop_enters(self): """The list of enter tensors for loop variables.""" return self._loop_enters @property def loop_exits(self): """The list of exit tensors for loop variables.""" return self._loop_exits @property def grad_state(self): """The gradient loop state.""" return self._grad_state def to_proto(self, export_scope=None): """Converts a `WhileContext` to a `WhileContextDef` protocol buffer. Args: export_scope: Optional `string`. Name scope to remove. Returns: A `WhileContextDef` protocol buffer. """ if (export_scope is None or self.name.startswith(export_scope)): context_def = control_flow_pb2.WhileContextDef() context_def.context_name = ops.strip_name_scope( self.name, export_scope) context_def.parallel_iterations = self._parallel_iterations context_def.back_prop = self._back_prop context_def.swap_memory = self._swap_memory context_def.pivot_for_pred_name = ops.strip_name_scope( self._pivot_for_pred.name, export_scope) context_def.pivot_for_body_name = ops.strip_name_scope( self._pivot_for_body.name, export_scope) context_def.pivot_name = ops.strip_name_scope( self._pivot.name, export_scope) context_def.loop_exit_names.extend( [ops.strip_name_scope(l.name, export_scope) for l in self._loop_exits]) context_def.loop_enter_names.extend( [ops.strip_name_scope(l.name, export_scope) for l in self._loop_enters]) context_def.values_def.MergeFrom( super(WhileContext, self)._to_proto( export_scope=export_scope)) return context_def else: return None @staticmethod def from_proto(context_def, import_scope=None): """Returns a `WhileContext` object created from `context_def`. Args: context_def: A `WhileContextDef` protocol buffer. import_scope: Optional `string`. Name scope to add. Returns: A `WhileContext` Python object. """ return WhileContext(context_def=context_def, import_scope=import_scope) def GetWhileContext(self): return self def GetControlPivot(self): if self._pivot_for_body is not None: return self._pivot_for_body return self._pivot_for_pred def AddValue(self, val): """Add `val` to the current context and its outer context recursively.""" result = val if val.name not in self._values: self._values.add(val.name) # If we are in a grad context and val is from its forward context, # use GetRealValue(), which adds the logic to save the history of # val in forward. grad_ctxt = ops.get_default_graph()._get_control_flow_context() if grad_ctxt: grad_ctxt = grad_ctxt.GetWhileContext() if grad_ctxt.grad_state: forward_ctxt = _GetWhileContext(val.op) if IsLoopExit(val.op): forward_ctxt = forward_ctxt.outer_context if forward_ctxt: forward_ctxt = forward_ctxt.GetWhileContext() if forward_ctxt == grad_ctxt.grad_state.forward_context: real_val = grad_ctxt.grad_state.GetRealValue(val) self._external_values[val.name] = real_val return real_val if self._outer_context is not None: result = self._outer_context.AddValue(val) # Create an Enter to make `result` known to this loop context. with ops.control_dependencies(None): enter = _Enter(result, self._name, is_constant=True, parallel_iterations=self._parallel_iterations) enter.graph.prevent_feeding(enter) if self._outer_context: self._outer_context.AddInnerOp(enter.op) # Fix the control inputs and control flow context of these enter ops. self._FixControlInputsAndContext([enter]) # Add `enter` in this context. self._values.add(enter.name) self._external_values[val.name] = enter result = enter else: actual_val = self._external_values.get(val.name) if actual_val is not None: result = actual_val return result def AddOp(self, op): """Add `op` to the current context.""" # For a reduction op, if op is in a grad context and its input is from # its forward context, moving op to the forward context means we would # store the tensor after the reduction as opposed to the tensor before # reduction, and therefore could significantly reduce memory consumption. # For now, we do this only for a few ops. if op.type in {"Shape", "Size", "Rank"}: grad_ctxt = ops.get_default_graph()._get_control_flow_context() if grad_ctxt: grad_ctxt = grad_ctxt.GetWhileContext() if grad_ctxt.grad_state: op_input_forward_ctxt = _GetWhileContext(op.inputs[0].op) if op_input_forward_ctxt == grad_ctxt.grad_state.forward_context: op_input_ctxt = op.inputs[0].op._get_control_flow_context() op._set_control_flow_context(op_input_ctxt) op_input_ctxt._AddOpInternal(op) return self._AddOpInternal(op) def _AddOpInternal(self, op): """Add `op` to the current context. In the case that op has only external data inputs, we remove all of its external control inputs so all its inputs are in the same while loop context. This is valid because op now has an Enter input that has all the right control dependency. """ if not op.inputs: # Remove any external control dependency on this op control_inputs = self._RemoveExternalControlEdges(op) # Add a control edge from the control pivot to this op. if not control_inputs: # pylint: disable=protected-access op._add_control_input(self.GetControlPivot().op) # pylint: enable=protected-access for x in op.outputs: self._values.add(x.name) else: for index in range(len(op.inputs)): x = op.inputs[index] real_x = self.AddValue(x) if real_x != x: op._update_input(index, real_x) # Remove any external control dependency on this op. self._RemoveExternalControlEdges(op) # Add a control dependency to prevent loop invariants from # enabling ops that should not be executed. self._MaybeAddControlDependency(op) for x in op.outputs: self._values.add(x.name) if self._outer_context or not IsLoopExit(op): op.graph.prevent_fetching(op) for x in op.outputs: op.graph.prevent_feeding(x) if self._outer_context: self._outer_context.AddInnerOp(op) def _MaybeAddControlDependency(self, op): """Add a control input to the op if it only depends on loop invariants.""" def _IsOpFree(op): """Determines if `op` needs a control dependency.""" if op.control_inputs: return False # pylint: disable=protected-access if op.graph._is_function(op.type) or op.type == "SymbolicGradient": return True # pylint: enable=protected-access for x in op.inputs: if not _IsLoopConstantEnter(x.op): return False return True if _IsOpFree(op): # pylint: disable=protected-access op._add_control_input(self.GetControlPivot().op) # pylint: enable=protected-access def AddForwardLoopCounter(self, outer_grad_state): """Adds a loop that counts the number of iterations. This is added to the forward loop at the time when we start to create the loop for backprop gradient computation. Called in the outer context of this forward context. The pseudocode is: `n = 0; while (_pivot) { n++; }` Note that a control dependency is added to `n` to ensure the correct execution order of stack push ops. Args: outer_grad_state: The outer grad state. None if not nested. Returns: The number of iterations taken by the forward loop and the loop index. """ n = constant_op.constant(0, name="f_count") if outer_grad_state is not None: # Force the stack pushes of i-th execution of an inner loop to be ordered # before the pushes of (i+1)-th execution of the same inner loop. outer_add_op = outer_grad_state.forward_index.op.inputs[0].op n.op._add_control_input(outer_add_op) # pylint: disable=protected-access self.Enter() self.AddName(n.name) enter_n = _Enter(n, self._name, is_constant=False, parallel_iterations=self._parallel_iterations, name="f_count") self.loop_enters.append(enter_n) merge_n = merge([enter_n, enter_n])[0] switch_n = switch(merge_n, self._pivot) index = math_ops.add(switch_n[1], 1) next_n = _NextIteration(index) merge_n.op._update_input(1, next_n) total_iterations = exit(switch_n[0], name="f_count") self.loop_exits.append(total_iterations) self.ExitResult([total_iterations]) self.Exit() return total_iterations, next_n def AddBackPropLoopCounter(self, count, outer_grad_state): """Add the backprop loop that controls the iterations. This is added to the backprop loop. It is used to control the loop termination of the backprop loop. Called in the outer context of this grad context. The pseudocode is: `n = count; while (n >= 1) { n--; }` Note that a control dependency is added to `final_zero` to ensure the correct execution order of stack pop ops. Args: count: The number of iterations for backprop. outer_grad_state: The outer grad state. None if not nested. Returns: The loop index. """ one = constant_op.constant(1, name="b_count") self.Enter() self.AddName(count.name) enter_count = _Enter(count, self._name, is_constant=False, parallel_iterations=self._parallel_iterations, name="b_count") self.loop_enters.append(enter_count) merge_count = merge([enter_count, enter_count])[0] self._pivot_for_pred = merge_count pred = math_ops.greater_equal(merge_count, one) self._pivot = loop_cond(pred, name="b_count") switch_count = switch(merge_count, self._pivot) index = math_ops.subtract(switch_count[1], one) self._pivot_for_body = index next_count = _NextIteration(index) merge_count.op._update_input(1, next_count) final_zero = exit(switch_count[0], name="b_count") self.loop_exits.append(final_zero) if outer_grad_state is not None: # Force the stack pops of i-th execution of an inner loop to be ordered # before the pops of (i+1)-th execution of the same inner loop. # pylint: disable=protected-access outer_grad_state.grad_sync._add_control_input(final_zero.op) # pylint: enable=protected-access self.ExitResult([final_zero]) self.Exit() return next_count def AddBackPropAccumulator(self, op, grad): """Add an accumulation loop for every loop invariant. This is added to the backprop loop. It is used to accumulate partial gradients within each loop iteration. Called when in the gradient while context. The pseudocode is: ``` acc = 0.0; while (_pivot) { acc += grad; } ``` Args: op: The Enter op for a loop invariant. grad: The partial gradient of an iteration for a loop invariant. Returns: The gradient for a loop invariant. """ self.Exit() # Create a zeros tensor with the right shape for acc. If we don't # know the full shape statically, we will have to get the shape # dynamically from the forward inference. Getting the shape right # for the zeros is only needed for the base case when the loop exits # without running any iterations. shape = grad.get_shape() if shape.is_fully_defined(): if self.outer_context: self.outer_context.Enter() acc = constant_op.constant(0, grad.dtype, shape=shape, name="b_acc") if self.outer_context: self.outer_context.Exit() else: value = op.inputs[0] if (isinstance(self.outer_context, WhileContext) and self.outer_context.grad_state is not None): # We are in a nested while loop. forward_ctxt = self.grad_state.forward_context forward_ctxt.outer_context.Enter() zeros_shape = array_ops.shape_internal(value, optimize=False) forward_ctxt.outer_context.Exit() outer_grad_state = self.grad_state.outer_grad_state history_zeros_shape = outer_grad_state.AddForwardAccumulator( zeros_shape) self.outer_context.Enter() real_shape = outer_grad_state.AddBackPropAccumulatedValue( history_zeros_shape, zeros_shape) acc = array_ops.zeros(real_shape, grad.dtype) self.outer_context.Exit() else: if self.outer_context: self.outer_context.Enter() zeros_shape = array_ops.shape_internal(value, optimize=False) acc = array_ops.zeros(zeros_shape, grad.dtype) if self.outer_context: self.outer_context.Exit() acc._shape = grad.get_shape() # pylint: disable=protected-access self.Enter() self.AddName(acc.name) enter_acc = _Enter(acc, self._name, is_constant=False, parallel_iterations=self._parallel_iterations, name="b_acc") self.loop_enters.append(enter_acc) merge_acc = merge([enter_acc, enter_acc], name="b_acc")[0] switch_acc_false, switch_acc_true = switch(merge_acc, self._pivot) add_acc = math_ops.add(switch_acc_true, grad) next_acc = _NextIteration(add_acc) merge_acc.op._update_input(1, next_acc) # pylint: disable=protected-access result_acc = exit(switch_acc_false, name="b_acc") self.loop_exits.append(result_acc) self.ExitResult([result_acc]) return result_acc def AddBackPropIndexedSlicesAccumulator(self, op, grad): """This is used for accumulating gradients that are IndexedSlices. This is essentially the equavalent of AddBackPropAccumulator but optimized for things like updating embeddings from within a while loop. Args: op: The Enter op for a loop invariant. grad: The partial gradients represented as an IndexedSlices. Returns: The accumulated IndexedSlices gradient of the loop invariant. """ values = grad.values indices = grad.indices dense_shape = grad.dense_shape self.Exit() if self.outer_context: self.outer_context.Enter() if values.get_shape().is_fully_defined(): values_shape = tensor_shape.TensorShape( [tensor_shape.Dimension(1)] + values.get_shape().dims[1:]) if self.outer_context: self.outer_context.Enter() values_acc = constant_op.constant(0, values.dtype, shape=values_shape, name="b_acc") if self.outer_context: self.outer_context.Exit() else: values_shape = _resource_safe_shape(op.inputs[0])[1:] values_shape = array_ops.concat([[1], values_shape], 0) values_acc = array_ops.zeros(values_shape, dtype=values.dtype) indices_acc = constant_op.constant([0], indices.dtype) shape_acc = None if dense_shape is not None: if dense_shape.get_shape().is_fully_defined(): if self.outer_context: self.outer_context.Enter() shape_acc = constant_op.constant(0, dense_shape.dtype, shape=dense_shape.get_shape()) if self.outer_context: self.outer_context.Exit() else: shape_acc = array_ops.zeros_like( array_ops.shape_internal(op.inputs[0], optimize=False), optimize=False) if self.outer_context: self.outer_context.Exit() self.Enter() self.AddName(values_acc.name) self.AddName(indices_acc.name) init_acc = [indices_acc, values_acc] if shape_acc is not None: self.AddName(shape_acc.name) init_acc.append(shape_acc) enter_acc = [_Enter(x, self._name, is_constant=False, parallel_iterations=self._parallel_iterations, name="b_acc") for x in init_acc] self.loop_enters.extend(enter_acc) merge_acc = [merge([x, x], name="b_acc")[0] for x in enter_acc] switch_acc = [switch(x, self._pivot) for x in merge_acc] # The actual accumulation. acc_indexed_slices = [ array_ops.concat([xa[1], xv], 0) for xa, xv in zip(switch_acc[:2], [indices, values]) ] if shape_acc is not None: # For the shape we just keep the maximum acc_indexed_slices.append( math_ops.maximum(dense_shape, switch_acc[2][1])) next_acc = [_NextIteration(x) for x in acc_indexed_slices] for xm, xn in zip(merge_acc, next_acc): xm.op._update_input(1, xn) # pylint: disable=protected-access exit_acc = [exit(x[0], name="b_acc") for x in switch_acc] self.loop_exits.extend(exit_acc) self.ExitResult(exit_acc) return ops.IndexedSlices( indices=exit_acc[0], values=exit_acc[1], dense_shape=exit_acc[2] if shape_acc is not None else None) def _InitializeValues(self, values): """Makes the values known to this context.""" self._values = set() for x in values: if isinstance(x, ops.Tensor): self._values.add(x.name) else: self._values.add(x.values.name) self._values.add(x.indices.name) if isinstance(x, ops.IndexedSlices): dense_shape = x.dense_shape elif isinstance(x, sparse_tensor.SparseTensor): dense_shape = x.dense_shape else: raise TypeError("Type %s not supported" % type(x)) if dense_shape is not None: self._values.add(dense_shape.name) def _BuildLoop(self, pred, body, original_loop_vars, loop_vars, shape_invariants): """Core: Add the loop termination condition and body to the graph.""" flat_loop_vars = nest.flatten(original_loop_vars) # Let the context know the loop variables so the loop variables # would be added in the outer contexts properly. self._InitializeValues(loop_vars) real_vars = loop_vars if self._outer_context: real_vars = [self._outer_context.AddValue(x) for x in loop_vars] with ops.control_dependencies(None): enter_vars = [_Enter(x, self._name, is_constant=False, parallel_iterations=self._parallel_iterations, use_input_shape=(shape_invariants is None)) for x in real_vars] for x in enter_vars: x.graph.prevent_feeding(x) if self._outer_context: self._outer_context.AddInnerOp(x.op) # Finds the closest enclosing non-None control pivot. outer_context = self._outer_context control_pivot = None while outer_context is not None and control_pivot is None: control_pivot = outer_context.GetControlPivot() # pylint: disable=protected-access outer_context = outer_context._outer_context # pylint: enable=protected-access if control_pivot is not None: for var in enter_vars: if _IsLoopConstantEnter(var.op.inputs[0].op): # pylint: disable=protected-access var.op._add_control_input(control_pivot.op) # pylint: enable=protected-access _SetShapeInvariants(real_vars, enter_vars, shape_invariants) # Fix the control inputs and control flow context of these enter ops. self._FixControlInputsAndContext(enter_vars) self._InitializeValues(enter_vars) self._loop_enters = enter_vars merge_vars = [merge([x, x])[0] for x in enter_vars] self._pivot_for_pred = merge_vars[0] # Build the graph for pred. merge_vars_with_tensor_arrays = ( _convert_flows_to_tensorarrays(flat_loop_vars, merge_vars)) packed_vars = nest.pack_sequence_as( structure=original_loop_vars, flat_sequence=merge_vars_with_tensor_arrays) c = ops.convert_to_tensor(pred(*packed_vars)) self._pivot = loop_cond(c, name="LoopCond") switch_vars = [_SwitchRefOrTensor(x, self._pivot) for x in merge_vars] # Build the graph for body. vars_for_body = [_Identity(x[1]) for x in switch_vars] self._pivot_for_body = vars_for_body[0] # Convert TensorArray flow variables inside the context back into # their associated TensorArrays for calling the body. vars_for_body_with_tensor_arrays = ( _convert_flows_to_tensorarrays(flat_loop_vars, vars_for_body)) packed_vars_for_body = nest.pack_sequence_as( structure=original_loop_vars, flat_sequence=vars_for_body_with_tensor_arrays) body_result = body(*packed_vars_for_body) if not nest.is_sequence(body_result): body_result = [body_result] # Compare the structure types of input and output of body. # For backwards compatibility, the first layer is forced to a list # during this comparison, because inputs are typically lists and # outputs of the body are typically tuples. nest.assert_same_structure(list(packed_vars_for_body), list(body_result)) # Store body_result to keep track of TensorArrays returned by body original_body_result = body_result # Convert TensorArrays returned by body into their flow variables result = nest.map_structure(_convert_tensorarray_to_flow, nest.flatten(body_result)) result = ops.convert_n_to_tensor_or_indexed_slices(result) # Add NextIteration and the back edges to complete the loop. if len(merge_vars) != len(result): raise ValueError("Number of inputs and outputs of body must match " "loop_vars: %d, %d" % (len(merge_vars), len(result))) next_vars = [] for m, v in zip(merge_vars, result): next_vars.append(_AddNextAndBackEdge(m, v)) # Add the exit ops. exit_vars = [exit(x[0]) for x in switch_vars] self._loop_exits = exit_vars # Make sure the shapes of loop outputs are correct. for m_var, n_var in zip(merge_vars, next_vars): if isinstance(m_var, ops.Tensor): _EnforceShapeInvariant(m_var, n_var) # Exit the loop. self.ExitResult(exit_vars) return original_body_result, exit_vars def BuildLoop(self, pred, body, loop_vars, shape_invariants): """Add the loop termination condition and body to the graph.""" # Keep original_loop_vars to identify which are TensorArrays original_loop_vars = loop_vars # Convert TensorArrays to their flow variables loop_vars = nest.map_structure(_convert_tensorarray_to_flow, nest.flatten(loop_vars)) loop_vars = ops.convert_n_to_tensor_or_indexed_slices(loop_vars) try: self.Enter() original_body_result, exit_vars = self._BuildLoop( pred, body, original_loop_vars, loop_vars, shape_invariants) finally: self.Exit() flat_result = nest.flatten(original_body_result) # Convert TensorArray flow variables outside the context back into # their associated TensorArrays for returning to caller. exit_vars_with_tensor_arrays = ( _convert_flows_to_tensorarrays(flat_result, exit_vars)) packed_exit_vars = nest.pack_sequence_as( structure=original_body_result, flat_sequence=exit_vars_with_tensor_arrays) return (packed_exit_vars[0] if len(exit_vars) == 1 else packed_exit_vars) def _FixControlInputsAndContext(self, enters): graph = ops.get_default_graph() # pylint: disable=protected-access for e in enters: if isinstance(e, ops.Tensor): xs = [e] else: if not isinstance(e, (ops.IndexedSlices, sparse_tensor.SparseTensor)): raise TypeError("Type %s not supported" % type(e)) xs = [e.values, e.indices] shape = e.dense_shape if shape is not None: xs.append(shape) for x in xs: inp_op = x.op.inputs[0] control_inputs = graph._control_dependencies_for_inputs([inp_op]) outer_control_inputs = [op for op in control_inputs if self._IsInOuterContext(op)] x.op._set_control_flow_context(self) x.op._add_control_inputs(outer_control_inputs) graph._record_op_seen_by_control_dependencies(x.op) # pylint: enable=protected-access def while_loop(cond, body, loop_vars, shape_invariants=None, parallel_iterations=10, back_prop=True, swap_memory=False, name=None): """Repeat `body` while the condition `cond` is true. `cond` is a callable returning a boolean scalar tensor. `body` is a callable returning a (possibly nested) tuple, namedtuple or list of tensors of the same arity (length and structure) and types as `loop_vars`. `loop_vars` is a (possibly nested) tuple, namedtuple or list of tensors that is passed to both `cond` and `body`. `cond` and `body` both take as many arguments as there are `loop_vars`. In addition to regular Tensors or IndexedSlices, the body may accept and return TensorArray objects. The flows of the TensorArray objects will be appropriately forwarded between loops and during gradient calculations. Note that `while_loop` calls `cond` and `body` *exactly once* (inside the call to `while_loop`, and not at all during `Session.run()`). `while_loop` stitches together the graph fragments created during the `cond` and `body` calls with some additional graph nodes to make something the repeats `body` until `cond` returns false. For correctness, `tf.while_loop()` strictly enforces shape invariants for the loop variables. A shape invariant is a (possibly partial) shape that is unchanged across the iterations of the loop. An error will be raised if the shape of a loop variable after an iteration is determined to be more general than or incompatible with its shape invariant. For example, a shape of [11, None] is more general than a shape of [11, 17], and [11, 21] is not compatible with [11, 17]. By default (if the argument `shape_invariants` is not specified), it is assumed that the initial shape of each tensor in `loop_vars` is the same in every iteration. The `shape_invariants` argument allows the caller to specify a less specific shape invariant for each loop variable, which is needed if the shape varies between iterations. The @{tf.Tensor.set_shape} function may also be used in the `body` function to indicate that the output loop variable has a particular shape. The shape invariant for SparseTensor and IndexedSlices are treated specially as follows: a) If a loop variable is a SparseTensor, the shape invariant must be TensorShape([r]) where r is the rank of the dense tensor represented by the sparse tensor. It means the shapes of the three tensors of the SparseTensor are ([None], [None, r], [r]). NOTE: The shape invariant here is the shape of the SparseTensor.dense_shape property. It must be the shape of a vector. b) If a loop variable is an IndexedSlices, the shape invariant must be a shape invariant of the values tensor of the IndexedSlices. It means the shapes of the three tensors of the IndexedSlices are (shape, [shape[0]], [shape.ndims]). `while_loop` implements non-strict semantics, enabling multiple iterations to run in parallel. The maximum number of parallel iterations can be controlled by `parallel_iterations`, which gives users some control over memory consumption and execution order. For correct programs, `while_loop` should return the same result for any parallel_iterations > 0. For training, TensorFlow remembers the tensors that are produced in the forward inference but needed in back propagation. These tensors can be a main source of memory consumption and often cause OOM problems when training on GPUs. When the flag swap_memory is true, we swap out these tensors from GPU to CPU. This for example allows us to train RNN models with very long sequences and large batches. Args: cond: A callable that represents the termination condition of the loop. body: A callable that represents the loop body. loop_vars: A (possibly nested) tuple, namedtuple or list of numpy array, `Tensor`, and `TensorArray` objects. shape_invariants: The shape invariants for the loop variables. parallel_iterations: The number of iterations allowed to run in parallel. It must be a positive integer. back_prop: Whether backprop is enabled for this while loop. swap_memory: Whether GPU-CPU memory swap is enabled for this loop. name: Optional name prefix for the returned tensors. Returns: The output tensors for the loop variables after the loop. When the length of `loop_vars` is 1 this is a Tensor, TensorArray or IndexedSlice and when the length of `loop_vars` is greater than 1 it returns a list. Raises: TypeError: if `cond` or `body` is not callable. ValueError: if `loop_vars` is empty. Example: ```python i = tf.constant(0) c = lambda i: tf.less(i, 10) b = lambda i: tf.add(i, 1) r = tf.while_loop(c, b, [i]) ``` Example with nesting and a namedtuple: ```python import collections Pair = collections.namedtuple('Pair', 'j, k') ijk_0 = (tf.constant(0), Pair(tf.constant(1), tf.constant(2))) c = lambda i, p: i < 10 b = lambda i, p: (i + 1, Pair((p.j + p.k), (p.j - p.k))) ijk_final = tf.while_loop(c, b, ijk_0) ``` Example using shape_invariants: ```python i0 = tf.constant(0) m0 = tf.ones([2, 2]) c = lambda i, m: i < 10 b = lambda i, m: [i+1, tf.concat([m, m], axis=0)] tf.while_loop( c, b, loop_vars=[i0, m0], shape_invariants=[i0.get_shape(), tf.TensorShape([None, 2])]) ``` """ with ops.name_scope(name, "while", loop_vars): if not loop_vars: raise ValueError("No loop variables provided") if not callable(cond): raise TypeError("cond must be callable.") if not callable(body): raise TypeError("body must be callable.") if parallel_iterations < 1: raise TypeError("parallel_iterations must be a positive integer.") if shape_invariants is not None: nest.assert_same_structure(loop_vars, shape_invariants) context = WhileContext(parallel_iterations, back_prop, swap_memory) ops.add_to_collection(ops.GraphKeys.WHILE_CONTEXT, context) result = context.BuildLoop(cond, body, loop_vars, shape_invariants) return result def _AsTensorList(x, p): """Return x as a list of Tensors or IndexedSlices. For entries of `x` that are Operations, this returns an Identity of `p` with a dependency on the operation. Args: x: A Tensor/IndexedSlices/Operation or a list or tuple of them. p: A Tensor to return for entries in `x` that are Operations. Returns: A list of Tensors or IndexedSlices. """ if not isinstance(x, (list, _basetuple)): x = [x] l = [] for v in x: if isinstance(v, ops.Operation): v = with_dependencies([v], p) v = ops.convert_to_tensor_or_indexed_slices(v) if isinstance(v, ops.Tensor): l.append(array_ops.identity(v)) else: l.append(ops.IndexedSlices(array_ops.identity(v.values), array_ops.identity(v.indices))) return l def _CheckResults(a, b): assert len(a) == len(b), ( "Values returned by a() and b() must have the same length.") for x, y in zip(a, b): assert x.dtype == y.dtype, ( "Values returned by a() [%s] and b() [%s] must have " "the same type: %s, %s." % (x.name, y.name, x.dtype.name, y.dtype.name)) def with_dependencies(dependencies, output_tensor, name=None): """Produces the content of `output_tensor` only after `dependencies`. In some cases, a user may want the output of an operation to be consumed externally only after some other dependencies have run first. This function ensures returns `output_tensor`, but only after all operations in `dependencies` have run. Note that this means that there is no guarantee that `output_tensor` will be evaluated after any `dependencies` have run. See also @{tf.tuple$tuple} and @{tf.group$group}. Args: dependencies: Iterable of operations to run before this op finishes. output_tensor: A `Tensor` or `IndexedSlices` that will be returned. name: (Optional) A name for this operation. Returns: Same as `output_tensor`. Raises: TypeError: if `output_tensor` is not a `Tensor` or `IndexedSlices`. """ with ops.name_scope(name, "control_dependency", list(dependencies) + [output_tensor]) as name: with ops.colocate_with(output_tensor): with ops.control_dependencies(dependencies): output_tensor = ops.convert_to_tensor_or_indexed_slices(output_tensor) if isinstance(output_tensor, ops.Tensor): return _Identity(output_tensor, name=name) else: return ops.IndexedSlices(_Identity(output_tensor.values, name=name), output_tensor.indices, output_tensor.dense_shape) def _GroupControlDeps(dev, deps, name=None): with ops.control_dependencies(deps): if dev is None: return no_op(name=name) else: with ops.device(dev): return no_op(name=name) # TODO(touts): Accept "inputs" as a list. def group(*inputs, **kwargs): """Create an op that groups multiple operations. When this op finishes, all ops in `input` have finished. This op has no output. See also @{tf.tuple$tuple} and @{tf.control_dependencies$control_dependencies}. Args: *inputs: Zero or more tensors to group. **kwargs: Optional parameters to pass when constructing the NodeDef. name: A name for this operation (optional). Returns: An Operation that executes all its inputs. Raises: ValueError: If an unknown keyword argument is provided. """ name = kwargs.pop("name", None) if kwargs: raise ValueError("Unknown keyword arguments: " + ", ".join(kwargs.keys())) with ops.name_scope(name, "group_deps", inputs) as name: # Grouping no inputs means do nothing if not inputs: return no_op(name=name) # Sorts *inputs according to their devices. ops_on_device = {} # device -> operations specified on the device. for inp in inputs: dev = inp.device if dev in ops_on_device: ops_on_device[dev].append(inp) else: ops_on_device[dev] = [inp] if len(ops_on_device) == 1: # 1-level tree. The root node is the returned NoOp node. (dev, deps), = ops_on_device.items() return _GroupControlDeps(dev, deps, name=name) # 2-level tree. The root node is the returned NoOp node. # deps contains 1 NoOp node for each device. deps = [] def device_key(dev): """A sort key that allows None to be compared to strings.""" return "" if dev is None else dev for dev in sorted(six.iterkeys(ops_on_device), key=device_key): deps.append(_GroupControlDeps(dev, ops_on_device[dev])) with ops.control_dependencies(deps): return no_op(name=name) def tuple(tensors, name=None, control_inputs=None): """Group tensors together. This creates a tuple of tensors with the same values as the `tensors` argument, except that the value of each tensor is only returned after the values of all tensors have been computed. `control_inputs` contains additional ops that have to finish before this op finishes, but whose outputs are not returned. This can be used as a "join" mechanism for parallel computations: all the argument tensors can be computed in parallel, but the values of any tensor returned by `tuple` are only available after all the parallel computations are done. See also @{tf.group$group} and @{tf.control_dependencies$control_dependencies}. Args: tensors: A list of `Tensor`s or `IndexedSlices`, some entries can be `None`. name: (optional) A name to use as a `name_scope` for the operation. control_inputs: List of additional ops to finish before returning. Returns: Same as `tensors`. Raises: ValueError: If `tensors` does not contain any `Tensor` or `IndexedSlices`. TypeError: If `control_inputs` is not a list of `Operation` or `Tensor` objects. """ with ops.name_scope(name, "tuple", tensors) as name: gating_ops = [t.op for t in tensors if t is not None] if control_inputs: for c in control_inputs: if isinstance(c, ops.Tensor): c = c.op elif not isinstance(c, ops.Operation): raise TypeError("Control input must be Operation or Tensor: %s" % c) gating_ops.append(c) # Note that in order to ensure ordering in the pbtxt, we must take care to # ensure the order here. gating_ops = sorted(set(gating_ops), key=lambda op: op._id) # Uniquify ops. if not gating_ops: raise ValueError("Must have at least one Tensor: %s" % tensors) gate = group(*gating_ops) tpl = [] for t in tensors: if t is not None: tpl.append(with_dependencies([gate], t)) else: tpl.append(None) return tpl def case(pred_fn_pairs, default, exclusive=False, strict=False, name="case"): """Create a case operation. The `pred_fn_pairs` parameter is a dict or list of pairs of size N. Each pair contains a boolean scalar tensor and a python callable that creates the tensors to be returned if the boolean evaluates to True. `default` is a callable generating a list of tensors. All the callables in `pred_fn_pairs` as well as `default` should return the same number and types of tensors. If `exclusive==True`, all predicates are evaluated, and an exception is thrown if more than one of the predicates evaluates to `True`. If `exclusive==False`, execution stops are the first predicate which evaluates to True, and the tensors generated by the corresponding function are returned immediately. If none of the predicates evaluate to True, this operation returns the tensors generated by `default`. `tf.case` supports nested structures as implemented in `tensorflow.python.util.nest`. All of the callables must return the same (possibly nested) value structure of lists, tuples, and/or named tuples. Singleton lists and tuples form the only exceptions to this: when returned by a callable, they are implicitly unpacked to single values. This behavior is disabled by passing `strict=True`. If an unordered dictionary is used for `pred_fn_pairs`, the order of the conditional tests is not guaranteed. However, the order is guaranteed to be deterministic, so that variables created in conditional branches are created in fixed order across runs. Example 1: Pseudocode: ``` if (x < y) return 17; else return 23; ``` Expressions: ``` f1 = lambda: tf.constant(17) f2 = lambda: tf.constant(23) r = case([(tf.less(x, y), f1)], default=f2) ``` Example 2: Pseudocode: ``` if (x < y && x > z) raise OpError("Only one predicate may evaluate true"); if (x < y) return 17; else if (x > z) return 23; else return -1; ``` Expressions: ``` def f1(): return tf.constant(17) def f2(): return tf.constant(23) def f3(): return tf.constant(-1) r = case({tf.less(x, y): f1, tf.greater(x, z): f2}, default=f3, exclusive=True) ``` Args: pred_fn_pairs: Dict or list of pairs of a boolean scalar tensor and a callable which returns a list of tensors. default: A callable that returns a list of tensors. exclusive: True iff at most one predicate is allowed to evaluate to `True`. strict: A boolean that enables/disables 'strict' mode; see above. name: A name for this operation (optional). Returns: The tensors returned by the first pair whose predicate evaluated to True, or those returned by `default` if none does. Raises: TypeError: If `pred_fn_pairs` is not a list/dictionary. TypeError: If `pred_fn_pairs` is a list but does not contain 2-tuples. TypeError: If `fns[i]` is not callable for any i, or `default` is not callable. """ pfp = pred_fn_pairs # For readability if not (isinstance(pfp, list) or isinstance(pfp, _basetuple) or isinstance(pfp, dict)): raise TypeError("fns must be a list, tuple, or dict") if isinstance(pfp, dict): if isinstance(pfp, collections.OrderedDict): pfp = pfp.items() else: pfp = sorted(pfp.items(), key=lambda item: item[0].name) if not exclusive: logging.warn("%s: An unordered dictionary of predicate/fn pairs was " "provided, but exclusive=False. The order of conditional " "tests is deterministic but not guaranteed.", name) for tup in pfp: if not isinstance(tup, _basetuple) or len(tup) != 2: raise TypeError("Each entry in pred_fn_pairs must be a 2-tuple") pred, fn = tup if pred.dtype != dtypes.bool: raise TypeError("pred must be of type bool: %s", pred.name) if not callable(fn): raise TypeError("fn for pred %s must be callable." % pred.name) if not callable(default): raise TypeError("default must be callable.") preds, fns = map(list, zip(*pfp)) with ops.name_scope(name, "case", [preds]): if not preds: return default() not_preds = [] for i, p in enumerate(preds): with ops.name_scope("not_%d" % i): not_preds.append(math_ops.logical_not(p)) and_not_preds = [constant_op.constant(True, name="always_true")] for i, notp in enumerate(not_preds): with ops.name_scope("and_not_%d" % i): and_not_preds.append(math_ops.logical_and(and_not_preds[-1], notp)) # preds = [p1, p2, p3] # fns = [f1, f2, f3] # not_preds = [~p1, ~p2, ~p3] # and_not_preds = [True, ~p1, ~p1 & ~p2, ~p1 & ~p2 & ~p3] # case_preds = [p1, # p2 & ~p1, # p3 & ~p2 & ~p1, # ~p3 & ~p2 & ~p1] case_preds = [] for i, (p, and_not_p_prev) in enumerate(zip(preds, and_not_preds[:-1])): with ops.name_scope("case_%d" % i): case_preds.append(math_ops.logical_and(p, and_not_p_prev)) with ops.name_scope("case_none_are_true"): case_preds.append(and_not_preds[-1]) # Create an empty tensor, or list, with the right type and shape with ops.name_scope("case_create_empty"): def _create_empty_constant(dtype, shape): value = ("" if dtype == dtypes.string else dtype.as_numpy_dtype()) if shape.ndims is None: return array_ops.constant(value, dtype=dtype) else: temp_shape = [1 if x.value is None else x.value for x in shape] result = array_ops.constant(value, shape=temp_shape, dtype=dtype) result._shape = shape # pylint: disable=protected-access return result def _correct_empty(v): if isinstance(v, ops.Operation): return no_op() elif isinstance(v, tensor_array_ops.TensorArray): return v elif not hasattr(v, "dtype"): return ops.convert_to_tensor(v) elif isinstance(v, sparse_tensor.SparseTensor): return sparse_tensor.SparseTensor(indices=[[0] * len(v.get_shape())], values=[v.dtype.as_numpy_dtype()], dense_shape=v.get_shape()) else: return _create_empty_constant(v.dtype, v.get_shape()) empty = lambda: nest.map_structure(_correct_empty, default()) # case_sequence = [ # cond(~p3 & ~p2 & ~p1, default, empty), # cond(p3 & ~p2 & ~p1, f3, lambda: case_sequence[0]), # cond(p2 & ~p1, f2, lambda: case_sequence[1]), # cond(p1, f1, lambda: case_sequence[2]) # ] # # And the return value will be case_sequence[-1] def _build_case(): all_fns = [fn for fn in fns] all_fns.append(default) prev_case = None for i, (cp, fn) in enumerate(list(zip(case_preds, all_fns))[::-1]): prev_case = cond( cp, fn, empty if i == 0 else lambda: prev_case, strict=strict, name="If_%d" % i) return prev_case if exclusive: preds_c = array_ops.stack(preds, name="preds_c") num_true_conditions = math_ops.reduce_sum( math_ops.cast(preds_c, dtypes.int32), name="num_true_conds") at_most_one_true_condition = math_ops.less( num_true_conditions, constant_op.constant(2, name="two_true_conds")) error_msg = [ ("More than one condition evaluated as True but " "exclusive=True. Conditions: (%s), Values:" % ", ".join([p.name for p in preds])), preds_c] with ops.control_dependencies([ Assert(condition=at_most_one_true_condition, data=error_msg, summarize=len(preds))]): case_seq = _build_case() else: case_seq = _build_case() if not strict: case_seq = _UnpackIfSingleton(case_seq) return case_seq ops.register_proto_function(ops.GraphKeys.COND_CONTEXT, proto_type=control_flow_pb2.CondContextDef, to_proto=CondContext.to_proto, from_proto=CondContext.from_proto) ops.register_proto_function(ops.GraphKeys.WHILE_CONTEXT, proto_type=control_flow_pb2.WhileContextDef, to_proto=WhileContext.to_proto, from_proto=WhileContext.from_proto)
apache-2.0
ImageEngine/gaffer
python/GafferUITest/CollapsibleTest.py
7
4050
########################################################################## # # Copyright (c) 2011-2012, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with # the distribution. # # * Neither the name of John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import os import unittest import GafferUI import GafferUITest class CollapsibleTest( GafferUITest.TestCase ) : def testConstructor( self ) : b = GafferUI.Button( "Hide Me" ) c = GafferUI.Collapsible( child = b, collapsed=True ) self.assertTrue( c.getChild() is b ) self.assertEqual( c.getCollapsed(), True ) def testSetCollapsed( self ) : c = GafferUI.Collapsible( collapsed=True ) self.assertEqual( c.getCollapsed(), True ) c.setCollapsed( False ) self.assertEqual( c.getCollapsed(), False ) def testStateChangedSignal( self ) : self.__states = [] def stateChanged( widget ) : self.__states.append( widget.getCollapsed( ) ) c = GafferUI.Collapsible( collapsed=True ) stateChangedConnection = c.stateChangedSignal().connect( stateChanged ) c.setCollapsed( False ) self.assertEqual( self.__states, [ False ] ) c.setCollapsed( False ) # shouldn't trigger as state is the same self.assertEqual( self.__states, [ False ] ) c.setCollapsed( True ) self.assertEqual( self.__states, [ False, True ] ) def testCornerWidget( self ) : c = GafferUI.Collapsible( collapsed = True ) self.assertEqual( c.getCornerWidget(), None ) b1 = GafferUI.Button() self.assertEqual( b1.parent(), None ) b2 = GafferUI.Button() self.assertEqual( b1.parent(), None ) c.setCornerWidget( b1 ) self.assertTrue( c.getCornerWidget() is b1 ) self.assertTrue( b1.parent() is c ) c.setCornerWidget( None ) self.assertIsNone( c.getCornerWidget() ) self.assertIsNone( b1.parent() ) c.setCornerWidget( b1 ) self.assertTrue( c.getCornerWidget() is b1 ) self.assertTrue( b1.parent() is c ) c.setCornerWidget( b2 ) self.assertTrue( c.getCornerWidget() is b2 ) self.assertTrue( b2.parent() is c ) self.assertIsNone( b1.parent() ) c.removeChild( b2 ) self.assertIsNone( c.getCornerWidget() ) self.assertIsNone( b2.parent() ) def testTransferChildren( self ) : c = GafferUI.Collapsible() b = GafferUI.Button() l = GafferUI.ListContainer() self.assertEqual( b.parent(), None ) l.append( b ) self.assertTrue( b.parent() is l ) c.setChild( b ) self.assertTrue( b.parent() is c ) self.assertEqual( len( l ), 0 ) if __name__ == "__main__": unittest.main()
bsd-3-clause
d/bazel
third_party/py/gflags/tests/gflags_googletest.py
132
4256
#!/usr/bin/env python # Copyright (c) 2011, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Some simple additions to the unittest framework useful for gflags testing.""" import re import unittest def Sorted(lst): """Equivalent of sorted(), but not dependent on python version.""" sorted_list = lst[:] sorted_list.sort() return sorted_list def MultiLineEqual(expected, actual): """Returns True if expected == actual, or returns False and logs.""" if actual == expected: return True print "Error: FLAGS.MainModuleHelp() didn't return the expected result." print "Got:" print actual print "[End of got]" actual_lines = actual.split("\n") expected_lines = expected.split("\n") num_actual_lines = len(actual_lines) num_expected_lines = len(expected_lines) if num_actual_lines != num_expected_lines: print "Number of actual lines = %d, expected %d" % ( num_actual_lines, num_expected_lines) num_to_match = min(num_actual_lines, num_expected_lines) for i in range(num_to_match): if actual_lines[i] != expected_lines[i]: print "One discrepancy: Got:" print actual_lines[i] print "Expected:" print expected_lines[i] break else: # If we got here, found no discrepancy, print first new line. if num_actual_lines > num_expected_lines: print "New help line:" print actual_lines[num_expected_lines] elif num_expected_lines > num_actual_lines: print "Missing expected help line:" print expected_lines[num_actual_lines] else: print "Bug in this test -- discrepancy detected but not found." return False class TestCase(unittest.TestCase): def assertListEqual(self, list1, list2): """Asserts that, when sorted, list1 and list2 are identical.""" # This exists in python 2.7, but not previous versions. Use the # built-in version if possible. if hasattr(unittest.TestCase, "assertListEqual"): unittest.TestCase.assertListEqual(self, Sorted(list1), Sorted(list2)) else: self.assertEqual(Sorted(list1), Sorted(list2)) def assertMultiLineEqual(self, expected, actual): # This exists in python 2.7, but not previous versions. Use the # built-in version if possible. if hasattr(unittest.TestCase, "assertMultiLineEqual"): unittest.TestCase.assertMultiLineEqual(self, expected, actual) else: self.assertTrue(MultiLineEqual(expected, actual)) def assertRaisesWithRegexpMatch(self, exception, regexp, fn, *args, **kwargs): try: fn(*args, **kwargs) except exception, why: self.assertTrue(re.search(regexp, str(why)), "'%s' does not match '%s'" % (regexp, why)) return self.fail(exception.__name__ + " not raised") def main(): unittest.main()
apache-2.0
mancoast/CPythonPyc_test
cpython/242_test_bisect.py
8
9127
import unittest from test import test_support from bisect import bisect_right, bisect_left, insort_left, insort_right, insort, bisect from UserList import UserList class TestBisect(unittest.TestCase): precomputedCases = [ (bisect_right, [], 1, 0), (bisect_right, [1], 0, 0), (bisect_right, [1], 1, 1), (bisect_right, [1], 2, 1), (bisect_right, [1, 1], 0, 0), (bisect_right, [1, 1], 1, 2), (bisect_right, [1, 1], 2, 2), (bisect_right, [1, 1, 1], 0, 0), (bisect_right, [1, 1, 1], 1, 3), (bisect_right, [1, 1, 1], 2, 3), (bisect_right, [1, 1, 1, 1], 0, 0), (bisect_right, [1, 1, 1, 1], 1, 4), (bisect_right, [1, 1, 1, 1], 2, 4), (bisect_right, [1, 2], 0, 0), (bisect_right, [1, 2], 1, 1), (bisect_right, [1, 2], 1.5, 1), (bisect_right, [1, 2], 2, 2), (bisect_right, [1, 2], 3, 2), (bisect_right, [1, 1, 2, 2], 0, 0), (bisect_right, [1, 1, 2, 2], 1, 2), (bisect_right, [1, 1, 2, 2], 1.5, 2), (bisect_right, [1, 1, 2, 2], 2, 4), (bisect_right, [1, 1, 2, 2], 3, 4), (bisect_right, [1, 2, 3], 0, 0), (bisect_right, [1, 2, 3], 1, 1), (bisect_right, [1, 2, 3], 1.5, 1), (bisect_right, [1, 2, 3], 2, 2), (bisect_right, [1, 2, 3], 2.5, 2), (bisect_right, [1, 2, 3], 3, 3), (bisect_right, [1, 2, 3], 4, 3), (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 0, 0), (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1, 1), (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1.5, 1), (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2, 3), (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2.5, 3), (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3, 6), (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3.5, 6), (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 4, 10), (bisect_right, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 5, 10), (bisect_left, [], 1, 0), (bisect_left, [1], 0, 0), (bisect_left, [1], 1, 0), (bisect_left, [1], 2, 1), (bisect_left, [1, 1], 0, 0), (bisect_left, [1, 1], 1, 0), (bisect_left, [1, 1], 2, 2), (bisect_left, [1, 1, 1], 0, 0), (bisect_left, [1, 1, 1], 1, 0), (bisect_left, [1, 1, 1], 2, 3), (bisect_left, [1, 1, 1, 1], 0, 0), (bisect_left, [1, 1, 1, 1], 1, 0), (bisect_left, [1, 1, 1, 1], 2, 4), (bisect_left, [1, 2], 0, 0), (bisect_left, [1, 2], 1, 0), (bisect_left, [1, 2], 1.5, 1), (bisect_left, [1, 2], 2, 1), (bisect_left, [1, 2], 3, 2), (bisect_left, [1, 1, 2, 2], 0, 0), (bisect_left, [1, 1, 2, 2], 1, 0), (bisect_left, [1, 1, 2, 2], 1.5, 2), (bisect_left, [1, 1, 2, 2], 2, 2), (bisect_left, [1, 1, 2, 2], 3, 4), (bisect_left, [1, 2, 3], 0, 0), (bisect_left, [1, 2, 3], 1, 0), (bisect_left, [1, 2, 3], 1.5, 1), (bisect_left, [1, 2, 3], 2, 1), (bisect_left, [1, 2, 3], 2.5, 2), (bisect_left, [1, 2, 3], 3, 2), (bisect_left, [1, 2, 3], 4, 3), (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 0, 0), (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1, 0), (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 1.5, 1), (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2, 1), (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 2.5, 3), (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3, 3), (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 3.5, 6), (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 4, 6), (bisect_left, [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], 5, 10) ] def test_precomputed(self): for func, data, elem, expected in self.precomputedCases: self.assertEqual(func(data, elem), expected) self.assertEqual(func(UserList(data), elem), expected) def test_random(self, n=25): from random import randrange for i in xrange(n): data = [randrange(0, n, 2) for j in xrange(i)] data.sort() elem = randrange(-1, n+1) ip = bisect_left(data, elem) if ip < len(data): self.failUnless(elem <= data[ip]) if ip > 0: self.failUnless(data[ip-1] < elem) ip = bisect_right(data, elem) if ip < len(data): self.failUnless(elem < data[ip]) if ip > 0: self.failUnless(data[ip-1] <= elem) def test_optionalSlicing(self): for func, data, elem, expected in self.precomputedCases: for lo in xrange(4): lo = min(len(data), lo) for hi in xrange(3,8): hi = min(len(data), hi) ip = func(data, elem, lo, hi) self.failUnless(lo <= ip <= hi) if func is bisect_left and ip < hi: self.failUnless(elem <= data[ip]) if func is bisect_left and ip > lo: self.failUnless(data[ip-1] < elem) if func is bisect_right and ip < hi: self.failUnless(elem < data[ip]) if func is bisect_right and ip > lo: self.failUnless(data[ip-1] <= elem) self.assertEqual(ip, max(lo, min(hi, expected))) def test_backcompatibility(self): self.assertEqual(bisect, bisect_right) #============================================================================== class TestInsort(unittest.TestCase): def test_vsBuiltinSort(self, n=500): from random import choice for insorted in (list(), UserList()): for i in xrange(n): digit = choice("0123456789") if digit in "02468": f = insort_left else: f = insort_right f(insorted, digit) self.assertEqual(sorted(insorted), insorted) def test_backcompatibility(self): self.assertEqual(insort, insort_right) #============================================================================== class LenOnly: "Dummy sequence class defining __len__ but not __getitem__." def __len__(self): return 10 class GetOnly: "Dummy sequence class defining __getitem__ but not __len__." def __getitem__(self, ndx): return 10 class CmpErr: "Dummy element that always raises an error during comparison" def __cmp__(self, other): raise ZeroDivisionError class TestErrorHandling(unittest.TestCase): def test_non_sequence(self): for f in (bisect_left, bisect_right, insort_left, insort_right): self.assertRaises(TypeError, f, 10, 10) def test_len_only(self): for f in (bisect_left, bisect_right, insort_left, insort_right): self.assertRaises(AttributeError, f, LenOnly(), 10) def test_get_only(self): for f in (bisect_left, bisect_right, insort_left, insort_right): self.assertRaises(AttributeError, f, GetOnly(), 10) def test_cmp_err(self): seq = [CmpErr(), CmpErr(), CmpErr()] for f in (bisect_left, bisect_right, insort_left, insort_right): self.assertRaises(ZeroDivisionError, f, seq, 10) def test_arg_parsing(self): for f in (bisect_left, bisect_right, insort_left, insort_right): self.assertRaises(TypeError, f, 10) #============================================================================== libreftest = """ Example from the Library Reference: Doc/lib/libbisect.tex The bisect() function is generally useful for categorizing numeric data. This example uses bisect() to look up a letter grade for an exam total (say) based on a set of ordered numeric breakpoints: 85 and up is an `A', 75..84 is a `B', etc. >>> grades = "FEDCBA" >>> breakpoints = [30, 44, 66, 75, 85] >>> from bisect import bisect >>> def grade(total): ... return grades[bisect(breakpoints, total)] ... >>> grade(66) 'C' >>> map(grade, [33, 99, 77, 44, 12, 88]) ['E', 'A', 'B', 'D', 'F', 'A'] """ #------------------------------------------------------------------------------ __test__ = {'libreftest' : libreftest} def test_main(verbose=None): from test import test_bisect from types import BuiltinFunctionType import sys test_classes = [TestBisect, TestInsort] if isinstance(bisect_left, BuiltinFunctionType): test_classes.append(TestErrorHandling) test_support.run_unittest(*test_classes) test_support.run_doctest(test_bisect, verbose) # verify reference counting if verbose and hasattr(sys, "gettotalrefcount"): import gc counts = [None] * 5 for i in xrange(len(counts)): test_support.run_unittest(*test_classes) gc.collect() counts[i] = sys.gettotalrefcount() print counts if __name__ == "__main__": test_main(verbose=True)
gpl-3.0
redhat-openstack/glance
glance/db/sqlalchemy/migrate_repo/versions/012_id_to_uuid.py
2
20307
# Copyright 2013 IBM Corp. # Copyright 2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ While SQLAlchemy/sqlalchemy-migrate should abstract this correctly, there are known issues with these libraries so SQLite and non-SQLite migrations must be done separately. """ import uuid import migrate import sqlalchemy meta = sqlalchemy.MetaData() and_ = sqlalchemy.and_ or_ = sqlalchemy.or_ def upgrade(migrate_engine): """ Call the correct dialect-specific upgrade. """ meta.bind = migrate_engine t_images = _get_table('images', meta) t_image_members = _get_table('image_members', meta) t_image_properties = _get_table('image_properties', meta) dialect = migrate_engine.url.get_dialect().name if dialect == "sqlite": _upgrade_sqlite(t_images, t_image_members, t_image_properties) _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties) elif dialect == "ibm_db_sa": _upgrade_db2(t_images, t_image_members, t_image_properties) _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties) _add_db2_constraints() else: _upgrade_other(t_images, t_image_members, t_image_properties, dialect) def downgrade(migrate_engine): """ Call the correct dialect-specific downgrade. """ meta.bind = migrate_engine t_images = _get_table('images', meta) t_image_members = _get_table('image_members', meta) t_image_properties = _get_table('image_properties', meta) dialect = migrate_engine.url.get_dialect().name if dialect == "sqlite": _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties) _downgrade_sqlite(t_images, t_image_members, t_image_properties) elif dialect == "ibm_db_sa": _remove_db2_constraints() _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties) _downgrade_db2(t_images, t_image_members, t_image_properties) else: _downgrade_other(t_images, t_image_members, t_image_properties, dialect) def _upgrade_sqlite(t_images, t_image_members, t_image_properties): """ Upgrade 011 -> 012 with special SQLite-compatible logic. """ sql_commands = [ """CREATE TABLE images_backup ( id VARCHAR(36) NOT NULL, name VARCHAR(255), size INTEGER, status VARCHAR(30) NOT NULL, is_public BOOLEAN NOT NULL, location TEXT, created_at DATETIME NOT NULL, updated_at DATETIME, deleted_at DATETIME, deleted BOOLEAN NOT NULL, disk_format VARCHAR(20), container_format VARCHAR(20), checksum VARCHAR(32), owner VARCHAR(255), min_disk INTEGER NOT NULL, min_ram INTEGER NOT NULL, PRIMARY KEY (id), CHECK (is_public IN (0, 1)), CHECK (deleted IN (0, 1)) );""", """INSERT INTO images_backup SELECT * FROM images;""", """CREATE TABLE image_members_backup ( id INTEGER NOT NULL, image_id VARCHAR(36) NOT NULL, member VARCHAR(255) NOT NULL, can_share BOOLEAN NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME, deleted_at DATETIME, deleted BOOLEAN NOT NULL, PRIMARY KEY (id), UNIQUE (image_id, member), CHECK (can_share IN (0, 1)), CHECK (deleted IN (0, 1)), FOREIGN KEY(image_id) REFERENCES images (id) );""", """INSERT INTO image_members_backup SELECT * FROM image_members;""", """CREATE TABLE image_properties_backup ( id INTEGER NOT NULL, image_id VARCHAR(36) NOT NULL, name VARCHAR(255) NOT NULL, value TEXT, created_at DATETIME NOT NULL, updated_at DATETIME, deleted_at DATETIME, deleted BOOLEAN NOT NULL, PRIMARY KEY (id), CHECK (deleted IN (0, 1)), UNIQUE (image_id, name), FOREIGN KEY(image_id) REFERENCES images (id) );""", """INSERT INTO image_properties_backup SELECT * FROM image_properties;""", ] for command in sql_commands: meta.bind.execute(command) _sqlite_table_swap(t_image_members, t_image_properties, t_images) def _upgrade_db2(t_images, t_image_members, t_image_properties): """ Upgrade for DB2. """ t_images.c.id.alter(sqlalchemy.String(36), primary_key=True) image_members_backup = sqlalchemy.Table( 'image_members_backup', meta, sqlalchemy.Column('id', sqlalchemy.Integer(), primary_key=True, nullable=False), sqlalchemy.Column('image_id', sqlalchemy.String(36), nullable=False, index=True), sqlalchemy.Column('member', sqlalchemy.String(255), nullable=False), sqlalchemy.Column('can_share', sqlalchemy.Boolean(), nullable=False, default=False), sqlalchemy.Column('created_at', sqlalchemy.DateTime(), nullable=False), sqlalchemy.Column('updated_at', sqlalchemy.DateTime()), sqlalchemy.Column('deleted_at', sqlalchemy.DateTime()), sqlalchemy.Column('deleted', sqlalchemy.Boolean(), nullable=False, default=False, index=True), sqlalchemy.UniqueConstraint('image_id', 'member'), extend_existing=True) image_properties_backup = sqlalchemy.Table( 'image_properties_backup', meta, sqlalchemy.Column('id', sqlalchemy.Integer(), primary_key=True, nullable=False), sqlalchemy.Column('image_id', sqlalchemy.String(36), nullable=False, index=True), sqlalchemy.Column('name', sqlalchemy.String(255), nullable=False), sqlalchemy.Column('value', sqlalchemy.Text()), sqlalchemy.Column('created_at', sqlalchemy.DateTime(), nullable=False), sqlalchemy.Column('updated_at', sqlalchemy.DateTime()), sqlalchemy.Column('deleted_at', sqlalchemy.DateTime()), sqlalchemy.Column('deleted', sqlalchemy.Boolean(), nullable=False, default=False, index=True), sqlalchemy.UniqueConstraint( 'image_id', 'name', name='ix_image_properties_image_id_name'), extend_existing=True) image_members_backup.create() image_properties_backup.create() sql_commands = [ """INSERT INTO image_members_backup SELECT * FROM image_members;""", """INSERT INTO image_properties_backup SELECT * FROM image_properties;""", ] for command in sql_commands: meta.bind.execute(command) t_image_members.drop() t_image_properties.drop() image_members_backup.rename(name='image_members') image_properties_backup.rename(name='image_properties') def _add_db2_constraints(): #Create the foreign keys sql_commands = [ """ALTER TABLE image_members ADD CONSTRAINT member_image_id FOREIGN KEY (image_id) REFERENCES images (id);""", """ALTER TABLE image_properties ADD CONSTRAINT property_image_id FOREIGN KEY (image_id) REFERENCES images (id);""", ] for command in sql_commands: meta.bind.execute(command) def _remove_db2_constraints(): #remove the foreign keys constraints sql_commands = [ """ALTER TABLE image_members DROP CONSTRAINT member_image_id;""", """ALTER TABLE image_properties DROP CONSTRAINT property_image_id;""" ] for command in sql_commands: meta.bind.execute(command) def _downgrade_db2(t_images, t_image_members, t_image_properties): """ Downgrade for DB2. """ t_images.c.id.alter(sqlalchemy.Integer(), primary_key=True) image_members_old = sqlalchemy.Table( 'image_members_old', meta, sqlalchemy.Column('id', sqlalchemy.Integer(), primary_key=True, nullable=False), sqlalchemy.Column('image_id', sqlalchemy.Integer(), nullable=False, index=True), sqlalchemy.Column('member', sqlalchemy.String(255), nullable=False), sqlalchemy.Column('can_share', sqlalchemy.Boolean(), nullable=False, default=False), sqlalchemy.Column('created_at', sqlalchemy.DateTime(), nullable=False), sqlalchemy.Column('updated_at', sqlalchemy.DateTime()), sqlalchemy.Column('deleted_at', sqlalchemy.DateTime()), sqlalchemy.Column('deleted', sqlalchemy.Boolean(), nullable=False, default=False, index=True), sqlalchemy.UniqueConstraint('image_id', 'member'), extend_existing=True) image_properties_old = sqlalchemy.Table( 'image_properties_old', meta, sqlalchemy.Column('id', sqlalchemy.Integer(), primary_key=True, nullable=False), sqlalchemy.Column('image_id', sqlalchemy.Integer(), nullable=False, index=True), sqlalchemy.Column('name', sqlalchemy.String(255), nullable=False), sqlalchemy.Column('value', sqlalchemy.Text()), sqlalchemy.Column('created_at', sqlalchemy.DateTime(), nullable=False), sqlalchemy.Column('updated_at', sqlalchemy.DateTime()), sqlalchemy.Column('deleted_at', sqlalchemy.DateTime()), sqlalchemy.Column('deleted', sqlalchemy.Boolean(), nullable=False, default=False, index=True), sqlalchemy.UniqueConstraint( 'image_id', 'name', name='ix_image_properties_image_id_name'), extend_existing=True) image_members_old.create() image_properties_old.create() sql_commands = [ """INSERT INTO image_members_old SELECT * FROM image_members;""", """INSERT INTO image_properties_old SELECT * FROM image_properties;""", ] for command in sql_commands: meta.bind.execute(command) t_image_members.drop() t_image_properties.drop() image_members_old.rename(name='image_members') image_properties_old.rename(name='image_properties') def _downgrade_sqlite(t_images, t_image_members, t_image_properties): """ Downgrade 012 -> 011 with special SQLite-compatible logic. """ sql_commands = [ """CREATE TABLE images_backup ( id INTEGER NOT NULL, name VARCHAR(255), size INTEGER, status VARCHAR(30) NOT NULL, is_public BOOLEAN NOT NULL, location TEXT, created_at DATETIME NOT NULL, updated_at DATETIME, deleted_at DATETIME, deleted BOOLEAN NOT NULL, disk_format VARCHAR(20), container_format VARCHAR(20), checksum VARCHAR(32), owner VARCHAR(255), min_disk INTEGER NOT NULL, min_ram INTEGER NOT NULL, PRIMARY KEY (id), CHECK (is_public IN (0, 1)), CHECK (deleted IN (0, 1)) );""", """INSERT INTO images_backup SELECT * FROM images;""", """CREATE TABLE image_members_backup ( id INTEGER NOT NULL, image_id INTEGER NOT NULL, member VARCHAR(255) NOT NULL, can_share BOOLEAN NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME, deleted_at DATETIME, deleted BOOLEAN NOT NULL, PRIMARY KEY (id), UNIQUE (image_id, member), CHECK (can_share IN (0, 1)), CHECK (deleted IN (0, 1)), FOREIGN KEY(image_id) REFERENCES images (id) );""", """INSERT INTO image_members_backup SELECT * FROM image_members;""", """CREATE TABLE image_properties_backup ( id INTEGER NOT NULL, image_id INTEGER NOT NULL, name VARCHAR(255) NOT NULL, value TEXT, created_at DATETIME NOT NULL, updated_at DATETIME, deleted_at DATETIME, deleted BOOLEAN NOT NULL, PRIMARY KEY (id), CHECK (deleted IN (0, 1)), UNIQUE (image_id, name), FOREIGN KEY(image_id) REFERENCES images (id) );""", """INSERT INTO image_properties_backup SELECT * FROM image_properties;""", ] for command in sql_commands: meta.bind.execute(command) _sqlite_table_swap(t_image_members, t_image_properties, t_images) def _upgrade_other(t_images, t_image_members, t_image_properties, dialect): """ Upgrade 011 -> 012 with logic for non-SQLite databases. """ foreign_keys = _get_foreign_keys(t_images, t_image_members, t_image_properties, dialect) for fk in foreign_keys: fk.drop() t_images.c.id.alter(sqlalchemy.String(36), primary_key=True) t_image_members.c.image_id.alter(sqlalchemy.String(36)) t_image_properties.c.image_id.alter(sqlalchemy.String(36)) _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties) for fk in foreign_keys: fk.create() def _downgrade_other(t_images, t_image_members, t_image_properties, dialect): """ Downgrade 012 -> 011 with logic for non-SQLite databases. """ foreign_keys = _get_foreign_keys(t_images, t_image_members, t_image_properties, dialect) for fk in foreign_keys: fk.drop() _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties) t_images.c.id.alter(sqlalchemy.Integer(), primary_key=True) t_image_members.c.image_id.alter(sqlalchemy.Integer()) t_image_properties.c.image_id.alter(sqlalchemy.Integer()) for fk in foreign_keys: fk.create() def _sqlite_table_swap(t_image_members, t_image_properties, t_images): t_image_members.drop() t_image_properties.drop() t_images.drop() meta.bind.execute("ALTER TABLE images_backup " "RENAME TO images") meta.bind.execute("ALTER TABLE image_members_backup " "RENAME TO image_members") meta.bind.execute("ALTER TABLE image_properties_backup " "RENAME TO image_properties") meta.bind.execute("""CREATE INDEX ix_image_properties_deleted ON image_properties (deleted);""") meta.bind.execute("""CREATE INDEX ix_image_properties_name ON image_properties (name);""") def _get_table(table_name, metadata): """Return a sqlalchemy Table definition with associated metadata.""" return sqlalchemy.Table(table_name, metadata, autoload=True) def _get_foreign_keys(t_images, t_image_members, t_image_properties, dialect): """Retrieve and return foreign keys for members/properties tables.""" foreign_keys = [] if t_image_members.foreign_keys: img_members_fk_name = list(t_image_members.foreign_keys)[0].name if dialect == 'mysql': fk1 = migrate.ForeignKeyConstraint([t_image_members.c.image_id], [t_images.c.id], name=img_members_fk_name) else: fk1 = migrate.ForeignKeyConstraint([t_image_members.c.image_id], [t_images.c.id]) foreign_keys.append(fk1) if t_image_properties.foreign_keys: img_properties_fk_name = list(t_image_properties.foreign_keys)[0].name if dialect == 'mysql': fk2 = migrate.ForeignKeyConstraint([t_image_properties.c.image_id], [t_images.c.id], name=img_properties_fk_name) else: fk2 = migrate.ForeignKeyConstraint([t_image_properties.c.image_id], [t_images.c.id]) foreign_keys.append(fk2) return foreign_keys def _update_all_ids_to_uuids(t_images, t_image_members, t_image_properties): """Transition from INTEGER id to VARCHAR(36) id.""" images = list(t_images.select().execute()) for image in images: old_id = image["id"] new_id = str(uuid.uuid4()) t_images.update().\ where(t_images.c.id == old_id).\ values(id=new_id).execute() t_image_members.update().\ where(t_image_members.c.image_id == old_id).\ values(image_id=new_id).execute() t_image_properties.update().\ where(t_image_properties.c.image_id == old_id).\ values(image_id=new_id).execute() t_image_properties.update().\ where(and_(or_(t_image_properties.c.name == 'kernel_id', t_image_properties.c.name == 'ramdisk_id'), t_image_properties.c.value == old_id)).\ values(value=new_id).execute() def _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties): """Transition from VARCHAR(36) id to INTEGER id.""" images = list(t_images.select().execute()) new_id = 1 for image in images: old_id = image["id"] t_images.update().\ where(t_images.c.id == old_id).\ values(id=str(new_id)).execute() t_image_members.update().\ where(t_image_members.c.image_id == old_id).\ values(image_id=str(new_id)).execute() t_image_properties.update().\ where(t_image_properties.c.image_id == old_id).\ values(image_id=str(new_id)).execute() t_image_properties.update().\ where(and_(or_(t_image_properties.c.name == 'kernel_id', t_image_properties.c.name == 'ramdisk_id'), t_image_properties.c.value == old_id)).\ values(value=str(new_id)).execute() new_id += 1
apache-2.0
lgfausak/sqlbridge
sqlbridge/twisted/dbengine.py
1
6399
#!/usr/bin/env python ############################################################################### ## ## Copyright (C) 2014 Greg Fausak ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## ############################################################################### from __future__ import absolute_import import sys,os,argparse,six from twisted.python import log from twisted.internet import reactor from twisted.internet.defer import inlineCallbacks from twisted.internet.endpoints import clientFromString #from myapprunner import MyApplicationRunner from autobahn.twisted.wamp import ApplicationSession,ApplicationRunner from autobahn import util from autobahn.wamp import auth from autobahn.wamp import types from autobahn.wamp.exception import ApplicationError from autobahn.twisted import wamp, websocket from autobahn.twisted.wamp import ApplicationSession class DB(ApplicationSession): """ An application component providing db access """ def __init__(self, *args, **kwargs): log.msg("__init__") self.db = {} self.svar = {} log.msg("got args {}, kwargs {}".format(args,kwargs)) # reap init variables meant only for us for i in ( 'engine', 'topic_base', 'dsn', 'authinfo', 'debug', ): if i in kwargs: if kwargs[i] is not None: self.svar[i] = kwargs[i] del kwargs[i] log.msg("sending to super.init args {}, kwargs {}".format(args,kwargs)) ApplicationSession.__init__(self, *args, **kwargs) def onConnect(self): log.msg("onConnect") auth_type = 'none' auth_user = 'anon' if 'authinfo' in self.svar: auth_type = self.svar['authinfo']['auth_type'] auth_user = self.svar['authinfo']['auth_user'] log.msg("onConnect with {} {}".format(auth_type, auth_user)) self.join(self.config.realm, [six.u(auth_type)], six.u(auth_user)) def onChallenge(self, challenge): log.msg("onChallenge - maynard") password = 'unknown' if 'authinfo' in self.svar: password = self.svar['authinfo']['auth_password'] log.msg("onChallenge with password {}".format(password)) if challenge.method == u'wampcra': if u'salt' in challenge.extra: key = auth.derive_key(password.encode('utf8'), challenge.extra['salt'].encode('utf8'), challenge.extra.get('iterations', None), challenge.extra.get('keylen', None)) else: key = password.encode('utf8') signature = auth.compute_wcs(key, challenge.extra['challenge'].encode('utf8')) return signature.decode('ascii') else: raise Exception("don't know how to compute challenge for authmethod {}".format(challenge.method)) @inlineCallbacks def onJoin(self, details): log.msg("db:onJoin session attached {}".format(details)) if 'engine' in self.svar and 'topic_base' in self.svar: if self.svar['engine'] == 'PG9_4' or self.svar['engine'] == 'PG': from .db import postgres dbo = postgres.PG9_4(topic_base = self.svar['topic_base'], app_session = self, debug = self.svar['debug']) elif self.svar['engine'] == 'MYSQL14_14' or self.svar['engine'] == 'MYSQL': from .db import mysql dbo = mysql.MYSQL14_14(topic_base = self.svar['topic_base'], app_session = self, debug = self.svar['debug']) elif self.svar['engine'] == 'SQLITE3_3_8_2' or self.svar['engine'] == 'SQLITE3' or self.svar['engine'] == 'SQLITE': from .db import ausqlite3 dbo = ausqlite3.SQLITE3_3_8_2(topic_base = self.svar['topic_base'], app_session = self, debug = self.svar['debug']) else: raise Exception("Unsupported dbtype {} ".format(self.svar['engine'])) else: raise Exception("when instantiating this class DB you must provide engine=X and topic_base=Y") self.db = { 'instance': dbo } self.db['registration'] = {} r = types.RegisterOptions(details_arg = 'details') self.db['registration']['connect'] = yield self.register(dbo.connect, self.svar['topic_base']+'.connect', options = r) self.db['registration']['disconnect'] = yield self.register(dbo.disconnect, self.svar['topic_base']+'.disconnect', options = r) self.db['registration']['query'] = yield self.register(dbo.query, self.svar['topic_base']+'.query', options = r) self.db['registration']['operation'] = yield self.register(dbo.operation, self.svar['topic_base']+'.operation', options = r) self.db['registration']['watch'] = yield self.register(dbo.watch, self.svar['topic_base']+'.watch', options = r) self.db['registration']['info'] = yield self.register(dbo.info, self.svar['topic_base']+'.info', options = r) if 'dsn' in self.svar: log.msg("db:onJoin connecting... {}".format(self.svar['dsn'])) yield self.call(self.svar['topic_base'] + '.connect', self.svar['dsn']) log.msg("db:onJoin connecting established") log.msg("db bootstrap procedures registered") def onLeave(self, details): print("onLeave: {}").format(details) yield self.db['registration']['connect'].unregister() yield self.db['registration']['disconnect'].unregister() yield self.db['registration']['query'].unregister() yield self.db['registration']['operation'].unregister() yield self.db['registration']['watch'].unregister() yield self.db['registration']['info'].unregister() del self.db self.disconnect() return def onDisconnect(self): print("onDisconnect:") reactor.stop()
apache-2.0
matplotlib/cmocean
cmocean/rgb/dense.py
2
13693
from matplotlib.colors import ListedColormap from numpy import nan, inf # Used to reconstruct the colormap in pycam02ucs.cm.viscm parameters = {'xp': [16.121891585344997, 33.901145962549492, 5.5873058066040926, -14.703203914141397, -17.875928056390336, -5.3288735306278738], 'yp': [-2.5423728813559308, -13.425925925925895, -42.422027290448327, -35.333333333333314, -8.83264462809916, -2.1686159844054487], 'min_Jp': 15.0, 'max_Jp': 95.0} cm_data = [[ 0.21298394, 0.05589169, 0.14220951], [ 0.21780744, 0.0570005 , 0.14665582], [ 0.22261214, 0.05808842, 0.15115908], [ 0.22739756, 0.05915624, 0.15572185], [ 0.23216536, 0.06020099, 0.16034977], [ 0.23691745, 0.06121879, 0.1650498 ], [ 0.24164654, 0.06222163, 0.169816 ], [ 0.24635153, 0.06321115, 0.17465056], [ 0.25103114, 0.06418929, 0.1795555 ], [ 0.25568737, 0.06515168, 0.1845388 ], [ 0.26031556, 0.06610638, 0.18959733], [ 0.26491272, 0.06705861, 0.19473015], [ 0.26947709, 0.0680114 , 0.19993831], [ 0.27400681, 0.06896804, 0.20522255], [ 0.27849993, 0.06993211, 0.21058327], [ 0.28295501, 0.07090603, 0.21602205], [ 0.28737014, 0.0718934 , 0.22153921], [ 0.29174204, 0.07290112, 0.22713094], [ 0.29606871, 0.07393344, 0.23279613], [ 0.30034822, 0.07499465, 0.23853326], [ 0.30457867, 0.07608911, 0.24434046], [ 0.30875826, 0.07722111, 0.25021549], [ 0.31288529, 0.0783949 , 0.25615575], [ 0.3169582 , 0.07961456, 0.26215837], [ 0.32097556, 0.08088399, 0.26822019], [ 0.32493609, 0.08220684, 0.27433782], [ 0.3288387 , 0.08358647, 0.28050768], [ 0.33268245, 0.08502593, 0.28672608], [ 0.33646657, 0.08652789, 0.2929892 ], [ 0.34019047, 0.08809468, 0.29929318], [ 0.34385372, 0.08972821, 0.30563417], [ 0.34745604, 0.09143006, 0.31200825], [ 0.35099729, 0.0932014 , 0.31841152], [ 0.35447749, 0.09504303, 0.32484029], [ 0.35789677, 0.09695535, 0.33129096], [ 0.36125536, 0.09893846, 0.33776007], [ 0.36455362, 0.10099212, 0.34424427], [ 0.36779195, 0.10311585, 0.35074041], [ 0.37097085, 0.10530889, 0.35724546], [ 0.37409088, 0.10757029, 0.36375657], [ 0.37715263, 0.10989888, 0.37027108], [ 0.38015674, 0.11229336, 0.37678646], [ 0.38310387, 0.11475229, 0.38330035], [ 0.38599472, 0.11727411, 0.38981058], [ 0.38882999, 0.1198572 , 0.3963151 ], [ 0.39161037, 0.12249987, 0.402812 ], [ 0.3943366 , 0.12520039, 0.40929955], [ 0.39700936, 0.12795703, 0.41577611], [ 0.39962936, 0.13076802, 0.42224018], [ 0.40219729, 0.13363161, 0.42869038], [ 0.40471394, 0.13654614, 0.43512488], [ 0.40717995, 0.13950986, 0.44154258], [ 0.4095959 , 0.14252107, 0.44794287], [ 0.41196239, 0.14557814, 0.45432475], [ 0.41428002, 0.1486795 , 0.4606873 ], [ 0.41654936, 0.15182361, 0.46702967], [ 0.41877098, 0.15500903, 0.47335108], [ 0.4209454 , 0.15823432, 0.4796508 ], [ 0.42307313, 0.16149814, 0.48592814], [ 0.42515465, 0.16479918, 0.49218247], [ 0.42719043, 0.1681362 , 0.49841321], [ 0.42918111, 0.17150798, 0.50461925], [ 0.431127 , 0.17491341, 0.5108004 ], [ 0.43302838, 0.17835141, 0.5169565 ], [ 0.43488561, 0.18182099, 0.52308708], [ 0.43669905, 0.18532117, 0.5291917 ], [ 0.43846903, 0.18885105, 0.53526994], [ 0.44019583, 0.19240976, 0.54132138], [ 0.44187976, 0.19599648, 0.54734563], [ 0.44352106, 0.19961045, 0.5533423 ], [ 0.44512012, 0.2032509 , 0.55931077], [ 0.44667705, 0.20691717, 0.56525088], [ 0.44819199, 0.21060865, 0.57116243], [ 0.44966511, 0.21432473, 0.57704502], [ 0.45109659, 0.21806485, 0.58289828], [ 0.45248658, 0.22182847, 0.58872183], [ 0.45383521, 0.2256151 , 0.59451528], [ 0.45514261, 0.22942427, 0.60027826], [ 0.45640887, 0.23325554, 0.60601037], [ 0.45763398, 0.23710854, 0.61171135], [ 0.45881803, 0.24098289, 0.61738074], [ 0.4599611 , 0.24487823, 0.62301809], [ 0.46106323, 0.24879421, 0.62862296], [ 0.46212445, 0.25273054, 0.63419487], [ 0.46314479, 0.25668693, 0.63973335], [ 0.46412426, 0.2606631 , 0.6452379 ], [ 0.46506286, 0.2646588 , 0.650708 ], [ 0.46596031, 0.26867393, 0.65614343], [ 0.46681665, 0.27270825, 0.66154354], [ 0.467632 , 0.27676148, 0.66690758], [ 0.46840632, 0.28083345, 0.67223496], [ 0.46913959, 0.28492398, 0.67752502], [ 0.46983176, 0.28903289, 0.68277713], [ 0.47048281, 0.29316004, 0.68799058], [ 0.4710927 , 0.29730529, 0.69316468], [ 0.47166137, 0.30146848, 0.69829868], [ 0.47218867, 0.30564956, 0.70339194], [ 0.47267406, 0.30984863, 0.70844403], [ 0.47311806, 0.3140653 , 0.71345366], [ 0.47352067, 0.31829946, 0.71841996], [ 0.47388188, 0.322551 , 0.72334205], [ 0.47420168, 0.32681981, 0.728219 ], [ 0.47448009, 0.33110575, 0.73304987], [ 0.47471715, 0.33540873, 0.73783366], [ 0.4749129 , 0.33972863, 0.74256938], [ 0.47506742, 0.34406531, 0.74725597], [ 0.4751808 , 0.34841867, 0.75189235], [ 0.47525316, 0.35278857, 0.75647742], [ 0.47528466, 0.35717487, 0.76101004], [ 0.47527514, 0.36157758, 0.76548918], [ 0.47522479, 0.36599656, 0.76991363], [ 0.47513427, 0.37043147, 0.77428199], [ 0.47500393, 0.37488213, 0.77859297], [ 0.47483412, 0.37934834, 0.7828453 ], [ 0.4746253 , 0.38382989, 0.78703766], [ 0.47437795, 0.38832654, 0.7911687 ], [ 0.47409263, 0.39283807, 0.79523708], [ 0.47376999, 0.39736419, 0.79924139], [ 0.47341074, 0.40190463, 0.80318024], [ 0.47301567, 0.40645908, 0.80705223], [ 0.47258566, 0.41102721, 0.81085591], [ 0.47212171, 0.41560865, 0.81458986], [ 0.4716249 , 0.42020304, 0.81825263], [ 0.47109642, 0.42480997, 0.82184277], [ 0.47053758, 0.42942898, 0.82535887], [ 0.4699498 , 0.43405962, 0.82879947], [ 0.46933466, 0.43870139, 0.83216318], [ 0.46869383, 0.44335376, 0.83544858], [ 0.46802917, 0.44801616, 0.83865432], [ 0.46734263, 0.45268799, 0.84177905], [ 0.46663636, 0.45736864, 0.84482148], [ 0.46591265, 0.46205743, 0.84778034], [ 0.46517394, 0.46675366, 0.85065444], [ 0.46442285, 0.47145661, 0.85344263], [ 0.46366216, 0.4761655 , 0.85614385], [ 0.46289481, 0.48087955, 0.85875708], [ 0.46212297, 0.48559831, 0.8612812 ], [ 0.4613509 , 0.49032052, 0.86371555], [ 0.46058208, 0.49504528, 0.86605942], [ 0.45982017, 0.49977167, 0.86831217], [ 0.45906898, 0.50449872, 0.87047333], [ 0.4583325 , 0.50922545, 0.87254251], [ 0.45761487, 0.51395086, 0.87451947], [ 0.45692037, 0.51867392, 0.87640412], [ 0.45625342, 0.52339359, 0.87819649], [ 0.45561856, 0.52810881, 0.87989676], [ 0.45502044, 0.53281852, 0.88150529], [ 0.45446291, 0.53752203, 0.8830221 ], [ 0.45395166, 0.5422179 , 0.88444824], [ 0.45349173, 0.54690499, 0.88578463], [ 0.45308803, 0.55158223, 0.88703226], [ 0.45274551, 0.55624857, 0.8881923 ], [ 0.45246908, 0.56090297, 0.88926607], [ 0.45226366, 0.5655444 , 0.89025507], [ 0.45213406, 0.57017185, 0.89116092], [ 0.45208461, 0.57478456, 0.89198505], [ 0.45212047, 0.57938135, 0.89272981], [ 0.45224622, 0.5839613 , 0.89339735], [ 0.45246621, 0.58852353, 0.89398987], [ 0.45278458, 0.59306722, 0.89450974], [ 0.45320531, 0.59759159, 0.89495941], [ 0.45373211, 0.60209592, 0.89534144], [ 0.45436847, 0.60657953, 0.8956585 ], [ 0.45511768, 0.61104174, 0.89591342], [ 0.45598269, 0.61548199, 0.89610905], [ 0.45696613, 0.61989976, 0.89624827], [ 0.45807033, 0.62429458, 0.89633399], [ 0.45929732, 0.62866605, 0.89636919], [ 0.46064879, 0.63301382, 0.89635684], [ 0.46212629, 0.6373375 , 0.89630027], [ 0.46373081, 0.6416369 , 0.89620239], [ 0.46546305, 0.64591186, 0.89606608], [ 0.46732345, 0.65016224, 0.89589433], [ 0.46931216, 0.65438798, 0.89569008], [ 0.47142903, 0.65858902, 0.89545627], [ 0.47367364, 0.66276538, 0.89519579], [ 0.47604536, 0.66691708, 0.89491161], [ 0.47854335, 0.67104413, 0.89460702], [ 0.48116628, 0.67514678, 0.89428415], [ 0.48391278, 0.67922522, 0.89394566], [ 0.48678129, 0.68327963, 0.89359417], [ 0.48977007, 0.68731025, 0.89323218], [ 0.4928772 , 0.69131735, 0.89286215], [ 0.49610063, 0.69530122, 0.89248647], [ 0.49943822, 0.69926217, 0.89210744], [ 0.50288765, 0.70320047, 0.89172772], [ 0.50644655, 0.70711649, 0.89134936], [ 0.51011248, 0.71101066, 0.8909741 ], [ 0.51388294, 0.71488334, 0.89060393], [ 0.51775541, 0.71873493, 0.89024078], [ 0.52172732, 0.72256583, 0.8898865 ], [ 0.5257961 , 0.72637645, 0.88954287], [ 0.52995915, 0.7301672 , 0.8892116 ], [ 0.53421391, 0.7339385 , 0.88889434], [ 0.5385578 , 0.73769077, 0.88859267], [ 0.5429883 , 0.74142444, 0.88830811], [ 0.54750281, 0.74513991, 0.88804246], [ 0.5520989 , 0.74883762, 0.88779685], [ 0.55677422, 0.75251799, 0.88757251], [ 0.56152638, 0.75618144, 0.88737072], [ 0.56635309, 0.75982839, 0.88719273], [ 0.57125208, 0.76345922, 0.88703974], [ 0.57622118, 0.76707435, 0.8869129 ], [ 0.58125826, 0.77067417, 0.88681333], [ 0.58636126, 0.77425906, 0.88674212], [ 0.59152819, 0.7778294 , 0.88670031], [ 0.59675713, 0.78138555, 0.88668891], [ 0.60204624, 0.78492789, 0.88670892], [ 0.60739371, 0.78845676, 0.88676131], [ 0.61279785, 0.79197249, 0.886847 ], [ 0.61825699, 0.79547544, 0.88696697], [ 0.62376953, 0.79896592, 0.88712212], [ 0.62933401, 0.80244424, 0.88731328], [ 0.63494897, 0.80591071, 0.88754133], [ 0.64061303, 0.80936562, 0.88780715], [ 0.64632485, 0.81280925, 0.88811162], [ 0.65208315, 0.81624189, 0.88845562], [ 0.65788673, 0.81966379, 0.88884001], [ 0.6637344 , 0.82307522, 0.88926568], [ 0.66962506, 0.82647642, 0.88973352], [ 0.67555762, 0.82986764, 0.89024441], [ 0.68153106, 0.83324911, 0.89079928], [ 0.68754438, 0.83662105, 0.89139904], [ 0.69359663, 0.83998369, 0.89204464], [ 0.69968688, 0.84333724, 0.89273702], [ 0.70581423, 0.84668191, 0.89347718], [ 0.71197782, 0.85001791, 0.8942661 ], [ 0.7181769 , 0.85334541, 0.89510469], [ 0.72441053, 0.85666464, 0.89599414], [ 0.73067788, 0.8599758 , 0.89693553], [ 0.73697811, 0.8632791 , 0.89793 ], [ 0.74331039, 0.86657473, 0.89897869], [ 0.74967389, 0.86986292, 0.90008279], [ 0.75606778, 0.87314387, 0.90124351], [ 0.76249117, 0.87641781, 0.90246212], [ 0.7689432 , 0.87968498, 0.90373988], [ 0.77542295, 0.88294564, 0.9050781 ], [ 0.78192947, 0.88620003, 0.90647814], [ 0.78846179, 0.88944845, 0.90794134], [ 0.79501887, 0.89269119, 0.9094691 ], [ 0.80159965, 0.89592859, 0.91106281], [ 0.80820295, 0.899161 , 0.91272391], [ 0.81482754, 0.90238881, 0.91445386], [ 0.82147215, 0.90561245, 0.91625407], [ 0.82813543, 0.90883237, 0.91812595], [ 0.83481598, 0.91204906, 0.92007088], [ 0.84151229, 0.91526306, 0.92209023], [ 0.84822279, 0.91847494, 0.92418529], [ 0.85494584, 0.92168533, 0.92635732], [ 0.8616797 , 0.9248949 , 0.92860749], [ 0.86842255, 0.92810438, 0.9309369 ], [ 0.87517248, 0.93131455, 0.93334654], [ 0.88192751, 0.93452625, 0.93583728], [ 0.88868558, 0.93774038, 0.93840987], [ 0.89544454, 0.94095789, 0.94106488], [ 0.90220216, 0.9441798 , 0.94380273]] test_cm = ListedColormap(cm_data, name=__file__) if __name__ == "__main__": import matplotlib.pyplot as plt import numpy as np try: from viscm import viscm viscm(test_cm) except ImportError: print("viscm not found, falling back on simple display") plt.imshow(np.linspace(0, 100, 256)[None, :], aspect='auto', cmap=test_cm) plt.show()
mit
cjaymes/pyscap
src/scap/model/ocil_2_0/ItemBaseType.py
1
1052
# Copyright 2016 Casey Jaymes # This file is part of PySCAP. # # PySCAP 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. # # PySCAP 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 PySCAP. If not, see <http://www.gnu.org/licenses/>. from scap.Model import Model import logging logger = logging.getLogger(__name__) class ItemBaseType(Model): MODEL_MAP = { 'elements': [ {'tag_name': 'notes', 'list': 'notes', 'type': 'StringType', 'min': 0, 'max': None}, ], 'attributes': { 'revision': {'type': 'NonNegativeIntegerType', 'default': 0}, } }
gpl-3.0
jmehnle/ansible
lib/ansible/modules/network/nxos/nxos_vtp_password.py
46
8006
#!/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.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: nxos_vtp_password extends_documentation_fragment: nxos version_added: "2.2" short_description: Manages VTP password configuration. description: - Manages VTP password configuration. author: - Gabriele Gerbino (@GGabriele) notes: - VTP feature must be active on the device to use this module. - This module is used to manage only VTP passwords. - Use this in combination with M(nxos_vtp_domain) and M(nxos_vtp_version) to fully manage VTP operations. - You can set/remove password only if a VTP domain already exist. - If C(state=absent) and no C(vtp_password) is provided, it remove the current VTP password. - If C(state=absent) and C(vtp_password) is provided, the proposed C(vtp_password) has to match the existing one in order to remove it. options: vtp_password: description: - VTP password required: false default: null state: description: - Manage the state of the resource required: false default: present choices: ['present','absent'] ''' EXAMPLES = ''' # ENSURE VTP PASSWORD IS SET - nxos_vtp_password: password: ntc state: present host: "{{ inventory_hostname }}" username: "{{ un }}" password: "{{ pwd }}" # ENSURE VTP PASSWORD IS REMOVED - nxos_vtp_password: password: ntc state: absent host: "{{ inventory_hostname }}" username: "{{ un }}" password: "{{ pwd }}" ''' RETURN = ''' proposed: description: k/v pairs of parameters passed into module returned: always type: dict sample: {"vtp_password": "new_ntc"} existing: description: - k/v pairs of existing vtp returned: always type: dict sample: {"domain": "ntc", "version": "1", "vtp_password": "ntc"} end_state: description: k/v pairs of vtp after module execution returned: always type: dict sample: {"domain": "ntc", "version": "1", "vtp_password": "new_ntc"} updates: description: command sent to the device returned: always type: list sample: ["vtp password new_ntc"] changed: description: check to see if a change was made on the device returned: always type: boolean sample: true ''' from ansible.module_utils.nxos import get_config, load_config, run_commands from ansible.module_utils.nxos import nxos_argument_spec, check_args from ansible.module_utils.basic import AnsibleModule import re def execute_show_command(command, module, command_type='cli_show'): if module.params['transport'] == 'cli': if 'show run' not in command: command += ' | json' cmds = [command] body = run_commands(module, cmds) elif module.params['transport'] == 'nxapi': cmds = [command] body = run_commands(module, cmds) return body def flatten_list(command_lists): flat_command_list = [] for command in command_lists: if isinstance(command, list): flat_command_list.extend(command) else: flat_command_list.append(command) return flat_command_list 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] = str(value) else: new_dict[new_key] = value return new_dict def get_vtp_config(module): command = 'show vtp status' body = execute_show_command( command, module, command_type='cli_show_ascii')[0] vtp_parsed = {} if body: version_regex = '.*VTP version running\s+:\s+(?P<version>\d).*' domain_regex = '.*VTP Domain Name\s+:\s+(?P<domain>\S+).*' try: match_version = re.match(version_regex, body, re.DOTALL) version = match_version.groupdict()['version'] except AttributeError: version = '' try: match_domain = re.match(domain_regex, body, re.DOTALL) domain = match_domain.groupdict()['domain'] except AttributeError: domain = '' if domain and version: vtp_parsed['domain'] = domain vtp_parsed['version'] = version vtp_parsed['vtp_password'] = get_vtp_password(module) return vtp_parsed def get_vtp_password(module): command = 'show vtp password' body = execute_show_command(command, module)[0] password = body['passwd'] if password: return str(password) else: return "" def main(): argument_spec = dict( vtp_password=dict(type='str', no_log=True), state=dict(choices=['absent', 'present'], default='present'), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() check_args(module, warnings) vtp_password = module.params['vtp_password'] or None state = module.params['state'] existing = get_vtp_config(module) end_state = existing args = dict(vtp_password=vtp_password) changed = False proposed = dict((k, v) for k, v in args.items() if v is not None) delta = dict(set(proposed.items()).difference(existing.items())) commands = [] if state == 'absent': if vtp_password is not None: if existing['vtp_password'] == proposed['vtp_password']: commands.append(['no vtp password']) else: module.fail_json(msg="Proposed vtp password doesn't match " "current vtp password. It cannot be " "removed when state=absent. If you are " "trying to change the vtp password, use " "state=present.") else: if not existing.get('domain'): module.fail_json(msg='Cannot remove a vtp password ' 'before vtp domain is set.') elif existing['vtp_password'] != ('\\'): commands.append(['no vtp password']) elif state == 'present': if delta: if not existing.get('domain'): module.fail_json(msg='Cannot set vtp password ' 'before vtp domain is set.') else: commands.append(['vtp password {0}'.format(vtp_password)]) cmds = flatten_list(commands) if cmds: if module.check_mode: module.exit_json(changed=True, commands=cmds) else: changed = True load_config(module, cmds) end_state = get_vtp_config(module) if 'configure' in cmds: cmds.pop(0) results = {} results['proposed'] = proposed results['existing'] = existing results['end_state'] = end_state results['updates'] = cmds results['changed'] = changed results['warnings'] = warnings module.exit_json(**results) if __name__ == '__main__': main()
gpl-3.0
bnkr/suds
suds/sudsobject.py
201
11165
# This program is free software; you can redistribute it and/or modify # it under the terms of the (LGPL) GNU Lesser General Public License as # published by the Free Software Foundation; either version 3 of the # License, or (at your option) any later version. # # 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 Library Lesser General Public License for more details at # ( http://www.gnu.org/licenses/lgpl.html ). # # You should have received a copy of the GNU Lesser General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # written by: Jeff Ortel ( jortel@redhat.com ) """ The I{sudsobject} module provides a collection of suds objects that are primarily used for the highly dynamic interactions with wsdl/xsd defined types. """ from logging import getLogger from suds import * from new import classobj log = getLogger(__name__) def items(sobject): """ Extract the I{items} from a suds object much like the items() method works on I{dict}. @param sobject: A suds object @type sobject: L{Object} @return: A list of items contained in I{sobject}. @rtype: [(key, value),...] """ for item in sobject: yield item def asdict(sobject): """ Convert a sudsobject into a dictionary. @param sobject: A suds object @type sobject: L{Object} @return: A python dictionary containing the items contained in I{sobject}. @rtype: dict """ return dict(items(sobject)) def merge(a, b): """ Merge all attributes and metadata from I{a} to I{b}. @param a: A I{source} object @type a: L{Object} @param b: A I{destination} object @type b: L{Object} """ for item in a: setattr(b, item[0], item[1]) b.__metadata__ = b.__metadata__ return b def footprint(sobject): """ Get the I{virtual footprint} of the object. This is really a count of the attributes in the branch with a significant value. @param sobject: A suds object. @type sobject: L{Object} @return: The branch footprint. @rtype: int """ n = 0 for a in sobject.__keylist__: v = getattr(sobject, a) if v is None: continue if isinstance(v, Object): n += footprint(v) continue if hasattr(v, '__len__'): if len(v): n += 1 continue n +=1 return n class Factory: cache = {} @classmethod def subclass(cls, name, bases, dict={}): if not isinstance(bases, tuple): bases = (bases,) name = name.encode('utf-8') key = '.'.join((name, str(bases))) subclass = cls.cache.get(key) if subclass is None: subclass = classobj(name, bases, dict) cls.cache[key] = subclass return subclass @classmethod def object(cls, classname=None, dict={}): if classname is not None: subclass = cls.subclass(classname, Object) inst = subclass() else: inst = Object() for a in dict.items(): setattr(inst, a[0], a[1]) return inst @classmethod def metadata(cls): return Metadata() @classmethod def property(cls, name, value=None): subclass = cls.subclass(name, Property) return subclass(value) class Object: def __init__(self): self.__keylist__ = [] self.__printer__ = Printer() self.__metadata__ = Metadata() def __setattr__(self, name, value): builtin = name.startswith('__') and name.endswith('__') if not builtin and \ name not in self.__keylist__: self.__keylist__.append(name) self.__dict__[name] = value def __delattr__(self, name): try: del self.__dict__[name] builtin = name.startswith('__') and name.endswith('__') if not builtin: self.__keylist__.remove(name) except: cls = self.__class__.__name__ raise AttributeError, "%s has no attribute '%s'" % (cls, name) def __getitem__(self, name): if isinstance(name, int): name = self.__keylist__[int(name)] return getattr(self, name) def __setitem__(self, name, value): setattr(self, name, value) def __iter__(self): return Iter(self) def __len__(self): return len(self.__keylist__) def __contains__(self, name): return name in self.__keylist__ def __repr__(self): return str(self) def __str__(self): return unicode(self).encode('utf-8') def __unicode__(self): return self.__printer__.tostr(self) class Iter: def __init__(self, sobject): self.sobject = sobject self.keylist = self.__keylist(sobject) self.index = 0 def next(self): keylist = self.keylist nkeys = len(self.keylist) while self.index < nkeys: k = keylist[self.index] self.index += 1 if hasattr(self.sobject, k): v = getattr(self.sobject, k) return (k, v) raise StopIteration() def __keylist(self, sobject): keylist = sobject.__keylist__ try: keyset = set(keylist) ordering = sobject.__metadata__.ordering ordered = set(ordering) if not ordered.issuperset(keyset): log.debug( '%s must be superset of %s, ordering ignored', keylist, ordering) raise KeyError() return ordering except: return keylist def __iter__(self): return self class Metadata(Object): def __init__(self): self.__keylist__ = [] self.__printer__ = Printer() class Facade(Object): def __init__(self, name): Object.__init__(self) md = self.__metadata__ md.facade = name class Property(Object): def __init__(self, value): Object.__init__(self) self.value = value def items(self): for item in self: if item[0] != 'value': yield item def get(self): return self.value def set(self, value): self.value = value return self class Printer: """ Pretty printing of a Object object. """ @classmethod def indent(cls, n): return '%*s'%(n*3,' ') def tostr(self, object, indent=-2): """ get s string representation of object """ history = [] return self.process(object, history, indent) def process(self, object, h, n=0, nl=False): """ print object using the specified indent (n) and newline (nl). """ if object is None: return 'None' if isinstance(object, Object): if len(object) == 0: return '<empty>' else: return self.print_object(object, h, n+2, nl) if isinstance(object, dict): if len(object) == 0: return '<empty>' else: return self.print_dictionary(object, h, n+2, nl) if isinstance(object, (list,tuple)): if len(object) == 0: return '<empty>' else: return self.print_collection(object, h, n+2) if isinstance(object, basestring): return '"%s"' % tostr(object) return '%s' % tostr(object) def print_object(self, d, h, n, nl=False): """ print complex using the specified indent (n) and newline (nl). """ s = [] cls = d.__class__ md = d.__metadata__ if d in h: s.append('(') s.append(cls.__name__) s.append(')') s.append('...') return ''.join(s) h.append(d) if nl: s.append('\n') s.append(self.indent(n)) if cls != Object: s.append('(') if isinstance(d, Facade): s.append(md.facade) else: s.append(cls.__name__) s.append(')') s.append('{') for item in d: if self.exclude(d, item): continue item = self.unwrap(d, item) s.append('\n') s.append(self.indent(n+1)) if isinstance(item[1], (list,tuple)): s.append(item[0]) s.append('[]') else: s.append(item[0]) s.append(' = ') s.append(self.process(item[1], h, n, True)) s.append('\n') s.append(self.indent(n)) s.append('}') h.pop() return ''.join(s) def print_dictionary(self, d, h, n, nl=False): """ print complex using the specified indent (n) and newline (nl). """ if d in h: return '{}...' h.append(d) s = [] if nl: s.append('\n') s.append(self.indent(n)) s.append('{') for item in d.items(): s.append('\n') s.append(self.indent(n+1)) if isinstance(item[1], (list,tuple)): s.append(tostr(item[0])) s.append('[]') else: s.append(tostr(item[0])) s.append(' = ') s.append(self.process(item[1], h, n, True)) s.append('\n') s.append(self.indent(n)) s.append('}') h.pop() return ''.join(s) def print_collection(self, c, h, n): """ print collection using the specified indent (n) and newline (nl). """ if c in h: return '[]...' h.append(c) s = [] for item in c: s.append('\n') s.append(self.indent(n)) s.append(self.process(item, h, n-2)) s.append(',') h.pop() return ''.join(s) def unwrap(self, d, item): """ translate (unwrap) using an optional wrapper function """ nopt = ( lambda x: x ) try: md = d.__metadata__ pmd = getattr(md, '__print__', None) if pmd is None: return item wrappers = getattr(pmd, 'wrappers', {}) fn = wrappers.get(item[0], nopt) return (item[0], fn(item[1])) except: pass return item def exclude(self, d, item): """ check metadata for excluded items """ try: md = d.__metadata__ pmd = getattr(md, '__print__', None) if pmd is None: return False excludes = getattr(pmd, 'excludes', []) return ( item[0] in excludes ) except: pass return False
lgpl-3.0
edespino/gpdb
gpAux/extensions/gphdfs/regression/input/regression/createData.py
23
7087
#!/usr/bin/env python """ Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved. This program and the accompanying materials are made available under the terms of the 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. """ ############################################################################ # Set up some globals, and import gptest # [YOU DO NOT NEED TO CHANGE THESE] # import sys,string, os, subprocess, signal,time #MYD = os.path.abspath(os.path.dirname(__file__)) #mkpath = lambda *x: os.path.join(MYD, *x) #UPD = os.path.abspath(mkpath('..')) #if UPD not in sys.path: # sys.path.append(UPD) #import gptest #from gptest import psql, shell #import re #from time import sleep if len(sys.argv) < 2: print "usage: createData.py <number of lines> <datatype>\n" print "datatype:" print "all:regression:time:timestamp:date:bigint:int:smallest:real:float:boolean:varchar:bpchar:numeric:text\n" sys.exit() LINE_NUM=int(sys.argv[1]) DATATYPE=sys.argv[2] def printtimestr(x, datatype): HH=str(x % 24).zfill(2) MM=str(x % 60).zfill(2) SS=str(x % 60).zfill(2) sss=str(x % 999) h=str(x % 12).zfill(2) ampm=x % 2 ampmlist= ['AM','PM'] timezone= x % 5 #timezonelist= ['ACDT','ACT','PST','ADT','ACWST','GMT0','EST5EDT','zulu'] timezonelist= ['ACT','PST','ADT','GMT0','zulu'] year = str((x % 1000) + 1).zfill(4) month = str((x % 12) + 1).zfill(2) monthindex = x%24 monthlist = ['January','Jan','February','Feb','March','Mar','April','Apr','May','May','June','Jun','July','Jul','August','Aug','September','Sept','October','Oct','November','Nov','December','Dec'] day = str((x % 30) + 1).zfill(2) daynofill = str((x % 30) + 1) if (datatype == 'time'): #col1 - HH:MM:SS col1 = HH+ ':' +MM+ ':' +SS #col2 - HH:MM:SS.sss col2 = col1+ '.' +sss #col3 - HHMMSS col3 = HH+MM+SS #col4 - HH:MM AM/PM col4 = h+ ':' +MM+ ' ' +ampmlist[ampm] #col5 - HH:MM:SS.sss-h (timeoffset) col5 = col2+ '-' +str(timezone) #col6 - HH:MM:SS-HH:MM(timeoffset) col6 = col1+ '-' +h+ ':00' #col7 - HH:MM-HH:MM(timeoffset) col7 = HH+':'+MM+ '-' +h+ ':00' #col8 - HHMMSS-HH(timeoffset) col8 = col3+ '-' +h #col9 - HH:MM:SS XXX(timezone) col9 = col1+ " " +timezonelist[timezone] return col1+'\t'+col2+'\t'+col3+'\t'+col4+'\t'+col5+'\t'+col6+'\t'+col7+'\t'+col8+'\t'+col9+'\t\\N' elif (datatype == 'timestamp'): #1999-01-08 04:05:06 col1 = year+'-' +month+ '-' +day+ ' ' +HH+ ':' +MM+ ':' +SS #1999-01-08 04:05:06 -8:00 col2 = col1+ ' -' +str(timezone)+ ':00' #January 8 04:05:06 1999 PST col3 = monthlist[monthindex]+ ' ' +daynofill+ ' ' +HH+ ':' +MM+ ':' +SS+ ' ' +year+ ' ' +timezonelist[timezone] return col1+'\t'+col2+'\t'+col3+'\t\\N' elif (datatype == 'date'): #1900-01-01 col1 = year+ '-' +month+ '-' +day #September 01, 1999 col2 = monthlist[monthindex]+ ' ' +day+ ', ' +year #1/8/1999 col3 = month+ '/' +day+ '/' +year #1999-Jan-08 col4 = year+ '-' +monthlist[monthindex]+ '-' +day #Jan-08-1999 col5 = monthlist[monthindex]+ '-' +month+ '-' +year #08-Jan-1999 col6 = month+ '-' +monthlist[monthindex]+ '-' +year #January 8, 99 BC col7 = monthlist[monthindex]+' ' +month+ ', ' +year+ ' BC' return col1+'\t'+col2+'\t'+col3+'\t'+col4+'\t'+col5+'\t'+col6+'\t'+col7+'\t\\N' def regression(x): numRecipes = str(1664525 * x + 1013904223) Borland = str(22695477 * x + 1) glibc = str(1103515245 * x + 12345) appCarbonLib = str((16807 * x) % 2147483647) vax = str(69069 * x + 1) javaRandomClass = str(25214903917 * x + 11) return str(x)+'\t'+str(hex(x))+'\t'+numRecipes+'\t'+Borland+'\t'+glibc+'\t'+appCarbonLib+'\t'+vax+'\t'+javaRandomClass def printintstr(x, max, min): if (x < max): m = x else: m = 0 maxsubx = max - m minplusx = min + m return str(max)+'\t'+str(min)+'\t'+str(m)+'\t'+str(maxsubx)+'\t'+str(minplusx)+'\t\\N' def printfloatstr(x,max,min): pi = float(22)/float(7) pimulti = pi*x return str(max)+'\t'+str(min)+'\t'+str(pi)+'\t'+str(pimulti)+'\t\\N' def printbool(x): n = x % 2 if n == 0: return 'true\t\\N' else: return 'false\t\\N' def printchar(x): strx = '' currentchar = x%128 for m in range(currentchar): strx = strx+chr(currentchar) if (currentchar == 9 or currentchar == 13 or currentchar == 10): strx = 'skip' return str(x)+'\t'+strx+'\t\\N' for x in range(LINE_NUM): if (DATATYPE == 'regression'): print regression(x) elif (DATATYPE == 'time'): print 'time\t'+printtimestr(x,'time') elif (DATATYPE == 'timestamp'): print 'timestamp\t'+printtimestr(x,'timestamp') elif (DATATYPE == 'date'): print 'date\t'+printtimestr(x,'date') elif (DATATYPE == 'bigint'): print 'bigint\t'+printintstr(x,9223372036854775807,-9223372036854775808) elif (DATATYPE == 'int'): print 'int\t'+printintstr(x,2147483647,-2147483648) elif (DATATYPE == 'smallint'): print 'smallint\t'+printintstr(x,32767,-32768) elif (DATATYPE == 'real'): print 'real\t'+printfloatstr(x, 3.4028235E+38, -3.4028234E+38) elif (DATATYPE == 'float'): print 'float\t'+printfloatstr(x,+1.797693134862315E+308, -1.797693134862315E+308) elif (DATATYPE == 'boolean'): print 'boolean\t'+printbool(x) elif (DATATYPE == 'varchar'): print 'varchar\t'+printchar(x) elif (DATATYPE == 'bpchar'): print 'bpchar\t'+printchar(x) elif (DATATYPE == 'numeric'): print 'numeric\t'+printintstr(x, 9223372036854775807000, -9223372036854775808000) elif (DATATYPE == 'text'): print 'text\t'+printchar(x) elif (DATATYPE == 'all'): print regression(x)+ '\t' +printtimestr(x,'time')+ '\t' +printtimestr(x,'timestamp')+ '\t' +printtimestr(x,'date')+ '\t' +printintstr(x,9223372036854775807,-9223372036854775808)+ '\t' +printintstr(x,2147483647,-2147483648)+ '\t' +printintstr(x,32767,-32768)+ '\t' +printfloatstr(x, 3.4028235E+38, -3.4028234E+38)+ '\t' +printfloatstr(x, +1.797693134862315E+308, -1.797693134862315E+308)+ '\t' +printbool(x)+ '\t' +printchar(x)+ '\t'+printchar(x)+ '\t'+printintstr(x,9223372036854775807000,-9223372036854775808000)+ '\t'+printchar(x)
apache-2.0
drawks/ansible
lib/ansible/modules/network/aci/aci_firmware_source.py
27
7594
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2018, Dag Wieers (dagwieers) <dag@wieers.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified'} DOCUMENTATION = r''' --- module: aci_firmware_source short_description: Manage firmware image sources (firmware:OSource) description: - Manage firmware image sources on Cisco ACI fabrics. version_added: '2.5' options: source: description: - The identifying name for the outside source of images, such as an HTTP or SCP server. type: str required: yes aliases: [ name, source_name ] polling_interval: description: - Polling interval in minutes. type: int url_protocol: description: - The Firmware download protocol. type: str choices: [ http, local, scp, usbkey ] default: scp aliases: [ url_proto ] url: description: The firmware URL for the image(s) on the source. type: str url_password: description: The Firmware password or key string. type: str url_username: description: The username for the source. type: str state: description: - Use C(present) or C(absent) for adding or removing. - Use C(query) for listing an object or multiple objects. type: str choices: [ absent, present, query ] default: present extends_documentation_fragment: aci seealso: - name: APIC Management Information Model reference description: More information about the internal APIC class B(firmware:OSource). link: https://developer.cisco.com/docs/apic-mim-ref/ author: - Dag Wieers (@dagwieers) ''' EXAMPLES = r''' - name: Add firmware source aci_firmware_source: host: apic username: admin password: SomeSecretPassword source: aci-msft-pkg-3.1.1i.zip url: foo.bar.cisco.com/download/cisco/aci/aci-msft-pkg-3.1.1i.zip url_protocol: http state: present delegate_to: localhost - name: Remove firmware source aci_firmware_source: host: apic username: admin password: SomeSecretPassword source: aci-msft-pkg-3.1.1i.zip state: absent delegate_to: localhost - name: Query a specific firmware source aci_firmware_source: host: apic username: admin password: SomeSecretPassword source: aci-msft-pkg-3.1.1i.zip state: query delegate_to: localhost register: query_result - name: Query all firmware sources aci_firmware_source: host: apic username: admin password: SomeSecretPassword state: query delegate_to: localhost register: query_result ''' RETURN = r''' current: description: The existing configuration from the APIC after the module has finished returned: success type: list sample: [ { "fvTenant": { "attributes": { "descr": "Production environment", "dn": "uni/tn-production", "name": "production", "nameAlias": "", "ownerKey": "", "ownerTag": "" } } } ] error: description: The error information as returned from the APIC returned: failure type: dict sample: { "code": "122", "text": "unknown managed object class foo" } raw: description: The raw output returned by the APIC REST API (xml or json) returned: parse error type: str sample: '<?xml version="1.0" encoding="UTF-8"?><imdata totalCount="1"><error code="122" text="unknown managed object class foo"/></imdata>' sent: description: The actual/minimal configuration pushed to the APIC returned: info type: list sample: { "fvTenant": { "attributes": { "descr": "Production environment" } } } previous: description: The original configuration from the APIC before the module has started returned: info type: list sample: [ { "fvTenant": { "attributes": { "descr": "Production", "dn": "uni/tn-production", "name": "production", "nameAlias": "", "ownerKey": "", "ownerTag": "" } } } ] proposed: description: The assembled configuration from the user-provided parameters returned: info type: dict sample: { "fvTenant": { "attributes": { "descr": "Production environment", "name": "production" } } } filter_string: description: The filter string used for the request returned: failure or debug type: str sample: ?rsp-prop-include=config-only method: description: The HTTP method used for the request to the APIC returned: failure or debug type: str sample: POST response: description: The HTTP response from the APIC returned: failure or debug type: str sample: OK (30 bytes) status: description: The HTTP status from the APIC returned: failure or debug type: int sample: 200 url: description: The HTTP url used for the request to the APIC returned: failure or debug type: str sample: https://10.11.12.13/api/mo/uni/tn-production.json ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.network.aci.aci import ACIModule, aci_argument_spec def main(): argument_spec = aci_argument_spec() argument_spec.update( source=dict(type='str', aliases=['name', 'source_name']), # Not required for querying all objects polling_interval=dict(type='int'), url=dict(type='str'), url_username=dict(type='str'), url_password=dict(type='str', no_log=True), url_protocol=dict(type='str', default='scp', choices=['http', 'local', 'scp', 'usbkey'], aliases=['url_proto']), state=dict(type='str', default='present', choices=['absent', 'present', 'query']), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ ['state', 'absent', ['source']], ['state', 'present', ['url_protocol', 'source', 'url']], ], ) polling_interval = module.params['polling_interval'] url_protocol = module.params['url_protocol'] state = module.params['state'] source = module.params['source'] url = module.params['url'] url_password = module.params['url_password'] url_username = module.params['url_username'] aci = ACIModule(module) aci.construct_url( root_class=dict( aci_class='firmwareOSource', aci_rn='fabric/fwrepop', module_object=source, target_filter={'name': source}, ), ) aci.get_existing() if state == 'present': aci.payload( aci_class='firmwareOSource', class_config=dict( name=source, url=url, password=url_password, pollingInterval=polling_interval, proto=url_protocol, user=url_username, ), ) aci.get_diff(aci_class='firmwareOSource') aci.post_config() elif state == 'absent': aci.delete_config() aci.exit_json() if __name__ == "__main__": main()
gpl-3.0
shitolepriya/test-erp
erpnext/accounts/doctype/bank_reconciliation/bank_reconciliation.py
23
2290
# 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.utils import flt, getdate, nowdate from frappe import msgprint, _ from frappe.model.document import Document class BankReconciliation(Document): def get_details(self): if not (self.bank_account and self.from_date and self.to_date): msgprint("Bank Account, From Date and To Date are Mandatory") return condition = "" if not self.include_reconciled_entries: condition = "and ifnull(clearance_date, '') in ('', '0000-00-00')" dl = frappe.db.sql("""select t1.name, t1.cheque_no, t1.cheque_date, t2.debit, t2.credit, t1.posting_date, t2.against_account, t1.clearance_date from `tabJournal Entry` t1, `tabJournal Entry Account` t2 where t2.parent = t1.name and t2.account = %s and t1.posting_date >= %s and t1.posting_date <= %s and t1.docstatus=1 and ifnull(t1.is_opening, 'No') = 'No' %s order by t1.posting_date""" % ('%s', '%s', '%s', condition), (self.bank_account, self.from_date, self.to_date), as_dict=1) self.set('journal_entries', []) self.total_amount = 0.0 for d in dl: nl = self.append('journal_entries', {}) nl.posting_date = d.posting_date nl.voucher_id = d.name nl.cheque_number = d.cheque_no nl.cheque_date = d.cheque_date nl.debit = d.debit nl.credit = d.credit nl.against_account = d.against_account nl.clearance_date = d.clearance_date self.total_amount += flt(d.debit) - flt(d.credit) def update_details(self): vouchers = [] for d in self.get('journal_entries'): if d.clearance_date: if d.cheque_date and getdate(d.clearance_date) < getdate(d.cheque_date): frappe.throw(_("Clearance date cannot be before check date in row {0}").format(d.idx)) frappe.db.set_value("Journal Entry", d.voucher_id, "clearance_date", d.clearance_date) frappe.db.sql("""update `tabJournal Entry` set clearance_date = %s, modified = %s where name=%s""", (d.clearance_date, nowdate(), d.voucher_id)) vouchers.append(d.voucher_id) if vouchers: msgprint("Clearance Date updated in: {0}".format(", ".join(vouchers))) else: msgprint(_("Clearance Date not mentioned"))
agpl-3.0
mancoast/CPythonPyc_test
fail/311_test_funcattrs.py
1
9974
from test import support import types import unittest class FuncAttrsTest(unittest.TestCase): def setUp(self): class F: def a(self): pass def b(): return 3 self.fi = F() self.F = F self.b = b def cannot_set_attr(self, obj, name, value, exceptions): try: setattr(obj, name, value) except exceptions: pass else: self.fail("shouldn't be able to set %s to %r" % (name, value)) try: delattr(obj, name) except exceptions: pass else: self.fail("shouldn't be able to del %s" % name) class FunctionPropertiesTest(FuncAttrsTest): # Include the external setUp method that is common to all tests def test_module(self): self.assertEqual(self.b.__module__, __name__) def test_dir_includes_correct_attrs(self): self.b.known_attr = 7 self.assertTrue('known_attr' in dir(self.b), "set attributes not in dir listing of method") # Test on underlying function object of method self.F.a.known_attr = 7 self.assertTrue('known_attr' in dir(self.fi.a), "set attribute on function " "implementations, should show up in next dir") def test_duplicate_function_equality(self): # Body of `duplicate' is the exact same as self.b def duplicate(): 'my docstring' return 3 self.assertNotEqual(self.b, duplicate) def test_copying___code__(self): def test(): pass self.assertEqual(test(), None) test.__code__ = self.b.__code__ self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily def test___globals__(self): self.assertEqual(self.b.__globals__, globals()) self.cannot_set_attr(self.b, '__globals__', 2, (AttributeError, TypeError)) def test___name__(self): self.assertEqual(self.b.__name__, 'b') self.b.__name__ = 'c' self.assertEqual(self.b.__name__, 'c') self.b.__name__ = 'd' self.assertEqual(self.b.__name__, 'd') # __name__ and __name__ must be a string self.cannot_set_attr(self.b, '__name__', 7, TypeError) # __name__ must be available when in restricted mode. Exec will raise # AttributeError if __name__ is not available on f. s = """def f(): pass\nf.__name__""" exec(s, {'__builtins__': {}}) # Test on methods, too self.assertEqual(self.fi.a.__name__, 'a') self.cannot_set_attr(self.fi.a, "__name__", 'a', AttributeError) def test___code__(self): num_one, num_two = 7, 8 def a(): pass def b(): return 12 def c(): return num_one def d(): return num_two def e(): return num_one, num_two for func in [a, b, c, d, e]: self.assertEqual(type(func.__code__), types.CodeType) self.assertEqual(c(), 7) self.assertEqual(d(), 8) d.__code__ = c.__code__ self.assertEqual(c.__code__, d.__code__) self.assertEqual(c(), 7) # self.assertEqual(d(), 7) try: b.__code__ = c.__code__ except ValueError: pass else: self.fail( "__code__ with different numbers of free vars should not be " "possible") try: e.__code__ = d.__code__ except ValueError: pass else: self.fail( "__code__ with different numbers of free vars should not be " "possible") def test_blank_func_defaults(self): self.assertEqual(self.b.__defaults__, None) del self.b.__defaults__ self.assertEqual(self.b.__defaults__, None) def test_func_default_args(self): def first_func(a, b): return a+b def second_func(a=1, b=2): return a+b self.assertEqual(first_func.__defaults__, None) self.assertEqual(second_func.__defaults__, (1, 2)) first_func.__defaults__ = (1, 2) self.assertEqual(first_func.__defaults__, (1, 2)) self.assertEqual(first_func(), 3) self.assertEqual(first_func(3), 5) self.assertEqual(first_func(3, 5), 8) del second_func.__defaults__ self.assertEqual(second_func.__defaults__, None) try: second_func() except TypeError: pass else: self.fail( "func_defaults does not update; deleting it does not remove " "requirement") class ImplicitReferencesTest(FuncAttrsTest): def test___class__(self): self.assertEqual(self.fi.a.__self__.__class__, self.F) self.cannot_set_attr(self.fi.a, "__class__", self.F, TypeError) def test___func__(self): self.assertEqual(self.fi.a.__func__, self.F.a) self.cannot_set_attr(self.fi.a, "__func__", self.F.a, AttributeError) def test___self__(self): self.assertEqual(self.fi.a.__self__, self.fi) self.cannot_set_attr(self.fi.a, "__self__", self.fi, AttributeError) def test___func___non_method(self): # Behavior should be the same when a method is added via an attr # assignment self.fi.id = types.MethodType(id, self.fi) self.assertEqual(self.fi.id(), id(self.fi)) # Test usage try: self.fi.id.unknown_attr except AttributeError: pass else: self.fail("using unknown attributes should raise AttributeError") # Test assignment and deletion self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError) class ArbitraryFunctionAttrTest(FuncAttrsTest): def test_set_attr(self): self.b.known_attr = 7 self.assertEqual(self.b.known_attr, 7) try: self.fi.a.known_attr = 7 except AttributeError: pass else: self.fail("setting attributes on methods should raise error") def test_delete_unknown_attr(self): try: del self.b.unknown_attr except AttributeError: pass else: self.fail("deleting unknown attribute should raise TypeError") def test_unset_attr(self): for func in [self.b, self.fi.a]: try: func.non_existent_attr except AttributeError: pass else: self.fail("using unknown attributes should raise " "AttributeError") class FunctionDictsTest(FuncAttrsTest): def test_setting_dict_to_invalid(self): self.cannot_set_attr(self.b, '__dict__', None, TypeError) from collections import UserDict d = UserDict({'known_attr': 7}) self.cannot_set_attr(self.fi.a.__func__, '__dict__', d, TypeError) def test_setting_dict_to_valid(self): d = {'known_attr': 7} self.b.__dict__ = d # Test assignment self.assertEqual(d, self.b.__dict__) # ... and on all the different ways of referencing the method's func self.F.a.__dict__ = d self.assertEqual(d, self.fi.a.__func__.__dict__) self.assertEqual(d, self.fi.a.__dict__) # Test value self.assertEqual(self.b.known_attr, 7) self.assertEqual(self.b.__dict__['known_attr'], 7) # ... and again, on all the different method's names self.assertEqual(self.fi.a.__func__.known_attr, 7) self.assertEqual(self.fi.a.known_attr, 7) def test_delete___dict__(self): try: del self.b.__dict__ except TypeError: pass else: self.fail("deleting function dictionary should raise TypeError") def test_unassigned_dict(self): self.assertEqual(self.b.__dict__, {}) def test_func_as_dict_key(self): value = "Some string" d = {} d[self.b] = value self.assertEqual(d[self.b], value) class FunctionDocstringTest(FuncAttrsTest): def test_set_docstring_attr(self): self.assertEqual(self.b.__doc__, None) docstr = "A test method that does nothing" self.b.__doc__ = docstr self.F.a.__doc__ = docstr self.assertEqual(self.b.__doc__, docstr) self.assertEqual(self.fi.a.__doc__, docstr) self.cannot_set_attr(self.fi.a, "__doc__", docstr, AttributeError) def test_delete_docstring(self): self.b.__doc__ = "The docstring" del self.b.__doc__ self.assertEqual(self.b.__doc__, None) def cell(value): """Create a cell containing the given value.""" def f(): print(a) a = value return f.__closure__[0] def empty_cell(empty=True): """Create an empty cell.""" def f(): print(a) # the intent of the following line is simply "if False:"; it's # spelt this way to avoid the danger that a future optimization # might simply remove an "if False:" code block. if not empty: a = 1729 return f.__closure__[0] class CellTest(unittest.TestCase): def test_comparison(self): # These tests are here simply to exercise the comparison code; # their presence should not be interpreted as providing any # guarantees about the semantics (or even existence) of cell # comparisons in future versions of CPython. self.assertTrue(cell(2) < cell(3)) self.assertTrue(empty_cell() < cell('saturday')) self.assertTrue(empty_cell() == empty_cell()) self.assertTrue(cell(-36) == cell(-36.0)) self.assertTrue(cell(True) > empty_cell()) class StaticMethodAttrsTest(unittest.TestCase): def test_func_attribute(self): def f(): pass c = classmethod(f) self.assertTrue(c.__func__ is f) s = staticmethod(f) self.assertTrue(s.__func__ is f) def test_main(): support.run_unittest(FunctionPropertiesTest, ImplicitReferencesTest, ArbitraryFunctionAttrTest, FunctionDictsTest, FunctionDocstringTest, CellTest, StaticMethodAttrsTest) if __name__ == "__main__": test_main()
gpl-3.0
wezhang/vim-setup
bundle/python-mode/pymode/libs3/rope/refactor/occurrences.py
91
10704
import re import rope.base.pynames from rope.base import pynames, pyobjects, codeanalyze, evaluate, exceptions, utils, worder class Finder(object): """For finding occurrences of a name The constructor takes a `filters` argument. It should be a list of functions that take a single argument. For each possible occurrence, these functions are called in order with the an instance of `Occurrence`: * If it returns `None` other filters are tried. * If it returns `True`, the occurrence will be a match. * If it returns `False`, the occurrence will be skipped. * If all of the filters return `None`, it is skipped also. """ def __init__(self, pycore, name, filters=[lambda o: True], docs=False): self.pycore = pycore self.name = name self.docs = docs self.filters = filters self._textual_finder = _TextualFinder(name, docs=docs) def find_occurrences(self, resource=None, pymodule=None): """Generate `Occurrence` instances""" tools = _OccurrenceToolsCreator(self.pycore, resource=resource, pymodule=pymodule, docs=self.docs) for offset in self._textual_finder.find_offsets(tools.source_code): occurrence = Occurrence(tools, offset) for filter in self.filters: result = filter(occurrence) if result is None: continue if result: yield occurrence break def create_finder(pycore, name, pyname, only_calls=False, imports=True, unsure=None, docs=False, instance=None, in_hierarchy=False): """A factory for `Finder` Based on the arguments it creates a list of filters. `instance` argument is needed only when you want implicit interfaces to be considered. """ pynames = set([pyname]) filters = [] if only_calls: filters.append(CallsFilter()) if not imports: filters.append(NoImportsFilter()) if isinstance(instance, rope.base.pynames.ParameterName): for pyobject in instance.get_objects(): try: pynames.add(pyobject[name]) except exceptions.AttributeNotFoundError: pass for pyname in pynames: filters.append(PyNameFilter(pyname)) if in_hierarchy: filters.append(InHierarchyFilter(pyname)) if unsure: filters.append(UnsureFilter(unsure)) return Finder(pycore, name, filters=filters, docs=docs) class Occurrence(object): def __init__(self, tools, offset): self.tools = tools self.offset = offset self.resource = tools.resource @utils.saveit def get_word_range(self): return self.tools.word_finder.get_word_range(self.offset) @utils.saveit def get_primary_range(self): return self.tools.word_finder.get_primary_range(self.offset) @utils.saveit def get_pyname(self): try: return self.tools.name_finder.get_pyname_at(self.offset) except exceptions.BadIdentifierError: pass @utils.saveit def get_primary_and_pyname(self): try: return self.tools.name_finder.get_primary_and_pyname_at(self.offset) except exceptions.BadIdentifierError: pass @utils.saveit def is_in_import_statement(self): return (self.tools.word_finder.is_from_statement(self.offset) or self.tools.word_finder.is_import_statement(self.offset)) def is_called(self): return self.tools.word_finder.is_a_function_being_called(self.offset) def is_defined(self): return self.tools.word_finder.is_a_class_or_function_name_in_header(self.offset) def is_a_fixed_primary(self): return self.tools.word_finder.is_a_class_or_function_name_in_header(self.offset) or \ self.tools.word_finder.is_a_name_after_from_import(self.offset) def is_written(self): return self.tools.word_finder.is_assigned_here(self.offset) def is_unsure(self): return unsure_pyname(self.get_pyname()) @property @utils.saveit def lineno(self): offset = self.get_word_range()[0] return self.tools.pymodule.lines.get_line_number(offset) def same_pyname(expected, pyname): """Check whether `expected` and `pyname` are the same""" if expected is None or pyname is None: return False if expected == pyname: return True if type(expected) not in (pynames.ImportedModule, pynames.ImportedName) and \ type(pyname) not in (pynames.ImportedModule, pynames.ImportedName): return False return expected.get_definition_location() == pyname.get_definition_location() and \ expected.get_object() == pyname.get_object() def unsure_pyname(pyname, unbound=True): """Return `True` if we don't know what this name references""" if pyname is None: return True if unbound and not isinstance(pyname, pynames.UnboundName): return False if pyname.get_object() == pyobjects.get_unknown(): return True class PyNameFilter(object): """For finding occurrences of a name""" def __init__(self, pyname): self.pyname = pyname def __call__(self, occurrence): if same_pyname(self.pyname, occurrence.get_pyname()): return True class InHierarchyFilter(object): """For finding occurrences of a name""" def __init__(self, pyname, implementations_only=False): self.pyname = pyname self.impl_only = implementations_only self.pyclass = self._get_containing_class(pyname) if self.pyclass is not None: self.name = pyname.get_object().get_name() self.roots = self._get_root_classes(self.pyclass, self.name) else: self.roots = None def __call__(self, occurrence): if self.roots is None: return pyclass = self._get_containing_class(occurrence.get_pyname()) if pyclass is not None: roots = self._get_root_classes(pyclass, self.name) if self.roots.intersection(roots): return True def _get_containing_class(self, pyname): if isinstance(pyname, pynames.DefinedName): scope = pyname.get_object().get_scope() parent = scope.parent if parent is not None and parent.get_kind() == 'Class': return parent.pyobject def _get_root_classes(self, pyclass, name): if self.impl_only and pyclass == self.pyclass: return set([pyclass]) result = set() for superclass in pyclass.get_superclasses(): if name in superclass: result.update(self._get_root_classes(superclass, name)) if not result: return set([pyclass]) return result class UnsureFilter(object): def __init__(self, unsure): self.unsure = unsure def __call__(self, occurrence): if occurrence.is_unsure() and self.unsure(occurrence): return True class NoImportsFilter(object): def __call__(self, occurrence): if occurrence.is_in_import_statement(): return False class CallsFilter(object): def __call__(self, occurrence): if not occurrence.is_called(): return False class _TextualFinder(object): def __init__(self, name, docs=False): self.name = name self.docs = docs self.comment_pattern = _TextualFinder.any('comment', [r'#[^\n]*']) self.string_pattern = _TextualFinder.any( 'string', [codeanalyze.get_string_pattern()]) self.pattern = self._get_occurrence_pattern(self.name) def find_offsets(self, source): if not self._fast_file_query(source): return if self.docs: searcher = self._normal_search else: searcher = self._re_search for matched in searcher(source): yield matched def _re_search(self, source): for match in self.pattern.finditer(source): for key, value in match.groupdict().items(): if value and key == 'occurrence': yield match.start(key) def _normal_search(self, source): current = 0 while True: try: found = source.index(self.name, current) current = found + len(self.name) if (found == 0 or not self._is_id_char(source[found - 1])) and \ (current == len(source) or not self._is_id_char(source[current])): yield found except ValueError: break def _is_id_char(self, c): return c.isalnum() or c == '_' def _fast_file_query(self, source): try: source.index(self.name) return True except ValueError: return False def _get_source(self, resource, pymodule): if resource is not None: return resource.read() else: return pymodule.source_code def _get_occurrence_pattern(self, name): occurrence_pattern = _TextualFinder.any('occurrence', ['\\b' + name + '\\b']) pattern = re.compile(occurrence_pattern + '|' + self.comment_pattern + '|' + self.string_pattern) return pattern @staticmethod def any(name, list_): return '(?P<%s>' % name + '|'.join(list_) + ')' class _OccurrenceToolsCreator(object): def __init__(self, pycore, resource=None, pymodule=None, docs=False): self.pycore = pycore self.__resource = resource self.__pymodule = pymodule self.docs = docs @property @utils.saveit def name_finder(self): return evaluate.ScopeNameFinder(self.pymodule) @property @utils.saveit def source_code(self): if self.__resource is not None: return self.resource.read() else: return self.pymodule.source_code @property @utils.saveit def word_finder(self): return worder.Worder(self.source_code, self.docs) @property @utils.saveit def resource(self): if self.__resource is not None: return self.__resource if self.__pymodule is not None: return self.__pymodule.resource @property @utils.saveit def pymodule(self): if self.__pymodule is not None: return self.__pymodule return self.pycore.resource_to_pyobject(self.resource)
apache-2.0
daniel1yuan/Persist
Persist/webapp/views.py
1
6162
from django.shortcuts import redirect,render from django.http import Http404, JsonResponse, HttpResponseForbidden, HttpResponse from django.contrib.auth import authenticate, login, logout from webapp.models import User, Customer, Habit from django.core import serializers from django.views.decorators.csrf import csrf_exempt from django.utils import timezone from datetime import datetime from webapp.helper import habits_arr, arr_str import json import os # Create your views here. def index(request): context = { 'title': 'Persist' } if request.user.is_authenticated(): return redirect("home") else: return render(request, 'webapp/landing.html', context) def home(request): if request.user.is_authenticated(): return render(request, 'webapp/home.html') else: return redirect("login_page") def login_page(request): if request.user.is_authenticated(): return redirect("home") context = { 'title': 'Persist' } return render(request, 'webapp/login.html', context) #Authentication Views @csrf_exempt def login_user(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return HttpResponse(json.dumps({"success": True})) else: return HttpResponse(json.dumps({"success": False})) def logout_user(request): logout(request) return HttpResponse(json.dumps({"success": True})) @csrf_exempt def add_user(request): username = request.POST['username'] password = request.POST['password'] user = User.objects.create_user(username=username, password=password) customer = Customer(user=user, habits="") customer.save() user.save() return HttpResponse(json.dumps({"success": True})) def del_cur_user(request): if request.user.is_authenticated(): user = request.user user.delete() return HttpResponse(json.dumps({"success": True})) else: return HttpResponse(json.dumps({"success": False})) def del_user(request): user = request.user #Check if the admin is logged on if user.is_authenticated() and user.has_perm('webapp'): username = request.POST['username'] user = User.objects.get(username=username) user.delete() return HttpResponse(json.dumps({"success": True})) return HttpResponse(json.dumps({"success": False})) def is_logged_in(request): if (request.user.is_authenticated()): return HttpResponse(json.dumps({"success": True, "logged_in": True})) else: return HttpResponse(json.dumps({"success": True, "logged_in": False})) return HttpResponse(json.dumps({"success": False})) def get_habit(request): habit_id = int(request.POST['habit_id']) try: habit_obj = Habit.objects.get(pk=habit_id) print habit_obj.monetary_amount habit_serial = serializers.serialize('json', [habit_obj]) #[1:-1] to remove brackets? return HttpResponse(json.dumps(habit_serial[1:-1]), content_type='application/json') except Habit.DoesNotExist: return HttpResponse(json.dumps({"pk": -1})) def create_habit(request): name = request.POST['name'] description = request.POST['description'] monetary_amount = int(request.POST['monetary_amount']) end_date = int(int((request.POST['end_date']))/(1000.0)) start_date = int((datetime.utcnow()-datetime(1970,1,1)).total_seconds()) last_clicked = int((datetime.utcnow()-datetime(1970,1,1)).total_seconds()) status = int(request.POST['success_status']) charity = int(request.POST['charity']) user = request.user if (not user.is_authenticated()): return HttpResponse(json.dumps({"success": False})) habit = Habit(name=name,description=description,monetary_amount=monetary_amount,end_date=end_date,status=status,charity=charity,user=user,start_date=start_date,last_clicked=last_clicked) print habit.start_date habit.save() user.customer.habits += "," + str(habit.pk) user.customer.save() return HttpResponse(json.dumps({"success": True,"pk":habit.pk})) def delete_habit(request): try: user = request.user customer = user.customer pk = request.POST['id'] habit = Habit.objects.get(pk=pk) habits = habits_arr(customer.habits) index = habits.index(int(pk)) del(habits[index]) customer.habits = arr_str(habits) customer.save() habit.delete() return HttpResponse(json.dumps({"success": True})) except: return HttpResponse(json.dumps({"success": False})) def change_habit(request): pk = request.POST['id'] habit = Habit.objects.get(pk=pk) if habit is None: return HttpResponse(json.dumps({"success": False})) else: try: habit.name = request.POST['name'] except: habit.name = habit.name try: habit.description = request.POST['description'] except: habit.description = habit.description try: habit.monetary_amount = request.POST['monetary_amount'] except: habit.monetary_amount = habit.monetary_amount try: habit.end_date = int((request.POST['end_date']))/(1000.0) except: habit.end_date = habit.end_date try: habit.last_clicked = int((request.POST['last_clicked']))/(1000.0) except: habit.last_clicked = habit.last_clicked try: habit.status = request.POST['success_status'] except: habit.status = habit.status try: habit.charity = request.POST['charity'] except: habit.charity = habit.charity habit.save() return HttpResponse(json.dumps({"success": True})) def get_all_habits(request): if request.user.is_authenticated(): habits = habits_arr(request.user.customer.habits) json_dict = {} for idx in habits: cur_habit = Habit.objects.get(pk=idx) cur_serial = serializers.serialize('json',[cur_habit])[1:-1] json_dict[idx] = cur_serial return HttpResponse(json.dumps(json_dict)) else: return HttpResponse(json.dumps({"success": False})) def get_username(request): if request.user.is_authenticated(): return HttpResponse(json.dumps({"success": True, "username": request.user.username})) else: return HttpResponse(json.dumps({"success": False}))
mit
matmutant/sl4a
python-build/python-libs/gdata/tests/gdata_test.py
87
14634
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'j.s@google.com (Jeff Scudder)' import unittest try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import gdata import atom from gdata import test_data import gdata.test_config as conf class StartIndexTest(unittest.TestCase): def setUp(self): self.start_index = gdata.StartIndex() def testToAndFromString(self): self.start_index.text = '1' self.assert_(self.start_index.text == '1') new_start_index = gdata.StartIndexFromString(self.start_index.ToString()) self.assert_(self.start_index.text == new_start_index.text) class ItemsPerPageTest(unittest.TestCase): def setUp(self): self.items_per_page = gdata.ItemsPerPage() def testToAndFromString(self): self.items_per_page.text = '10' self.assert_(self.items_per_page.text == '10') new_items_per_page = gdata.ItemsPerPageFromString( self.items_per_page.ToString()) self.assert_(self.items_per_page.text == new_items_per_page.text) class GDataEntryTest(unittest.TestCase): def testIdShouldBeCleaned(self): entry = gdata.GDataEntryFromString(test_data.XML_ENTRY_1) element_tree = ElementTree.fromstring(test_data.XML_ENTRY_1) self.assert_(element_tree.findall( '{http://www.w3.org/2005/Atom}id')[0].text != entry.id.text) self.assert_(entry.id.text == 'http://www.google.com/test/id/url') def testGeneratorShouldBeCleaned(self): feed = gdata.GDataFeedFromString(test_data.GBASE_FEED) element_tree = ElementTree.fromstring(test_data.GBASE_FEED) self.assert_(element_tree.findall('{http://www.w3.org/2005/Atom}generator' )[0].text != feed.generator.text) self.assert_(feed.generator.text == 'GoogleBase') def testAllowsEmptyId(self): entry = gdata.GDataEntry() try: entry.id = atom.Id() except AttributeError: self.fail('Empty id should not raise an attribute error.') class LinkFinderTest(unittest.TestCase): def setUp(self): self.entry = gdata.GDataEntryFromString(test_data.XML_ENTRY_1) def testLinkFinderGetsLicenseLink(self): self.assertEquals(isinstance(self.entry.GetLicenseLink(), atom.Link), True) self.assertEquals(self.entry.GetLicenseLink().href, 'http://creativecommons.org/licenses/by-nc/2.5/rdf') self.assertEquals(self.entry.GetLicenseLink().rel, 'license') def testLinkFinderGetsAlternateLink(self): self.assertEquals(isinstance(self.entry.GetAlternateLink(), atom.Link), True) self.assertEquals(self.entry.GetAlternateLink().href, 'http://www.provider-host.com/123456789') self.assertEquals(self.entry.GetAlternateLink().rel, 'alternate') class GDataFeedTest(unittest.TestCase): def testCorrectConversionToElementTree(self): test_feed = gdata.GDataFeedFromString(test_data.GBASE_FEED) self.assert_(test_feed.total_results is not None) element_tree = test_feed._ToElementTree() feed = element_tree.find('{http://www.w3.org/2005/Atom}feed') self.assert_(element_tree.find( '{http://a9.com/-/spec/opensearchrss/1.0/}totalResults') is not None) def testAllowsEmptyId(self): feed = gdata.GDataFeed() try: feed.id = atom.Id() except AttributeError: self.fail('Empty id should not raise an attribute error.') class BatchEntryTest(unittest.TestCase): def testCorrectConversionFromAndToString(self): batch_entry = gdata.BatchEntryFromString(test_data.BATCH_ENTRY) self.assertEquals(batch_entry.batch_id.text, 'itemB') self.assertEquals(batch_entry.id.text, 'http://www.google.com/base/feeds/items/' '2173859253842813008') self.assertEquals(batch_entry.batch_operation.type, 'insert') self.assertEquals(batch_entry.batch_status.code, '201') self.assertEquals(batch_entry.batch_status.reason, 'Created') new_entry = gdata.BatchEntryFromString(str(batch_entry)) self.assertEquals(batch_entry.batch_id.text, new_entry.batch_id.text) self.assertEquals(batch_entry.id.text, new_entry.id.text) self.assertEquals(batch_entry.batch_operation.type, new_entry.batch_operation.type) self.assertEquals(batch_entry.batch_status.code, new_entry.batch_status.code) self.assertEquals(batch_entry.batch_status.reason, new_entry.batch_status.reason) class BatchFeedTest(unittest.TestCase): def setUp(self): self.batch_feed = gdata.BatchFeed() self.example_entry = gdata.BatchEntry( atom_id=atom.Id(text='http://example.com/1'), text='This is a test') def testConvertRequestFeed(self): batch_feed = gdata.BatchFeedFromString(test_data.BATCH_FEED_REQUEST) self.assertEquals(len(batch_feed.entry), 4) for entry in batch_feed.entry: self.assert_(isinstance(entry, gdata.BatchEntry)) self.assertEquals(batch_feed.title.text, 'My Batch Feed') new_feed = gdata.BatchFeedFromString(str(batch_feed)) self.assertEquals(len(new_feed.entry), 4) for entry in new_feed.entry: self.assert_(isinstance(entry, gdata.BatchEntry)) self.assertEquals(new_feed.title.text, 'My Batch Feed') def testConvertResultFeed(self): batch_feed = gdata.BatchFeedFromString(test_data.BATCH_FEED_RESULT) self.assertEquals(len(batch_feed.entry), 4) for entry in batch_feed.entry: self.assert_(isinstance(entry, gdata.BatchEntry)) if entry.id.text == ('http://www.google.com/base/feeds/items/' '2173859253842813008'): self.assertEquals(entry.batch_operation.type, 'insert') self.assertEquals(entry.batch_id.text, 'itemB') self.assertEquals(entry.batch_status.code, '201') self.assertEquals(entry.batch_status.reason, 'Created') self.assertEquals(batch_feed.title.text, 'My Batch') new_feed = gdata.BatchFeedFromString(str(batch_feed)) self.assertEquals(len(new_feed.entry), 4) for entry in new_feed.entry: self.assert_(isinstance(entry, gdata.BatchEntry)) if entry.id.text == ('http://www.google.com/base/feeds/items/' '2173859253842813008'): self.assertEquals(entry.batch_operation.type, 'insert') self.assertEquals(entry.batch_id.text, 'itemB') self.assertEquals(entry.batch_status.code, '201') self.assertEquals(entry.batch_status.reason, 'Created') self.assertEquals(new_feed.title.text, 'My Batch') def testAddBatchEntry(self): try: self.batch_feed.AddBatchEntry(batch_id_string='a') self.fail('AddBatchEntry with neither entry or URL should raise Error') except gdata.MissingRequiredParameters: pass new_entry = self.batch_feed.AddBatchEntry( id_url_string='http://example.com/1') self.assertEquals(len(self.batch_feed.entry), 1) self.assertEquals(self.batch_feed.entry[0].id.text, 'http://example.com/1') self.assertEquals(self.batch_feed.entry[0].batch_id.text, '0') self.assertEquals(new_entry.id.text, 'http://example.com/1') self.assertEquals(new_entry.batch_id.text, '0') to_add = gdata.BatchEntry(atom_id=atom.Id(text='originalId')) new_entry = self.batch_feed.AddBatchEntry(entry=to_add, batch_id_string='foo') self.assertEquals(new_entry.batch_id.text, 'foo') self.assertEquals(new_entry.id.text, 'originalId') to_add = gdata.BatchEntry(atom_id=atom.Id(text='originalId'), batch_id=gdata.BatchId(text='bar')) new_entry = self.batch_feed.AddBatchEntry(entry=to_add, id_url_string='newId', batch_id_string='foo') self.assertEquals(new_entry.batch_id.text, 'foo') self.assertEquals(new_entry.id.text, 'originalId') to_add = gdata.BatchEntry(atom_id=atom.Id(text='originalId'), batch_id=gdata.BatchId(text='bar')) new_entry = self.batch_feed.AddBatchEntry(entry=to_add, id_url_string='newId') self.assertEquals(new_entry.batch_id.text, 'bar') self.assertEquals(new_entry.id.text, 'originalId') to_add = gdata.BatchEntry(atom_id=atom.Id(text='originalId'), batch_id=gdata.BatchId(text='bar'), batch_operation=gdata.BatchOperation( op_type=gdata.BATCH_INSERT)) self.assertEquals(to_add.batch_operation.type, gdata.BATCH_INSERT) new_entry = self.batch_feed.AddBatchEntry(entry=to_add, id_url_string='newId', batch_id_string='foo', operation_string=gdata.BATCH_UPDATE) self.assertEquals(new_entry.batch_operation.type, gdata.BATCH_UPDATE) def testAddInsert(self): first_entry = gdata.BatchEntry( atom_id=atom.Id(text='http://example.com/1'), text='This is a test1') self.batch_feed.AddInsert(first_entry) self.assertEquals(self.batch_feed.entry[0].batch_operation.type, gdata.BATCH_INSERT) self.assertEquals(self.batch_feed.entry[0].batch_id.text, '0') second_entry = gdata.BatchEntry( atom_id=atom.Id(text='http://example.com/2'), text='This is a test2') self.batch_feed.AddInsert(second_entry, batch_id_string='foo') self.assertEquals(self.batch_feed.entry[1].batch_operation.type, gdata.BATCH_INSERT) self.assertEquals(self.batch_feed.entry[1].batch_id.text, 'foo') third_entry = gdata.BatchEntry( atom_id=atom.Id(text='http://example.com/3'), text='This is a test3') third_entry.batch_operation = gdata.BatchOperation( op_type=gdata.BATCH_DELETE) # Add an entry with a delete operation already assigned. self.batch_feed.AddInsert(third_entry) # The batch entry should not have the original operation, it should # have been changed to an insert. self.assertEquals(self.batch_feed.entry[2].batch_operation.type, gdata.BATCH_INSERT) self.assertEquals(self.batch_feed.entry[2].batch_id.text, '2') def testAddDelete(self): # Try deleting an entry delete_entry = gdata.BatchEntry( atom_id=atom.Id(text='http://example.com/1'), text='This is a test') self.batch_feed.AddDelete(entry=delete_entry) self.assertEquals(self.batch_feed.entry[0].batch_operation.type, gdata.BATCH_DELETE) self.assertEquals(self.batch_feed.entry[0].id.text, 'http://example.com/1') self.assertEquals(self.batch_feed.entry[0].text, 'This is a test') # Try deleting a URL self.batch_feed.AddDelete(url_string='http://example.com/2') self.assertEquals(self.batch_feed.entry[0].batch_operation.type, gdata.BATCH_DELETE) self.assertEquals(self.batch_feed.entry[1].id.text, 'http://example.com/2') self.assert_(self.batch_feed.entry[1].text is None) def testAddQuery(self): # Try querying with an existing batch entry delete_entry = gdata.BatchEntry( atom_id=atom.Id(text='http://example.com/1')) self.batch_feed.AddQuery(entry=delete_entry) self.assertEquals(self.batch_feed.entry[0].batch_operation.type, gdata.BATCH_QUERY) self.assertEquals(self.batch_feed.entry[0].id.text, 'http://example.com/1') # Try querying a URL self.batch_feed.AddQuery(url_string='http://example.com/2') self.assertEquals(self.batch_feed.entry[0].batch_operation.type, gdata.BATCH_QUERY) self.assertEquals(self.batch_feed.entry[1].id.text, 'http://example.com/2') def testAddUpdate(self): # Try updating an entry delete_entry = gdata.BatchEntry( atom_id=atom.Id(text='http://example.com/1'), text='This is a test') self.batch_feed.AddUpdate(entry=delete_entry) self.assertEquals(self.batch_feed.entry[0].batch_operation.type, gdata.BATCH_UPDATE) self.assertEquals(self.batch_feed.entry[0].id.text, 'http://example.com/1') self.assertEquals(self.batch_feed.entry[0].text, 'This is a test') class ExtendedPropertyTest(unittest.TestCase): def testXmlBlobRoundTrip(self): ep = gdata.ExtendedProperty(name='blobby') ep.SetXmlBlob('<some_xml attr="test"/>') extension = ep.GetXmlBlobExtensionElement() self.assertEquals(extension.tag, 'some_xml') self.assert_(extension.namespace is None) self.assertEquals(extension.attributes['attr'], 'test') ep2 = gdata.ExtendedPropertyFromString(ep.ToString()) extension = ep2.GetXmlBlobExtensionElement() self.assertEquals(extension.tag, 'some_xml') self.assert_(extension.namespace is None) self.assertEquals(extension.attributes['attr'], 'test') def testGettersShouldReturnNoneWithNoBlob(self): ep = gdata.ExtendedProperty(name='no blob') self.assert_(ep.GetXmlBlobExtensionElement() is None) self.assert_(ep.GetXmlBlobString() is None) def testGettersReturnCorrectTypes(self): ep = gdata.ExtendedProperty(name='has blob') ep.SetXmlBlob('<some_xml attr="test"/>') self.assert_(isinstance(ep.GetXmlBlobExtensionElement(), atom.ExtensionElement)) self.assert_(isinstance(ep.GetXmlBlobString(), str)) class FeedLinkTest(unittest.TestCase): def testCorrectFromStringType(self): link = gdata.FeedLinkFromString( '<feedLink xmlns="http://schemas.google.com/g/2005" countHint="5"/>') self.assertTrue(isinstance(link, gdata.FeedLink)) self.assertEqual(link.count_hint, '5') def suite(): return conf.build_suite([StartIndexTest, StartIndexTest, GDataEntryTest, LinkFinderTest, GDataFeedTest, BatchEntryTest, BatchFeedTest, ExtendedPropertyTest, FeedLinkTest]) if __name__ == '__main__': unittest.main()
apache-2.0
RafaelPalomar/girder
plugins/provenance/server/__init__.py
3
1966
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2014 Kitware 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. ############################################################################### import six from girder import events from girder.models.model_base import ValidationException from girder.utility import setting_utilities from . import constants from .resource import ResourceExt @setting_utilities.validator(constants.PluginSettings.PROVENANCE_RESOURCES) def validateProvenanceResources(doc): val = doc['value'] if val: if not isinstance(val, six.string_types): raise ValidationException('Provenance Resources must be a string.', 'value') # accept comma or space separated lists resources = val.replace(',', ' ').strip().split() # reformat to a comma-separated list doc['value'] = ','.join(resources) def load(info): ext = ResourceExt(info) events.bind('model.setting.save.after', 'provenanceMain', ext.bindModels) events.bind('provenance.initialize', 'provenanceMain', ext.bindModels) events.trigger('provenance.initialize', info={}) events.bind('model.file.save', 'provenanceMain', ext.fileSaveHandler) events.bind('model.file.save.created', 'provenanceMain', ext.fileSaveCreatedHandler) events.bind('model.file.remove', 'provenance', ext.fileRemoveHandler)
apache-2.0
MackZxh/OCA-Choice
account-invoicing/account_invoice_rounding/__openerp__.py
12
2100
# -*- coding: utf-8 -*- ############################################################################## # # Author: Yannick Vaucher # Copyright 2013 Camptocamp SA # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## {'name': 'Unit rounded invoice', 'version': '8.0.1.0.0', 'category': 'Accounting', 'description': """ Unit rounded invoice (_`Swedish rounding`) ========================================== Add a parameter to give a unit for rounding such as CHF 0.05 for Swiss invoices In Settings -> Configuration -> Accounting you will find 2 new types of rounding - `Swedish Round globally` To round your invoice total amount, this option will do the adjustment in the most important tax line of your invoice. - `Swedish Round by adding an invoice line` To round your invoice total amount, this option create a invoice line without taxes on it. This invoice line is tagged as `is_rounding` You can choose the account on which the invoice line will be written .. _Swedish rounding : https://en.wikipedia.org/wiki/Swedish_rounding """, 'author': "Camptocamp,Odoo Community Association (OCA)", 'maintainer': 'Camptocamp', 'website': 'http://www.camptocamp.com/', 'license': 'AGPL-3', 'depends': ['account'], 'data': ['res_config_view.xml'], 'test': ['test/test_invoice_rounding.yml'], 'installable': True, 'auto_install': False, 'application': True, }
lgpl-3.0
ctozlm/Dato-Core
src/unity/python/graphlab/data_structures/sframe.py
13
196438
""" This module defines the SFrame class which provides the ability to create, access and manipulate a remote scalable dataframe object. SFrame acts similarly to pandas.DataFrame, but the data is completely immutable and is stored column wise on the GraphLab Server side. """ ''' Copyright (C) 2015 Dato, Inc. All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the DATO-PYTHON-LICENSE file for details. ''' import graphlab.connect as _mt import graphlab.connect.main as glconnect from graphlab.cython.cy_type_utils import infer_type_of_list from graphlab.cython.context import debug_trace as cython_context from graphlab.cython.cy_sframe import UnitySFrameProxy from graphlab.util import _check_canvas_enabled, _make_internal_url, _is_callable from graphlab.data_structures.sarray import SArray, _create_sequential_sarray import graphlab.aggregate import graphlab import array from prettytable import PrettyTable from textwrap import wrap import datetime import inspect from graphlab.deps import pandas, HAS_PANDAS import time import itertools import os import subprocess import uuid import platform __all__ = ['SFrame'] SFRAME_GARBAGE_COLLECTOR = [] FOOTER_STRS = ['Note: Only the head of the SFrame is printed.', 'You can use print_rows(num_rows=m, num_columns=n) to print more rows and columns.'] LAZY_FOOTER_STRS = ['Note: Only the head of the SFrame is printed. This SFrame is lazily evaluated.', 'You can use len(sf) to force materialization.'] SFRAME_ROOTS = [# Binary/lib location in production egg os.path.abspath(os.path.join(os.path.dirname( os.path.realpath(__file__)), '..')), # Build tree location of SFrame binaries os.path.abspath(os.path.join(os.path.dirname( os.path.realpath(__file__)), '..', '..', '..', '..', 'sframe')), # Location of python sources os.path.abspath(os.path.join(os.path.dirname( os.path.realpath(__file__)), '..', '..', '..', '..', 'unity', 'python', 'graphlab')), # Build tree dependency location os.path.abspath(os.path.join(os.path.dirname( os.path.realpath(__file__)), '..', '..', '..', '..', '..', '..', 'deps', 'local', 'lib')) ] RDD_SFRAME_PICKLE = "rddtosf_pickle" RDD_SFRAME_NONPICKLE = "rddtosf_nonpickle" SFRAME_RDD_PICKLE = "sftordd_pickle" HDFS_LIB = "libhdfs.so" RDD_JAR_FILE = "graphlab-create-spark-integration.jar" SYS_UTIL_PY = "sys_util.py" RDD_SUPPORT_INITED = False BINARY_PATHS = {} STAGING_DIR = None RDD_SUPPORT = True PRODUCTION_RUN = False YARN_OS = None SPARK_SUPPORT_NAMES = {'RDD_SFRAME_PATH':'rddtosf_pickle', 'RDD_SFRAME_NONPICKLE_PATH':'rddtosf_nonpickle', 'SFRAME_RDD_PATH':'sftordd_pickle', 'HDFS_LIB_PATH':'libhdfs.so', 'RDD_JAR_PATH':'graphlab-create-spark-integration.jar', 'SYS_UTIL_PY_PATH':'sys_util.py', 'SPARK_PIPE_WRAPPER_PATH':'spark_pipe_wrapper'} first = True for i in SFRAME_ROOTS: for key,val in SPARK_SUPPORT_NAMES.iteritems(): tmp_path = os.path.join(i, val) if key not in BINARY_PATHS and os.path.isfile(tmp_path): BINARY_PATHS[key] = tmp_path if all(name in BINARY_PATHS for name in SPARK_SUPPORT_NAMES.keys()): if first: PRODUCTION_RUN = True break first = False if not all(name in BINARY_PATHS for name in SPARK_SUPPORT_NAMES.keys()): RDD_SUPPORT = False def get_spark_integration_jar_path(): """ The absolute path of the jar file required to enable GraphLab Create's integration with Apache Spark. """ if 'RDD_JAR_PATH' not in BINARY_PATHS: raise RuntimeError("Could not find a spark integration jar. "\ "Does your version of GraphLab Create support Spark Integration (is it >= 1.0)?") return BINARY_PATHS['RDD_JAR_PATH'] def __rdd_support_init__(sprk_ctx): global YARN_OS global RDD_SUPPORT_INITED global STAGING_DIR global BINARY_PATHS if not RDD_SUPPORT or RDD_SUPPORT_INITED: return # Make sure our GraphLabUtil scala functions are accessible from the driver try: tmp = sprk_ctx._jvm.org.graphlab.create.GraphLabUtil.EscapeString(sprk_ctx._jvm.java.lang.String("1,2,3,4")) except: raise RuntimeError("Could not execute RDD translation functions. "\ "Please make sure you have started Spark "\ "(either with spark-submit or pyspark) with the following flag set:\n"\ "'--driver-class-path " + BINARY_PATHS['RDD_JAR_PATH']+"'\n"\ "OR set the property spark.driver.extraClassPath in spark-defaults.conf") dummy_rdd = sprk_ctx.parallelize([1]) if PRODUCTION_RUN and sprk_ctx.master == 'yarn-client': # Get cluster operating system os_rdd = dummy_rdd.map(lambda x: platform.system()) YARN_OS = os_rdd.collect()[0] # Set binary path for i in BINARY_PATHS.keys(): s = BINARY_PATHS[i] if os.path.basename(s) == SPARK_SUPPORT_NAMES['SYS_UTIL_PY_PATH']: continue if YARN_OS == 'Linux': BINARY_PATHS[i] = os.path.join(os.path.dirname(s), 'linux', os.path.basename(s)) elif YARN_OS == 'Darwin': BINARY_PATHS[i] = os.path.join(os.path.dirname(s), 'osx', os.path.basename(s)) else: raise RuntimeError("YARN cluster has unsupported operating system "\ "(something other than Linux or Mac OS X). "\ "Cannot convert RDDs on this cluster to SFrame.") # Create staging directory staging_dir = '.graphlabStaging' if sprk_ctx.master == 'yarn-client': tmp_loc = None # Get that staging directory's full name tmp_loc = dummy_rdd.map( lambda x: subprocess.check_output( ["hdfs", "getconf", "-confKey", "fs.defaultFS"]).rstrip()).collect()[0] STAGING_DIR = os.path.join(tmp_loc, "user", sprk_ctx.sparkUser(), staging_dir) if STAGING_DIR is None: raise RuntimeError("Failed to create a staging directory on HDFS. "\ "Do your cluster nodes have a working hdfs client?") # Actually create the staging dir unity = glconnect.get_unity() unity.__mkdir__(STAGING_DIR) unity.__chmod__(STAGING_DIR, 0777) elif sprk_ctx.master[0:5] == 'local': # Save the output sframes to the same temp workspace this engine is # using #TODO: Consider cases where server and client aren't on the same machine unity = glconnect.get_unity() STAGING_DIR = unity.get_current_cache_file_location() if STAGING_DIR is None: raise RuntimeError("Could not retrieve local staging directory! \ Please contact us on http://forum.dato.com.") else: raise RuntimeError("Your spark context's master is '" + str(sprk_ctx.master) + "'. Only 'local' and 'yarn-client' are supported.") if sprk_ctx.master == 'yarn-client': sprk_ctx.addFile(BINARY_PATHS['RDD_SFRAME_PATH']) sprk_ctx.addFile(BINARY_PATHS['HDFS_LIB_PATH']) sprk_ctx.addFile(BINARY_PATHS['SFRAME_RDD_PATH']) sprk_ctx.addFile(BINARY_PATHS['RDD_SFRAME_NONPICKLE_PATH']) sprk_ctx.addFile(BINARY_PATHS['SYS_UTIL_PY_PATH']) sprk_ctx.addFile(BINARY_PATHS['SPARK_PIPE_WRAPPER_PATH']) sprk_ctx._jsc.addJar(BINARY_PATHS['RDD_JAR_PATH']) RDD_SUPPORT_INITED = True def load_sframe(filename): """ Load an SFrame. The filename extension is used to determine the format automatically. This function is particularly useful for SFrames previously saved in binary format. For CSV imports the ``SFrame.read_csv`` function provides greater control. If the SFrame is in binary format, ``filename`` is actually a directory, created when the SFrame is saved. Parameters ---------- filename : string Location of the file to load. Can be a local path or a remote URL. Returns ------- out : SFrame See Also -------- SFrame.save, SFrame.read_csv Examples -------- >>> sf = graphlab.SFrame({'id':[1,2,3], 'val':['A','B','C']}) >>> sf.save('my_sframe') # 'my_sframe' is a directory >>> sf_loaded = graphlab.load_sframe('my_sframe') """ sf = SFrame(data=filename) return sf class SFrame(object): """ A tabular, column-mutable dataframe object that can scale to big data. The data in SFrame is stored column-wise on the GraphLab Server side, and is stored on persistent storage (e.g. disk) to avoid being constrained by memory size. Each column in an SFrame is a size-immutable :class:`~graphlab.SArray`, but SFrames are mutable in that columns can be added and subtracted with ease. An SFrame essentially acts as an ordered dict of SArrays. Currently, we support constructing an SFrame from the following data formats: * csv file (comma separated value) * sframe directory archive (A directory where an sframe was saved previously) * general text file (with csv parsing options, See :py:meth:`read_csv()`) * a Python dictionary * pandas.DataFrame * JSON * Apache Avro * PySpark RDD and from the following sources: * your local file system * the GraphLab Server's file system * HDFS * Amazon S3 * HTTP(S). Only basic examples of construction are covered here. For more information and examples, please see the `User Guide <https://dato.com/learn/user guide/index.html#Working_with_data_Tabular_data>`_, `API Translator <https://dato.com/learn/translator>`_, `How-Tos <https://dato.com/learn/how-to>`_, and data science `Gallery <https://dato.com/learn/gallery>`_. Parameters ---------- data : array | pandas.DataFrame | string | dict, optional The actual interpretation of this field is dependent on the ``format`` parameter. If ``data`` is an array or Pandas DataFrame, the contents are stored in the SFrame. If ``data`` is a string, it is interpreted as a file. Files can be read from local file system or urls (local://, hdfs://, s3://, http://). format : string, optional Format of the data. The default, "auto" will automatically infer the input data format. The inference rules are simple: If the data is an array or a dataframe, it is associated with 'array' and 'dataframe' respectively. If the data is a string, it is interpreted as a file, and the file extension is used to infer the file format. The explicit options are: - "auto" - "array" - "dict" - "sarray" - "dataframe" - "csv" - "tsv" - "sframe". See Also -------- read_csv: Create a new SFrame from a csv file. Preferred for text and CSV formats, because it has a lot more options for controlling the parser. save : Save an SFrame for later use. Notes ----- - When working with the GraphLab EC2 instance (see :py:func:`graphlab.aws.launch_EC2()`), an SFrame cannot be constructed using local file path, because it involves a potentially large amount of data transfer from client to server. However, it is still okay to use a remote file path. See the examples below. A similar restriction applies to :py:class:`graphlab.SGraph` and :py:class:`graphlab.SArray`. - When reading from HDFS on Linux we must guess the location of your java installation. By default, we will use the location pointed to by the JAVA_HOME environment variable. If this is not set, we check many common installation paths. You may use two environment variables to override this behavior. GRAPHLAB_JAVA_HOME allows you to specify a specific java installation and overrides JAVA_HOME. GRAPHLAB_LIBJVM_DIRECTORY overrides all and expects the exact directory that your preferred libjvm.so file is located. Use this ONLY if you'd like to use a non-standard JVM. Examples -------- >>> import graphlab >>> from graphlab import SFrame **Construction** Construct an SFrame from a dataframe and transfers the dataframe object across the network. >>> df = pandas.DataFrame() >>> sf = SFrame(data=df) Construct an SFrame from a local csv file (only works for local server). >>> sf = SFrame(data='~/mydata/foo.csv') Construct an SFrame from a csv file on Amazon S3. This requires the environment variables: *AWS_ACCESS_KEY_ID* and *AWS_SECRET_ACCESS_KEY* to be set before the python session started. Alternatively, you can use :py:func:`graphlab.aws.set_credentials()` to set the credentials after python is started and :py:func:`graphlab.aws.get_credentials()` to verify these environment variables. >>> sf = SFrame(data='s3://mybucket/foo.csv') Read from HDFS using a specific java installation (environment variable only applies when using Linux) >>> import os >>> os.environ['GRAPHLAB_JAVA_HOME'] = '/my/path/to/java' >>> from graphlab import SFrame >>> sf = SFrame("hdfs://mycluster.example.com:8020/user/myname/coolfile.txt") An SFrame can be constructed from a dictionary of values or SArrays: >>> sf = gl.SFrame({'id':[1,2,3],'val':['A','B','C']}) >>> sf Columns: id int val str Rows: 3 Data: id val 0 1 A 1 2 B 2 3 C Or equivalently: >>> ids = SArray([1,2,3]) >>> vals = SArray(['A','B','C']) >>> sf = SFrame({'id':ids,'val':vals}) It can also be constructed from an array of SArrays in which case column names are automatically assigned. >>> ids = SArray([1,2,3]) >>> vals = SArray(['A','B','C']) >>> sf = SFrame([ids, vals]) >>> sf Columns: X1 int X2 str Rows: 3 Data: X1 X2 0 1 A 1 2 B 2 3 C If the SFrame is constructed from a list of values, an SFrame of a single column is constructed. >>> sf = SFrame([1,2,3]) >>> sf Columns: X1 int Rows: 3 Data: X1 0 1 1 2 2 3 **Parsing** The :py:func:`graphlab.SFrame.read_csv()` is quite powerful and, can be used to import a variety of row-based formats. First, some simple cases: >>> !cat ratings.csv user_id,movie_id,rating 10210,1,1 10213,2,5 10217,2,2 10102,1,3 10109,3,4 10117,5,2 10122,2,4 10114,1,5 10125,1,1 >>> gl.SFrame.read_csv('ratings.csv') Columns: user_id int movie_id int rating int Rows: 9 Data: +---------+----------+--------+ | user_id | movie_id | rating | +---------+----------+--------+ | 10210 | 1 | 1 | | 10213 | 2 | 5 | | 10217 | 2 | 2 | | 10102 | 1 | 3 | | 10109 | 3 | 4 | | 10117 | 5 | 2 | | 10122 | 2 | 4 | | 10114 | 1 | 5 | | 10125 | 1 | 1 | +---------+----------+--------+ [9 rows x 3 columns] Delimiters can be specified, if "," is not the delimiter, for instance space ' ' in this case. Only single character delimiters are supported. >>> !cat ratings.csv user_id movie_id rating 10210 1 1 10213 2 5 10217 2 2 10102 1 3 10109 3 4 10117 5 2 10122 2 4 10114 1 5 10125 1 1 >>> gl.SFrame.read_csv('ratings.csv', delimiter=' ') By default, "NA" or a missing element are interpreted as missing values. >>> !cat ratings2.csv user,movie,rating "tom",,1 harry,5, jack,2,2 bill,, >>> gl.SFrame.read_csv('ratings2.csv') Columns: user str movie int rating int Rows: 4 Data: +---------+-------+--------+ | user | movie | rating | +---------+-------+--------+ | tom | None | 1 | | harry | 5 | None | | jack | 2 | 2 | | missing | None | None | +---------+-------+--------+ [4 rows x 3 columns] Furthermore due to the dictionary types and list types, can handle parsing of JSON-like formats. >>> !cat ratings3.csv business, categories, ratings "Restaurant 1", [1 4 9 10], {"funny":5, "cool":2} "Restaurant 2", [], {"happy":2, "sad":2} "Restaurant 3", [2, 11, 12], {} >>> gl.SFrame.read_csv('ratings3.csv') Columns: business str categories array ratings dict Rows: 3 Data: +--------------+--------------------------------+-------------------------+ | business | categories | ratings | +--------------+--------------------------------+-------------------------+ | Restaurant 1 | array('d', [1.0, 4.0, 9.0, ... | {'funny': 5, 'cool': 2} | | Restaurant 2 | array('d') | {'sad': 2, 'happy': 2} | | Restaurant 3 | array('d', [2.0, 11.0, 12.0]) | {} | +--------------+--------------------------------+-------------------------+ [3 rows x 3 columns] The list and dictionary parsers are quite flexible and can absorb a variety of purely formatted inputs. Also, note that the list and dictionary types are recursive, allowing for arbitrary values to be contained. All these are valid lists: >>> !cat interesting_lists.csv list [] [1,2,3] [1;2,3] [1 2 3] [{a:b}] ["c",d, e] [[a]] >>> gl.SFrame.read_csv('interesting_lists.csv') Columns: list list Rows: 7 Data: +-----------------+ | list | +-----------------+ | [] | | [1, 2, 3] | | [1, 2, 3] | | [1, 2, 3] | | [{'a': 'b'}] | | ['c', 'd', 'e'] | | [['a']] | +-----------------+ [7 rows x 1 columns] All these are valid dicts: >>> !cat interesting_dicts.csv dict {"classic":1,"dict":1} {space:1 seperated:1} {emptyvalue:} {} {:} {recursive1:[{a:b}]} {:[{:[a]}]} >>> gl.SFrame.read_csv('interesting_dicts.csv') Columns: dict dict Rows: 7 Data: +------------------------------+ | dict | +------------------------------+ | {'dict': 1, 'classic': 1} | | {'seperated': 1, 'space': 1} | | {'emptyvalue': None} | | {} | | {None: None} | | {'recursive1': [{'a': 'b'}]} | | {None: [{None: array('d')}]} | +------------------------------+ [7 rows x 1 columns] **Saving** Save and load the sframe in native format. >>> sf.save('mysframedir') >>> sf2 = graphlab.load_sframe('mysframedir') **Column Manipulation ** An SFrame is composed of a collection of columns of SArrays, and individual SArrays can be extracted easily. For instance given an SFrame: >>> sf = SFrame({'id':[1,2,3],'val':['A','B','C']}) >>> sf Columns: id int val str Rows: 3 Data: id val 0 1 A 1 2 B 2 3 C The "id" column can be extracted using: >>> sf["id"] dtype: int Rows: 3 [1, 2, 3] And can be deleted using: >>> del sf["id"] Multiple columns can be selected by passing a list of column names: >>> sf = SFrame({'id':[1,2,3],'val':['A','B','C'],'val2':[5,6,7]}) >>> sf Columns: id int val str val2 int Rows: 3 Data: id val val2 0 1 A 5 1 2 B 6 2 3 C 7 >>> sf2 = sf[['id','val']] >>> sf2 Columns: id int val str Rows: 3 Data: id val 0 1 A 1 2 B 2 3 C The same mechanism can be used to re-order columns: >>> sf = SFrame({'id':[1,2,3],'val':['A','B','C']}) >>> sf Columns: id int val str Rows: 3 Data: id val 0 1 A 1 2 B 2 3 C >>> sf[['val','id']] >>> sf Columns: val str id int Rows: 3 Data: val id 0 A 1 1 B 2 2 C 3 **Element Access and Slicing** SFrames can be accessed by integer keys just like a regular python list. Such operations may not be fast on large datasets so looping over an SFrame should be avoided. >>> sf = SFrame({'id':[1,2,3],'val':['A','B','C']}) >>> sf[0] {'id': 1, 'val': 'A'} >>> sf[2] {'id': 3, 'val': 'C'} >>> sf[5] IndexError: SFrame index out of range Negative indices can be used to access elements from the tail of the array >>> sf[-1] # returns the last element {'id': 3, 'val': 'C'} >>> sf[-2] # returns the second to last element {'id': 2, 'val': 'B'} The SFrame also supports the full range of python slicing operators: >>> sf[1000:] # Returns an SFrame containing rows 1000 to the end >>> sf[:1000] # Returns an SFrame containing rows 0 to row 999 inclusive >>> sf[0:1000:2] # Returns an SFrame containing rows 0 to row 1000 in steps of 2 >>> sf[-100:] # Returns an SFrame containing last 100 rows >>> sf[-100:len(sf):2] # Returns an SFrame containing last 100 rows in steps of 2 **Logical Filter** An SFrame can be filtered using >>> sframe[binary_filter] where sframe is an SFrame and binary_filter is an SArray of the same length. The result is a new SFrame which contains only rows of the SFrame where its matching row in the binary_filter is non zero. This permits the use of boolean operators that can be used to perform logical filtering operations. For instance, given an SFrame >>> sf Columns: id int val str Rows: 3 Data: id val 0 1 A 1 2 B 2 3 C >>> sf[(sf['id'] >= 1) & (sf['id'] <= 2)] Columns: id int val str Rows: 3 Data: id val 0 1 A 1 2 B See :class:`~graphlab.SArray` for more details on the use of the logical filter. This can also be used more generally to provide filtering capability which is otherwise not expressible with simple boolean functions. For instance: >>> sf[sf['id'].apply(lambda x: math.log(x) <= 1)] Columns: id int val str Rows: 3 Data: id val 0 1 A 1 2 B Or alternatively: >>> sf[sf.apply(lambda x: math.log(x['id']) <= 1)] Create an SFrame from a Python dictionary. >>> from graphlab import SFrame >>> sf = SFrame({'id':[1,2,3], 'val':['A','B','C']}) >>> sf Columns: id int val str Rows: 3 Data: id val 0 1 A 1 2 B 2 3 C """ __slots__ = ['shape', '__proxy__', '_proxy'] def __init__(self, data=None, format='auto', _proxy=None): """__init__(data=list(), format='auto') Construct a new SFrame from a url or a pandas.DataFrame. """ # emit metrics for num_rows, num_columns, and type (local://, s3, hdfs, http) tracker = _mt._get_metric_tracker() if (_proxy): self.__proxy__ = _proxy else: self.__proxy__ = UnitySFrameProxy(glconnect.get_client()) _format = None if (format == 'auto'): if (HAS_PANDAS and isinstance(data, pandas.DataFrame)): _format = 'dataframe' tracker.track('sframe.location.memory', value=1) elif (isinstance(data, str) or isinstance(data, unicode)): if data.find('://') == -1: suffix = 'local' else: suffix = data.split('://')[0] tracker.track(('sframe.location.%s' % (suffix)), value=1) if data.endswith(('.csv', '.csv.gz')): _format = 'csv' elif data.endswith(('.tsv', '.tsv.gz')): _format = 'tsv' elif data.endswith(('.txt', '.txt.gz')): print "Assuming file is csv. For other delimiters, " + \ "please use `SFrame.read_csv`." _format = 'csv' else: _format = 'sframe' elif type(data) == SArray: _format = 'sarray' elif isinstance(data, SFrame): _format = 'sframe_obj' elif (hasattr(data, 'iteritems')): _format = 'dict' tracker.track('sframe.location.memory', value=1) elif hasattr(data, '__iter__'): _format = 'array' tracker.track('sframe.location.memory', value=1) elif data is None: _format = 'empty' else: raise ValueError('Cannot infer input type for data ' + str(data)) else: _format = format tracker.track(('sframe.format.%s' % _format), value=1) with cython_context(): if (_format == 'dataframe'): self.__proxy__.load_from_dataframe(data) elif (_format == 'sframe_obj'): for col in data.column_names(): self.__proxy__.add_column(data[col].__proxy__, col) elif (_format == 'sarray'): self.__proxy__.add_column(data.__proxy__, "") elif (_format == 'array'): if len(data) > 0: unique_types = set([type(x) for x in data if x is not None]) if len(unique_types) == 1 and SArray in unique_types: for arr in data: self.add_column(arr) elif SArray in unique_types: raise ValueError("Cannot create SFrame from mix of regular values and SArrays") else: self.__proxy__.add_column(SArray(data).__proxy__, "") elif (_format == 'dict'): for key,val in iter(sorted(data.iteritems())): if (type(val) == SArray): self.__proxy__.add_column(val.__proxy__, key) else: self.__proxy__.add_column(SArray(val).__proxy__, key) elif (_format == 'csv'): url = _make_internal_url(data) tmpsf = SFrame.read_csv(url, delimiter=',', header=True) self.__proxy__ = tmpsf.__proxy__ elif (_format == 'tsv'): url = _make_internal_url(data) tmpsf = SFrame.read_csv(url, delimiter='\t', header=True) self.__proxy__ = tmpsf.__proxy__ elif (_format == 'sframe'): url = _make_internal_url(data) self.__proxy__.load_from_sframe_index(url) elif (_format == 'empty'): pass else: raise ValueError('Unknown input type: ' + format) sframe_size = -1 if self.__has_size__(): sframe_size = self.num_rows() tracker.track('sframe.row.size', value=sframe_size) tracker.track('sframe.col.size', value=self.num_cols()) @staticmethod def _infer_column_types_from_lines(first_rows): if (len(first_rows.column_names()) < 1): print "Insufficient number of columns to perform type inference" raise RuntimeError("Insufficient columns ") if len(first_rows) < 1: print "Insufficient number of rows to perform type inference" raise RuntimeError("Insufficient rows") # gets all the values column-wise all_column_values_transposed = [list(first_rows[col]) for col in first_rows.column_names()] # transpose all_column_values = [list(x) for x in zip(*all_column_values_transposed)] all_column_type_hints = [[type(t) for t in vals] for vals in all_column_values] # collect the hints # if every line was inferred to have a different number of elements, die if len(set(len(x) for x in all_column_type_hints)) != 1: print "Unable to infer column types. Defaulting to str" return str import types column_type_hints = all_column_type_hints[0] # now perform type combining across rows for i in range(1, len(all_column_type_hints)): currow = all_column_type_hints[i] for j in range(len(column_type_hints)): # combine types d = set([currow[j], column_type_hints[j]]) if (len(d) == 1): # easy case. both agree on the type continue if ((int in d) and (float in d)): # one is an int, one is a float. its a float column_type_hints[j] = float elif ((array.array in d) and (list in d)): # one is an array , one is a list. its a list column_type_hints[j] = list elif types.NoneType in d: # one is a NoneType. assign to other type if currow[j] != types.NoneType: column_type_hints[j] = currow[j] else: column_type_hints[j] = str # final pass. everything whih is still NoneType is now a str for i in range(len(column_type_hints)): if column_type_hints[i] == types.NoneType: column_type_hints[i] = str return column_type_hints @classmethod def _read_csv_impl(cls, url, delimiter=',', header=True, error_bad_lines=False, comment_char='', escape_char='\\', double_quote=True, quote_char='\"', skip_initial_space=True, column_type_hints=None, na_values=["NA"], nrows=None, verbose=True, store_errors=True): """ Constructs an SFrame from a CSV file or a path to multiple CSVs, and returns a pair containing the SFrame and optionally (if store_errors=True) a dict of filenames to SArrays indicating for each file, what are the incorrectly parsed lines encountered. Parameters ---------- store_errors : bool If true, the output errors dict will be filled. See `read_csv` for the rest of the parameters. """ parsing_config = dict() parsing_config["delimiter"] = delimiter parsing_config["use_header"] = header parsing_config["continue_on_failure"] = not error_bad_lines parsing_config["comment_char"] = comment_char parsing_config["escape_char"] = escape_char parsing_config["double_quote"] = double_quote parsing_config["quote_char"] = quote_char parsing_config["skip_initial_space"] = skip_initial_space parsing_config["store_errors"] = store_errors if type(na_values) is str: na_values = [na_values] if na_values is not None and len(na_values) > 0: parsing_config["na_values"] = na_values if nrows != None: parsing_config["row_limit"] = nrows proxy = UnitySFrameProxy(glconnect.get_client()) internal_url = _make_internal_url(url) if (not verbose): glconnect.get_client().set_log_progress(False) # Attempt to automatically detect the column types. Either produce a # list of types; otherwise default to all str types. column_type_inference_was_used = False if column_type_hints is None: try: # Get the first 100 rows (using all the desired arguments). first_rows = graphlab.SFrame.read_csv(url, nrows=100, column_type_hints=type(None), header=header, delimiter=delimiter, comment_char=comment_char, escape_char=escape_char, double_quote=double_quote, quote_char=quote_char, skip_initial_space=skip_initial_space, na_values = na_values) column_type_hints = SFrame._infer_column_types_from_lines(first_rows) typelist = '[' + ','.join(t.__name__ for t in column_type_hints) + ']' print "------------------------------------------------------" print "Inferred types from first line of file as " print "column_type_hints="+ typelist print "If parsing fails due to incorrect types, you can correct" print "the inferred type list above and pass it to read_csv in" print "the column_type_hints argument" print "------------------------------------------------------" column_type_inference_was_used = True except Exception as e: if type(e) == RuntimeError and "CSV parsing cancelled" in e.message: raise e # If the above fails, default back to str for all columns. column_type_hints = str print 'Could not detect types. Using str for each column.' if type(column_type_hints) is type: type_hints = {'__all_columns__': column_type_hints} elif type(column_type_hints) is list: type_hints = dict(zip(['__X%d__' % i for i in range(len(column_type_hints))], column_type_hints)) elif type(column_type_hints) is dict: type_hints = column_type_hints else: raise TypeError("Invalid type for column_type_hints. Must be a dictionary, list or a single type.") _mt._get_metric_tracker().track('sframe.csv.parse') suffix='' if url.find('://') == -1: suffix = 'local' else: suffix = url.split('://')[0] _mt._get_metric_tracker().track(('sframe.location.%s' % (suffix)), value=1) try: with cython_context(): errors = proxy.load_from_csvs(internal_url, parsing_config, type_hints) except Exception as e: if type(e) == RuntimeError and "CSV parsing cancelled" in e.message: raise e if column_type_inference_was_used: # try again print "Unable to parse the file with automatic type inference." print "Defaulting to column_type_hints=str" type_hints = {'__all_columns__': str} try: with cython_context(): errors = proxy.load_from_csvs(internal_url, parsing_config, type_hints) except: raise else: raise glconnect.get_client().set_log_progress(True) return (cls(_proxy=proxy), { f: SArray(_proxy = es) for (f, es) in errors.iteritems() }) @classmethod def read_csv_with_errors(cls, url, delimiter=',', header=True, comment_char='', escape_char='\\', double_quote=True, quote_char='\"', skip_initial_space=True, column_type_hints=None, na_values=["NA"], nrows=None, verbose=True): """ Constructs an SFrame from a CSV file or a path to multiple CSVs, and returns a pair containing the SFrame and a dict of filenames to SArrays indicating for each file, what are the incorrectly parsed lines encountered. Parameters ---------- url : string Location of the CSV file or directory to load. If URL is a directory or a "glob" pattern, all matching files will be loaded. delimiter : string, optional This describes the delimiter used for parsing csv files. header : bool, optional If true, uses the first row as the column names. Otherwise use the default column names: 'X1, X2, ...'. comment_char : string, optional The character which denotes that the remainder of the line is a comment. escape_char : string, optional Character which begins a C escape sequence double_quote : bool, optional If True, two consecutive quotes in a string are parsed to a single quote. quote_char : string, optional Character sequence that indicates a quote. skip_initial_space : bool, optional Ignore extra spaces at the start of a field column_type_hints : None, type, list[type], dict[string, type], optional This provides type hints for each column. By default, this method attempts to detect the type of each column automatically. Supported types are int, float, str, list, dict, and array.array. * If a single type is provided, the type will be applied to all columns. For instance, column_type_hints=float will force all columns to be parsed as float. * If a list of types is provided, the types applies to each column in order, e.g.[int, float, str] will parse the first column as int, second as float and third as string. * If a dictionary of column name to type is provided, each type value in the dictionary is applied to the key it belongs to. For instance {'user':int} will hint that the column called "user" should be parsed as an integer, and the rest will default to string. na_values : str | list of str, optional A string or list of strings to be interpreted as missing values. nrows : int, optional If set, only this many rows will be read from the file. verbose : bool, optional If True, print the progress. Returns ------- out : tuple The first element is the SFrame with good data. The second element is a dictionary of filenames to SArrays indicating for each file, what are the incorrectly parsed lines encountered. See Also -------- read_csv, SFrame Examples -------- >>> bad_url = 'https://s3.amazonaws.com/gl-testdata/bad_csv_example.csv' >>> (sf, bad_lines) = graphlab.SFrame.read_csv_with_errors(bad_url) >>> sf +---------+----------+--------+ | user_id | movie_id | rating | +---------+----------+--------+ | 25904 | 1663 | 3 | | 25907 | 1663 | 3 | | 25923 | 1663 | 3 | | 25924 | 1663 | 3 | | 25928 | 1663 | 2 | | ... | ... | ... | +---------+----------+--------+ [98 rows x 3 columns] >>> bad_lines {'https://s3.amazonaws.com/gl-testdata/bad_csv_example.csv': dtype: str Rows: 1 ['x,y,z,a,b,c']} """ return cls._read_csv_impl(url, delimiter=delimiter, header=header, error_bad_lines=False, # we are storing errors, # thus we must not fail # on bad lines comment_char=comment_char, escape_char=escape_char, double_quote=double_quote, quote_char=quote_char, skip_initial_space=skip_initial_space, column_type_hints=column_type_hints, na_values=na_values, nrows=nrows, verbose=verbose, store_errors=True) @classmethod def read_csv(cls, url, delimiter=',', header=True, error_bad_lines=False, comment_char='', escape_char='\\', double_quote=True, quote_char='\"', skip_initial_space=True, column_type_hints=None, na_values=["NA"], nrows=None, verbose=True): """ Constructs an SFrame from a CSV file or a path to multiple CSVs. Parameters ---------- url : string Location of the CSV file or directory to load. If URL is a directory or a "glob" pattern, all matching files will be loaded. delimiter : string, optional This describes the delimiter used for parsing csv files. header : bool, optional If true, uses the first row as the column names. Otherwise use the default column names : 'X1, X2, ...'. error_bad_lines : bool If true, will fail upon encountering a bad line. If false, will continue parsing skipping lines which fail to parse correctly. A sample of the first 10 encountered bad lines will be printed. comment_char : string, optional The character which denotes that the remainder of the line is a comment. escape_char : string, optional Character which begins a C escape sequence double_quote : bool, optional If True, two consecutive quotes in a string are parsed to a single quote. quote_char : string, optional Character sequence that indicates a quote. skip_initial_space : bool, optional Ignore extra spaces at the start of a field column_type_hints : None, type, list[type], dict[string, type], optional This provides type hints for each column. By default, this method attempts to detect the type of each column automatically. Supported types are int, float, str, list, dict, and array.array. * If a single type is provided, the type will be applied to all columns. For instance, column_type_hints=float will force all columns to be parsed as float. * If a list of types is provided, the types applies to each column in order, e.g.[int, float, str] will parse the first column as int, second as float and third as string. * If a dictionary of column name to type is provided, each type value in the dictionary is applied to the key it belongs to. For instance {'user':int} will hint that the column called "user" should be parsed as an integer, and the rest will default to string. na_values : str | list of str, optional A string or list of strings to be interpreted as missing values. nrows : int, optional If set, only this many rows will be read from the file. verbose : bool, optional If True, print the progress. Returns ------- out : SFrame See Also -------- read_csv_with_errors, SFrame Examples -------- Read a regular csv file, with all default options, automatically determine types: >>> url = 'http://s3.amazonaws.com/gl-testdata/rating_data_example.csv' >>> sf = graphlab.SFrame.read_csv(url) >>> sf Columns: user_id int movie_id int rating int Rows: 10000 +---------+----------+--------+ | user_id | movie_id | rating | +---------+----------+--------+ | 25904 | 1663 | 3 | | 25907 | 1663 | 3 | | 25923 | 1663 | 3 | | 25924 | 1663 | 3 | | 25928 | 1663 | 2 | | ... | ... | ... | +---------+----------+--------+ [10000 rows x 3 columns] Read only the first 100 lines of the csv file: >>> sf = graphlab.SFrame.read_csv(url, nrows=100) >>> sf Columns: user_id int movie_id int rating int Rows: 100 +---------+----------+--------+ | user_id | movie_id | rating | +---------+----------+--------+ | 25904 | 1663 | 3 | | 25907 | 1663 | 3 | | 25923 | 1663 | 3 | | 25924 | 1663 | 3 | | 25928 | 1663 | 2 | | ... | ... | ... | +---------+----------+--------+ [100 rows x 3 columns] Read all columns as str type >>> sf = graphlab.SFrame.read_csv(url, column_type_hints=str) >>> sf Columns: user_id str movie_id str rating str Rows: 10000 +---------+----------+--------+ | user_id | movie_id | rating | +---------+----------+--------+ | 25904 | 1663 | 3 | | 25907 | 1663 | 3 | | 25923 | 1663 | 3 | | 25924 | 1663 | 3 | | 25928 | 1663 | 2 | | ... | ... | ... | +---------+----------+--------+ [10000 rows x 3 columns] Specify types for a subset of columns and leave the rest to be str. >>> sf = graphlab.SFrame.read_csv(url, ... column_type_hints={ ... 'user_id':int, 'rating':float ... }) >>> sf Columns: user_id str movie_id str rating float Rows: 10000 +---------+----------+--------+ | user_id | movie_id | rating | +---------+----------+--------+ | 25904 | 1663 | 3.0 | | 25907 | 1663 | 3.0 | | 25923 | 1663 | 3.0 | | 25924 | 1663 | 3.0 | | 25928 | 1663 | 2.0 | | ... | ... | ... | +---------+----------+--------+ [10000 rows x 3 columns] Not treat first line as header: >>> sf = graphlab.SFrame.read_csv(url, header=False) >>> sf Columns: X1 str X2 str X3 str Rows: 10001 +---------+----------+--------+ | X1 | X2 | X3 | +---------+----------+--------+ | user_id | movie_id | rating | | 25904 | 1663 | 3 | | 25907 | 1663 | 3 | | 25923 | 1663 | 3 | | 25924 | 1663 | 3 | | 25928 | 1663 | 2 | | ... | ... | ... | +---------+----------+--------+ [10001 rows x 3 columns] Treat '3' as missing value: >>> sf = graphlab.SFrame.read_csv(url, na_values=['3'], column_type_hints=str) >>> sf Columns: user_id str movie_id str rating str Rows: 10000 +---------+----------+--------+ | user_id | movie_id | rating | +---------+----------+--------+ | 25904 | 1663 | None | | 25907 | 1663 | None | | 25923 | 1663 | None | | 25924 | 1663 | None | | 25928 | 1663 | 2 | | ... | ... | ... | +---------+----------+--------+ [10000 rows x 3 columns] Throw error on parse failure: >>> bad_url = 'https://s3.amazonaws.com/gl-testdata/bad_csv_example.csv' >>> sf = graphlab.SFrame.read_csv(bad_url, error_bad_lines=True) RuntimeError: Runtime Exception. Unable to parse line "x,y,z,a,b,c" Set error_bad_lines=False to skip bad lines """ return cls._read_csv_impl(url, delimiter=delimiter, header=header, error_bad_lines=error_bad_lines, comment_char=comment_char, escape_char=escape_char, double_quote=double_quote, quote_char=quote_char, skip_initial_space=skip_initial_space, column_type_hints=column_type_hints, na_values=na_values, nrows=nrows, verbose=verbose, store_errors=False)[0] def to_schema_rdd(self,sc,sql,number_of_partitions=4): """ Convert the current SFrame to the Spark SchemaRDD. To enable this function, you must add the jar file bundled with GraphLab Create to the Spark driver's classpath. This must happen BEFORE Spark launches its JVM, or else it will have no effect. To do this, first get the location of the packaged jar with `graphlab.get_spark_integration_jar_path`. You then have two options: 1. Add the path to the jar to your spark-defaults.conf file. The property to set is 'spark.driver.extraClassPath'. OR 2. Add the jar's path as a command line option to your favorite way to start pyspark (either spark-submit or pyspark). For this, use the command line option '--driver-class-path'. Parameters ---------- sc : SparkContext sc is an existing SparkContext. sql : SQLContext sql is an existing SQLContext. number_of_partitions : int number of partitions for the output rdd Returns ---------- out: SchemaRDD Examples -------- >>> from pyspark import SparkContext, SQLContext >>> from graphlab import SFrame >>> sc = SparkContext('local') >>> sqlc = SQLContext(sc) >>> sf = SFrame({'x': [1,2,3], 'y': ['fish', 'chips', 'salad']}) >>> rdd = sf.to_schema_rdd(sc, sqlc) >>> rdd.collect() [Row(x=1, y=u'fish'), Row(x=2, y=u'chips'), Row(x=3, y=u'salad')] """ def homogeneous_type(seq): if seq is None or len(seq) == 0: return True iseq = iter(seq) first_type = type(next(iseq)) return True if all( (type(x) is first_type) for x in iseq ) else False if len(self) == 0: raise ValueError("SFrame is empty") column_names = self.column_names() first_row = self.head(1)[0] for name in column_names: if hasattr(first_row[name],'__iter__') and homogeneous_type(first_row[name]) is not True: raise TypeError("Support for translation to Spark SchemaRDD not enabled for heterogeneous iterable type (column: %s). Use SFrame.to_rdd()." % name) for _type in self.column_types(): if(_type.__name__ == 'datetime'): raise TypeError("Support for translation to Spark SchemaRDD not enabled for datetime type. Use SFrame.to_rdd() ") rdd = self.to_rdd(sc,number_of_partitions); from pyspark.sql import Row rowRdd = rdd.map(lambda x: Row(**x)) return sql.inferSchema(rowRdd) def to_rdd(self, sc, number_of_partitions=4): """ Convert the current SFrame to the Spark RDD. To enable this function, you must add the jar file bundled with GraphLab Create to the Spark driver's classpath. This must happen BEFORE Spark launches its JVM, or else it will have no effect. To do this, first get the location of the packaged jar with `graphlab.get_spark_integration_jar_path`. You then have two options: 1. Add the path to the jar to your spark-defaults.conf file. The property to set is 'spark.driver.extraClassPath'. OR 2. Add the jar's path as a command line option to your favorite way to start pyspark (either spark-submit or pyspark). For this, use the command line option '--driver-class-path'. Parameters ---------- sc : SparkContext sc is an existing SparkContext. number_of_partitions: int number of partitions for the output rdd Returns ---------- out: RDD Examples -------- >>> from pyspark import SparkContext >>> from graphlab import SFrame >>> sc = SparkContext('local') >>> sf = SFrame({'x': [1,2,3], 'y': ['fish', 'chips', 'salad']}) >>> rdd = sf.to_rdd(sc) >>> rdd.collect() [{'x': 1L, 'y': 'fish'}, {'x': 2L, 'y': 'chips'}, {'x': 3L, 'y': 'salad'}] """ _mt._get_metric_tracker().track('sframe.to_rdd') if not RDD_SUPPORT: raise Exception("Support for translation to Spark RDDs not enabled.") for _type in self.column_types(): if(_type.__name__ == 'Image'): raise TypeError("Support for translation to Spark RDDs not enabled for Image type.") if type(number_of_partitions) is not int: raise ValueError("number_of_partitions parameter expects an integer type") if number_of_partitions == 0: raise ValueError("number_of_partitions can not be initialized to zero") # Save SFrame in a temporary place tmp_loc = self.__get_staging_dir__(sc) sf_loc = os.path.join(tmp_loc, str(uuid.uuid4())) self.save(sf_loc) # Keep track of the temporary sframe that is saved(). We need to delete it eventually. dummysf = load_sframe(sf_loc) dummysf.__proxy__.delete_on_close() SFRAME_GARBAGE_COLLECTOR.append(dummysf) sframe_len = self.__len__() small_partition_size = sframe_len/number_of_partitions big_partition_size = small_partition_size + 1 num_big_partition_size = sframe_len % number_of_partitions num_small_partition_size = number_of_partitions - num_big_partition_size count = 0 start_index = 0 ranges = [] while(count < number_of_partitions): if(count < num_big_partition_size): ranges.append((str(start_index)+":"+str(start_index + big_partition_size))) start_index = start_index + big_partition_size else: ranges.append((str(start_index)+":"+str(start_index + small_partition_size))) start_index = start_index + small_partition_size count+=1 from pyspark import RDD rdd = sc.parallelize(ranges,number_of_partitions) if sc.master[0:5] == 'local': pipeRdd = sc._jvm.org.graphlab.create.GraphLabUtil.pythonToJava( rdd._jrdd).pipe( BINARY_PATHS['SPARK_PIPE_WRAPPER_PATH'] + \ " " + BINARY_PATHS['SFRAME_RDD_PATH'] + " " + sf_loc) elif sc.master == 'yarn-client': pipeRdd = sc._jvm.org.graphlab.create.GraphLabUtil.pythonToJava( rdd._jrdd).pipe( "./" + SPARK_SUPPORT_NAMES['SPARK_PIPE_WRAPPER_PATH'] + \ " " + "./" + SPARK_SUPPORT_NAMES['SFRAME_RDD_PATH'] + \ " " + sf_loc) serializedRdd = sc._jvm.org.graphlab.create.GraphLabUtil.stringToByte(pipeRdd) import pyspark output_rdd = RDD(serializedRdd,sc,pyspark.serializers.PickleSerializer()) return output_rdd @classmethod def __get_staging_dir__(cls,cur_sc): if not RDD_SUPPORT_INITED: __rdd_support_init__(cur_sc) return STAGING_DIR @classmethod def from_rdd(cls, rdd): """ Convert a Spark RDD into a GraphLab Create SFrame. To enable this function, you must add the jar file bundled with GraphLab Create to the Spark driver's classpath. This must happen BEFORE Spark launches its JVM, or else it will have no effect. To do this, first get the location of the packaged jar with `graphlab.get_spark_integration_jar_path`. You then have two options: 1. Add the path to the jar to your spark-defaults.conf file. The property to set is 'spark.driver.extraClassPath'. OR 2. Add the jar's path as a command line option to your favorite way to start pyspark (either spark-submit or pyspark). For this, use the command line option '--driver-class-path'. Parameters ---------- rdd : pyspark.rdd.RDD Returns ------- out : SFrame Examples -------- >>> from pyspark import SparkContext >>> from graphlab import SFrame >>> sc = SparkContext('local') >>> rdd = sc.parallelize([1,2,3]) >>> sf = SFrame.from_rdd(rdd) >>> sf Data: +-----+ | X1 | +-----+ | 1.0 | | 2.0 | | 3.0 | +-----+ [3 rows x 1 columns] """ _mt._get_metric_tracker().track('sframe.from_rdd') if not RDD_SUPPORT: raise Exception("Support for translation to Spark RDDs not enabled.") checkRes = rdd.take(1); if len(checkRes) > 0 and checkRes[0].__class__.__name__ == 'Row' and rdd.__class__.__name__ not in {'SchemaRDD','DataFrame'}: raise Exception("Conversion from RDD(pyspark.sql.Row) to SFrame not supported. Please call inferSchema(RDD) first.") if(rdd._jrdd_deserializer.__class__.__name__ == 'UTF8Deserializer'): return SFrame.__from_UTF8Deserialized_rdd__(rdd) sf_names = None rdd_type = "rdd" if rdd.__class__.__name__ in {'SchemaRDD','DataFrame'}: rdd_type = "schemardd" first_row = rdd.take(1)[0] if hasattr(first_row, 'keys'): sf_names = first_row.keys() else: sf_names = first_row.__FIELDS__ sf_names = [str(i) for i in sf_names] cur_sc = rdd.ctx tmp_loc = SFrame.__get_staging_dir__(cur_sc) if tmp_loc is None: raise RuntimeError("Could not determine staging directory for SFrame files.") mode = "batch" if(rdd._jrdd_deserializer.__class__.__name__ == 'PickleSerializer'): mode = "pickle" if cur_sc.master[0:5] == 'local': t = cur_sc._jvm.org.graphlab.create.GraphLabUtil.byteToString( rdd._jrdd).pipe( BINARY_PATHS['SPARK_PIPE_WRAPPER_PATH'] + " " + \ BINARY_PATHS['RDD_SFRAME_PATH'] + " " + tmp_loc +\ " " + mode + " " + rdd_type) else: t = cur_sc._jvm.org.graphlab.create.GraphLabUtil.byteToString( rdd._jrdd).pipe( "./" + SPARK_SUPPORT_NAMES['SPARK_PIPE_WRAPPER_PATH'] +\ " " + "./" + SPARK_SUPPORT_NAMES['RDD_SFRAME_PATH'] + " " +\ tmp_loc + " " + mode + " " + rdd_type) # We get the location of an SFrame index file per Spark partition in # the result. We assume that this is in partition order. res = t.collect() out_sf = cls() sframe_list = [] for url in res: sf = SFrame() sf.__proxy__.load_from_sframe_index(_make_internal_url(url)) sf.__proxy__.delete_on_close() out_sf_coltypes = out_sf.column_types() if(len(out_sf_coltypes) != 0): sf_coltypes = sf.column_types() sf_temp_names = sf.column_names() out_sf_temp_names = out_sf.column_names() for i in range(len(sf_coltypes)): if sf_coltypes[i] != out_sf_coltypes[i]: print "mismatch for types %s and %s" % (sf_coltypes[i],out_sf_coltypes[i]) sf[sf_temp_names[i]] = sf[sf_temp_names[i]].astype(str) out_sf[out_sf_temp_names[i]] = out_sf[out_sf_temp_names[i]].astype(str) out_sf = out_sf.append(sf) out_sf.__proxy__.delete_on_close() if sf_names is not None: out_names = out_sf.column_names() if(set(out_names) != set(sf_names)): out_sf = out_sf.rename(dict(zip(out_names, sf_names))) return out_sf @classmethod def __from_UTF8Deserialized_rdd__(cls, rdd): _mt._get_metric_tracker().track('sframe.__from_UTF8Deserialized_rdd__') if not RDD_SUPPORT: raise Exception("Support for translation to Spark RDDs not enabled.") cur_sc = rdd.ctx sf_names = None sf_types = None tmp_loc = SFrame.__get_staging_dir__(cur_sc) if tmp_loc is None: raise RuntimeError("Could not determine staging directory for SFrame files.") if(rdd.__class__.__name__ in {'SchemaRDD','DataFrame'}): first_row = rdd.take(1)[0] if hasattr(first_row, 'keys'): sf_names = first_row.keys() sf_types = [type(i) for i in first_row.values()] else: sf_names = first_row.__FIELDS__ sf_types = [type(i) for i in first_row] sf_names = [str(i) for i in sf_names] for _type in sf_types: if(_type != int and _type != str and _type != float and _type != unicode): raise TypeError("Only int, str, and float are supported for now") types = "" for i in sf_types: types += i.__name__ + "," if cur_sc.master[0:5] == 'local': t = rdd._jschema_rdd.toJavaStringOfValues().pipe( BINARY_PATHS['SPARK_PIPE_WRAPPER_PATH'] + " " +\ BINARY_PATHS['RDD_SFRAME_NONPICKLE_PATH'] + " " + tmp_loc +\ " " + types) else: t = cur_sc._jvm.org.graphlab.create.GraphLabUtil.toJavaStringOfValues( rdd._jschema_rdd).pipe( "./" + SPARK_SUPPORT_NAMES['SPARK_PIPE_WRAPPER_PATH'] +\ " " + "./" +\ SPARK_SUPPORT_NAMES['RDD_SFRAME_NONPICKLE_PATH'] + " " +\ tmp_loc + " " + types) else: if cur_sc.master[0:5] == 'local': t = cur_sc._jvm.org.graphlab.create.GraphLabUtil.pythonToJava( rdd._jrdd).pipe( BINARY_PATHS['SPARK_PIPE_WRAPPER_PATH'] + " " +\ BINARY_PATHS['RDD_SFRAME_NONPICKLE_PATH'] + " " +\ tmp_loc) else: t = cur_sc._jvm.org.graphlab.create.GraphLabUtil.pythonToJava( rdd._jrdd).pipe( "./" + SPARK_SUPPORT_NAMES['SPARK_PIPE_WRAPPER_PATH'] +\ " " + "./" +\ SPARK_SUPPORT_NAMES['RDD_SFRAME_NONPICKLE_PATH'] + " " +\ tmp_loc) # We get the location of an SFrame index file per Spark partition in # the result. We assume that this is in partition order. res = t.collect() out_sf = cls() sframe_list = [] for url in res: sf = SFrame() sf.__proxy__.load_from_sframe_index(_make_internal_url(url)) sf.__proxy__.delete_on_close() out_sf = out_sf.append(sf) out_sf.__proxy__.delete_on_close() if sf_names is not None: out_names = out_sf.column_names() if(set(out_names) != set(sf_names)): out_sf = out_sf.rename(dict(zip(out_names, sf_names))) return out_sf @classmethod def from_odbc(cls, db, sql, verbose=False): """ Convert a table or query from a database to an SFrame. This function does not do any checking on the given SQL query, and cannot know what effect it will have on the database. Any side effects from the query will be reflected on the database. If no result rows are returned, an empty SFrame is created. Keep in mind the default case your database stores table names in. In some cases, you may need to add quotation marks (or whatever character your database uses to quote identifiers), especially if you created the table using `to_odbc`. Parameters ---------- db : `graphlab.extensions._odbc_connection.unity_odbc_connection` An ODBC connection object. This can only be obtained by calling `graphlab.connect_odbc`. Check that documentation for how to create this object. sql : str A SQL query. The query must be acceptable by the ODBC driver used by `graphlab.extensions._odbc_connection.unity_odbc_connection`. Returns ------- out : SFrame Notes ----- This functionality is only supported when using GraphLab Create entirely on your local machine. Therefore, GraphLab Create's EC2 and Hadoop execution modes will not be able to use ODBC. Note that this does not apply to the machine your database is running, which can (and often will) be running on a separate machine. Examples -------- >>> db = graphlab.connect_odbc("DSN=my_awesome_dsn;UID=user;PWD=mypassword") >>> a_table = graphlab.SFrame.from_odbc(db, "SELECT * FROM a_table") >>> join_result = graphlab.SFrame.from_odbc(db, 'SELECT * FROM "MyTable" a, "AnotherTable" b WHERE a.id=b.id') """ result = db.execute_query(sql) if not isinstance(result, SFrame): raise RuntimeError("Cannot create an SFrame for query. No result set.") cls = result return cls def to_odbc(self, db, table_name, append_if_exists=False, verbose=True): """ Convert an SFrame to a table in a database. By default, searches for a table in the database with the given name. If found, this will attempt to append all the rows of the SFrame to the end of the table. If not, this will create a new table with the given name. This behavior is toggled with the `append_if_exists` flag. When creating a new table, GraphLab Create uses a heuristic approach to pick a corresponding type for each column in the SFrame using the type information supplied by the database's ODBC driver. Your driver must support giving this type information for GraphLab Create to support writing to the database. To allow more expressive and accurate naming, `to_odbc` puts quotes around each identifier (table names and column names). Depending on your database, you may need to refer to the created table with quote characters around the name. This character is not the same for all databases, but '"' is the most common. Parameters ---------- db : `graphlab.extensions._odbc_connection.unity_odbc_connection` An ODBC connection object. This can only be obtained by calling `graphlab.connect_odbc`. Check that documentation for how to create this object. table_name : str The name of the table you would like to create/append to. append_if_exists : bool If True, this will attempt to append to the table named `table_name` if it is found to exist in the database. verbose : bool Print progress updates on the insertion process. Notes ----- This functionality is only supported when using GraphLab Create entirely on your local machine. Therefore, GraphLab Create's EC2 and Hadoop execution modes will not be able to use ODBC. Note that this "local machine" rule does not apply to the machine your database is running on, which can (and often will) be running on a separate machine. Examples -------- >>> db = graphlab.connect_odbc("DSN=my_awesome_dsn;UID=user;PWD=mypassword") >>> sf = graphlab.SFrame({'a':[1,2,3],'b':['hi','pika','bye']}) >>> sf.to_odbc(db, 'a_cool_table') """ if (not verbose): glconnect.get_client().set_log_progress(False) db._insert_sframe(self, table_name, append_if_exists) if (not verbose): glconnect.get_client().set_log_progress(True) def __repr__(self): """ Returns a string description of the frame """ printed_sf = self._imagecols_to_stringcols() ret = self.__get_column_description__() if self.__has_size__(): ret = ret + "Rows: " + str(len(self)) + "\n\n" else: ret = ret + "Rows: Unknown" + "\n\n" ret = ret + "Data:\n" if (len(printed_sf.head()) > 0): ret = ret + str(self) else: ret = ret + "\t[]" return ret def __get_column_description__(self): colnames = self.column_names() coltypes = self.column_types() ret = "Columns:\n" if len(colnames) > 0: for i in range(len(colnames)): ret = ret + "\t" + colnames[i] + "\t" + coltypes[i].__name__ + "\n" ret = ret + "\n" else: ret = ret + "\tNone\n\n" return ret def __get_pretty_tables__(self, wrap_text=False, max_row_width=80, max_column_width=30, max_columns=20, max_rows_to_display=60): """ Returns a list of pretty print tables representing the current SFrame. If the number of columns is larger than max_columns, the last pretty table will contain an extra column of "...". Parameters ---------- wrap_text : bool, optional max_row_width : int, optional Max number of characters per table. max_column_width : int, optional Max number of characters per column. max_columns : int, optional Max number of columns per table. max_rows_to_display : int, optional Max number of rows to display. Returns ------- out : list[PrettyTable] """ headsf = self.head(max_rows_to_display) if headsf.shape == (0, 0): return [PrettyTable()] # convert array.array column to list column so they print like [...] # and not array('d', ...) for col in headsf.column_names(): if headsf[col].dtype() is array.array: headsf[col] = headsf[col].astype(list) def _value_to_str(value): if (type(value) is array.array): return str(list(value)) elif (type(value) is list): return '[' + ", ".join(_value_to_str(x) for x in value) + ']' else: return str(value) def _escape_space(s): return "".join([ch.encode('string_escape') if ch.isspace() else ch for ch in s]) def _truncate_respect_unicode(s, max_length): if (len(s) <= max_length): return s else: u = unicode(s, 'utf-8', errors='replace') return u[:max_length].encode('utf-8') def _truncate_str(s, wrap_str=False): """ Truncate and optionally wrap the input string as unicode, replace unconvertible character with a diamond ?. """ s = _escape_space(s) if len(s) <= max_column_width: return unicode(s, 'utf-8', errors='replace') else: ret = '' # if wrap_str is true, wrap the text and take at most 2 rows if wrap_str: wrapped_lines = wrap(s, max_column_width) if len(wrapped_lines) == 1: return wrapped_lines[0] last_line = wrapped_lines[1] if len(last_line) >= max_column_width: last_line = _truncate_respect_unicode(last_line, max_column_width - 4) ret = wrapped_lines[0] + '\n' + last_line + ' ...' else: ret = _truncate_respect_unicode(s, max_column_width - 4) + '...' return unicode(ret, 'utf-8', errors='replace') columns = self.column_names()[:max_columns] columns.reverse() # reverse the order of columns and we will pop from the end num_column_of_last_table = 0 row_of_tables = [] # let's build a list of tables with max_columns # each table should satisfy, max_row_width, and max_column_width while len(columns) > 0: tbl = PrettyTable() table_width = 0 num_column_of_last_table = 0 while len(columns) > 0: col = columns.pop() # check the max length of element in the column if len(headsf) > 0: col_width = min(max_column_width, max(len(str(x)) for x in headsf[col])) else: col_width = max_column_width if (table_width + col_width < max_row_width): # truncate the header if necessary header = _truncate_str(col, wrap_text) tbl.add_column(header, [_truncate_str(_value_to_str(x), wrap_text) for x in headsf[col]]) table_width = str(tbl).find('\n') num_column_of_last_table += 1 else: # the column does not fit in the current table, push it back to columns columns.append(col) break tbl.align = 'c' row_of_tables.append(tbl) # add a column of all "..." if there are more columns than displayed if self.num_cols() > max_columns: row_of_tables[-1].add_column('...', ['...'] * len(headsf)) num_column_of_last_table += 1 # add a row of all "..." if there are more rows than displayed if self.__has_size__() and self.num_rows() > headsf.num_rows(): row_of_tables[-1].add_row(['...'] * num_column_of_last_table) return row_of_tables def print_rows(self, num_rows=10, num_columns=40, max_column_width=30, max_row_width=80): """ Print the first M rows and N columns of the SFrame in human readable format. Parameters ---------- num_rows : int, optional Number of rows to print. num_columns : int, optional Number of columns to print. max_column_width : int, optional Maximum width of a column. Columns use fewer characters if possible. max_row_width : int, optional Maximum width of a printed row. Columns beyond this width wrap to a new line. `max_row_width` is automatically reset to be the larger of itself and `max_column_width`. See Also -------- head, tail """ max_row_width = max(max_row_width, max_column_width + 1) printed_sf = self._imagecols_to_stringcols(num_rows) row_of_tables = printed_sf.__get_pretty_tables__(wrap_text=False, max_rows_to_display=num_rows, max_columns=num_columns, max_column_width=max_column_width, max_row_width=max_row_width) footer = "[%d rows x %d columns]\n" % self.shape print '\n'.join([str(tb) for tb in row_of_tables]) + "\n" + footer def _imagecols_to_stringcols(self, num_rows=10): # A list of column types types = self.column_types() # A list of indexable column names names = self.column_names() # Constructing names of sframe columns that are of image type image_column_names = [names[i] for i in range(len(names)) if types[i] == graphlab.Image] #If there are image-type columns, copy the SFrame and cast the top MAX_NUM_ROWS_TO_DISPLAY of those columns to string if len(image_column_names) > 0: printed_sf = SFrame() for t in names: if t in image_column_names: printed_sf[t] = self[t]._head_str(num_rows) else: printed_sf[t] = self[t].head(num_rows) else: printed_sf = self return printed_sf def __str__(self, num_rows=10, footer=True): """ Returns a string containing the first 10 elements of the frame, along with a description of the frame. """ MAX_ROWS_TO_DISPLAY = num_rows printed_sf = self._imagecols_to_stringcols(MAX_ROWS_TO_DISPLAY) row_of_tables = printed_sf.__get_pretty_tables__(wrap_text=False, max_rows_to_display=MAX_ROWS_TO_DISPLAY) if (not footer): return '\n'.join([str(tb) for tb in row_of_tables]) if self.__has_size__(): footer = '[%d rows x %d columns]\n' % self.shape if (self.num_rows() > MAX_ROWS_TO_DISPLAY): footer += '\n'.join(FOOTER_STRS) else: footer = '[? rows x %d columns]\n' % self.num_columns() footer += '\n'.join(LAZY_FOOTER_STRS) return '\n'.join([str(tb) for tb in row_of_tables]) + "\n" + footer def _repr_html_(self): MAX_ROWS_TO_DISPLAY = 10 printed_sf = self._imagecols_to_stringcols(MAX_ROWS_TO_DISPLAY) row_of_tables = printed_sf.__get_pretty_tables__(wrap_text=True, max_row_width=120, max_columns=40, max_column_width=25, max_rows_to_display=MAX_ROWS_TO_DISPLAY) if self.__has_size__(): footer = '[%d rows x %d columns]<br/>' % self.shape if (self.num_rows() > MAX_ROWS_TO_DISPLAY): footer += '<br/>'.join(FOOTER_STRS) else: footer = '[? rows x %d columns]<br/>' % self.num_columns() footer += '<br/>'.join(LAZY_FOOTER_STRS) begin = '<div style="max-height:1000px;max-width:1500px;overflow:auto;">' end = '\n</div>' return begin + '\n'.join([tb.get_html_string(format=True) for tb in row_of_tables]) + "\n" + footer + end def __nonzero__(self): """ Returns true if the frame is not empty. """ return self.num_rows() != 0 def __len__(self): """ Returns the number of rows of the sframe. """ return self.num_rows() def __copy__(self): """ Returns a shallow copy of the sframe. """ return self.select_columns(self.column_names()) def __eq__(self, other): raise NotImplementedError def __ne__(self, other): raise NotImplementedError def _row_selector(self, other): """ Where other is an SArray of identical length as the current Frame, this returns a selection of a subset of rows in the current SFrame where the corresponding row in the selector is non-zero. """ if type(other) is SArray: if len(other) != len(self): raise IndexError("Cannot perform logical indexing on arrays of different length.") with cython_context(): return SFrame(_proxy=self.__proxy__.logical_filter(other.__proxy__)) def dtype(self): """ The type of each column. Returns ------- out : list[type] Column types of the SFrame. See Also -------- column_types """ return self.column_types() def num_rows(self): """ The number of rows in this SFrame. Returns ------- out : int Number of rows in the SFrame. See Also -------- num_columns """ return self.__proxy__.num_rows() def num_cols(self): """ The number of columns in this SFrame. Returns ------- out : int Number of columns in the SFrame. See Also -------- num_columns, num_rows """ return self.__proxy__.num_columns() def num_columns(self): """ The number of columns in this SFrame. Returns ------- out : int Number of columns in the SFrame. See Also -------- num_cols, num_rows """ return self.__proxy__.num_columns() def column_names(self): """ The name of each column in the SFrame. Returns ------- out : list[string] Column names of the SFrame. See Also -------- rename """ return self.__proxy__.column_names() def column_types(self): """ The type of each column in the SFrame. Returns ------- out : list[type] Column types of the SFrame. See Also -------- dtype """ return self.__proxy__.dtype() def head(self, n=10): """ The first n rows of the SFrame. Parameters ---------- n : int, optional The number of rows to fetch. Returns ------- out : SFrame A new SFrame which contains the first n rows of the current SFrame See Also -------- tail, print_rows """ return SFrame(_proxy=self.__proxy__.head(n)) def to_dataframe(self): """ Convert this SFrame to pandas.DataFrame. This operation will construct a pandas.DataFrame in memory. Care must be taken when size of the returned object is big. Returns ------- out : pandas.DataFrame The dataframe which contains all rows of SFrame """ assert HAS_PANDAS df = pandas.DataFrame() for i in range(self.num_columns()): column_name = self.column_names()[i] df[column_name] = list(self[column_name]) if len(df[column_name]) == 0: df[column_name] = df[column_name].astype(self.column_types()[i]) return df def tail(self, n=10): """ The last n rows of the SFrame. Parameters ---------- n : int, optional The number of rows to fetch. Returns ------- out : SFrame A new SFrame which contains the last n rows of the current SFrame See Also -------- head, print_rows """ return SFrame(_proxy=self.__proxy__.tail(n)) def apply(self, fn, dtype=None, seed=None): """ Transform each row to an :class:`~graphlab.SArray` according to a specified function. Returns a new SArray of ``dtype`` where each element in this SArray is transformed by `fn(x)` where `x` is a single row in the sframe represented as a dictionary. The ``fn`` should return exactly one value which can be cast into type ``dtype``. If ``dtype`` is not specified, the first 100 rows of the SFrame are used to make a guess of the target data type. Parameters ---------- fn : function The function to transform each row of the SFrame. The return type should be convertible to `dtype` if `dtype` is not None. This can also be a toolkit extension function which is compiled as a native shared library using SDK. dtype : dtype, optional The dtype of the new SArray. If None, the first 100 elements of the array are used to guess the target data type. seed : int, optional Used as the seed if a random number generator is included in `fn`. Returns ------- out : SArray The SArray transformed by fn. Each element of the SArray is of type ``dtype`` Examples -------- Concatenate strings from several columns: >>> sf = graphlab.SFrame({'user_id': [1, 2, 3], 'movie_id': [3, 3, 6], 'rating': [4, 5, 1]}) >>> sf.apply(lambda x: str(x['user_id']) + str(x['movie_id']) + str(x['rating'])) dtype: str Rows: 3 ['134', '235', '361'] Using native toolkit extension function: .. code-block:: c++ #include <graphlab/sdk/toolkit_function_macros.hpp> double mean(const std::map<flexible_type, flexible_type>& dict) { double sum = 0.0; for (const auto& kv: dict) sum += (double)kv.second; return sum / dict.size(); } BEGIN_FUNCTION_REGISTRATION REGISTER_FUNCTION(mean, "row"); END_FUNCTION_REGISTRATION compiled into example.so >>> import example >>> sf = graphlab.SFrame({'x0': [1, 2, 3], 'x1': [2, 3, 1], ... 'x2': [3, 1, 2]}) >>> sf.apply(example.mean) dtype: float Rows: 3 [2.0,2.0,2.0] """ assert _is_callable(fn), "Input must be a function" test_sf = self[:10] dryrun = [fn(row) for row in test_sf] if dtype is None: dtype = SArray(dryrun).dtype() if not seed: seed = int(time.time()) _mt._get_metric_tracker().track('sframe.apply') nativefn = None try: import graphlab.extensions as extensions nativefn = extensions._build_native_function_call(fn) except: pass if nativefn is not None: # this is a toolkit lambda. We can do something about it with cython_context(): return SArray(_proxy=self.__proxy__.transform_native(nativefn, dtype, seed)) with cython_context(): return SArray(_proxy=self.__proxy__.transform(fn, dtype, seed)) def flat_map(self, column_names, fn, column_types='auto', seed=None): """ Map each row of the SFrame to multiple rows in a new SFrame via a function. The output of `fn` must have type List[List[...]]. Each inner list will be a single row in the new output, and the collection of these rows within the outer list make up the data for the output SFrame. All rows must have the same length and the same order of types to make sure the result columns are homogeneously typed. For example, if the first element emitted into in the outer list by `fn` is [43, 2.3, 'string'], then all other elements emitted into the outer list must be a list with three elements, where the first is an int, second is a float, and third is a string. If column_types is not specified, the first 10 rows of the SFrame are used to determine the column types of the returned sframe. Parameters ---------- column_names : list[str] The column names for the returned SFrame. fn : function The function that maps each of the sframe row into multiple rows, returning List[List[...]]. All outputted rows must have the same length and order of types. column_types : list[type], optional The column types of the output SFrame. Default value will be automatically inferred by running `fn` on the first 10 rows of the input. If the types cannot be inferred from the first 10 rows, an error is raised. seed : int, optional Used as the seed if a random number generator is included in `fn`. Returns ------- out : SFrame A new SFrame containing the results of the flat_map of the original SFrame. Examples --------- Repeat each row according to the value in the 'number' column. >>> sf = graphlab.SFrame({'letter': ['a', 'b', 'c'], ... 'number': [1, 2, 3]}) >>> sf.flat_map(['number', 'letter'], ... lambda x: [list(x.itervalues()) for i in range(0, x['number'])]) +--------+--------+ | number | letter | +--------+--------+ | 1 | a | | 2 | b | | 2 | b | | 3 | c | | 3 | c | | 3 | c | +--------+--------+ [6 rows x 2 columns] """ assert inspect.isfunction(fn), "Input must be a function" if not seed: seed = int(time.time()) _mt._get_metric_tracker().track('sframe.flat_map') # determine the column_types if column_types == 'auto': types = set() sample = self[0:10] results = [fn(row) for row in sample] for rows in results: if type(rows) is not list: raise TypeError("Output type of the lambda function must be a list of lists") # note: this skips empty lists for row in rows: if type(row) is not list: raise TypeError("Output type of the lambda function must be a list of lists") types.add(tuple([type(v) for v in row])) if len(types) == 0: raise TypeError, \ "Could not infer output column types from the first ten rows " +\ "of the SFrame. Please use the 'column_types' parameter to " +\ "set the types." if len(types) > 1: raise TypeError("Mapped rows must have the same length and types") column_types = list(types.pop()) assert type(column_types) is list assert len(column_types) == len(column_names), "Number of output columns must match the size of column names" with cython_context(): return SFrame(_proxy=self.__proxy__.flat_map(fn, column_names, column_types, seed)) def sample(self, fraction, seed=None): """ Sample the current SFrame's rows. Parameters ---------- fraction : float Approximate fraction of the rows to fetch. Must be between 0 and 1. The number of rows returned is approximately the fraction times the number of rows. seed : int, optional Seed for the random number generator used to sample. Returns ------- out : SFrame A new SFrame containing sampled rows of the current SFrame. Examples -------- Suppose we have an SFrame with 6,145 rows. >>> import random >>> sf = SFrame({'id': range(0, 6145)}) Retrieve about 30% of the SFrame rows with repeatable results by setting the random seed. >>> len(sf.sample(.3, seed=5)) 1783 """ if not seed: seed = int(time.time()) if (fraction > 1 or fraction < 0): raise ValueError('Invalid sampling rate: ' + str(fraction)) _mt._get_metric_tracker().track('sframe.sample') if (self.num_rows() == 0 or self.num_cols() == 0): return self else: with cython_context(): return SFrame(_proxy=self.__proxy__.sample(fraction, seed)) def random_split(self, fraction, seed=None): """ Randomly split the rows of an SFrame into two SFrames. The first SFrame contains *M* rows, sampled uniformly (without replacement) from the original SFrame. *M* is approximately the fraction times the original number of rows. The second SFrame contains the remaining rows of the original SFrame. Parameters ---------- fraction : float Approximate fraction of the rows to fetch for the first returned SFrame. Must be between 0 and 1. seed : int, optional Seed for the random number generator used to split. Returns ------- out : tuple [SFrame] Two new SFrames. Examples -------- Suppose we have an SFrame with 1,024 rows and we want to randomly split it into training and testing datasets with about a 90%/10% split. >>> sf = graphlab.SFrame({'id': range(1024)}) >>> sf_train, sf_test = sf.random_split(.9, seed=5) >>> print len(sf_train), len(sf_test) 922 102 """ if (fraction > 1 or fraction < 0): raise ValueError('Invalid sampling rate: ' + str(fraction)) if (self.num_rows() == 0 or self.num_cols() == 0): return (SFrame(), SFrame()) if not seed: seed = int(time.time()) # The server side requires this to be an int, so cast if we can try: seed = int(seed) except ValueError: raise ValueError('The \'seed\' parameter must be of type int.') _mt._get_metric_tracker().track('sframe.random_split') with cython_context(): proxy_pair = self.__proxy__.random_split(fraction, seed) return (SFrame(data=[], _proxy=proxy_pair[0]), SFrame(data=[], _proxy=proxy_pair[1])) def topk(self, column_name, k=10, reverse=False): """ Get top k rows according to the given column. Result is according to and sorted by `column_name` in the given order (default is descending). When `k` is small, `topk` is more efficient than `sort`. Parameters ---------- column_name : string The column to sort on k : int, optional The number of rows to return reverse : bool, optional If True, return the top k rows in ascending order, otherwise, in descending order. Returns ------- out : SFrame an SFrame containing the top k rows sorted by column_name. See Also -------- sort Examples -------- >>> sf = graphlab.SFrame({'id': range(1000)}) >>> sf['value'] = -sf['id'] >>> sf.topk('id', k=3) +--------+--------+ | id | value | +--------+--------+ | 999 | -999 | | 998 | -998 | | 997 | -997 | +--------+--------+ [3 rows x 2 columns] >>> sf.topk('value', k=3) +--------+--------+ | id | value | +--------+--------+ | 1 | -1 | | 2 | -2 | | 3 | -3 | +--------+--------+ [3 rows x 2 columns] """ if type(column_name) is not str: raise TypeError("column_name must be a string") _mt._get_metric_tracker().track('sframe.topk') sf = self[self[column_name].topk_index(k, reverse)] return sf.sort(column_name, ascending=reverse) def save(self, filename, format=None): """ Save the SFrame to a file system for later use. Parameters ---------- filename : string The location to save the SFrame. Either a local directory or a remote URL. If the format is 'binary', a directory will be created at the location which will contain the sframe. format : {'binary', 'csv'}, optional Format in which to save the SFrame. Binary saved SFrames can be loaded much faster and without any format conversion losses. If not given, will try to infer the format from filename given. If file name ends with 'csv' or '.csv.gz', then save as 'csv' format, otherwise save as 'binary' format. See Also -------- load_sframe, SFrame Examples -------- >>> # Save the sframe into binary format >>> sf.save('data/training_data_sframe') >>> # Save the sframe into csv format >>> sf.save('data/training_data.csv', format='csv') """ _mt._get_metric_tracker().track('sframe.save', properties={'format':format}) if format == None: if filename.endswith(('.csv', '.csv.gz')): format = 'csv' else: format = 'binary' else: if format is 'csv': if not filename.endswith(('.csv', '.csv.gz')): filename = filename + '.csv' elif format is not 'binary': raise ValueError("Invalid format: {}. Supported formats are 'csv' and 'binary'".format(format)) ## Save the SFrame url = _make_internal_url(filename) with cython_context(): if format is 'binary': self.__proxy__.save(url) elif format is 'csv': assert filename.endswith(('.csv', '.csv.gz')) self.__proxy__.save_as_csv(url, {}) else: raise ValueError("Unsupported format: {}".format(format)) def select_column(self, key): """ Get a reference to the :class:`~graphlab.SArray` that corresponds with the given key. Throws an exception if the key is something other than a string or if the key is not found. Parameters ---------- key : str The column name. Returns ------- out : SArray The SArray that is referred by ``key``. See Also -------- select_columns Examples -------- >>> sf = graphlab.SFrame({'user_id': [1,2,3], ... 'user_name': ['alice', 'bob', 'charlie']}) >>> # This line is equivalent to `sa = sf['user_name']` >>> sa = sf.select_column('user_name') >>> sa dtype: str Rows: 3 ['alice', 'bob', 'charlie'] """ if not isinstance(key, str): raise TypeError("Invalid key type: must be str") with cython_context(): return SArray(data=[], _proxy=self.__proxy__.select_column(key)) def select_columns(self, keylist): """ Get SFrame composed only of the columns referred to in the given list of keys. Throws an exception if ANY of the keys are not in this SFrame or if ``keylist`` is anything other than a list of strings. Parameters ---------- keylist : list[str] The list of column names. Returns ------- out : SFrame A new SFrame that is made up of the columns referred to in ``keylist`` from the current SFrame. See Also -------- select_column Examples -------- >>> sf = graphlab.SFrame({'user_id': [1,2,3], ... 'user_name': ['alice', 'bob', 'charlie'], ... 'zipcode': [98101, 98102, 98103] ... }) >>> # This line is equivalent to `sf2 = sf[['user_id', 'zipcode']]` >>> sf2 = sf.select_columns(['user_id', 'zipcode']) >>> sf2 +---------+---------+ | user_id | zipcode | +---------+---------+ | 1 | 98101 | | 2 | 98102 | | 3 | 98103 | +---------+---------+ [3 rows x 2 columns] """ if not hasattr(keylist, '__iter__'): raise TypeError("keylist must be an iterable") if not all([isinstance(x, str) for x in keylist]): raise TypeError("Invalid key type: must be str") key_set = set(keylist) if (len(key_set)) != len(keylist): for key in key_set: if keylist.count(key) > 1: raise ValueError("There are duplicate keys in key list: '" + key + "'") with cython_context(): return SFrame(data=[], _proxy=self.__proxy__.select_columns(keylist)) def add_column(self, data, name=""): """ Add a column to this SFrame. The number of elements in the data given must match the length of every other column of the SFrame. This operation modifies the current SFrame in place and returns self. If no name is given, a default name is chosen. Parameters ---------- data : SArray The 'column' of data to add. name : string, optional The name of the column. If no name is given, a default name is chosen. Returns ------- out : SFrame The current SFrame. See Also -------- add_columns Examples -------- >>> sf = graphlab.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> sa = graphlab.SArray(['cat', 'dog', 'fossa']) >>> # This line is equivalant to `sf['species'] = sa` >>> sf.add_column(sa, name='species') >>> sf +----+-----+---------+ | id | val | species | +----+-----+---------+ | 1 | A | cat | | 2 | B | dog | | 3 | C | fossa | +----+-----+---------+ [3 rows x 3 columns] """ # Check type for pandas dataframe or SArray? if not isinstance(data, SArray): raise TypeError("Must give column as SArray") if not isinstance(name, str): raise TypeError("Invalid column name: must be str") with cython_context(): self.__proxy__.add_column(data.__proxy__, name) return self def add_columns(self, data, namelist=None): """ Adds multiple columns to this SFrame. The number of elements in all columns must match the length of every other column of the SFrame. This operation modifies the current SFrame in place and returns self. Parameters ---------- data : list[SArray] or SFrame The columns to add. namelist : list of string, optional A list of column names. All names must be specified. ``namelist`` is ignored if data is an SFrame. Returns ------- out : SFrame The current SFrame. See Also -------- add_column Examples -------- >>> sf = graphlab.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> sf2 = graphlab.SFrame({'species': ['cat', 'dog', 'fossa'], ... 'age': [3, 5, 9]}) >>> sf.add_columns(sf2) >>> sf +----+-----+-----+---------+ | id | val | age | species | +----+-----+-----+---------+ | 1 | A | 3 | cat | | 2 | B | 5 | dog | | 3 | C | 9 | fossa | +----+-----+-----+---------+ [3 rows x 4 columns] """ datalist = data if isinstance(data, SFrame): other = data datalist = [other.select_column(name) for name in other.column_names()] namelist = other.column_names() my_columns = set(self.column_names()) for name in namelist: if name in my_columns: raise ValueError("Column '" + name + "' already exists in current SFrame") else: if not hasattr(datalist, '__iter__'): raise TypeError("datalist must be an iterable") if not hasattr(namelist, '__iter__'): raise TypeError("namelist must be an iterable") if not all([isinstance(x, SArray) for x in datalist]): raise TypeError("Must give column as SArray") if not all([isinstance(x, str) for x in namelist]): raise TypeError("Invalid column name in list : must all be str") with cython_context(): self.__proxy__.add_columns([x.__proxy__ for x in datalist], namelist) return self def remove_column(self, name): """ Remove a column from this SFrame. This operation modifies the current SFrame in place and returns self. Parameters ---------- name : string The name of the column to remove. Returns ------- out : SFrame The SFrame with given column removed. Examples -------- >>> sf = graphlab.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> # This is equivalent to `del sf['val']` >>> sf.remove_column('val') >>> sf +----+ | id | +----+ | 1 | | 2 | | 3 | +----+ [3 rows x 1 columns] """ if name not in self.column_names(): raise KeyError('Cannot find column %s' % name) colid = self.column_names().index(name) with cython_context(): self.__proxy__.remove_column(colid) return self def remove_columns(self, column_names): """ Remove one or more columns from this SFrame. This operation modifies the current SFrame in place and returns self. Parameters ---------- column_names : list or iterable A list or iterable of column names. Returns ------- out : SFrame The SFrame with given columns removed. Examples -------- >>> sf = graphlab.SFrame({'id': [1, 2, 3], 'val1': ['A', 'B', 'C'], 'val2' : [10, 11, 12]}) >>> sf.remove_columns(['val1', 'val2']) >>> sf +----+ | id | +----+ | 1 | | 2 | | 3 | +----+ [3 rows x 1 columns] """ column_names = list(column_names) existing_columns = dict((k, i) for i, k in enumerate(self.column_names())) for name in column_names: if name not in existing_columns: raise KeyError('Cannot find column %s' % name) # Delete it going backwards so we don't invalidate indices deletion_indices = sorted(existing_columns[name] for name in column_names) for colid in reversed(deletion_indices): with cython_context(): self.__proxy__.remove_column(colid) return self def swap_columns(self, column_1, column_2): """ Swap the columns with the given names. This operation modifies the current SFrame in place and returns self. Parameters ---------- column_1 : string Name of column to swap column_2 : string Name of other column to swap Returns ------- out : SFrame The SFrame with swapped columns. Examples -------- >>> sf = graphlab.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> sf.swap_columns('id', 'val') >>> sf +-----+-----+ | val | id | +-----+-----+ | A | 1 | | B | 2 | | C | 3 | +----+-----+ [3 rows x 2 columns] """ colnames = self.column_names() colid_1 = colnames.index(column_1) colid_2 = colnames.index(column_2) with cython_context(): self.__proxy__.swap_columns(colid_1, colid_2) return self def rename(self, names): """ Rename the given columns. ``names`` is expected to be a dict specifying the old and new names. This changes the names of the columns given as the keys and replaces them with the names given as the values. This operation modifies the current SFrame in place and returns self. Parameters ---------- names : dict [string, string] Dictionary of [old_name, new_name] Returns ------- out : SFrame The current SFrame. See Also -------- column_names Examples -------- >>> sf = SFrame({'X1': ['Alice','Bob'], ... 'X2': ['123 Fake Street','456 Fake Street']}) >>> sf.rename({'X1': 'name', 'X2':'address'}) >>> sf +-------+-----------------+ | name | address | +-------+-----------------+ | Alice | 123 Fake Street | | Bob | 456 Fake Street | +-------+-----------------+ [2 rows x 2 columns] """ if (type(names) is not dict): raise TypeError('names must be a dictionary: oldname -> newname') all_columns = set(self.column_names()) for k in names: if not k in all_columns: raise ValueError('Cannot find column %s in the SFrame' % k) with cython_context(): for k in names: colid = self.column_names().index(k) self.__proxy__.set_column_name(colid, names[k]) return self def __getitem__(self, key): """ This method does things based on the type of `key`. If `key` is: * str Calls `select_column` on `key` * SArray Performs a logical filter. Expects given SArray to be the same length as all columns in current SFrame. Every row corresponding with an entry in the given SArray that is equivalent to False is filtered from the result. * int Returns a single row of the SFrame (the `key`th one) as a dictionary. * slice Returns an SFrame including only the sliced rows. """ if type(key) is SArray: return self._row_selector(key) elif type(key) is list: return self.select_columns(key) elif type(key) is str: return self.select_column(key) elif type(key) is int: if key < 0: key = len(self) + key if key >= len(self): raise IndexError("SFrame index out of range") return list(SFrame(_proxy = self.__proxy__.copy_range(key, 1, key+1)))[0] elif type(key) is slice: start = key.start stop = key.stop step = key.step if start is None: start = 0 if stop is None: stop = len(self) if step is None: step = 1 # handle negative indices if start < 0: start = len(self) + start if stop < 0: stop = len(self) + stop return SFrame(_proxy = self.__proxy__.copy_range(start, step, stop)) else: raise TypeError("Invalid index type: must be SArray, list, or str") def __setitem__(self, key, value): """ A wrapper around add_column(s). Key can be either a list or a str. If value is an SArray, it is added to the SFrame as a column. If it is a constant value (int, str, or float), then a column is created where every entry is equal to the constant value. Existing columns can also be replaced using this wrapper. """ if type(key) is list: self.add_columns(value, key) elif type(key) is str: sa_value = None if (type(value) is SArray): sa_value = value elif hasattr(value, '__iter__'): # wrap list, array... to sarray sa_value = SArray(value) else: # create an sarray of constant value sa_value = SArray.from_const(value, self.num_rows()) # set new column if not key in self.column_names(): with cython_context(): self.add_column(sa_value, key) else: # special case if replacing the only column. # server would fail the replacement if the new column has different # length than current one, which doesn't make sense if we are replacing # the only column. To support this, we first take out the only column # and then put it back if exception happens single_column = (self.num_cols() == 1) if (single_column): tmpname = key saved_column = self.select_column(key) self.remove_column(key) else: # add the column to a unique column name. tmpname = '__' + '-'.join(self.column_names()) try: self.add_column(sa_value, tmpname) except Exception as e: if (single_column): self.add_column(saved_column, key) raise if (not single_column): # if add succeeded, remove the column name and rename tmpname->columnname. self.swap_columns(key, tmpname) self.remove_column(key) self.rename({tmpname: key}) else: raise TypeError('Cannot set column with key type ' + str(type(key))) def __delitem__(self, key): """ Wrapper around remove_column. """ self.remove_column(key) def __materialize__(self): """ For an SFrame that is lazily evaluated, force the persistence of the SFrame to disk, committing all lazy evaluated operations. """ with cython_context(): self.__proxy__.materialize() def __is_materialized__(self): """ Returns whether or not the SFrame has been materialized. """ return self.__proxy__.is_materialized() def __has_size__(self): """ Returns whether or not the size of the SFrame is known. """ return self.__proxy__.has_size() def __iter__(self): """ Provides an iterator to the rows of the SFrame. """ _mt._get_metric_tracker().track('sframe.__iter__') def generator(): elems_at_a_time = 262144 self.__proxy__.begin_iterator() ret = self.__proxy__.iterator_get_next(elems_at_a_time) column_names = self.column_names() while(True): for j in ret: yield dict(zip(column_names, j)) if len(ret) == elems_at_a_time: ret = self.__proxy__.iterator_get_next(elems_at_a_time) else: break return generator() def append(self, other): """ Add the rows of an SFrame to the end of this SFrame. Both SFrames must have the same set of columns with the same column names and column types. Parameters ---------- other : SFrame Another SFrame whose rows are appended to the current SFrame. Returns ------- out : SFrame The result SFrame from the append operation. Examples -------- >>> sf = graphlab.SFrame({'id': [4, 6, 8], 'val': ['D', 'F', 'H']}) >>> sf2 = graphlab.SFrame({'id': [1, 2, 3], 'val': ['A', 'B', 'C']}) >>> sf = sf.append(sf2) >>> sf +----+-----+ | id | val | +----+-----+ | 4 | D | | 6 | F | | 8 | H | | 1 | A | | 2 | B | | 3 | C | +----+-----+ [6 rows x 2 columns] """ _mt._get_metric_tracker().track('sframe.append') if type(other) is not SFrame: raise RuntimeError("SFrame append can only work with SFrame") left_empty = len(self.column_names()) == 0 right_empty = len(other.column_names()) == 0 if (left_empty and right_empty): return SFrame() if (left_empty or right_empty): non_empty_sframe = self if right_empty else other return non_empty_sframe my_column_names = self.column_names() my_column_types = self.column_types() other_column_names = other.column_names() if (len(my_column_names) != len(other_column_names)): raise RuntimeError("Two SFrames have to have the same number of columns") # check if the order of column name is the same column_name_order_match = True for i in range(len(my_column_names)): if other_column_names[i] != my_column_names[i]: column_name_order_match = False break; processed_other_frame = other if not column_name_order_match: # we allow name order of two sframes to be different, so we create a new sframe from # "other" sframe to make it has exactly the same shape processed_other_frame = SFrame() for i in range(len(my_column_names)): col_name = my_column_names[i] if(col_name not in other_column_names): raise RuntimeError("Column " + my_column_names[i] + " does not exist in second SFrame") other_column = other.select_column(col_name); processed_other_frame.add_column(other_column, col_name) # check column type if my_column_types[i] != other_column.dtype(): raise RuntimeError("Column " + my_column_names[i] + " type is not the same in two SFrames, one is " + str(my_column_types[i]) + ", the other is " + str(other_column.dtype())) with cython_context(): processed_other_frame.__materialize__() return SFrame(_proxy=self.__proxy__.append(processed_other_frame.__proxy__)) def groupby(self, key_columns, operations, *args): """ Perform a group on the key_columns followed by aggregations on the columns listed in operations. The operations parameter is a dictionary that indicates which aggregation operators to use and which columns to use them on. The available operators are SUM, MAX, MIN, COUNT, AVG, VAR, STDV, CONCAT, SELECT_ONE, ARGMIN, ARGMAX, and QUANTILE. For convenience, aggregators MEAN, STD, and VARIANCE are available as synonyms for AVG, STDV, and VAR. See :mod:`~graphlab.aggregate` for more detail on the aggregators. Parameters ---------- key_columns : string | list[string] Column(s) to group by. Key columns can be of any type other than dictionary. operations : dict, list Dictionary of columns and aggregation operations. Each key is a output column name and each value is an aggregator. This can also be a list of aggregators, in which case column names will be automatically assigned. *args All other remaining arguments will be interpreted in the same way as the operations argument. Returns ------- out_sf : SFrame A new SFrame, with a column for each groupby column and each aggregation operation. See Also -------- aggregate Examples -------- Suppose we have an SFrame with movie ratings by many users. >>> import graphlab.aggregate as agg >>> url = 'http://s3.amazonaws.com/gl-testdata/rating_data_example.csv' >>> sf = graphlab.SFrame.read_csv(url) >>> sf +---------+----------+--------+ | user_id | movie_id | rating | +---------+----------+--------+ | 25904 | 1663 | 3 | | 25907 | 1663 | 3 | | 25923 | 1663 | 3 | | 25924 | 1663 | 3 | | 25928 | 1663 | 2 | | 25933 | 1663 | 4 | | 25934 | 1663 | 4 | | 25935 | 1663 | 4 | | 25936 | 1663 | 5 | | 25937 | 1663 | 2 | | ... | ... | ... | +---------+----------+--------+ [10000 rows x 3 columns] Compute the number of occurrences of each user. >>> user_count = sf.groupby(key_columns='user_id', ... operations={'count': agg.COUNT()}) >>> user_count +---------+-------+ | user_id | count | +---------+-------+ | 62361 | 1 | | 30727 | 1 | | 40111 | 1 | | 50513 | 1 | | 35140 | 1 | | 42352 | 1 | | 29667 | 1 | | 46242 | 1 | | 58310 | 1 | | 64614 | 1 | | ... | ... | +---------+-------+ [9852 rows x 2 columns] Compute the mean and standard deviation of ratings per user. >>> user_rating_stats = sf.groupby(key_columns='user_id', ... operations={ ... 'mean_rating': agg.MEAN('rating'), ... 'std_rating': agg.STD('rating') ... }) >>> user_rating_stats +---------+-------------+------------+ | user_id | mean_rating | std_rating | +---------+-------------+------------+ | 62361 | 5.0 | 0.0 | | 30727 | 4.0 | 0.0 | | 40111 | 2.0 | 0.0 | | 50513 | 4.0 | 0.0 | | 35140 | 4.0 | 0.0 | | 42352 | 5.0 | 0.0 | | 29667 | 4.0 | 0.0 | | 46242 | 5.0 | 0.0 | | 58310 | 2.0 | 0.0 | | 64614 | 2.0 | 0.0 | | ... | ... | ... | +---------+-------------+------------+ [9852 rows x 3 columns] Compute the movie with the minimum rating per user. >>> chosen_movies = sf.groupby(key_columns='user_id', ... operations={ ... 'worst_movies': agg.ARGMIN('rating','movie_id') ... }) >>> chosen_movies +---------+-------------+ | user_id | worst_movies | +---------+-------------+ | 62361 | 1663 | | 30727 | 1663 | | 40111 | 1663 | | 50513 | 1663 | | 35140 | 1663 | | 42352 | 1663 | | 29667 | 1663 | | 46242 | 1663 | | 58310 | 1663 | | 64614 | 1663 | | ... | ... | +---------+-------------+ [9852 rows x 2 columns] Compute the movie with the max rating per user and also the movie with the maximum imdb-ranking per user. >>> sf['imdb-ranking'] = sf['rating'] * 10 >>> chosen_movies = sf.groupby(key_columns='user_id', ... operations={('max_rating_movie','max_imdb_ranking_movie'): agg.ARGMAX(('rating','imdb-ranking'),'movie_id')}) >>> chosen_movies +---------+------------------+------------------------+ | user_id | max_rating_movie | max_imdb_ranking_movie | +---------+------------------+------------------------+ | 62361 | 1663 | 16630 | | 30727 | 1663 | 16630 | | 40111 | 1663 | 16630 | | 50513 | 1663 | 16630 | | 35140 | 1663 | 16630 | | 42352 | 1663 | 16630 | | 29667 | 1663 | 16630 | | 46242 | 1663 | 16630 | | 58310 | 1663 | 16630 | | 64614 | 1663 | 16630 | | ... | ... | ... | +---------+------------------+------------------------+ [9852 rows x 3 columns] Compute the movie with the max rating per user. >>> chosen_movies = sf.groupby(key_columns='user_id', operations={'best_movies': agg.ARGMAX('rating','movie')}) Compute the movie with the max rating per user and also the movie with the maximum imdb-ranking per user. >>> chosen_movies = sf.groupby(key_columns='user_id', operations={('max_rating_movie','max_imdb_ranking_movie'): agg.ARGMAX(('rating','imdb-ranking'),'movie')}) Compute the count, mean, and standard deviation of ratings per (user, time), automatically assigning output column names. >>> sf['time'] = sf.apply(lambda x: (x['user_id'] + x['movie_id']) % 11 + 2000) >>> user_rating_stats = sf.groupby(['user_id', 'time'], ... [agg.COUNT(), ... agg.AVG('rating'), ... agg.STDV('rating')]) >>> user_rating_stats +------+---------+-------+---------------+----------------+ | time | user_id | Count | Avg of rating | Stdv of rating | +------+---------+-------+---------------+----------------+ | 2006 | 61285 | 1 | 4.0 | 0.0 | | 2000 | 36078 | 1 | 4.0 | 0.0 | | 2003 | 47158 | 1 | 3.0 | 0.0 | | 2007 | 34446 | 1 | 3.0 | 0.0 | | 2010 | 47990 | 1 | 3.0 | 0.0 | | 2003 | 42120 | 1 | 5.0 | 0.0 | | 2007 | 44940 | 1 | 4.0 | 0.0 | | 2008 | 58240 | 1 | 4.0 | 0.0 | | 2002 | 102 | 1 | 1.0 | 0.0 | | 2009 | 52708 | 1 | 3.0 | 0.0 | | ... | ... | ... | ... | ... | +------+---------+-------+---------------+----------------+ [10000 rows x 5 columns] The groupby function can take a variable length list of aggregation specifiers so if we want the count and the 0.25 and 0.75 quantiles of ratings: >>> user_rating_stats = sf.groupby(['user_id', 'time'], agg.COUNT(), ... {'rating_quantiles': agg.QUANTILE('rating',[0.25, 0.75])}) >>> user_rating_stats +------+---------+-------+------------------------+ | time | user_id | Count | rating_quantiles | +------+---------+-------+------------------------+ | 2006 | 61285 | 1 | array('d', [4.0, 4.0]) | | 2000 | 36078 | 1 | array('d', [4.0, 4.0]) | | 2003 | 47158 | 1 | array('d', [3.0, 3.0]) | | 2007 | 34446 | 1 | array('d', [3.0, 3.0]) | | 2010 | 47990 | 1 | array('d', [3.0, 3.0]) | | 2003 | 42120 | 1 | array('d', [5.0, 5.0]) | | 2007 | 44940 | 1 | array('d', [4.0, 4.0]) | | 2008 | 58240 | 1 | array('d', [4.0, 4.0]) | | 2002 | 102 | 1 | array('d', [1.0, 1.0]) | | 2009 | 52708 | 1 | array('d', [3.0, 3.0]) | | ... | ... | ... | ... | +------+---------+-------+------------------------+ [10000 rows x 4 columns] To put all items a user rated into one list value by their star rating: >>> user_rating_stats = sf.groupby(["user_id", "rating"], ... {"rated_movie_ids":agg.CONCAT("movie_id")}) >>> user_rating_stats +--------+---------+----------------------+ | rating | user_id | rated_movie_ids | +--------+---------+----------------------+ | 3 | 31434 | array('d', [1663.0]) | | 5 | 25944 | array('d', [1663.0]) | | 4 | 38827 | array('d', [1663.0]) | | 4 | 51437 | array('d', [1663.0]) | | 4 | 42549 | array('d', [1663.0]) | | 4 | 49532 | array('d', [1663.0]) | | 3 | 26124 | array('d', [1663.0]) | | 4 | 46336 | array('d', [1663.0]) | | 4 | 52133 | array('d', [1663.0]) | | 5 | 62361 | array('d', [1663.0]) | | ... | ... | ... | +--------+---------+----------------------+ [9952 rows x 3 columns] To put all items and rating of a given user together into a dictionary value: >>> user_rating_stats = sf.groupby("user_id", ... {"movie_rating":agg.CONCAT("movie_id", "rating")}) >>> user_rating_stats +---------+--------------+ | user_id | movie_rating | +---------+--------------+ | 62361 | {1663: 5} | | 30727 | {1663: 4} | | 40111 | {1663: 2} | | 50513 | {1663: 4} | | 35140 | {1663: 4} | | 42352 | {1663: 5} | | 29667 | {1663: 4} | | 46242 | {1663: 5} | | 58310 | {1663: 2} | | 64614 | {1663: 2} | | ... | ... | +---------+--------------+ [9852 rows x 2 columns] """ # some basic checking first # make sure key_columns is a list if isinstance(key_columns, str): key_columns = [key_columns] # check that every column is a string, and is a valid column name my_column_names = self.column_names() key_columns_array = [] for column in key_columns: if not isinstance(column, str): raise TypeError("Column name must be a string") if column not in my_column_names: raise KeyError("Column " + column + " does not exist in SFrame") if self[column].dtype() == dict: raise TypeError("Cannot group on a dictionary column.") key_columns_array.append(column) group_output_columns = [] group_columns = [] group_ops = [] all_ops = [operations] + list(args) for op_entry in all_ops: # if it is not a dict, nor a list, it is just a single aggregator # element (probably COUNT). wrap it in a list so we can reuse the # list processing code operation = op_entry if not(isinstance(operation, list) or isinstance(operation, dict)): operation = [operation] if isinstance(operation, dict): # now sweep the dict and add to group_columns and group_ops for key in operation: val = operation[key] if type(val) is tuple: (op, column) = val if (op == '__builtin__avg__' and self[column[0]].dtype() is array.array): op = '__builtin__vector__avg__' if (op == '__builtin__sum__' and self[column[0]].dtype() is array.array): op = '__builtin__vector__sum__' if (op == '__builtin__argmax__' or op == '__builtin__argmin__') and ((type(column[0]) is tuple) != (type(key) is tuple)): raise TypeError("Output column(s) and aggregate column(s) for aggregate operation should be either all tuple or all string.") if (op == '__builtin__argmax__' or op == '__builtin__argmin__') and type(column[0]) is tuple: for (col,output) in zip(column[0],key): group_columns = group_columns + [[col,column[1]]] group_ops = group_ops + [op] group_output_columns = group_output_columns + [output] else: group_columns = group_columns + [column] group_ops = group_ops + [op] group_output_columns = group_output_columns + [key] elif val == graphlab.aggregate.COUNT: group_output_columns = group_output_columns + [key] val = graphlab.aggregate.COUNT() (op, column) = val group_columns = group_columns + [column] group_ops = group_ops + [op] else: raise TypeError("Unexpected type in aggregator definition of output column: " + key) elif isinstance(operation, list): # we will be using automatically defined column names for val in operation: if type(val) is tuple: (op, column) = val if (op == '__builtin__avg__' and self[column[0]].dtype() is array.array): op = '__builtin__vector__avg__' if (op == '__builtin__sum__' and self[column[0]].dtype() is array.array): op = '__builtin__vector__sum__' if (op == '__builtin__argmax__' or op == '__builtin__argmin__') and type(column[0]) is tuple: for col in column[0]: group_columns = group_columns + [[col,column[1]]] group_ops = group_ops + [op] group_output_columns = group_output_columns + [""] else: group_columns = group_columns + [column] group_ops = group_ops + [op] group_output_columns = group_output_columns + [""] elif val == graphlab.aggregate.COUNT: group_output_columns = group_output_columns + [""] val = graphlab.aggregate.COUNT() (op, column) = val group_columns = group_columns + [column] group_ops = group_ops + [op] else: raise TypeError("Unexpected type in aggregator definition.") # let's validate group_columns and group_ops are valid for (cols, op) in zip(group_columns, group_ops): for col in cols: if not isinstance(col, str): raise TypeError("Column name must be a string") if not isinstance(op, str): raise TypeError("Operation type not recognized.") if op is not graphlab.aggregate.COUNT()[0]: for col in cols: if col not in my_column_names: raise KeyError("Column " + col + " does not exist in SFrame") _mt._get_metric_tracker().track('sframe.groupby', properties={'operator':op}) with cython_context(): return SFrame(_proxy=self.__proxy__.groupby_aggregate(key_columns_array, group_columns, group_output_columns, group_ops)) def join(self, right, on=None, how='inner'): """ Merge two SFrames. Merges the current (left) SFrame with the given (right) SFrame using a SQL-style equi-join operation by columns. Parameters ---------- right : SFrame The SFrame to join. on : None | str | list | dict, optional The column name(s) representing the set of join keys. Each row that has the same value in this set of columns will be merged together. * If 'None' is given, join will use all columns that have the same name as the set of join keys. * If a str is given, this is interpreted as a join using one column, where both SFrames have the same column name. * If a list is given, this is interpreted as a join using one or more column names, where each column name given exists in both SFrames. * If a dict is given, each dict key is taken as a column name in the left SFrame, and each dict value is taken as the column name in right SFrame that will be joined together. e.g. {'left_col_name':'right_col_name'}. how : {'left', 'right', 'outer', 'inner'}, optional The type of join to perform. 'inner' is default. * inner: Equivalent to a SQL inner join. Result consists of the rows from the two frames whose join key values match exactly, merged together into one SFrame. * left: Equivalent to a SQL left outer join. Result is the union between the result of an inner join and the rest of the rows from the left SFrame, merged with missing values. * right: Equivalent to a SQL right outer join. Result is the union between the result of an inner join and the rest of the rows from the right SFrame, merged with missing values. * outer: Equivalent to a SQL full outer join. Result is the union between the result of a left outer join and a right outer join. Returns ------- out : SFrame Examples -------- >>> animals = graphlab.SFrame({'id': [1, 2, 3, 4], ... 'name': ['dog', 'cat', 'sheep', 'cow']}) >>> sounds = graphlab.SFrame({'id': [1, 3, 4, 5], ... 'sound': ['woof', 'baa', 'moo', 'oink']}) >>> animals.join(sounds, how='inner') +----+-------+-------+ | id | name | sound | +----+-------+-------+ | 1 | dog | woof | | 3 | sheep | baa | | 4 | cow | moo | +----+-------+-------+ [3 rows x 3 columns] >>> animals.join(sounds, on='id', how='left') +----+-------+-------+ | id | name | sound | +----+-------+-------+ | 1 | dog | woof | | 3 | sheep | baa | | 4 | cow | moo | | 2 | cat | None | +----+-------+-------+ [4 rows x 3 columns] >>> animals.join(sounds, on=['id'], how='right') +----+-------+-------+ | id | name | sound | +----+-------+-------+ | 1 | dog | woof | | 3 | sheep | baa | | 4 | cow | moo | | 5 | None | oink | +----+-------+-------+ [4 rows x 3 columns] >>> animals.join(sounds, on={'id':'id'}, how='outer') +----+-------+-------+ | id | name | sound | +----+-------+-------+ | 1 | dog | woof | | 3 | sheep | baa | | 4 | cow | moo | | 5 | None | oink | | 2 | cat | None | +----+-------+-------+ [5 rows x 3 columns] """ _mt._get_metric_tracker().track('sframe.join', properties={'type':how}) available_join_types = ['left','right','outer','inner'] if not isinstance(right, SFrame): raise TypeError("Can only join two SFrames") if how not in available_join_types: raise ValueError("Invalid join type") join_keys = dict() if on is None: left_names = self.column_names() right_names = right.column_names() common_columns = [name for name in left_names if name in right_names] for name in common_columns: join_keys[name] = name elif type(on) is str: join_keys[on] = on elif type(on) is list: for name in on: if type(name) is not str: raise TypeError("Join keys must each be a str.") join_keys[name] = name elif type(on) is dict: join_keys = on else: raise TypeError("Must pass a str, list, or dict of join keys") with cython_context(): return SFrame(_proxy=self.__proxy__.join(right.__proxy__, how, join_keys)) def filter_by(self, values, column_name, exclude=False): """ Filter an SFrame by values inside an iterable object. Result is an SFrame that only includes (or excludes) the rows that have a column with the given ``column_name`` which holds one of the values in the given ``values`` :class:`~graphlab.SArray`. If ``values`` is not an SArray, we attempt to convert it to one before filtering. Parameters ---------- values : SArray | list | numpy.ndarray | pandas.Series | str The values to use to filter the SFrame. The resulting SFrame will only include rows that have one of these values in the given column. column_name : str The column of the SFrame to match with the given `values`. exclude : bool If True, the result SFrame will contain all rows EXCEPT those that have one of ``values`` in ``column_name``. Returns ------- out : SFrame The filtered SFrame. Examples -------- >>> sf = graphlab.SFrame({'id': [1, 2, 3, 4], ... 'animal_type': ['dog', 'cat', 'cow', 'horse'], ... 'name': ['bob', 'jim', 'jimbob', 'bobjim']}) >>> household_pets = ['cat', 'hamster', 'dog', 'fish', 'bird', 'snake'] >>> sf.filter_by(household_pets, 'animal_type') +-------------+----+------+ | animal_type | id | name | +-------------+----+------+ | dog | 1 | bob | | cat | 2 | jim | +-------------+----+------+ [2 rows x 3 columns] >>> sf.filter_by(household_pets, 'animal_type', exclude=True) +-------------+----+--------+ | animal_type | id | name | +-------------+----+--------+ | horse | 4 | bobjim | | cow | 3 | jimbob | +-------------+----+--------+ [2 rows x 3 columns] """ _mt._get_metric_tracker().track('sframe.filter_by') if type(column_name) is not str: raise TypeError("Must pass a str as column_name") if type(values) is not SArray: # If we were given a single element, try to put in list and convert # to SArray if not hasattr(values, '__iter__'): values = [values] values = SArray(values) value_sf = SFrame() value_sf.add_column(values, column_name) # Make sure the values list has unique values, or else join will not # filter. value_sf = value_sf.groupby(column_name, {}) existing_columns = self.column_names() if column_name not in existing_columns: raise KeyError("Column '" + column_name + "' not in SFrame.") existing_type = self.column_types()[self.column_names().index(column_name)] given_type = value_sf.column_types()[0] if given_type != existing_type: raise TypeError("Type of given values does not match type of column '" + column_name + "' in SFrame.") with cython_context(): if exclude: id_name = "id" # Make sure this name is unique so we know what to remove in # the result while id_name in existing_columns: id_name += "1" value_sf = value_sf.add_row_number(id_name) tmp = SFrame(_proxy=self.__proxy__.join(value_sf.__proxy__, 'left', {column_name:column_name})) ret_sf = tmp[tmp[id_name] == None] del ret_sf[id_name] return ret_sf else: return SFrame(_proxy=self.__proxy__.join(value_sf.__proxy__, 'inner', {column_name:column_name})) @_check_canvas_enabled def show(self, columns=None, view=None, x=None, y=None): """ show(columns=None, view=None, x=None, y=None) Visualize the SFrame with GraphLab Create :mod:`~graphlab.canvas`. This function starts Canvas if it is not already running. If the SFrame has already been plotted, this function will update the plot. Parameters ---------- columns : list of str, optional The columns of this SFrame to show in the SFrame view. In an interactive browser target of Canvas, the columns will be selectable and reorderable through the UI as well. If not specified, the SFrame view will use all columns of the SFrame. view : str, optional The name of the SFrame view to show. Can be one of: - None: Use the default (depends on which Canvas target is set). - 'Table': Show a scrollable, tabular view of the data in the SFrame. - 'Summary': Show a list of columns with some summary statistics and plots for each column. - 'Scatter Plot': Show a scatter plot of two numeric columns. - 'Heat Map': Show a heat map of two numeric columns. - 'Bar Chart': Show a bar chart of one numeric and one categorical column. - 'Line Chart': Show a line chart of one numeric and one categorical column. x : str, optional The column to use for the X axis in a Scatter Plot, Heat Map, Bar Chart, or Line Chart view. Must be the name of one of the columns in this SFrame. For Scatter Plot and Heat Map, the column must be numeric (int or float). If not set, defaults to the first available valid column. y : str, optional The column to use for the Y axis in a Scatter Plot, Heat Map, Bar Chart, or Line Chart view. Must be the name of one of the numeric columns in this SFrame. If not set, defaults to the second available numeric column. Returns ------- view : graphlab.canvas.view.View An object representing the GraphLab Canvas view. See Also -------- canvas Examples -------- Suppose 'sf' is an SFrame, we can view it in GraphLab Canvas using: >>> sf.show() To choose a column filter (applied to all SFrame views): >>> sf.show(columns=["Foo", "Bar"]) # use only columns 'Foo' and 'Bar' >>> sf.show(columns=sf.column_names()[3:7]) # use columns 3-7 To choose a specific view of the SFrame: >>> sf.show(view="Summary") >>> sf.show(view="Table") >>> sf.show(view="Bar Chart", x="col1", y="col2") >>> sf.show(view="Line Chart", x="col1", y="col2") >>> sf.show(view="Scatter Plot", x="col1", y="col2") >>> sf.show(view="Heat Map", x="col1", y="col2") """ import graphlab.canvas import graphlab.canvas.inspect import graphlab.canvas.views.sframe graphlab.canvas.inspect.find_vars(self) return graphlab.canvas.show(graphlab.canvas.views.sframe.SFrameView(self, params={ 'view': view, 'columns': columns, 'x': x, 'y': y })) def pack_columns(self, columns=None, column_prefix=None, dtype=list, fill_na=None, remove_prefix=True, new_column_name=None): """ Pack two or more columns of the current SFrame into one single column.The result is a new SFrame with the unaffected columns from the original SFrame plus the newly created column. The list of columns that are packed is chosen through either the ``columns`` or ``column_prefix`` parameter. Only one of the parameters is allowed to be provided. ``columns`` explicitly specifies the list of columns to pack, while ``column_prefix`` specifies that all columns that have the given prefix are to be packed. The type of the resulting column is decided by the ``dtype`` parameter. Allowed values for ``dtype`` are dict, array.array and list: - *dict*: pack to a dictionary SArray where column name becomes dictionary key and column value becomes dictionary value - *array.array*: pack all values from the packing columns into an array - *list*: pack all values from the packing columns into a list. Parameters ---------- columns : list[str], optional A list of column names to be packed. There needs to have at least two columns to pack. If omitted and `column_prefix` is not specified, all columns from current SFrame are packed. This parameter is mutually exclusive with the `column_prefix` parameter. column_prefix : str, optional Pack all columns with the given `column_prefix`. This parameter is mutually exclusive with the `columns` parameter. dtype : dict | array.array | list, optional The resulting packed column type. If not provided, dtype is list. fill_na : value, optional Value to fill into packed column if missing value is encountered. If packing to dictionary, `fill_na` is only applicable to dictionary values; missing keys are not replaced. remove_prefix : bool, optional If True and `column_prefix` is specified, the dictionary key will be constructed by removing the prefix from the column name. This option is only applicable when packing to dict type. new_column_name : str, optional Packed column name. If not given and `column_prefix` is given, then the prefix will be used as the new column name, otherwise name is generated automatically. Returns ------- out : SFrame An SFrame that contains columns that are not packed, plus the newly packed column. See Also -------- unpack Notes ----- - There must be at least two columns to pack. - If packing to dictionary, missing key is always dropped. Missing values are dropped if fill_na is not provided, otherwise, missing value is replaced by 'fill_na'. If packing to list or array, missing values will be kept. If 'fill_na' is provided, the missing value is replaced with 'fill_na' value. Examples -------- Suppose 'sf' is an an SFrame that maintains business category information: >>> sf = graphlab.SFrame({'business': range(1, 5), ... 'category.retail': [1, None, 1, None], ... 'category.food': [1, 1, None, None], ... 'category.service': [None, 1, 1, None], ... 'category.shop': [1, 1, None, 1]}) >>> sf +----------+-----------------+---------------+------------------+---------------+ | business | category.retail | category.food | category.service | category.shop | +----------+-----------------+---------------+------------------+---------------+ | 1 | 1 | 1 | None | 1 | | 2 | None | 1 | 1 | 1 | | 3 | 1 | None | 1 | None | | 4 | None | 1 | None | 1 | +----------+-----------------+---------------+------------------+---------------+ [4 rows x 5 columns] To pack all category columns into a list: >>> sf.pack_columns(column_prefix='category') +----------+--------------------+ | business | X2 | +----------+--------------------+ | 1 | [1, 1, None, 1] | | 2 | [None, 1, 1, 1] | | 3 | [1, None, 1, None] | | 4 | [None, 1, None, 1] | +----------+--------------------+ [4 rows x 2 columns] To pack all category columns into a dictionary, with new column name: >>> sf.pack_columns(column_prefix='category', dtype=dict, ... new_column_name='category') +----------+--------------------------------+ | business | category | +----------+--------------------------------+ | 1 | {'food': 1, 'shop': 1, 're ... | | 2 | {'food': 1, 'shop': 1, 'se ... | | 3 | {'retail': 1, 'service': 1} | | 4 | {'food': 1, 'shop': 1} | +----------+--------------------------------+ [4 rows x 2 columns] To keep column prefix in the resulting dict key: >>> sf.pack_columns(column_prefix='category', dtype=dict, remove_prefix=False) +----------+--------------------------------+ | business | X2 | +----------+--------------------------------+ | 1 | {'category.retail': 1, 'ca ... | | 2 | {'category.food': 1, 'cate ... | | 3 | {'category.retail': 1, 'ca ... | | 4 | {'category.food': 1, 'cate ... | +----------+--------------------------------+ [4 rows x 2 columns] To explicitly pack a set of columns: >>> sf.pack_columns(columns = ['business', 'category.retail', 'category.food', 'category.service', 'category.shop']) +-----------------------+ | X1 | +-----------------------+ | [1, 1, 1, None, 1] | | [2, None, 1, 1, 1] | | [3, 1, None, 1, None] | | [4, None, 1, None, 1] | +-----------------------+ [4 rows x 1 columns] To pack all columns with name starting with 'category' into an array type, and with missing value replaced with 0: >>> sf.pack_columns(column_prefix="category", dtype=array.array, ... fill_na=0) +----------+--------------------------------+ | business | X2 | +----------+--------------------------------+ | 1 | array('d', [1.0, 1.0, 0.0, ... | | 2 | array('d', [0.0, 1.0, 1.0, ... | | 3 | array('d', [1.0, 0.0, 1.0, ... | | 4 | array('d', [0.0, 1.0, 0.0, ... | +----------+--------------------------------+ [4 rows x 2 columns] """ if columns != None and column_prefix != None: raise ValueError("'columns' and 'column_prefix' parameter cannot be given at the same time.") if new_column_name == None and column_prefix != None: new_column_name = column_prefix if column_prefix != None: if type(column_prefix) != str: raise TypeError("'column_prefix' must be a string") columns = [name for name in self.column_names() if name.startswith(column_prefix)] if len(columns) == 0: raise ValueError("There is no column starts with prefix '" + column_prefix + "'") elif columns == None: columns = self.column_names() else: if not hasattr(columns, '__iter__'): raise TypeError("columns must be an iterable type") column_names = set(self.column_names()) for column in columns: if (column not in column_names): raise ValueError("Current SFrame has no column called '" + str(column) + "'.") # check duplicate names if len(set(columns)) != len(columns): raise ValueError("There is duplicate column names in columns parameter") if (len(columns) <= 1): raise ValueError("Please provide at least two columns to pack") if (dtype not in (dict, list, array.array)): raise ValueError("Resulting dtype has to be one of dict/array.array/list type") # fill_na value for array needs to be numeric if dtype == array.array: if (fill_na != None) and (type(fill_na) not in (int, float)): raise ValueError("fill_na value for array needs to be numeric type") # all columns have to be numeric type for column in columns: if self[column].dtype() not in (int, float): raise TypeError("Column '" + column + "' type is not numeric, cannot pack into array type") # generate dict key names if pack to dictionary # we try to be smart here # if all column names are like: a.b, a.c, a.d,... # we then use "b", "c", "d", etc as the dictionary key during packing if (dtype == dict) and (column_prefix != None) and (remove_prefix == True): size_prefix = len(column_prefix) first_char = set([c[size_prefix:size_prefix+1] for c in columns]) if ((len(first_char) == 1) and first_char.pop() in ['.','-','_']): dict_keys = [name[size_prefix+1:] for name in columns] else: dict_keys = [name[size_prefix:] for name in columns] else: dict_keys = columns rest_columns = [name for name in self.column_names() if name not in columns] if new_column_name != None: if type(new_column_name) != str: raise TypeError("'new_column_name' has to be a string") if new_column_name in rest_columns: raise KeyError("Current SFrame already contains a column name " + new_column_name) else: new_column_name = "" _mt._get_metric_tracker().track('sframe.pack_columns') ret_sa = None with cython_context(): ret_sa = SArray(_proxy=self.__proxy__.pack_columns(columns, dict_keys, dtype, fill_na)) new_sf = self.select_columns(rest_columns) new_sf.add_column(ret_sa, new_column_name) return new_sf def split_datetime(self, expand_column, column_name_prefix=None, limit=None, tzone=False): """ Splits a datetime column of SFrame to multiple columns, with each value in a separate column. Returns a new SFrame with the expanded column replaced with a list of new columns. The expanded column must be of datetime type. For more details regarding name generation and other, refer to :py:func:`graphlab.SArray.split_datetim()` Parameters ---------- expand_column : str Name of the unpacked column. column_name_prefix : str, optional If provided, expanded column names would start with the given prefix. If not provided, the default value is the name of the expanded column. limit : list[str], optional Limits the set of datetime elements to expand. Elements are 'year','month','day','hour','minute', and 'second'. tzone : bool, optional A boolean parameter that determines whether to show the timezone column or not. Defaults to False. Returns ------- out : SFrame A new SFrame that contains rest of columns from original SFrame with the given column replaced with a collection of expanded columns. Examples --------- >>> sf Columns: id int submission datetime Rows: 2 Data: +----+-------------------------------------------------+ | id | submission | +----+-------------------------------------------------+ | 1 | datetime(2011, 1, 21, 7, 17, 21, tzinfo=GMT(+1))| | 2 | datetime(2011, 1, 21, 5, 43, 21, tzinfo=GMT(+1))| +----+-------------------------------------------------+ >>> sf.split_datetime('submission',limit=['hour','minute']) Columns: id int submission.hour int submission.minute int Rows: 2 Data: +----+-----------------+-------------------+ | id | submission.hour | submission.minute | +----+-----------------+-------------------+ | 1 | 7 | 17 | | 2 | 5 | 43 | +----+-----------------+-------------------+ """ if expand_column not in self.column_names(): raise KeyError("column '" + expand_column + "' does not exist in current SFrame") if column_name_prefix == None: column_name_prefix = expand_column new_sf = self[expand_column].split_datetime(column_name_prefix, limit, tzone) # construct return SFrame, check if there is conflict rest_columns = [name for name in self.column_names() if name != expand_column] new_names = new_sf.column_names() while set(new_names).intersection(rest_columns): new_names = [name + ".1" for name in new_names] new_sf.rename(dict(zip(new_sf.column_names(), new_names))) _mt._get_metric_tracker().track('sframe.split_datetime') ret_sf = self.select_columns(rest_columns) ret_sf.add_columns(new_sf) return ret_sf def unpack(self, unpack_column, column_name_prefix=None, column_types=None, na_value=None, limit=None): """ Expand one column of this SFrame to multiple columns with each value in a separate column. Returns a new SFrame with the unpacked column replaced with a list of new columns. The column must be of list/array/dict type. For more details regarding name generation, missing value handling and other, refer to the SArray version of :py:func:`~graphlab.SArray.unpack()`. Parameters ---------- unpack_column : str Name of the unpacked column column_name_prefix : str, optional If provided, unpacked column names would start with the given prefix. If not provided, default value is the name of the unpacked column. column_types : [type], optional Column types for the unpacked columns. If not provided, column types are automatically inferred from first 100 rows. For array type, default column types are float. If provided, column_types also restricts how many columns to unpack. na_value : flexible_type, optional If provided, convert all values that are equal to "na_value" to missing value (None). limit : list[str] | list[int], optional Control unpacking only a subset of list/array/dict value. For dictionary SArray, `limit` is a list of dictionary keys to restrict. For list/array SArray, `limit` is a list of integers that are indexes into the list/array value. Returns ------- out : SFrame A new SFrame that contains rest of columns from original SFrame with the given column replaced with a collection of unpacked columns. See Also -------- pack_columns, SArray.unpack Examples --------- >>> sf = graphlab.SFrame({'id': [1,2,3], ... 'wc': [{'a': 1}, {'b': 2}, {'a': 1, 'b': 2}]}) +----+------------------+ | id | wc | +----+------------------+ | 1 | {'a': 1} | | 2 | {'b': 2} | | 3 | {'a': 1, 'b': 2} | +----+------------------+ [3 rows x 2 columns] >>> sf.unpack('wc') +----+------+------+ | id | wc.a | wc.b | +----+------+------+ | 1 | 1 | None | | 2 | None | 2 | | 3 | 1 | 2 | +----+------+------+ [3 rows x 3 columns] To not have prefix in the generated column name: >>> sf.unpack('wc', column_name_prefix="") +----+------+------+ | id | a | b | +----+------+------+ | 1 | 1 | None | | 2 | None | 2 | | 3 | 1 | 2 | +----+------+------+ [3 rows x 3 columns] To limit subset of keys to unpack: >>> sf.unpack('wc', limit=['b']) +----+------+ | id | wc.b | +----+------+ | 1 | None | | 2 | 2 | | 3 | 2 | +----+------+ [3 rows x 3 columns] To unpack an array column: >>> sf = graphlab.SFrame({'id': [1,2,3], ... 'friends': [array.array('d', [1.0, 2.0, 3.0]), ... array.array('d', [2.0, 3.0, 4.0]), ... array.array('d', [3.0, 4.0, 5.0])]}) >>> sf +----+-----------------------------+ | id | friends | +----+-----------------------------+ | 1 | array('d', [1.0, 2.0, 3.0]) | | 2 | array('d', [2.0, 3.0, 4.0]) | | 3 | array('d', [3.0, 4.0, 5.0]) | +----+-----------------------------+ [3 rows x 2 columns] >>> sf.unpack('friends') +----+-----------+-----------+-----------+ | id | friends.0 | friends.1 | friends.2 | +----+-----------+-----------+-----------+ | 1 | 1.0 | 2.0 | 3.0 | | 2 | 2.0 | 3.0 | 4.0 | | 3 | 3.0 | 4.0 | 5.0 | +----+-----------+-----------+-----------+ [3 rows x 4 columns] """ if unpack_column not in self.column_names(): raise KeyError("column '" + unpack_column + "' does not exist in current SFrame") if column_name_prefix == None: column_name_prefix = unpack_column new_sf = self[unpack_column].unpack(column_name_prefix, column_types, na_value, limit) # construct return SFrame, check if there is conflict rest_columns = [name for name in self.column_names() if name != unpack_column] new_names = new_sf.column_names() while set(new_names).intersection(rest_columns): new_names = [name + ".1" for name in new_names] new_sf.rename(dict(zip(new_sf.column_names(), new_names))) _mt._get_metric_tracker().track('sframe.unpack') ret_sf = self.select_columns(rest_columns) ret_sf.add_columns(new_sf) return ret_sf def stack(self, column_name, new_column_name=None, drop_na=False): """ Convert a "wide" column of an SFrame to one or two "tall" columns by stacking all values. The stack works only for columns of dict, list, or array type. If the column is dict type, two new columns are created as a result of stacking: one column holds the key and another column holds the value. The rest of the columns are repeated for each key/value pair. If the column is array or list type, one new column is created as a result of stacking. With each row holds one element of the array or list value, and the rest columns from the same original row repeated. The new SFrame includes the newly created column and all columns other than the one that is stacked. Parameters -------------- column_name : str The column to stack. This column must be of dict/list/array type new_column_name : str | list of str, optional The new column name(s). If original column is list/array type, new_column_name must a string. If original column is dict type, new_column_name must be a list of two strings. If not given, column names are generated automatically. drop_na : boolean, optional If True, missing values and empty list/array/dict are all dropped from the resulting column(s). If False, missing values are maintained in stacked column(s). Returns ------- out : SFrame A new SFrame that contains newly stacked column(s) plus columns in original SFrame other than the stacked column. See Also -------- unstack Examples --------- Suppose 'sf' is an SFrame that contains a column of dict type: >>> sf = graphlab.SFrame({'topic':[1,2,3,4], ... 'words': [{'a':3, 'cat':2}, ... {'a':1, 'the':2}, ... {'the':1, 'dog':3}, ... {}] ... }) +-------+----------------------+ | topic | words | +-------+----------------------+ | 1 | {'a': 3, 'cat': 2} | | 2 | {'a': 1, 'the': 2} | | 3 | {'the': 1, 'dog': 3} | | 4 | {} | +-------+----------------------+ [4 rows x 2 columns] Stack would stack all keys in one column and all values in another column: >>> sf.stack('words', new_column_name=['word', 'count']) +-------+------+-------+ | topic | word | count | +-------+------+-------+ | 1 | a | 3 | | 1 | cat | 2 | | 2 | a | 1 | | 2 | the | 2 | | 3 | the | 1 | | 3 | dog | 3 | | 4 | None | None | +-------+------+-------+ [7 rows x 3 columns] Observe that since topic 4 had no words, an empty row is inserted. To drop that row, set dropna=True in the parameters to stack. Suppose 'sf' is an SFrame that contains a user and his/her friends, where 'friends' columns is an array type. Stack on 'friends' column would create a user/friend list for each user/friend pair: >>> sf = graphlab.SFrame({'topic':[1,2,3], ... 'friends':[[2,3,4], [5,6], ... [4,5,10,None]] ... }) >>> sf +-------+------------------+ | topic | friends | +-------+------------------+ | 1 | [2, 3, 4] | | 2 | [5, 6] | | 3 | [4, 5, 10, None] | +----- -+------------------+ [3 rows x 2 columns] >>> sf.stack('friends', new_column_name='friend') +------+--------+ | user | friend | +------+--------+ | 1 | 2 | | 1 | 3 | | 1 | 4 | | 2 | 5 | | 2 | 6 | | 3 | 4 | | 3 | 5 | | 3 | 10 | | 3 | None | +------+--------+ [9 rows x 2 columns] """ # validate column_name column_name = str(column_name) if column_name not in self.column_names(): raise ValueError("Cannot find column '" + str(column_name) + "' in the SFrame.") stack_column_type = self[column_name].dtype() if (stack_column_type not in [dict, array.array, list]): raise TypeError("Stack is only supported for column of dict/list/array type.") if (new_column_name != None): if stack_column_type == dict: if (type(new_column_name) is not list): raise TypeError("new_column_name has to be a list to stack dict type") elif (len(new_column_name) != 2): raise TypeError("new_column_name must have length of two") else: if (type(new_column_name) != str): raise TypeError("new_column_name has to be a str") new_column_name = [new_column_name] # check if the new column name conflicts with existing ones for name in new_column_name: if (name in self.column_names()) and (name != column_name): raise ValueError("Column with name '" + name + "' already exists, pick a new column name") else: if stack_column_type == dict: new_column_name = ["",""] else: new_column_name = [""] # infer column types head_row = SArray(self[column_name].head(100)).dropna() if (len(head_row) == 0): raise ValueError("Cannot infer column type because there is not enough rows to infer value") if stack_column_type == dict: # infer key/value type keys = []; values = [] for row in head_row: for val in row: keys.append(val) if val != None: values.append(row[val]) new_column_type = [ infer_type_of_list(keys), infer_type_of_list(values) ] else: values = [v for v in itertools.chain.from_iterable(head_row)] new_column_type = [infer_type_of_list(values)] _mt._get_metric_tracker().track('sframe.stack') with cython_context(): return SFrame(_proxy=self.__proxy__.stack(column_name, new_column_name, new_column_type, drop_na)) def unstack(self, column, new_column_name=None): """ Concatenate values from one or two columns into one column, grouping by all other columns. The resulting column could be of type list, array or dictionary. If ``column`` is a numeric column, the result will be of array.array type. If ``column`` is a non-numeric column, the new column will be of list type. If ``column`` is a list of two columns, the new column will be of dict type where the keys are taken from the first column in the list. Parameters ---------- column : str | [str, str] The column(s) that is(are) to be concatenated. If str, then collapsed column type is either array or list. If [str, str], then collapsed column type is dict new_column_name : str, optional New column name. If not given, a name is generated automatically. Returns ------- out : SFrame A new SFrame containing the grouped columns as well as the new column. See Also -------- stack : The inverse of unstack. groupby : ``unstack`` is a special version of ``groupby`` that uses the :mod:`~graphlab.aggregate.CONCAT` aggregator Notes ----- - There is no guarantee the resulting SFrame maintains the same order as the original SFrame. - Missing values are maintained during unstack. - When unstacking into a dictionary, if there is more than one instance of a given key for a particular group, an arbitrary value is selected. Examples -------- >>> sf = graphlab.SFrame({'count':[4, 2, 1, 1, 2, None], ... 'topic':['cat', 'cat', 'dog', 'elephant', 'elephant', 'fish'], ... 'word':['a', 'c', 'c', 'a', 'b', None]}) >>> sf.unstack(column=['word', 'count'], new_column_name='words') +----------+------------------+ | topic | words | +----------+------------------+ | elephant | {'a': 1, 'b': 2} | | dog | {'c': 1} | | cat | {'a': 4, 'c': 2} | | fish | None | +----------+------------------+ [4 rows x 2 columns] >>> sf = graphlab.SFrame({'friend': [2, 3, 4, 5, 6, 4, 5, 2, 3], ... 'user': [1, 1, 1, 2, 2, 2, 3, 4, 4]}) >>> sf.unstack('friend', new_column_name='friends') +------+-----------------------------+ | user | friends | +------+-----------------------------+ | 3 | array('d', [5.0]) | | 1 | array('d', [2.0, 4.0, 3.0]) | | 2 | array('d', [5.0, 6.0, 4.0]) | | 4 | array('d', [2.0, 3.0]) | +------+-----------------------------+ [4 rows x 2 columns] """ if (type(column) != str and len(column) != 2): raise TypeError("'column' parameter has to be either a string or a list of two strings.") _mt._get_metric_tracker().track('sframe.unstack') with cython_context(): if type(column) == str: key_columns = [i for i in self.column_names() if i != column] if new_column_name != None: return self.groupby(key_columns, {new_column_name : graphlab.aggregate.CONCAT(column)}) else: return self.groupby(key_columns, graphlab.aggregate.CONCAT(column)) elif len(column) == 2: key_columns = [i for i in self.column_names() if i not in column] if new_column_name != None: return self.groupby(key_columns, {new_column_name:graphlab.aggregate.CONCAT(column[0], column[1])}) else: return self.groupby(key_columns, graphlab.aggregate.CONCAT(column[0], column[1])) def unique(self): """ Remove duplicate rows of the SFrame. Will not necessarily preserve the order of the given SFrame in the new SFrame. Returns ------- out : SFrame A new SFrame that contains the unique rows of the current SFrame. Raises ------ TypeError If any column in the SFrame is a dictionary type. See Also -------- SArray.unique Examples -------- >>> sf = graphlab.SFrame({'id':[1,2,3,3,4], 'value':[1,2,3,3,4]}) >>> sf +----+-------+ | id | value | +----+-------+ | 1 | 1 | | 2 | 2 | | 3 | 3 | | 3 | 3 | | 4 | 4 | +----+-------+ [5 rows x 2 columns] >>> sf.unique() +----+-------+ | id | value | +----+-------+ | 2 | 2 | | 4 | 4 | | 3 | 3 | | 1 | 1 | +----+-------+ [4 rows x 2 columns] """ return self.groupby(self.column_names(),{}) def sort(self, sort_columns, ascending=True): """ Sort current SFrame by the given columns, using the given sort order. Only columns that are type of str, int and float can be sorted. Parameters ---------- sort_columns : str | list of str | list of (str, bool) pairs Names of columns to be sorted. The result will be sorted first by first column, followed by second column, and so on. All columns will be sorted in the same order as governed by the `ascending` parameter. To control the sort ordering for each column individually, `sort_columns` must be a list of (str, bool) pairs. Given this case, the first value is the column name and the second value is a boolean indicating whether the sort order is ascending. ascending : bool, optional Sort all columns in the given order. Returns ------- out : SFrame A new SFrame that is sorted according to given sort criteria See Also -------- topk Examples -------- Suppose 'sf' is an sframe that has three columns 'a', 'b', 'c'. To sort by column 'a', ascending >>> sf = graphlab.SFrame({'a':[1,3,2,1], ... 'b':['a','c','b','b'], ... 'c':['x','y','z','y']}) >>> sf +---+---+---+ | a | b | c | +---+---+---+ | 1 | a | x | | 3 | c | y | | 2 | b | z | | 1 | b | y | +---+---+---+ [4 rows x 3 columns] >>> sf.sort('a') +---+---+---+ | a | b | c | +---+---+---+ | 1 | a | x | | 1 | b | y | | 2 | b | z | | 3 | c | y | +---+---+---+ [4 rows x 3 columns] To sort by column 'a', descending >>> sf.sort('a', ascending = False) +---+---+---+ | a | b | c | +---+---+---+ | 3 | c | y | | 2 | b | z | | 1 | a | x | | 1 | b | y | +---+---+---+ [4 rows x 3 columns] To sort by column 'a' and 'b', all ascending >>> sf.sort(['a', 'b']) +---+---+---+ | a | b | c | +---+---+---+ | 1 | a | x | | 1 | b | y | | 2 | b | z | | 3 | c | y | +---+---+---+ [4 rows x 3 columns] To sort by column 'a' ascending, and then by column 'c' descending >>> sf.sort([('a', True), ('c', False)]) +---+---+---+ | a | b | c | +---+---+---+ | 1 | b | y | | 1 | a | x | | 2 | b | z | | 3 | c | y | +---+---+---+ [4 rows x 3 columns] """ sort_column_names = [] sort_column_orders = [] # validate sort_columns if (type(sort_columns) == str): sort_column_names = [sort_columns] elif (type(sort_columns) == list): if (len(sort_columns) == 0): raise ValueError("Please provide at least one column to sort") first_param_types = set([type(i) for i in sort_columns]) if (len(first_param_types) != 1): raise ValueError("sort_columns element are not of the same type") first_param_type = first_param_types.pop() if (first_param_type == tuple): sort_column_names = [i[0] for i in sort_columns] sort_column_orders = [i[1] for i in sort_columns] elif(first_param_type == str): sort_column_names = sort_columns else: raise TypeError("sort_columns type is not supported") else: raise TypeError("sort_columns type is not correct. Supported types are str, list of str or list of (str,bool) pair.") # use the second parameter if the sort order is not given if (len(sort_column_orders) == 0): sort_column_orders = [ascending for i in sort_column_names] # make sure all column exists my_column_names = set(self.column_names()) for column in sort_column_names: if (type(column) != str): raise TypeError("Only string parameter can be passed in as column names") if (column not in my_column_names): raise ValueError("SFrame has no column named: '" + str(column) + "'") if (self[column].dtype() not in (str, int, float,datetime.datetime)): raise TypeError("Only columns of type (str, int, float) can be sorted") _mt._get_metric_tracker().track('sframe.sort') with cython_context(): return SFrame(_proxy=self.__proxy__.sort(sort_column_names, sort_column_orders)) def dropna(self, columns=None, how='any'): """ Remove missing values from an SFrame. A missing value is either ``None`` or ``NaN``. If ``how`` is 'any', a row will be removed if any of the columns in the ``columns`` parameter contains at least one missing value. If ``how`` is 'all', a row will be removed if all of the columns in the ``columns`` parameter are missing values. If the ``columns`` parameter is not specified, the default is to consider all columns when searching for missing values. Parameters ---------- columns : list or str, optional The columns to use when looking for missing values. By default, all columns are used. how : {'any', 'all'}, optional Specifies whether a row should be dropped if at least one column has missing values, or if all columns have missing values. 'any' is default. Returns ------- out : SFrame SFrame with missing values removed (according to the given rules). See Also -------- dropna_split : Drops missing rows from the SFrame and returns them. Examples -------- Drop all missing values. >>> sf = graphlab.SFrame({'a': [1, None, None], 'b': ['a', 'b', None]}) >>> sf.dropna() +---+---+ | a | b | +---+---+ | 1 | a | +---+---+ [1 rows x 2 columns] Drop rows where every value is missing. >>> sf.dropna(any="all") +------+---+ | a | b | +------+---+ | 1 | a | | None | b | +------+---+ [2 rows x 2 columns] Drop rows where column 'a' has a missing value. >>> sf.dropna('a', any="all") +---+---+ | a | b | +---+---+ | 1 | a | +---+---+ [1 rows x 2 columns] """ _mt._get_metric_tracker().track('sframe.dropna') # If the user gives me an empty list (the indicator to use all columns) # NA values being dropped would not be the expected behavior. This # is a NOOP, so let's not bother the server if type(columns) is list and len(columns) == 0: return SFrame(_proxy=self.__proxy__) (columns, all_behavior) = self.__dropna_errchk(columns, how) with cython_context(): return SFrame(_proxy=self.__proxy__.drop_missing_values(columns, all_behavior, False)) def dropna_split(self, columns=None, how='any'): """ Split rows with missing values from this SFrame. This function has the same functionality as :py:func:`~graphlab.SFrame.dropna`, but returns a tuple of two SFrames. The first item is the expected output from :py:func:`~graphlab.SFrame.dropna`, and the second item contains all the rows filtered out by the `dropna` algorithm. Parameters ---------- columns : list or str, optional The columns to use when looking for missing values. By default, all columns are used. how : {'any', 'all'}, optional Specifies whether a row should be dropped if at least one column has missing values, or if all columns have missing values. 'any' is default. Returns ------- out : (SFrame, SFrame) (SFrame with missing values removed, SFrame with the removed missing values) See Also -------- dropna Examples -------- >>> sf = graphlab.SFrame({'a': [1, None, None], 'b': ['a', 'b', None]}) >>> good, bad = sf.dropna_split() >>> good +---+---+ | a | b | +---+---+ | 1 | a | +---+---+ [1 rows x 2 columns] >>> bad +------+------+ | a | b | +------+------+ | None | b | | None | None | +------+------+ [2 rows x 2 columns] """ _mt._get_metric_tracker().track('sframe.dropna_split') # If the user gives me an empty list (the indicator to use all columns) # NA values being dropped would not be the expected behavior. This # is a NOOP, so let's not bother the server if type(columns) is list and len(columns) == 0: return (SFrame(_proxy=self.__proxy__), SFrame()) (columns, all_behavior) = self.__dropna_errchk(columns, how) sframe_tuple = self.__proxy__.drop_missing_values(columns, all_behavior, True) if len(sframe_tuple) != 2: raise RuntimeError("Did not return two SFrames!") with cython_context(): return (SFrame(_proxy=sframe_tuple[0]), SFrame(_proxy=sframe_tuple[1])) def __dropna_errchk(self, columns, how): if columns is None: # Default behavior is to consider every column, specified to # the server by an empty list (to avoid sending all the column # in this case, since it is the most common) columns = list() elif type(columns) is str: columns = [columns] elif type(columns) is not list: raise TypeError("Must give columns as a list, str, or 'None'") else: # Verify that we are only passing strings in our list list_types = set([type(i) for i in columns]) if (str not in list_types) or (len(list_types) > 1): raise TypeError("All columns must be of 'str' type") if how not in ['any','all']: raise ValueError("Must specify 'any' or 'all'") if how == 'all': all_behavior = True else: all_behavior = False return (columns, all_behavior) def fillna(self, column, value): """ Fill all missing values with a given value in a given column. If the ``value`` is not the same type as the values in ``column``, this method attempts to convert the value to the original column's type. If this fails, an error is raised. Parameters ---------- column : str The name of the column to modify. value : type convertible to SArray's type The value used to replace all missing values. Returns ------- out : SFrame A new SFrame with the specified value in place of missing values. See Also -------- dropna Examples -------- >>> sf = graphlab.SFrame({'a':[1, None, None], ... 'b':['13.1', '17.2', None]}) >>> sf = sf.fillna('a', 0) >>> sf +---+------+ | a | b | +---+------+ | 1 | 13.1 | | 0 | 17.2 | | 0 | None | +---+------+ [3 rows x 2 columns] """ # Normal error checking if type(column) is not str: raise TypeError("Must give column name as a str") ret = self[self.column_names()] ret[column] = ret[column].fillna(value) return ret def add_row_number(self, column_name='id', start=0): """ Returns a new SFrame with a new column that numbers each row sequentially. By default the count starts at 0, but this can be changed to a positive or negative number. The new column will be named with the given column name. An error will be raised if the given column name already exists in the SFrame. Parameters ---------- column_name : str, optional The name of the new column that will hold the row numbers. start : int, optional The number used to start the row number count. Returns ------- out : SFrame The new SFrame with a column name Notes ----- The range of numbers is constrained by a signed 64-bit integer, so beware of overflow if you think the results in the row number column will be greater than 9 quintillion. Examples -------- >>> sf = graphlab.SFrame({'a': [1, None, None], 'b': ['a', 'b', None]}) >>> sf.add_row_number() +----+------+------+ | id | a | b | +----+------+------+ | 0 | 1 | a | | 1 | None | b | | 2 | None | None | +----+------+------+ [3 rows x 3 columns] """ _mt._get_metric_tracker().track('sframe.add_row_number') if type(column_name) is not str: raise TypeError("Must give column_name as strs") if type(start) is not int: raise TypeError("Must give start as int") if column_name in self.column_names(): raise RuntimeError("Column '" + column_name + "' already exists in the current SFrame") the_col = _create_sequential_sarray(self.num_rows(), start) # Make sure the row number column is the first column new_sf = SFrame() new_sf.add_column(the_col, column_name) new_sf.add_columns(self) return new_sf @property def shape(self): """ The shape of the SFrame, in a tuple. The first entry is the number of rows, the second is the number of columns. Examples -------- >>> sf = graphlab.SFrame({'id':[1,2,3], 'val':['A','B','C']}) >>> sf.shape (3, 2) """ return (self.num_rows(), self.num_cols()) @property def __proxy__(self): return self._proxy @__proxy__.setter def __proxy__(self, value): assert type(value) is UnitySFrameProxy self._proxy = value
agpl-3.0
vrv/tensorflow
tensorflow/python/kernel_tests/distributions/categorical_test.py
12
11556
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for Categorical distribution.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import math_ops from tensorflow.python.ops import nn_ops from tensorflow.python.ops import random_ops from tensorflow.python.ops.distributions import categorical from tensorflow.python.ops.distributions import kullback_leibler from tensorflow.python.platform import test def make_categorical(batch_shape, num_classes, dtype=dtypes.int32): logits = random_ops.random_uniform( list(batch_shape) + [num_classes], -10, 10, dtype=dtypes.float32) - 50. return categorical.Categorical(logits, dtype=dtype) class CategoricalTest(test.TestCase): def testP(self): p = [0.2, 0.8] dist = categorical.Categorical(probs=p) with self.test_session(): self.assertAllClose(p, dist.probs.eval()) self.assertAllEqual([2], dist.logits.get_shape()) def testLogits(self): p = np.array([0.2, 0.8], dtype=np.float32) logits = np.log(p) - 50. dist = categorical.Categorical(logits=logits) with self.test_session(): self.assertAllEqual([2], dist.probs.get_shape()) self.assertAllEqual([2], dist.logits.get_shape()) self.assertAllClose(dist.probs.eval(), p) self.assertAllClose(dist.logits.eval(), logits) def testShapes(self): with self.test_session(): for batch_shape in ([], [1], [2, 3, 4]): dist = make_categorical(batch_shape, 10) self.assertAllEqual(batch_shape, dist.batch_shape) self.assertAllEqual(batch_shape, dist.batch_shape_tensor().eval()) self.assertAllEqual([], dist.event_shape) self.assertAllEqual([], dist.event_shape_tensor().eval()) self.assertEqual(10, dist.event_size.eval()) # event_size is available as a constant because the shape is # known at graph build time. self.assertEqual(10, tensor_util.constant_value(dist.event_size)) for batch_shape in ([], [1], [2, 3, 4]): dist = make_categorical( batch_shape, constant_op.constant( 10, dtype=dtypes.int32)) self.assertAllEqual(len(batch_shape), dist.batch_shape.ndims) self.assertAllEqual(batch_shape, dist.batch_shape_tensor().eval()) self.assertAllEqual([], dist.event_shape) self.assertAllEqual([], dist.event_shape_tensor().eval()) self.assertEqual(10, dist.event_size.eval()) def testDtype(self): dist = make_categorical([], 5, dtype=dtypes.int32) self.assertEqual(dist.dtype, dtypes.int32) self.assertEqual(dist.dtype, dist.sample(5).dtype) self.assertEqual(dist.dtype, dist.mode().dtype) dist = make_categorical([], 5, dtype=dtypes.int64) self.assertEqual(dist.dtype, dtypes.int64) self.assertEqual(dist.dtype, dist.sample(5).dtype) self.assertEqual(dist.dtype, dist.mode().dtype) self.assertEqual(dist.probs.dtype, dtypes.float32) self.assertEqual(dist.logits.dtype, dtypes.float32) self.assertEqual(dist.logits.dtype, dist.entropy().dtype) self.assertEqual( dist.logits.dtype, dist.prob(np.array( 0, dtype=np.int64)).dtype) self.assertEqual( dist.logits.dtype, dist.log_prob(np.array( 0, dtype=np.int64)).dtype) def testUnknownShape(self): with self.test_session(): logits = array_ops.placeholder(dtype=dtypes.float32) dist = categorical.Categorical(logits) sample = dist.sample() # Will sample class 1. sample_value = sample.eval(feed_dict={logits: [-1000.0, 1000.0]}) self.assertEqual(1, sample_value) # Batch entry 0 will sample class 1, batch entry 1 will sample class 0. sample_value_batch = sample.eval( feed_dict={logits: [[-1000.0, 1000.0], [1000.0, -1000.0]]}) self.assertAllEqual([1, 0], sample_value_batch) def testPMFWithBatch(self): histograms = [[0.2, 0.8], [0.6, 0.4]] dist = categorical.Categorical(math_ops.log(histograms) - 50.) with self.test_session(): self.assertAllClose(dist.prob([0, 1]).eval(), [0.2, 0.4]) def testPMFNoBatch(self): histograms = [0.2, 0.8] dist = categorical.Categorical(math_ops.log(histograms) - 50.) with self.test_session(): self.assertAllClose(dist.prob(0).eval(), 0.2) def testLogPMF(self): logits = np.log([[0.2, 0.8], [0.6, 0.4]]) - 50. dist = categorical.Categorical(logits) with self.test_session(): self.assertAllClose(dist.log_prob([0, 1]).eval(), np.log([0.2, 0.4])) def testEntropyNoBatch(self): logits = np.log([0.2, 0.8]) - 50. dist = categorical.Categorical(logits) with self.test_session(): self.assertAllClose(dist.entropy().eval(), -(0.2 * np.log(0.2) + 0.8 * np.log(0.8))) def testEntropyWithBatch(self): logits = np.log([[0.2, 0.8], [0.6, 0.4]]) - 50. dist = categorical.Categorical(logits) with self.test_session(): self.assertAllClose(dist.entropy().eval(), [ -(0.2 * np.log(0.2) + 0.8 * np.log(0.8)), -(0.6 * np.log(0.6) + 0.4 * np.log(0.4)) ]) def testEntropyGradient(self): with self.test_session() as sess: logits = constant_op.constant([[1., 2., 3.], [2., 5., 1.]]) probabilities = nn_ops.softmax(logits) log_probabilities = nn_ops.log_softmax(logits) true_entropy = - math_ops.reduce_sum( probabilities * log_probabilities, axis=-1) categorical_distribution = categorical.Categorical(probs=probabilities) categorical_entropy = categorical_distribution.entropy() # works true_entropy_g = gradients_impl.gradients(true_entropy, [logits]) categorical_entropy_g = gradients_impl.gradients( categorical_entropy, [logits]) res = sess.run({"true_entropy": true_entropy, "categorical_entropy": categorical_entropy, "true_entropy_g": true_entropy_g, "categorical_entropy_g": categorical_entropy_g}) self.assertAllClose(res["true_entropy"], res["categorical_entropy"]) self.assertAllClose(res["true_entropy_g"], res["categorical_entropy_g"]) def testSample(self): with self.test_session(): histograms = [[[0.2, 0.8], [0.4, 0.6]]] dist = categorical.Categorical(math_ops.log(histograms) - 50.) n = 10000 samples = dist.sample(n, seed=123) samples.set_shape([n, 1, 2]) self.assertEqual(samples.dtype, dtypes.int32) sample_values = samples.eval() self.assertFalse(np.any(sample_values < 0)) self.assertFalse(np.any(sample_values > 1)) self.assertAllClose( [[0.2, 0.4]], np.mean( sample_values == 0, axis=0), atol=1e-2) self.assertAllClose( [[0.8, 0.6]], np.mean( sample_values == 1, axis=0), atol=1e-2) def testSampleWithSampleShape(self): with self.test_session(): histograms = [[[0.2, 0.8], [0.4, 0.6]]] dist = categorical.Categorical(math_ops.log(histograms) - 50.) samples = dist.sample((100, 100), seed=123) prob = dist.prob(samples) prob_val = prob.eval() self.assertAllClose( [0.2**2 + 0.8**2], [prob_val[:, :, :, 0].mean()], atol=1e-2) self.assertAllClose( [0.4**2 + 0.6**2], [prob_val[:, :, :, 1].mean()], atol=1e-2) def testLogPMFBroadcasting(self): with self.test_session(): histograms = [[[0.2, 0.8], [0.4, 0.6]]] dist = categorical.Categorical(math_ops.log(histograms) - 50.) prob = dist.prob(1) self.assertAllClose([[0.8, 0.6]], prob.eval()) prob = dist.prob([1]) self.assertAllClose([[0.8, 0.6]], prob.eval()) prob = dist.prob([0, 1]) self.assertAllClose([[0.2, 0.6]], prob.eval()) prob = dist.prob([[0, 1]]) self.assertAllClose([[0.2, 0.6]], prob.eval()) prob = dist.prob([[[0, 1]]]) self.assertAllClose([[[0.2, 0.6]]], prob.eval()) prob = dist.prob([[1, 0], [0, 1]]) self.assertAllClose([[0.8, 0.4], [0.2, 0.6]], prob.eval()) prob = dist.prob([[[1, 1], [1, 0]], [[1, 0], [0, 1]]]) self.assertAllClose([[[0.8, 0.6], [0.8, 0.4]], [[0.8, 0.4], [0.2, 0.6]]], prob.eval()) def testLogPMFShape(self): with self.test_session(): # shape [1, 2, 2] histograms = [[[0.2, 0.8], [0.4, 0.6]]] dist = categorical.Categorical(math_ops.log(histograms)) log_prob = dist.log_prob([0, 1]) self.assertEqual(2, log_prob.get_shape().ndims) self.assertAllEqual([1, 2], log_prob.get_shape()) log_prob = dist.log_prob([[[1, 1], [1, 0]], [[1, 0], [0, 1]]]) self.assertEqual(3, log_prob.get_shape().ndims) self.assertAllEqual([2, 2, 2], log_prob.get_shape()) def testLogPMFShapeNoBatch(self): histograms = [0.2, 0.8] dist = categorical.Categorical(math_ops.log(histograms)) log_prob = dist.log_prob(0) self.assertEqual(0, log_prob.get_shape().ndims) self.assertAllEqual([], log_prob.get_shape()) log_prob = dist.log_prob([[[1, 1], [1, 0]], [[1, 0], [0, 1]]]) self.assertEqual(3, log_prob.get_shape().ndims) self.assertAllEqual([2, 2, 2], log_prob.get_shape()) def testMode(self): with self.test_session(): histograms = [[[0.2, 0.8], [0.6, 0.4]]] dist = categorical.Categorical(math_ops.log(histograms) - 50.) self.assertAllEqual(dist.mode().eval(), [[1, 0]]) def testCategoricalCategoricalKL(self): def np_softmax(logits): exp_logits = np.exp(logits) return exp_logits / exp_logits.sum(axis=-1, keepdims=True) with self.test_session() as sess: for categories in [2, 4]: for batch_size in [1, 10]: a_logits = np.random.randn(batch_size, categories) b_logits = np.random.randn(batch_size, categories) a = categorical.Categorical(logits=a_logits) b = categorical.Categorical(logits=b_logits) kl = kullback_leibler.kl_divergence(a, b) kl_val = sess.run(kl) # Make sure KL(a||a) is 0 kl_same = sess.run(kullback_leibler.kl_divergence(a, a)) prob_a = np_softmax(a_logits) prob_b = np_softmax(b_logits) kl_expected = np.sum(prob_a * (np.log(prob_a) - np.log(prob_b)), axis=-1) self.assertEqual(kl.get_shape(), (batch_size,)) self.assertAllClose(kl_val, kl_expected) self.assertAllClose(kl_same, np.zeros_like(kl_expected)) if __name__ == "__main__": test.main()
apache-2.0
revmischa/boto
boto/services/__init__.py
782
1108
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/ # # 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. #
mit
marratj/ansible
lib/ansible/modules/windows/win_domain.py
31
2009
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Red Hat, Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'core'} DOCUMENTATION = ''' module: win_domain short_description: Ensures the existence of a Windows domain. version_added: 2.3 description: - Ensure that the domain named by C(dns_domain_name) exists and is reachable. If the domain is not reachable, the domain is created in a new forest on the target Windows Server 2012R2+ host. This module may require subsequent use of the M(win_reboot) action if changes are made. options: dns_domain_name: description: - the DNS name of the domain which should exist and be reachable or reside on the target Windows host required: true safe_mode_password: description: - safe mode password for the domain controller required: true author: - Matt Davis (@nitzmahone) ''' RETURN = ''' reboot_required: description: True if changes were made that require a reboot. returned: always type: boolean sample: true ''' EXAMPLES = r''' # ensure the named domain is reachable from the target host; if not, create the domain in a new forest residing on the target host - win_domain: dns_domain_name: ansible.vagrant safe_mode_password: password123! '''
gpl-3.0
clebergnu/avocado-vt
virttest/nfs.py
2
18942
""" Basic nfs support for Linux host. It can support the remote nfs mount and the local nfs set up and mount. """ import re import aexpect import logging from avocado.utils import path from avocado.utils import process from avocado.utils import distro from avocado.utils.astring import to_text from avocado.core import exceptions from virttest import utils_misc from virttest import test_setup from virttest.utils_iptables import Iptables from virttest.utils_conn import SSHConnection from virttest.staging import service def nfs_exported(session=None): """ Get the list for nfs file system already exported :param session: ShellSessionObject of remote/guest :return: a list of nfs that is already exported in system :rtype: a lit of nfs file system exported """ func = process.system_output if session: func = session.cmd_output exportfs = to_text(func("exportfs -v")) if not exportfs: return {} nfs_exported_dict = {} for fs_info in re.findall("[/\w+]+.*?\(.*?\)", exportfs, re.S): fs_info = fs_info.strip().split() if len(fs_info) == 2: nfs_src = fs_info[0] access_ip = re.findall(r"(.*)\(", fs_info[1])[0] if "world" in access_ip: access_ip = "*" nfs_tag = "%s_%s" % (nfs_src, access_ip) permission = re.findall(r"\((.*)\)", fs_info[1])[0] nfs_exported_dict[nfs_tag] = permission return nfs_exported_dict class Exportfs(object): """ Add or remove one entry to exported nfs file system. """ def __init__(self, path, client="*", options="", ori_exported=None, session=None): if ori_exported is None: ori_exported = [] self.path = path self.client = client self.options = options.split(",") self.ori_exported = ori_exported self.entry_tag = "%s_%s" % (self.path, self.client) self.already_exported = False self.ori_options = "" self.session = session self.func = process.getoutput if self.session: self.func = self.session.cmd_output def is_exported(self): """ Check if the directory is already exported. :return: If the entry is exported :rtype: Boolean """ ori_exported = self.ori_exported or nfs_exported(session=self.session) if self.entry_tag in list(ori_exported.keys()): return True return False def need_reexport(self): """ Check if the entry is already exported but the options are not the same as we required. :return: Need re export the entry or not :rtype: Boolean """ ori_exported = self.ori_exported or nfs_exported(session=self.session) if self.is_exported(): exported_options = ori_exported[self.entry_tag] options = [_ for _ in self.options if _ not in exported_options] if options: self.ori_options = exported_options return True return False def unexport(self): """ Unexport an entry. """ if self.is_exported(): unexport_cmd = "exportfs -u %s:%s" % (self.client, self.path) self.func(unexport_cmd) else: logging.warn("Target %s %s is not exported yet." "Can not unexport it." % (self.client, self.path)) def reset_export(self): """ Reset the exportfs to the original status before we export the specific entry. """ self.unexport() if self.ori_options: tmp_options = self.options self.options = self.ori_options.split(",") self.export() self.options = tmp_options def export(self): """ Export one directory if it is not in exported list. :return: Export nfs file system succeed or not """ if self.is_exported(): if self.need_reexport(): self.unexport() else: self.already_exported = True logging.warn("Already exported target." " Don't need export it again") return True export_cmd = "exportfs" if self.options: export_cmd += " -o %s" % ",".join(self.options) export_cmd += " %s:%s" % (self.client, self.path) try: self.func(export_cmd) except (process.CmdError, aexpect.ShellTimeoutError) as export_failed_err: logging.error("Can not export target: %s" % export_failed_err) return False return True class Nfs(object): """ Nfs class for handle nfs mount and umount. If a local nfs service is required, it will configure a local nfs server accroding the params. """ def __init__(self, params): self.mount_dir = params.get("nfs_mount_dir") self.mount_options = params.get("nfs_mount_options") self.mount_src = params.get("nfs_mount_src") self.nfs_setup = False path.find_command("mount") self.rm_mount_dir = False self.rm_export_dir = False self.unexportfs_in_clean = False distro_details = distro.detect().name self.session = None self.setup_nfs_ip = params.get("nfs_server_ip", "127.0.0.1") self.export_dir = (params.get("export_dir") or self.mount_src.split(":")[-1]) self.export_ip = params.get("export_ip", "*") self.export_options = params.get("export_options", "").strip() if params.get("setup_remote_nfs") == "yes": self.nfs_setup = True self.setup_nfs_ip = params["nfs_server_ip"] nfs_server_params = {'server_ip': self.setup_nfs_ip, 'server_pwd': params["nfs_server_pwd"], 'server_user': params.get("nfs_server_user", "root")} self.session = test_setup.remote_session(nfs_server_params) distro_details = utils_misc.get_distro(self.session) if self.session.cmd_status("exportfs -h") != 0: logging.error("exportfs cmd not available in remote host") elif params.get("setup_local_nfs") == "yes": self.nfs_setup = True self.setup_nfs_ip = "127.0.0.1" path.find_command("service") path.find_command("exportfs") if(params.get("setup_remote_nfs") == "yes" or params.get("setup_local_nfs") == "yes"): if 'Ubuntu' in distro_details or 'rhel' in distro_details: self.nfs_service = service.Service("nfs-server", session=self.session) else: self.nfs_service = service.Service("nfs", session=self.session) self.rpcbind_service = service.Service("rpcbind", session=self.session) self.exportfs = Exportfs(self.export_dir, self.export_ip, self.export_options, session=self.session) self.mount_src = "%s:%s" % (self.setup_nfs_ip, self.export_dir) def is_mounted(self): """ Check the NFS is mounted or not. :return: If the src is mounted as expect :rtype: Boolean """ return utils_misc.is_mounted(self.mount_src, self.mount_dir, "nfs") def mount(self): """ Mount source into given mount point. """ return utils_misc.mount(self.mount_src, self.mount_dir, "nfs", perm=self.mount_options) def umount(self): """ Umount the given mount point. """ return utils_misc.umount(self.mount_src, self.mount_dir, "nfs") def setup(self): """ Setup NFS in host. Mount NFS as configured. If a local nfs is requested, setup the NFS service and exportfs too. """ if self.nfs_setup: if not self.nfs_service.status(): logging.debug("Restart NFS service.") self.rpcbind_service.restart() self.nfs_service.restart() if not utils_misc.check_isdir(self.export_dir, session=self.session): utils_misc.make_dirs(self.export_dir, session=self.session) self.rm_export_dir = True self.exportfs.export() self.unexportfs_in_clean = not self.exportfs.already_exported logging.debug("Mount %s to %s" % (self.mount_src, self.mount_dir)) if(utils_misc.check_exists(self.mount_dir, session=self.session) and not utils_misc.check_isdir(self.mount_dir, session=self.session)): raise OSError( "Mount point %s is not a directory, check your setup." % self.mount_dir) if not utils_misc.check_isdir(self.mount_dir, session=self.session): utils_misc.make_dirs(self.mount_dir, session=self.session) self.rm_mount_dir = True self.mount() def cleanup(self): """ Clean up the host env. Umount NFS from the mount point. If there has some change for exported file system in host when setup, also clean up that. """ self.umount() if self.nfs_setup and self.unexportfs_in_clean: self.exportfs.reset_export() if self.rm_export_dir and utils_misc.check_isdir(self.export_dir, session=self.session): utils_misc.safe_rmdir(self.export_dir) if self.rm_mount_dir and utils_misc.check_isdir(self.mount_dir, session=self.session): utils_misc.safe_rmdir(self.mount_dir, session=self.session) class NFSClient(object): """ NFSClient class for handle nfs remotely mount and umount. """ def __init__(self, params): self.nfs_client_ip = params.get("nfs_client_ip") # To Avoid host key verification failure ret = process.run("ssh-keygen -R %s" % self.nfs_client_ip, ignore_status=True) stderr = ret.stderr_text if ret.exit_status and "No such file or directory" not in stderr: raise exceptions.TestFail("Failed to update host key: %s" % stderr) # Setup SSH connection self.ssh_obj = SSHConnection(params) ssh_timeout = int(params.get("ssh_timeout", 10)) self.ssh_obj.conn_setup(timeout=ssh_timeout) self.params = params self.mkdir_mount_remote = False self.mount_dir = params.get("nfs_mount_dir") self.mount_options = params.get("nfs_mount_options") self.mount_src = params.get("nfs_mount_src") self.nfs_server_ip = params.get("nfs_server_ip") self.ssh_user = params.get("ssh_username", "root") self.remote_nfs_mount = params.get("remote_nfs_mount", "yes") self.ssh_hostkey_check = params.get("ssh_hostkey_check", "no") == "yes" self.ssh_cmd = "ssh %s@%s " % (self.ssh_user, self.nfs_client_ip) if not self.ssh_hostkey_check: self.ssh_cmd += "-o StrictHostKeyChecking=no " def is_mounted(self): """ Check the NFS is mounted or not. :return: If the src is mounted as expect :rtype: Boolean """ find_mountpoint_cmd = "mount | grep -E '.*%s.*%s.*'" % (self.mount_src, self.mount_dir) cmd = self.ssh_cmd + "'%s'" % find_mountpoint_cmd logging.debug("The command: %s", cmd) status, output = process.getstatusoutput(cmd) if status: logging.debug("The command result: <%s:%s>", status, output) return False return True def setup(self): """ Setup NFS client. """ # Mount sharing directory to local host # it has been covered by class Nfs # Mount sharing directory to remote host if self.remote_nfs_mount == "yes": # stale file mounted causes test to fail instead # unmount it and perform the setup if self.is_mounted(): self.umount() self.setup_remote() def umount(self): """ Unmount the mount directory in remote host """ logging.debug("Umount %s from %s" % (self.mount_dir, self.nfs_client_ip)) umount_cmd = self.ssh_cmd + "'umount -l %s'" % self.mount_dir try: process.system(umount_cmd, verbose=True) except process.CmdError: raise exceptions.TestFail("Failed to run: %s" % umount_cmd) def cleanup(self, ssh_auto_recover=False): """ Cleanup NFS client. """ self.umount() if self.mkdir_mount_remote: rmdir_cmd = self.ssh_cmd + "'rm -rf %s'" % self.mount_dir try: process.system(rmdir_cmd, verbose=True) except process.CmdError: raise exceptions.TestFail("Failed to run: %s" % rmdir_cmd) if self.is_mounted(): raise exceptions.TestFail("Failed to umount %s" % self.mount_dir) # Recover SSH connection if ssh_auto_recover: self.ssh_obj.auto_recover = ssh_auto_recover del self.ssh_obj def firewall_to_permit_nfs(self): """ Method to configure firewall to permit NFS to be mounted from remote host """ # Check firewall in host permit nfs service to mount from remote server try: firewalld = service.Factory.create_service("firewalld") if not firewalld.status(): firewalld.start() firewall_cmd = "firewall-cmd --list-all | grep services:" try: ret = process.run(firewall_cmd, shell=True) if not ret.exit_status: firewall_services = ret.stdout_text.split(':')[1].strip().split(' ') if 'nfs' not in firewall_services: service_cmd = "firewall-cmd --permanent --zone=public " service_cmd += "--add-service=nfs" ret = process.run(service_cmd, shell=True) if ret.exit_status: logging.error("nfs service not added in firewall: " "%s", ret.stdout_text) else: logging.debug("nfs service added to firewall " "sucessfully") firewalld.restart() else: logging.debug("nfs service already permitted by firewall") except process.CmdError: # For RHEL 6 based system firewall-cmd is not available logging.debug("Using iptables to permit NFS service") nfs_ports = [] rule_list = [] nfsd = service.Factory.create_service("nfs") rpcd = service.Factory.create_service("rpcbind") iptables = service.Factory.create_service("iptables") nfs_sysconfig = self.params.get("nfs_sysconfig_path", "/etc/sysconfig/nfs") tcp_port = self.params.get("nfs_tcp_port", "32803") udp_port = self.params.get("nfs_udp_port", "32769") mountd_port = self.params.get("nfs_mountd_port", "892") subnet_mask = self.params.get("priv_subnet", "192.168.2.0/24") nfs_ports.append("LOCKD_TCPPORT=%s" % tcp_port) nfs_ports.append("LOCKD_UDPPORT=%s" % udp_port) nfs_ports.append("MOUNTD_PORT=%s" % mountd_port) cmd_output = process.run("cat %s" % nfs_sysconfig, shell=True).stdout_text exist_ports = cmd_output.strip().split('\n') # check if the ports are already configured, if not then add it for each_port in nfs_ports: if each_port not in exist_ports: process.run("echo '%s' >> %s" % (each_port, nfs_sysconfig), shell=True) rpcd.restart() nfsd.restart() rule_temp = "INPUT -m state --state NEW -p %s -m multiport " rule_temp += "--dport 111,892,2049,%s -s %s -j ACCEPT" rule = rule_temp % ("tcp", tcp_port, subnet_mask) rule_list.append(rule) rule = rule_temp % ("udp", udp_port, subnet_mask) rule_list.append(rule) Iptables.setup_or_cleanup_iptables_rules(rule_list) iptables.restart() except Exception as info: logging.error("Firewall setting to add nfs service " "failed: %s", info) def setup_remote(self): """ Mount sharing directory to remote host. """ check_mount_dir_cmd = self.ssh_cmd + "'ls -d %s'" % self.mount_dir logging.debug("To check if the %s exists", self.mount_dir) output = process.getoutput(check_mount_dir_cmd) if re.findall("No such file or directory", output, re.M): mkdir_cmd = self.ssh_cmd + "'mkdir -p %s'" % self.mount_dir logging.debug("Prepare to create %s", self.mount_dir) s, o = process.getstatusoutput(mkdir_cmd) if s != 0: raise exceptions.TestFail("Failed to run %s: %s" % (mkdir_cmd, o)) self.mkdir_mount_remote = True if self.params.get("firewall_to_permit_nfs", "yes") == "yes": if distro.detect().name != "Ubuntu": self.firewall_to_permit_nfs() self.mount_src = "%s:%s" % (self.nfs_server_ip, self.mount_src) logging.debug("Mount %s to %s" % (self.mount_src, self.mount_dir)) mount_cmd = "mount -t nfs %s %s" % (self.mount_src, self.mount_dir) if self.mount_options: mount_cmd += " -o %s" % self.mount_options try: cmd = "%s '%s'" % (self.ssh_cmd, mount_cmd) process.system(cmd, verbose=True) except process.CmdError: raise exceptions.TestFail("Failed to run: %s" % cmd) # Check if the sharing directory is mounted if not self.is_mounted(): raise exceptions.TestFail("Failed to mount from %s to %s" % self.mount_src, self.mount_dir)
gpl-2.0
jelugbo/tundex
common/lib/xmodule/xmodule/modulestore/tests/test_modulestore.py
25
2199
from nose.tools import assert_equals, assert_true, assert_false # pylint: disable=E0611 def check_has_course_method(modulestore, locator, locator_key_fields): error_message = "Called has_course with query {0} and ignore_case is {1}." for ignore_case in [True, False]: # should find the course with exact locator assert_true(modulestore.has_course(locator, ignore_case)) for key_field in locator_key_fields: if getattr(locator, key_field): locator_changes_that_should_not_be_found = [ # pylint: disable=invalid-name # replace value for one of the keys {key_field: 'fake'}, # add a character at the end {key_field: getattr(locator, key_field) + 'X'}, # add a character in the beginning {key_field: 'X' + getattr(locator, key_field)}, ] for changes in locator_changes_that_should_not_be_found: search_locator = locator.replace(**changes) assert_false( modulestore.has_course(search_locator), error_message.format(search_locator, ignore_case) ) # test case [in]sensitivity locator_case_changes = [ {key_field: getattr(locator, key_field).upper()}, {key_field: getattr(locator, key_field).capitalize()}, {key_field: getattr(locator, key_field).capitalize().swapcase()}, ] for changes in locator_case_changes: search_locator = locator.replace(**changes) # if ignore_case is true, the course would be found with a different-cased course locator. # if ignore_case is false, the course should NOT found given an incorrectly-cased locator. assert_equals( modulestore.has_course(search_locator, ignore_case) is not None, ignore_case, error_message.format(search_locator, ignore_case) )
agpl-3.0
dmarcosgon/linux
tools/perf/scripts/python/sctop.py
1996
2102
# system call top # (c) 2010, Tom Zanussi <tzanussi@gmail.com> # Licensed under the terms of the GNU GPL License version 2 # # Periodically displays system-wide system call totals, broken down by # syscall. If a [comm] arg is specified, only syscalls called by # [comm] are displayed. If an [interval] arg is specified, the display # will be refreshed every [interval] seconds. The default interval is # 3 seconds. import os, sys, thread, time sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * usage = "perf script -s sctop.py [comm] [interval]\n"; for_comm = None default_interval = 3 interval = default_interval if len(sys.argv) > 3: sys.exit(usage) if len(sys.argv) > 2: for_comm = sys.argv[1] interval = int(sys.argv[2]) elif len(sys.argv) > 1: try: interval = int(sys.argv[1]) except ValueError: for_comm = sys.argv[1] interval = default_interval syscalls = autodict() def trace_begin(): thread.start_new_thread(print_syscall_totals, (interval,)) pass def raw_syscalls__sys_enter(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, common_callchain, id, args): if for_comm is not None: if common_comm != for_comm: return try: syscalls[id] += 1 except TypeError: syscalls[id] = 1 def syscalls__sys_enter(event_name, context, common_cpu, common_secs, common_nsecs, common_pid, common_comm, id, args): raw_syscalls__sys_enter(**locals()) def print_syscall_totals(interval): while 1: clear_term() if for_comm is not None: print "\nsyscall events for %s:\n\n" % (for_comm), else: print "\nsyscall events:\n\n", print "%-40s %10s\n" % ("event", "count"), print "%-40s %10s\n" % ("----------------------------------------", \ "----------"), for id, val in sorted(syscalls.iteritems(), key = lambda(k, v): (v, k), \ reverse = True): try: print "%-40s %10d\n" % (syscall_name(id), val), except TypeError: pass syscalls.clear() time.sleep(interval)
gpl-2.0
mtrbean/scipy
scipy/io/matlab/mio.py
64
8782
""" Module for reading and writing matlab (TM) .mat files """ # Authors: Travis Oliphant, Matthew Brett from __future__ import division, print_function, absolute_import import numpy as np from scipy._lib.six import string_types from .miobase import get_matfile_version, docfiller from .mio4 import MatFile4Reader, MatFile4Writer from .mio5 import MatFile5Reader, MatFile5Writer __all__ = ['mat_reader_factory', 'loadmat', 'savemat', 'whosmat'] def _open_file(file_like, appendmat): ''' Open `file_like` and return as file-like object ''' if isinstance(file_like, string_types): try: return open(file_like, 'rb') except IOError as e: if appendmat and not file_like.endswith('.mat'): file_like += '.mat' try: return open(file_like, 'rb') except IOError: pass # Rethrow the original exception. raise # not a string - maybe file-like object try: file_like.read(0) except AttributeError: raise IOError('Reader needs file name or open file-like object') return file_like @docfiller def mat_reader_factory(file_name, appendmat=True, **kwargs): """Create reader for matlab .mat format files Parameters ---------- %(file_arg)s %(append_arg)s %(load_args)s %(struct_arg)s Returns ------- matreader : MatFileReader object Initialized instance of MatFileReader class matching the mat file type detected in `filename`. """ byte_stream = _open_file(file_name, appendmat) mjv, mnv = get_matfile_version(byte_stream) if mjv == 0: return MatFile4Reader(byte_stream, **kwargs) elif mjv == 1: return MatFile5Reader(byte_stream, **kwargs) elif mjv == 2: raise NotImplementedError('Please use HDF reader for matlab v7.3 files') else: raise TypeError('Did not recognize version %s' % mjv) @docfiller def loadmat(file_name, mdict=None, appendmat=True, **kwargs): """ Load MATLAB file Parameters ---------- file_name : str Name of the mat file (do not need .mat extension if appendmat==True) Can also pass open file-like object. m_dict : dict, optional Dictionary in which to insert matfile variables. appendmat : bool, optional True to append the .mat extension to the end of the given filename, if not already present. byte_order : str or None, optional None by default, implying byte order guessed from mat file. Otherwise can be one of ('native', '=', 'little', '<', 'BIG', '>'). mat_dtype : bool, optional If True, return arrays in same dtype as would be loaded into MATLAB (instead of the dtype with which they are saved). squeeze_me : bool, optional Whether to squeeze unit matrix dimensions or not. chars_as_strings : bool, optional Whether to convert char arrays to string arrays. matlab_compatible : bool, optional Returns matrices as would be loaded by MATLAB (implies squeeze_me=False, chars_as_strings=False, mat_dtype=True, struct_as_record=True). struct_as_record : bool, optional Whether to load MATLAB structs as numpy record arrays, or as old-style numpy arrays with dtype=object. Setting this flag to False replicates the behavior of scipy version 0.7.x (returning numpy object arrays). The default setting is True, because it allows easier round-trip load and save of MATLAB files. verify_compressed_data_integrity : bool, optional Whether the length of compressed sequences in the MATLAB file should be checked, to ensure that they are not longer than we expect. It is advisable to enable this (the default) because overlong compressed sequences in MATLAB files generally indicate that the files have experienced some sort of corruption. variable_names : None or sequence If None (the default) - read all variables in file. Otherwise `variable_names` should be a sequence of strings, giving names of the matlab variables to read from the file. The reader will skip any variable with a name not in this sequence, possibly saving some read processing. Returns ------- mat_dict : dict dictionary with variable names as keys, and loaded matrices as values Notes ----- v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported. You will need an HDF5 python library to read matlab 7.3 format mat files. Because scipy does not supply one, we do not implement the HDF5 / 7.3 interface here. """ variable_names = kwargs.pop('variable_names', None) MR = mat_reader_factory(file_name, appendmat, **kwargs) matfile_dict = MR.get_variables(variable_names) if mdict is not None: mdict.update(matfile_dict) else: mdict = matfile_dict if isinstance(file_name, string_types): MR.mat_stream.close() return mdict @docfiller def savemat(file_name, mdict, appendmat=True, format='5', long_field_names=False, do_compression=False, oned_as='row'): """ Save a dictionary of names and arrays into a MATLAB-style .mat file. This saves the array objects in the given dictionary to a MATLAB- style .mat file. Parameters ---------- file_name : str or file-like object Name of the .mat file (.mat extension not needed if ``appendmat == True``). Can also pass open file_like object. mdict : dict Dictionary from which to save matfile variables. appendmat : bool, optional True (the default) to append the .mat extension to the end of the given filename, if not already present. format : {'5', '4'}, string, optional '5' (the default) for MATLAB 5 and up (to 7.2), '4' for MATLAB 4 .mat files long_field_names : bool, optional False (the default) - maximum field name length in a structure is 31 characters which is the documented maximum length. True - maximum field name length in a structure is 63 characters which works for MATLAB 7.6+ do_compression : bool, optional Whether or not to compress matrices on write. Default is False. oned_as : {'row', 'column'}, optional If 'column', write 1-D numpy arrays as column vectors. If 'row', write 1-D numpy arrays as row vectors. See also -------- mio4.MatFile4Writer mio5.MatFile5Writer """ file_is_string = isinstance(file_name, string_types) if file_is_string: if appendmat and file_name[-4:] != ".mat": file_name = file_name + ".mat" file_stream = open(file_name, 'wb') else: if not hasattr(file_name, 'write'): raise IOError('Writer needs file name or writeable ' 'file-like object') file_stream = file_name if format == '4': if long_field_names: raise ValueError("Long field names are not available for version 4 files") MW = MatFile4Writer(file_stream, oned_as) elif format == '5': MW = MatFile5Writer(file_stream, do_compression=do_compression, unicode_strings=True, long_field_names=long_field_names, oned_as=oned_as) else: raise ValueError("Format should be '4' or '5'") MW.put_variables(mdict) if file_is_string: file_stream.close() @docfiller def whosmat(file_name, appendmat=True, **kwargs): """ List variables inside a MATLAB file Parameters ---------- %(file_arg)s %(append_arg)s %(load_args)s %(struct_arg)s Returns ------- variables : list of tuples A list of tuples, where each tuple holds the matrix name (a string), its shape (tuple of ints), and its data class (a string). Possible data classes are: int8, uint8, int16, uint16, int32, uint32, int64, uint64, single, double, cell, struct, object, char, sparse, function, opaque, logical, unknown. Notes ----- v4 (Level 1.0), v6 and v7 to 7.2 matfiles are supported. You will need an HDF5 python library to read matlab 7.3 format mat files. Because scipy does not supply one, we do not implement the HDF5 / 7.3 interface here. .. versionadded:: 0.12.0 """ ML = mat_reader_factory(file_name, **kwargs) variables = ML.list_variables() if isinstance(file_name, string_types): ML.mat_stream.close() return variables
bsd-3-clause
Bforartists/scons
scons-local/SCons/Scanner/Prog.py
7
3233
# # Copyright (c) 2001 - 2014 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Scanner/Prog.py 2014/07/05 09:42:21 garyo" import SCons.Node import SCons.Node.FS import SCons.Scanner import SCons.Util # global, set by --debug=findlibs print_find_libs = None def ProgramScanner(**kw): """Return a prototype Scanner instance for scanning executable files for static-lib dependencies""" kw['path_function'] = SCons.Scanner.FindPathDirs('LIBPATH') ps = SCons.Scanner.Base(scan, "ProgramScanner", **kw) return ps def scan(node, env, libpath = ()): """ This scanner scans program files for static-library dependencies. It will search the LIBPATH environment variable for libraries specified in the LIBS variable, returning any files it finds as dependencies. """ try: libs = env['LIBS'] except KeyError: # There are no LIBS in this environment, so just return a null list: return [] if SCons.Util.is_String(libs): libs = libs.split() else: libs = SCons.Util.flatten(libs) try: prefix = env['LIBPREFIXES'] if not SCons.Util.is_List(prefix): prefix = [ prefix ] except KeyError: prefix = [ '' ] try: suffix = env['LIBSUFFIXES'] if not SCons.Util.is_List(suffix): suffix = [ suffix ] except KeyError: suffix = [ '' ] pairs = [] for suf in map(env.subst, suffix): for pref in map(env.subst, prefix): pairs.append((pref, suf)) result = [] if callable(libpath): libpath = libpath() find_file = SCons.Node.FS.find_file adjustixes = SCons.Util.adjustixes for lib in libs: if SCons.Util.is_String(lib): lib = env.subst(lib) for pref, suf in pairs: l = adjustixes(lib, pref, suf) l = find_file(l, libpath, verbose=print_find_libs) if l: result.append(l) else: result.append(lib) return result # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
mit
jonathanlurie/Tubular
lib/python/gooey/gui/widgets/components.py
2
7463
from gooey.gui.widgets import widget_pack __author__ = 'Chris' import wx from gooey.gui import styling class BaseGuiComponent(object): def __init__(self, data, widget_pack): self.data = data # parent self.panel = None # Widgets self.title = None self.help_msg = None # Internal WidgetPack self.widget_pack = widget_pack # used to throttle resizing (to avoid widget jiggle) # TODO: figure out anti-jiggle technology # self.event_stack = [] def build(self, parent): return self.do_layout(parent) def do_layout(self, parent): self.panel = wx.Panel(parent) self.title = self.createTitle(self.panel) self.help_msg = self.createHelpMsgWidget(self.panel) self.help_msg.SetMinSize((0, -1)) core_widget_set = self.widget_pack.build(self.panel, self.data) vertical_container = wx.BoxSizer(wx.VERTICAL) vertical_container.Add(self.title) vertical_container.AddSpacer(2) if self.help_msg.GetLabelText(): vertical_container.Add(self.help_msg, 1, wx.EXPAND) vertical_container.AddSpacer(2) else: vertical_container.AddStretchSpacer(1) vertical_container.Add(core_widget_set, 0, wx.EXPAND) self.panel.SetSizer(vertical_container) self.panel.Bind(wx.EVT_SIZE, self.onResize) return self.panel def createHelpMsgWidget(self, parent): label_text = (self.formatExtendedHelpMsg(self.data) if self.data['nargs'] else self.data['help']) base_text = wx.StaticText(parent, label=label_text or '') styling.MakeDarkGrey(base_text) return base_text def createTitle(self, parent): text = wx.StaticText(parent, label=self.data['display_name'].title()) styling.MakeBold(text) return text def formatExtendedHelpMsg(self, data): base_text = data.get('help', '') nargs = data['nargs'] if isinstance(nargs, int): return '{base}\n(Note: exactly {nargs} arguments are required)'.format(base=base_text, nargs=nargs) elif nargs == '+': return '{base}\n(Note: at least 1 or more arguments are required)'.format(base=base_text) return base_text def onResize(self, evt): # handle internal widgets self.panel.Freeze() self._onResize(evt) # propagate event to child widgets self.widget_pack.onResize(evt) evt.Skip() self.panel.Thaw() def _onResize(self, evt): if not self.help_msg: return self.panel.Size = evt.GetSize() container_width, _ = self.panel.Size text_width, _ = self.help_msg.Size if text_width != container_width: self.help_msg.SetLabel(self.help_msg.GetLabelText().replace('\n', ' ')) self.help_msg.Wrap(container_width) evt.Skip() def GetValue(self): return self.widget_pack.getValue() def _GetWidget(self): # used only for unittesting return self.widget_pack.widget class CheckBox(BaseGuiComponent): def __init__(self, data, widget_pack=None): BaseGuiComponent.__init__(self, data, widget_pack) self.widget = None # data self.option_strings = data['commands'][0] def build(self, parent): return self.do_layout(parent) def do_layout(self, parent): self.panel = wx.Panel(parent) self.widget = wx.CheckBox(self.panel) self.title = self.createTitle(self.panel) self.help_msg = self.createHelpMsgWidget(self.panel) self.help_msg.SetMinSize((0, -1)) vertical_container = wx.BoxSizer(wx.VERTICAL) vertical_container.Add(self.title) horizontal_sizer = wx.BoxSizer(wx.HORIZONTAL) horizontal_sizer.Add(self.widget, 0, wx.EXPAND | wx.RIGHT, 10) horizontal_sizer.Add(self.help_msg, 1, wx.EXPAND) vertical_container.Add(horizontal_sizer, 0, wx.EXPAND) self.panel.SetSizer(vertical_container) self.panel.Bind(wx.EVT_SIZE, self.onResize) return self.panel def onSetter(self, evt): self.getValue() def onResize(self, evt): msg = self.help_msg container_width, _ = self.panel.Size text_width, _ = msg.Size if text_width != container_width: msg.SetLabel(msg.GetLabelText().replace('\n', ' ')) msg.Wrap(container_width) evt.Skip() def GetValue(self): return self.option_strings if self.widget.GetValue() else '' def _GetWidget(self): return self.widget class RadioGroup(object): def __init__(self, data): self.panel = None self.data = data self.radio_buttons = [] self.option_stings = [] self.help_msgs = [] self.btn_names = [] def build(self, parent): return self.do_layout(parent) def do_layout(self, parent): self.panel = wx.Panel(parent) self.radio_buttons = [wx.RadioButton(self.panel, -1) for _ in self.data] self.btn_names = [wx.StaticText(self.panel, label=btn_data['display_name'].title()) for btn_data in self.data] self.help_msgs = [wx.StaticText(self.panel, label=btn_data['help'].title()) for btn_data in self.data] self.option_stings = [btn_data['commands'] for btn_data in self.data] # box = wx.StaticBox(self.panel, -1, label=self.data['group_name']) box = wx.StaticBox(self.panel, -1, label='Set Verbosity Level') vertical_container = wx.StaticBoxSizer(box, wx.VERTICAL) for button, name, help in zip(self.radio_buttons, self.btn_names, self.help_msgs): hbox = wx.BoxSizer(wx.HORIZONTAL) hbox.Add(button, 0, wx.ALIGN_TOP | wx.ALIGN_LEFT) hbox.Add(name, 0, wx.LEFT, 10) vertical_container.Add(hbox, 0, wx.EXPAND) vertical_container.Add(help, 1, wx.EXPAND | wx.LEFT, 25) vertical_container.AddSpacer(5) # self.panel.Bind(wx.EVT_RADIOBUTTON, self.onSetter, button) self.panel.SetSizer(vertical_container) self.panel.Bind(wx.EVT_SIZE, self.onResize) return self.panel def onSetter(self, evt): self.getValue() def onResize(self, evt): msg = self.help_msgs[0] container_width, _ = self.panel.Size text_width, _ = msg.Size if text_width != container_width: msg.SetLabel(msg.GetLabelText().replace('\n', ' ')) msg.Wrap(container_width) evt.Skip() def GetValue(self): vals = [button.GetValue() for button in self.radio_buttons] # print self.option_stings[vals.index(True)] try: opts = self.option_stings[vals.index(True)][0] except: return '' def _GetWidget(self): return self.radio_buttons FileChooser = lambda data: BaseGuiComponent(data=data, widget_pack=widget_pack.FileChooserPayload()) MultiFileChooser = lambda data: BaseGuiComponent(data=data, widget_pack=widget_pack.MultiFileSaverPayload()) DirChooser = lambda data: BaseGuiComponent(data=data, widget_pack=widget_pack.DirChooserPayload()) FileSaver = lambda data: BaseGuiComponent(data=data, widget_pack=widget_pack.FileSaverPayload()) DateChooser = lambda data: BaseGuiComponent(data=data, widget_pack=widget_pack.DateChooserPayload()) TextField = lambda data: BaseGuiComponent(data=data, widget_pack=widget_pack.TextInputPayload()) Dropdown = lambda data: BaseGuiComponent(data=data, widget_pack=widget_pack.DropdownPayload()) Counter = lambda data: BaseGuiComponent(data=data, widget_pack=widget_pack.CounterPayload())
mit
TeamTwisted/external_chromium_org
third_party/markdown/extensions/meta.py
109
4514
# markdown is released under the BSD license # Copyright 2007, 2008 The Python Markdown Project (v. 1.7 and later) # Copyright 2004, 2005, 2006 Yuri Takhteyev (v. 0.2-1.6b) # Copyright 2004 Manfred Stienstra (the original version) # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the <organization> 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 PYTHON MARKDOWN PROJECT ''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 ANY CONTRIBUTORS TO THE PYTHON MARKDOWN PROJECT # 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. """ Meta Data Extension for Python-Markdown ======================================= This extension adds Meta Data handling to markdown. Basic Usage: >>> import markdown >>> text = '''Title: A Test Doc. ... Author: Waylan Limberg ... John Doe ... Blank_Data: ... ... The body. This is paragraph one. ... ''' >>> md = markdown.Markdown(['meta']) >>> print md.convert(text) <p>The body. This is paragraph one.</p> >>> print md.Meta {u'blank_data': [u''], u'author': [u'Waylan Limberg', u'John Doe'], u'title': [u'A Test Doc.']} Make sure text without Meta Data still works (markdown < 1.6b returns a <p>). >>> text = ' Some Code - not extra lines of meta data.' >>> md = markdown.Markdown(['meta']) >>> print md.convert(text) <pre><code>Some Code - not extra lines of meta data. </code></pre> >>> md.Meta {} Copyright 2007-2008 [Waylan Limberg](http://achinghead.com). Project website: <http://packages.python.org/Markdown/meta_data.html> Contact: markdown@freewisdom.org License: BSD (see ../LICENSE.md for details) """ from __future__ import absolute_import from __future__ import unicode_literals from . import Extension from ..preprocessors import Preprocessor import re # Global Vars META_RE = re.compile(r'^[ ]{0,3}(?P<key>[A-Za-z0-9_-]+):\s*(?P<value>.*)') META_MORE_RE = re.compile(r'^[ ]{4,}(?P<value>.*)') class MetaExtension (Extension): """ Meta-Data extension for Python-Markdown. """ def extendMarkdown(self, md, md_globals): """ Add MetaPreprocessor to Markdown instance. """ md.preprocessors.add("meta", MetaPreprocessor(md), "_begin") class MetaPreprocessor(Preprocessor): """ Get Meta-Data. """ def run(self, lines): """ Parse Meta-Data and store in Markdown.Meta. """ meta = {} key = None while 1: line = lines.pop(0) if line.strip() == '': break # blank line - done m1 = META_RE.match(line) if m1: key = m1.group('key').lower().strip() value = m1.group('value').strip() try: meta[key].append(value) except KeyError: meta[key] = [value] else: m2 = META_MORE_RE.match(line) if m2 and key: # Add another line to existing key meta[key].append(m2.group('value').strip()) else: lines.insert(0, line) break # no meta data - done self.markdown.Meta = meta return lines def makeExtension(configs={}): return MetaExtension(configs=configs)
bsd-3-clause
enigmamarketing/csf-allow-domains
usr/local/csf/bin/csf-allow-domains/dns/rdtypes/ANY/SSHFP.py
44
3129
# Copyright (C) 2005-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and this permission notice # appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. import struct import dns.rdata import dns.rdatatype class SSHFP(dns.rdata.Rdata): """SSHFP record @ivar algorithm: the algorithm @type algorithm: int @ivar fp_type: the digest type @type fp_type: int @ivar fingerprint: the fingerprint @type fingerprint: string @see: draft-ietf-secsh-dns-05.txt""" __slots__ = ['algorithm', 'fp_type', 'fingerprint'] def __init__(self, rdclass, rdtype, algorithm, fp_type, fingerprint): super(SSHFP, self).__init__(rdclass, rdtype) self.algorithm = algorithm self.fp_type = fp_type self.fingerprint = fingerprint def to_text(self, origin=None, relativize=True, **kw): return '%d %d %s' % (self.algorithm, self.fp_type, dns.rdata._hexify(self.fingerprint, chunksize=128)) def from_text(cls, rdclass, rdtype, tok, origin = None, relativize = True): algorithm = tok.get_uint8() fp_type = tok.get_uint8() chunks = [] while 1: t = tok.get().unescape() if t.is_eol_or_eof(): break if not t.is_identifier(): raise dns.exception.SyntaxError chunks.append(t.value) fingerprint = ''.join(chunks) fingerprint = fingerprint.decode('hex_codec') return cls(rdclass, rdtype, algorithm, fp_type, fingerprint) from_text = classmethod(from_text) def to_wire(self, file, compress = None, origin = None): header = struct.pack("!BB", self.algorithm, self.fp_type) file.write(header) file.write(self.fingerprint) def from_wire(cls, rdclass, rdtype, wire, current, rdlen, origin = None): header = struct.unpack("!BB", wire[current : current + 2]) current += 2 rdlen -= 2 fingerprint = wire[current : current + rdlen].unwrap() return cls(rdclass, rdtype, header[0], header[1], fingerprint) from_wire = classmethod(from_wire) def _cmp(self, other): hs = struct.pack("!BB", self.algorithm, self.fp_type) ho = struct.pack("!BB", other.algorithm, other.fp_type) v = cmp(hs, ho) if v == 0: v = cmp(self.fingerprint, other.fingerprint) return v
mit
alertedsnake/pycrust
pycrust/__init__.py
1
5061
""" Pycrust A collection of CherryPy extensions See also the following submodules: pycrust.auth pycrust.saplugin pycrust.satool pycrust.tools """ __author__ = 'Michael Stella <pycrust@thismetalsky.org>' __version__ = '1.0.0' import inspect, logging, os, sys import cherrypy import codecs class BaseHandler(object): """A Base class for web handler objects.""" _cp_config = {} def log(self, msg, severity=logging.INFO, context=None): """Logs to the Cherrypy error log but in a much more pretty way, with the handler name and line number """ if not context: context = inspect.getouterframes(inspect.currentframe())[1] cherrypy.log.error(msg=msg.strip().replace('\n', '; '), severity=severity, context='HANDLER ({}:{}:{})'.format( self.__class__.__name__, context[3], context[2])) def log_debug(self, msg): return self.log(msg, severity=logging.DEBUG, context=inspect.getouterframes(inspect.currentframe())[1]) def log_info(self, msg): return self.log(msg, severity=logging.INFO, context=inspect.getouterframes(inspect.currentframe())[1]) def log_warn(self, msg): return self.log(msg, severity=logging.WARN, context=inspect.getouterframes(inspect.currentframe())[1]) def log_error(self, msg): return self.log(msg, severity=logging.ERROR, context=inspect.getouterframes(inspect.currentframe())[1]) def log_fatal(self, msg): return self.log(msg, severity=logging.FATAL, context=inspect.getouterframes(inspect.currentframe())[1]) def url(*args, **kwargs): """Find the given URL using routes. Throws an exception if you're not using routes. """ import routes if 'absolute' in kwargs and kwargs['absolute']: del(kwargs['absolute']) return cherrypy.url(routes.url_for(*args, **kwargs)) return routes.url_for(*args, **kwargs) def dump_request(*args, **kwargs): """Dumps the request out to a file in /tmp, for debugging Enable by setting, in your config file: tools.debug_request.on = True """ with codecs.open('/tmp/request.%s.txt' % cherrypy.request.method, 'w', encoding='utf-8') as f: f.write(cherrypy.request.request_line) f.write("\n") # write headers for (k,v) in cherrypy.request.headers.items(): f.write('%s: %s\n' % (k,v)) f.write("\n") # dump out the POST data when submitted if ('Content-Type' in cherrypy.request.headers and 'application/x-www-form-urlencoded' in cherrypy.request.headers['Content-Type']): for (k,v) in cherrypy.request.params.items(): f.write('%s: %s\n' % (k,v)) # otherwise, dump the body elif cherrypy.request.body: with cherrypy.request.body.make_file() as fin: f.write(str(fin.read())) def dump_response(*args, **kwargs): """Dumps the response out to a file in /tmp, for debugging. Enable by setting, in your config file: tools.debug_response.on = True """ # when a 500 error is displayed, cherrypy handles this # differently, and we don't really need to dump it out if not cherrypy.response.status: return status = 200 if isinstance(cherrypy.response.status, int): status = cherrypy.response.status elif isinstance(cherrypy.response.status, str): status = int(cherrypy.response.status.split(' ', 1)[0]) with codecs.open('/tmp/response.%d.txt' % status, 'w', encoding='utf-8') as f: f.write("HTTP/1.1 %s\n" % cherrypy.response.status) for (k,v) in cherrypy.response.headers.items(): f.write('%s: %s\n' % (k,v)) f.write("Status: %d\n\n" % status) if cherrypy.response.body: if sys.version < '3': f.write(str(cherrypy.response.collapse_body().decode())) else: f.write(str(cherrypy.response.collapse_body())) cherrypy.tools.debug_request = cherrypy.Tool('before_handler', dump_request, priority=1) cherrypy.tools.debug_response = cherrypy.Tool('on_end_resource', dump_response) def load_class(fullname): """Loads a class given the full dotted class name""" assert fullname is not None, "fullname must not be None" modulename, classname = fullname.rsplit('.', 1) try: module = __import__(modulename, globals(), locals(), [classname]) except ImportError as e: cherrypy.log("Error loading module {}".format(modulename), context='ENGINE', severity=loging.ERROR) raise try: cls = getattr(module, classname) except AttributeError as e: cherrypy.log("Error loading class {} from module {}".format(classname, modulename), context='ENGINE', severity=logging.ERROR) return None return cls
mit
kmkolasinski/Quantulaba
plots/plot_lattice.py
2
1492
#!/usr/bin/python import numpy as np import matplotlib.pyplot as plt import csv from matplotlib.collections import LineCollection file = "lattice.dat" #ax = plt.gca(projection='3d') pscale=1.0 lscale=10.0 fig, ax = plt. subplots() ax.set_aspect('equal') desired=[1,2] with open(file, 'r') as fin: reader=csv.reader(fin) result=[[(s) for s in row] for i,row in enumerate(reader) if i in desired] minCorner = map(float,result[0][0].split()) maxCorner = map(float,result[1][0].split()) xWidth = abs(minCorner[0]-maxCorner[0]) yWidth = abs(minCorner[1]-maxCorner[1]) zWidth = abs(minCorner[2]-maxCorner[2]) ax.scatter(minCorner[0],minCorner[1],s=0) ax.scatter(maxCorner[0],maxCorner[1],s=0) ax.margins(0.1) data = np.loadtxt(file,skiprows=4) no_lines = np.size(data[:,0]) wlist = [] lines = [] for i in range(no_lines): lines.append([ (data[i,0],data[i,1]) , (data[i,3],data[i,4]) ]) wlist.extend([data[i,6]*lscale]) lc = LineCollection(lines, linewidths=wlist,colors='black',lw=1.0) ax.add_collection(lc) wlist = [] points = [] for i in range(no_lines): if(data[i,6] > 1.0): points.append([data[i,0],data[i,1] ]) wlist.extend([data[i,6]*pscale]) points = np.array(points) wlist = np.array(wlist) if(np.size(points) > 0): ax.scatter(points[:,0],points[:,1], cmap='PuBu', c=wlist , s=50 , edgecolors='k' , zorder=2 ) plt.savefig("lattice.pdf")
mit
onitake/ansible
test/units/modules/network/f5/test_bigip_firewall_rule.py
21
4718
# -*- coding: utf-8 -*- # # Copyright: (c) 2018, F5 Networks Inc. # 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 import os import json import pytest import sys if sys.version_info < (2, 7): pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7") from ansible.module_utils.basic import AnsibleModule try: from library.modules.bigip_firewall_rule import ApiParameters from library.modules.bigip_firewall_rule import ModuleParameters from library.modules.bigip_firewall_rule import ModuleManager from library.modules.bigip_firewall_rule import ArgumentSpec # In Ansible 2.8, Ansible changed import paths. from test.units.compat import unittest from test.units.compat.mock import Mock from test.units.compat.mock import patch from test.units.modules.utils import set_module_args except ImportError: from ansible.modules.network.f5.bigip_firewall_rule import ApiParameters from ansible.modules.network.f5.bigip_firewall_rule import ModuleParameters from ansible.modules.network.f5.bigip_firewall_rule import ModuleManager from ansible.modules.network.f5.bigip_firewall_rule import ArgumentSpec # Ansible 2.8 imports from units.compat import unittest from units.compat.mock import Mock from units.compat.mock import patch from units.modules.utils import set_module_args fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') fixture_data = {} def load_fixture(name): path = os.path.join(fixture_path, name) if path in fixture_data: return fixture_data[path] with open(path) as f: data = f.read() try: data = json.loads(data) except Exception: pass fixture_data[path] = data return data class TestParameters(unittest.TestCase): def test_module_parameters(self): args = dict( name='foo', parent_policy='policy1', protocol='tcp', source=[ dict(address='1.2.3.4'), dict(address='::1'), dict(address_list='foo-list1'), dict(address_range='1.1.1.1-2.2.2.2.'), dict(vlan='vlan1'), dict(country='US'), dict(port='22'), dict(port_list='port-list1'), dict(port_range='80-443'), ], destination=[ dict(address='1.2.3.4'), dict(address='::1'), dict(address_list='foo-list1'), dict(address_range='1.1.1.1-2.2.2.2.'), dict(country='US'), dict(port='22'), dict(port_list='port-list1'), dict(port_range='80-443'), ], irule='irule1', action='accept', logging=True, ) p = ModuleParameters(params=args) assert p.irule == '/Common/irule1' assert p.action == 'accept' assert p.logging is True class TestManager(unittest.TestCase): def setUp(self): self.spec = ArgumentSpec() def test_create_monitor(self, *args): set_module_args(dict( name='foo', parent_policy='policy1', protocol='tcp', source=[ dict(address='1.2.3.4'), dict(address='::1'), dict(address_list='foo-list1'), dict(address_range='1.1.1.1-2.2.2.2.'), dict(vlan='vlan1'), dict(country='US'), dict(port='22'), dict(port_list='port-list1'), dict(port_range='80-443'), ], destination=[ dict(address='1.2.3.4'), dict(address='::1'), dict(address_list='foo-list1'), dict(address_range='1.1.1.1-2.2.2.2.'), dict(country='US'), dict(port='22'), dict(port_list='port-list1'), dict(port_range='80-443'), ], irule='irule1', action='accept', logging='yes', )) module = AnsibleModule( argument_spec=self.spec.argument_spec, supports_check_mode=self.spec.supports_check_mode ) # Override methods in the specific type of manager mm = ModuleManager(module=module) mm.exists = Mock(side_effect=[False, True]) mm.create_on_device = Mock(return_value=True) results = mm.exec_module() assert results['changed'] is True
gpl-3.0
Sumith1896/sympy
sympy/physics/quantum/matrixcache.py
124
3519
"""A cache for storing small matrices in multiple formats.""" from __future__ import print_function, division from sympy import Matrix, I, Pow, Rational, exp, pi from sympy.physics.quantum.matrixutils import ( to_sympy, to_numpy, to_scipy_sparse ) class MatrixCache(object): """A cache for small matrices in different formats. This class takes small matrices in the standard ``sympy.Matrix`` format, and then converts these to both ``numpy.matrix`` and ``scipy.sparse.csr_matrix`` matrices. These matrices are then stored for future recovery. """ def __init__(self, dtype='complex'): self._cache = {} self.dtype = dtype def cache_matrix(self, name, m): """Cache a matrix by its name. Parameters ---------- name : str A descriptive name for the matrix, like "identity2". m : list of lists The raw matrix data as a sympy Matrix. """ try: self._sympy_matrix(name, m) except ImportError: pass try: self._numpy_matrix(name, m) except ImportError: pass try: self._scipy_sparse_matrix(name, m) except ImportError: pass def get_matrix(self, name, format): """Get a cached matrix by name and format. Parameters ---------- name : str A descriptive name for the matrix, like "identity2". format : str The format desired ('sympy', 'numpy', 'scipy.sparse') """ m = self._cache.get((name, format)) if m is not None: return m raise NotImplementedError( 'Matrix with name %s and format %s is not available.' % (name, format) ) def _store_matrix(self, name, format, m): self._cache[(name, format)] = m def _sympy_matrix(self, name, m): self._store_matrix(name, 'sympy', to_sympy(m)) def _numpy_matrix(self, name, m): m = to_numpy(m, dtype=self.dtype) self._store_matrix(name, 'numpy', m) def _scipy_sparse_matrix(self, name, m): # TODO: explore different sparse formats. But sparse.kron will use # coo in most cases, so we use that here. m = to_scipy_sparse(m, dtype=self.dtype) self._store_matrix(name, 'scipy.sparse', m) sqrt2_inv = Pow(2, Rational(-1, 2), evaluate=False) # Save the common matrices that we will need matrix_cache = MatrixCache() matrix_cache.cache_matrix('eye2', Matrix([[1, 0], [0, 1]])) matrix_cache.cache_matrix('op11', Matrix([[0, 0], [0, 1]])) # |1><1| matrix_cache.cache_matrix('op00', Matrix([[1, 0], [0, 0]])) # |0><0| matrix_cache.cache_matrix('op10', Matrix([[0, 0], [1, 0]])) # |1><0| matrix_cache.cache_matrix('op01', Matrix([[0, 1], [0, 0]])) # |0><1| matrix_cache.cache_matrix('X', Matrix([[0, 1], [1, 0]])) matrix_cache.cache_matrix('Y', Matrix([[0, -I], [I, 0]])) matrix_cache.cache_matrix('Z', Matrix([[1, 0], [0, -1]])) matrix_cache.cache_matrix('S', Matrix([[1, 0], [0, I]])) matrix_cache.cache_matrix('T', Matrix([[1, 0], [0, exp(I*pi/4)]])) matrix_cache.cache_matrix('H', sqrt2_inv*Matrix([[1, 1], [1, -1]])) matrix_cache.cache_matrix('Hsqrt2', Matrix([[1, 1], [1, -1]])) matrix_cache.cache_matrix( 'SWAP', Matrix([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]])) matrix_cache.cache_matrix('ZX', sqrt2_inv*Matrix([[1, 1], [1, -1]])) matrix_cache.cache_matrix('ZY', Matrix([[I, 0], [0, -I]]))
bsd-3-clause
WarrenWeckesser/numpy
numpy/distutils/msvccompiler.py
17
1928
import os from distutils.msvccompiler import MSVCCompiler as _MSVCCompiler from .system_info import platform_bits def _merge(old, new): """Concatenate two environment paths avoiding repeats. Here `old` is the environment string before the base class initialize function is called and `new` is the string after the call. The new string will be a fixed string if it is not obtained from the current environment, or the same as the old string if obtained from the same environment. The aim here is not to append the new string if it is already contained in the old string so as to limit the growth of the environment string. Parameters ---------- old : string Previous environment string. new : string New environment string. Returns ------- ret : string Updated environment string. """ if new in old: return old if not old: return new # Neither new nor old is empty. Give old priority. return ';'.join([old, new]) class MSVCCompiler(_MSVCCompiler): def __init__(self, verbose=0, dry_run=0, force=0): _MSVCCompiler.__init__(self, verbose, dry_run, force) def initialize(self): # The 'lib' and 'include' variables may be overwritten # by MSVCCompiler.initialize, so save them for later merge. environ_lib = os.getenv('lib', '') environ_include = os.getenv('include', '') _MSVCCompiler.initialize(self) # Merge current and previous values of 'lib' and 'include' os.environ['lib'] = _merge(environ_lib, os.environ['lib']) os.environ['include'] = _merge(environ_include, os.environ['include']) # msvc9 building for 32 bits requires SSE2 to work around a # compiler bug. if platform_bits == 32: self.compile_options += ['/arch:SSE2'] self.compile_options_debug += ['/arch:SSE2']
bsd-3-clause
Serag8/Bachelor
google_appengine/google/appengine/dist/py_imp.py
6
3739
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Stub replacement for Python's imp module.""" import os import sys PY_SOURCE, PY_COMPILED, C_EXTENSION = 1, 2, 3 PKG_DIRECTORY, C_BUILTIN, PY_FROZEN = 5, 6, 7 def get_magic(): """Return the magic string used to recognize byte-compiled code files.""" return '\xb3\xf2\r\n' _PY_SOURCE_SUFFIX = ('.py', 'U', PY_SOURCE) _PKG_DIRECTORY_SUFFIX = ('', '', PKG_DIRECTORY) def get_suffixes(): """Return a list that describes the files that find_module() looks for.""" return [_PY_SOURCE_SUFFIX] def find_module(name, path=None): """Try to find the named module on the given search path or sys.path.""" if path == None: path = sys.path for directory in path: filename = os.path.join(directory, '%s.py' % name) if os.path.exists(filename): return open(filename, 'U'), filename, _PY_SOURCE_SUFFIX dirname = os.path.join(directory, name) filename = os.path.join(dirname, '__init__.py') if os.path.exists(filename): return None, dirname, _PKG_DIRECTORY_SUFFIX raise ImportError('No module named %s' % name) def load_module(name, file_, pathname, description): """Load or reload the specified module. Please note that this function has only rudimentary supported on App Engine: Only loading packages is supported. """ suffix, mode, type_ = description if type_ == PKG_DIRECTORY: if name in sys.modules: mod = sys.modules[name] else: mod = new_module(name) sys.modules[name] = mod filename = os.path.join(pathname, '__init__.py') mod.__file__ = filename execfile(filename, mod.__dict__, mod.__dict__) return mod else: raise NotImplementedError('Only importing packages is supported on ' 'App Engine') def new_module(name): """Return a new empty module object.""" return type(sys)(name) def lock_held(): """Return False since threading is not supported.""" return False def acquire_lock(): """Acquiring the lock is a no-op since no threading is supported.""" pass def release_lock(): """There is no lock to release since acquiring is a no-op when there is no threading.""" pass def init_builtin(name): raise NotImplementedError('This function is not supported on App Engine.') def init_frozen(name): raise NotImplementedError('This function is not supported on App Engine.') def is_builtin(name): return name in sys.builtin_module_names def is_frozen(name): return False def load_compiled(name, pathname, file_=None): raise NotImplementedError('This function is not supported on App Engine.') def load_dynamic(name, pathname, file_=None): raise NotImplementedError('This function is not supported on App Engine.') def load_source(name, pathname, file_=None): raise NotImplementedError('This function is not supported on App Engine.') class NullImporter(object): """Null importer object""" def __init__(self, path_string): if not path_string: raise ImportError("empty pathname") elif os.path.isdir(path_string): raise ImportError("existing directory") def find_module(self, fullname): return None
mit
PauloSantos13/android
user_manual/conf.py
2
9666
# -*- coding: utf-8 -*- # # ownCloud Documentation documentation build configuration file, created by # sphinx-quickstart on Mon Oct 22 23:16:40 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os, inspect # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) #path to this script scriptpath = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.todo'] # Add any paths that contain templates here, relative to this directory. templates_path = [scriptpath+'/ocdoc/_shared_assets/templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # The short X.Y.Z version. version = '2.0.0' # The full version, including alpha/beta/rc tags. release = '2.0.0' # General information about the project. project = u'ownCloud Android App %s Manual' % (version) copyright = u'2013-2016, The ownCloud developers' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build','scripts/*', 'ocdoc/*'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True 2 # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. html_theme_path = [scriptpath+'/ocdoc/_shared_assets/themes'] # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. #html_theme = 'bootstrap' html_theme = 'default' # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. html_short_title = "Android App Manual" # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [scriptpath+'/ocdoc/_shared_assets/static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. html_show_sphinx = False # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'ownCloudAndroidAppManual' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'ownCloudAndroidAppManual.tex', u'ownCloud Android App Manual', u'The ownCloud developers', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('owncloud.1', 'owncloud', u'Android synchronisation and file management utility.', [u'The ownCloud developers'], 1), ('owncloudcmd.1', 'owncloudcmd', u'ownCloud Android app.', [u'The ownCloud developers'], 1), ] # If true, show URL addresses after external links. man_show_urls = True # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'ownCloudClientManual', u'ownCloud Android App Manual', u'The ownCloud developers', 'ownCloud', 'The ownCloud Android App Manual.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # -- Options for Epub output --------------------------------------------------- # Bibliographic Dublin Core info. epub_title = u'ownCloud Android App Manual' epub_author = u'The ownCloud developers' epub_publisher = u'The ownCloud developers' epub_copyright = u'2013-2015, The ownCloud developers' # The language of the text. It defaults to the language option # or en if the language is not set. #epub_language = '' # The scheme of the identifier. Typical schemes are ISBN or URL. #epub_scheme = '' # The unique identifier of the text. This can be a ISBN number # or the project homepage. #epub_identifier = '' # A unique identification for the text. #epub_uid = '' # A tuple containing the cover image and cover page html template filenames. #epub_cover = () # HTML files that should be inserted before the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_pre_files = [] # HTML files shat should be inserted after the pages created by sphinx. # The format is a list of tuples containing the path and title. #epub_post_files = [] # A list of files that should not be packed into the epub file. #epub_exclude_files = [] # The depth of the table of contents in toc.ncx. #epub_tocdepth = 3 # Allow duplicate toc entries. #epub_tocdup = True # Include todos? todo_include_todos = True
gpl-2.0
ayseyo/oclapi
django-nonrel/ocl/oclapi/settings/common.py
1
10523
import os from configurations import Configuration BASE_DIR = os.path.dirname(os.path.dirname(__file__)) class Common(Configuration): DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( ('Jon Payne', 'paynejd@gmail.com'), ('PK Shiu', 'pk@pkshiu.com'), ) MANAGERS = ADMINS DEFAULT_FROM_EMAIL = 'no-reply@openconceptlab.org' EMAIL_HOST = 'openconceptlab.org' EMAIL_SUBJECT_PREFIX = '[openconceptlab.org] ' # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.3/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/New_York' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # If you set this to False, Django will not format dates, numbers and # calendars according to the current locale USE_L10N = True DEFAULT_LOCALE = 'en' # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = '' # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = '' # In the deployment environment, comment out the above line, and uncomment the one below #STATIC_ROOT = '/usr/local/wsgi/static/' # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = '/static/' # URL prefix for admin static files -- CSS, JavaScript and images. # Make sure to use a trailing slash. # Examples: "http://foo.com/static/admin/", "/static/admin/". ADMIN_MEDIA_PREFIX = '/static/admin/' # Additional locations of static files STATICFILES_DIRS = ( # Put strings here, like "/home/html/static" or "C:/www/django/static". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # Make this unique, and don't share it with anybody. SECRET_KEY = '+p+lx2*o3ywq+z)%f7929b6)93)^mcc9-0eu9ynq77gc+pe=ck' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', # 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'oclapi.middlewares.RequestLogMiddleware', ) ROOT_URLCONF = 'urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Uncomment the next line to enable the admin: 'django.contrib.admin', 'corsheaders', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', # Core OCL app 'oclapi', # Third-party apps: 'djangotoolbox', 'django_mongodb_engine', 'rest_framework', 'rest_framework.authtoken', 'haystack', # Project-specific apps: 'users', 'orgs', 'sources', 'concepts', 'collection', 'mappings', 'integration_tests', ) # Django Rest Framework configuration REST_FRAMEWORK = { # Default to token-based authentication; fall back on session-based # A user gets a unique token upon account creation (residing in the authtoken_token data store). # To pass an authentication token along with your request, include the following header: # Authorization: Token [TOKEN_VALUE] # e.g. # Authorization: Token ad73f481096c3b6202bce395820199 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', 'oclapi.renderers.ZippedJSONRenderer', ), 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'oclapi.negotiation.OptionallyCompressContentNegotiation', # Use hyperlinked styles by default. # Only used if the `serializer_class` attribute is not set on a view. 'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.HyperlinkedModelSerializer', 'DEFAULT_PAGINATION_SERIALIZER_CLASS': 'oclapi.serializers.HeaderPaginationSerializer', # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ #'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly', 'rest_framework.permissions.IsAuthenticated', ], 'PAGINATE_BY': 10, # Default to 10 'PAGINATE_BY_PARAM': 'limit', # Allow client to override, using `?limit=xxx`. 'MAX_PAGINATE_BY': 100 # Maximum limit allowed when using `?limit=xxx`. } HAYSTACK_CONNECTIONS = { 'default': { 'ENGINE': 'oclapi.search_backends.OCLSolrEngine', 'URL': 'http://solr.openconceptlab.org:8983/solr/collection1' # ...or for multicore... # 'URL': 'http://127.0.0.1:8983/solr/mysite', }, } DATABASES = { 'default': { 'ENGINE': 'django_mongodb_engine', 'HOST': 'mongo.openconceptlab.org', 'NAME': 'ocl', } } BROKER_URL = 'redis://redis.openconceptlab.org:6379/0' CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = ( 'GET', ) # CORS_ORIGIN_WHITELIST = ( # 'google.com', # 'hostname.example.com', # ) # Haystack processor determines when/how updates to mongo are indexed by Solr # RealtimeSignalProcessor will update the index for every mongo update, sometimes at # the cost of performance. BaseSignalProcessor does not update the index at all, which # means the index must be updated manually (e.g. using the haystack update_index command). HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor' HAYSTACK_ITERATOR_LOAD_PER_QUERY = 25 HAYSTACK_SEARCH_RESULTS_PER_PAGE = 25 # Celery settings CELERY_RESULT_BACKEND = 'redis://redis.openconceptlab.org:6379/0' # Set these in your postactivate hook if you use virtualenvwrapper AWS_ACCESS_KEY_ID=os.environ.get('AWS_ACCESS_KEY_ID', '') AWS_SECRET_ACCESS_KEY=os.environ.get('AWS_SECRET_ACCESS_KEY', '') AWS_STORAGE_BUCKET_NAME=os.environ.get('AWS_STORAGE_BUCKET_NAME', '') # Model that stores auxiliary user profile attributes. # A user must have a profile in order to access the system. # (A profile is created automatically for any user created using the 'POST /users' endpoint.) AUTH_PROFILE_MODULE = 'users.UserProfile' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'formatters': { 'normal': { 'format': "[%(asctime)s] %(levelname)-8s: %(message)s", 'datefmt': "%Y/%m/%d %H:%M:%S" }, }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'null': { 'class': 'django.utils.log.NullHandler', }, 'console': { 'class': 'logging.StreamHandler', 'formatter': 'normal', }, 'logfile': { 'level': 'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', 'when': 'midnight', 'filename': os.path.join(BASE_DIR, 'ocl_api.log'), 'formatter': 'normal', }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, 'oclapi': { 'handlers': ['console', 'logfile'], 'level': 'DEBUG', }, 'request_logger': { 'handlers': ['console', 'logfile'], 'level': 'INFO', }, } }
mpl-2.0
xeddmc/PyBitmessage
src/bitmessageqt/connect.py
19
2951
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'connect.ui' # # Created: Wed Jul 24 12:42:01 2013 # by: PyQt4 UI code generator 4.10 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_connectDialog(object): def setupUi(self, connectDialog): connectDialog.setObjectName(_fromUtf8("connectDialog")) connectDialog.resize(400, 124) self.gridLayout = QtGui.QGridLayout(connectDialog) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.label = QtGui.QLabel(connectDialog) self.label.setObjectName(_fromUtf8("label")) self.gridLayout.addWidget(self.label, 0, 0, 1, 2) self.radioButtonConnectNow = QtGui.QRadioButton(connectDialog) self.radioButtonConnectNow.setChecked(True) self.radioButtonConnectNow.setObjectName(_fromUtf8("radioButtonConnectNow")) self.gridLayout.addWidget(self.radioButtonConnectNow, 1, 0, 1, 2) self.radioButtonConfigureNetwork = QtGui.QRadioButton(connectDialog) self.radioButtonConfigureNetwork.setObjectName(_fromUtf8("radioButtonConfigureNetwork")) self.gridLayout.addWidget(self.radioButtonConfigureNetwork, 2, 0, 1, 2) spacerItem = QtGui.QSpacerItem(185, 24, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout.addItem(spacerItem, 3, 0, 1, 1) self.buttonBox = QtGui.QDialogButtonBox(connectDialog) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok) self.buttonBox.setObjectName(_fromUtf8("buttonBox")) self.gridLayout.addWidget(self.buttonBox, 3, 1, 1, 1) self.retranslateUi(connectDialog) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), connectDialog.accept) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), connectDialog.reject) QtCore.QMetaObject.connectSlotsByName(connectDialog) def retranslateUi(self, connectDialog): connectDialog.setWindowTitle(_translate("connectDialog", "Bitmessage", None)) self.label.setText(_translate("connectDialog", "Bitmessage won\'t connect to anyone until you let it. ", None)) self.radioButtonConnectNow.setText(_translate("connectDialog", "Connect now", None)) self.radioButtonConfigureNetwork.setText(_translate("connectDialog", "Let me configure special network settings first", None))
mit
jbonofre/beam
sdks/python/apache_beam/runners/test/__init__.py
25
1243
# # 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. # """Test runner objects that's only for end-to-end tests. This package defines runners, which are used to execute test pipeline and verify results. """ # Protect against environments where dataflow runner is not available. # pylint: disable=wrong-import-order, wrong-import-position try: from apache_beam.runners.dataflow.test_dataflow_runner import TestDataflowRunner except ImportError: pass # pylint: enable=wrong-import-order, wrong-import-position
apache-2.0
stuart-knock/tvb-framework
tvb_test/adapters/visualizers/eegmonitor_test.py
1
4412
# -*- coding: utf-8 -*- # # # TheVirtualBrain-Framework Package. This package holds all Data Management, and # Web-UI helpful to run brain-simulations. To use it, you also need do download # TheVirtualBrain-Scientific Package (for simulators). See content of the # documentation-folder for more details. See also http://www.thevirtualbrain.org # # (c) 2012-2013, Baycrest Centre for Geriatric Care ("Baycrest") # # This program is free software; you can redistribute it and/or modify it under # the terms of the GNU General Public License version 2 as published by the Free # Software Foundation. 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, you can download it here # http://www.gnu.org/licenses/old-licenses/gpl-2.0 # # # CITATION: # When using The Virtual Brain for scientific publications, please cite it as follows: # # Paula Sanz Leon, Stuart A. Knock, M. Marmaduke Woodman, Lia Domide, # Jochen Mersmann, Anthony R. McIntosh, Viktor Jirsa (2013) # The Virtual Brain: a simulator of primate brain network dynamics. # Frontiers in Neuroinformatics (7:10. doi: 10.3389/fninf.2013.00010) # # """ .. moduleauthor:: Bogdan Neacsa <bogdan.neacsa@codemart.ro> """ import os import unittest import demo_data.sensors as sensors_dataset from tvb.core.entities.file.files_helper import FilesHelper from tvb.adapters.visualizers.eeg_monitor import EegMonitor from tvb.datatypes.surfaces import CorticalSurface from tvb.datatypes.connectivity import Connectivity from tvb.datatypes.sensors import SensorsEEG from tvb_test.core.test_factory import TestFactory from tvb_test.datatypes.datatypes_factory import DatatypesFactory from tvb_test.core.base_testcase import TransactionalTestCase class EEGMonitorTest(TransactionalTestCase): """ Unit-tests for EEG Viewer. """ def setUp(self): """ Sets up the environment for running the tests; creates a test user, a test project, a connectivity and a surface; imports a CFF data-set """ self.datatypeFactory = DatatypesFactory() self.test_project = self.datatypeFactory.get_project() self.test_user = self.datatypeFactory.get_user() TestFactory.import_cff(test_user=self.test_user, test_project=self.test_project) self.connectivity = TestFactory.get_entity(self.test_project, Connectivity()) self.assertTrue(self.connectivity is not None) self.surface = TestFactory.get_entity(self.test_project, CorticalSurface()) self.assertTrue(self.surface is not None) def tearDown(self): """ Clean-up tests data """ FilesHelper().remove_project_structure(self.test_project.name) def test_launch(self): """ Check that all required keys are present in output from BrainViewer launch. """ zip_path = os.path.join(os.path.dirname(sensors_dataset.__file__), 'EEG_unit_vectors_BrainProducts_62.txt.bz2') TestFactory.import_sensors(self.test_user, self.test_project, zip_path, 'EEG Sensors') sensors = TestFactory.get_entity(self.test_project, SensorsEEG()) time_series = self.datatypeFactory.create_timeseries(self.connectivity, 'EEG', sensors) viewer = EegMonitor() result = viewer.launch(time_series) expected_keys = ['tsStateVars', 'tsModes', 'translationStep', 'total_length', 'title', 'timeSetPaths', 'number_of_visible_points', 'normalizedSteps', 'noOfChannels', 'labelsForCheckBoxes', 'label_x', 'graphLabels', 'entities', 'channelsPage'] for key in expected_keys: self.assertTrue(key in result) def suite(): """ Gather all the tests in a test suite. """ test_suite = unittest.TestSuite() test_suite.addTest(unittest.makeSuite(EEGMonitorTest)) return test_suite if __name__ == "__main__": #So you can run tests from this package individually. TEST_RUNNER = unittest.TextTestRunner() TEST_SUITE = suite() TEST_RUNNER.run(TEST_SUITE)
gpl-2.0
sammerry/ansible
lib/ansible/plugins/lookup/dict.py
84
1113
# (c) 2014, Kent R. Spillner <kspillner@acm.org> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase class LookupModule(LookupBase): def run(self, terms, varibles=None, **kwargs): if not isinstance(terms, dict): raise AnsibleError("with_dict expects a dict") return self._flatten_hash_to_list(terms)
gpl-3.0
lshain-android-source/external-chromium_org-tools-grit
grit/test_suite_all.py
8
6803
#!/usr/bin/env python # Copyright (c) 2011 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. '''Unit test suite that collects all test cases for GRIT.''' import os import sys if __name__ == '__main__': sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import unittest # TODO(joi) Use unittest.defaultTestLoader to automatically load tests # from modules. Iterating over the directory and importing could then # automate this all the way, if desired. class TestSuiteAll(unittest.TestSuite): def __init__(self): super(TestSuiteAll, self).__init__() # Imports placed here to prevent circular imports. # pylint: disable-msg=C6204 import grit.clique_unittest import grit.grd_reader_unittest import grit.grit_runner_unittest import grit.lazy_re_unittest import grit.shortcuts_unittests import grit.tclib_unittest import grit.util_unittest import grit.xtb_reader_unittest import grit.format.android_xml_unittest import grit.format.c_format_unittest import grit.format.chrome_messages_json_unittest import grit.format.data_pack_unittest import grit.format.html_inline_unittest import grit.format.js_map_format_unittest import grit.format.rc_header_unittest import grit.format.rc_unittest import grit.format.resource_map_unittest import grit.format.policy_templates.policy_template_generator_unittest import grit.format.policy_templates.writers.adm_writer_unittest import grit.format.policy_templates.writers.doc_writer_unittest import grit.format.policy_templates.writers.json_writer_unittest import grit.format.policy_templates.writers.plist_strings_writer_unittest import grit.format.policy_templates.writers.plist_writer_unittest import grit.format.policy_templates.writers.reg_writer_unittest import grit.format.policy_templates.writers.template_writer_unittest import grit.format.policy_templates.writers.xml_writer_base_unittest import grit.gather.admin_template_unittest import grit.gather.chrome_html_unittest import grit.gather.chrome_scaled_image_unittest import grit.gather.igoogle_strings_unittest import grit.gather.muppet_strings_unittest import grit.gather.policy_json_unittest import grit.gather.rc_unittest import grit.gather.tr_html_unittest import grit.gather.txt_unittest import grit.node.base_unittest import grit.node.io_unittest import grit.node.include_unittest import grit.node.message_unittest import grit.node.misc_unittest import grit.node.structure_unittest # import grit.node.custom.filename_unittest import grit.tool.android2grd_unittest import grit.tool.build_unittest import grit.tool.buildinfo_unittest import grit.tool.postprocess_unittest import grit.tool.preprocess_unittest import grit.tool.rc2grd_unittest import grit.tool.transl2tc_unittest import grit.tool.xmb_unittest test_classes = [ grit.clique_unittest.MessageCliqueUnittest, grit.grd_reader_unittest.GrdReaderUnittest, grit.grit_runner_unittest.OptionArgsUnittest, grit.lazy_re_unittest.LazyReUnittest, grit.shortcuts_unittests.ShortcutsUnittest, grit.tclib_unittest.TclibUnittest, grit.util_unittest.UtilUnittest, grit.xtb_reader_unittest.XtbReaderUnittest, grit.format.android_xml_unittest.AndroidXmlUnittest, grit.format.c_format_unittest.CFormatUnittest, grit.format.chrome_messages_json_unittest. ChromeMessagesJsonFormatUnittest, grit.format.data_pack_unittest.FormatDataPackUnittest, grit.format.html_inline_unittest.HtmlInlineUnittest, grit.format.js_map_format_unittest.JsMapFormatUnittest, grit.format.rc_header_unittest.RcHeaderFormatterUnittest, grit.format.rc_unittest.FormatRcUnittest, grit.format.resource_map_unittest.FormatResourceMapUnittest, grit.format.policy_templates.policy_template_generator_unittest. PolicyTemplateGeneratorUnittest, grit.format.policy_templates.writers.adm_writer_unittest. AdmWriterUnittest, grit.format.policy_templates.writers.doc_writer_unittest. DocWriterUnittest, grit.format.policy_templates.writers.json_writer_unittest. JsonWriterUnittest, grit.format.policy_templates.writers.plist_strings_writer_unittest. PListStringsWriterUnittest, grit.format.policy_templates.writers.plist_writer_unittest. PListWriterUnittest, grit.format.policy_templates.writers.reg_writer_unittest. RegWriterUnittest, grit.format.policy_templates.writers.template_writer_unittest. TemplateWriterUnittests, grit.format.policy_templates.writers.xml_writer_base_unittest. XmlWriterBaseTest, grit.gather.admin_template_unittest.AdmGathererUnittest, grit.gather.chrome_html_unittest.ChromeHtmlUnittest, grit.gather.chrome_scaled_image_unittest.ChromeScaledImageUnittest, grit.gather.igoogle_strings_unittest.IgoogleStringsUnittest, grit.gather.muppet_strings_unittest.MuppetStringsUnittest, grit.gather.policy_json_unittest.PolicyJsonUnittest, grit.gather.rc_unittest.RcUnittest, grit.gather.tr_html_unittest.ParserUnittest, grit.gather.tr_html_unittest.TrHtmlUnittest, grit.gather.txt_unittest.TxtUnittest, grit.node.base_unittest.NodeUnittest, grit.node.io_unittest.FileNodeUnittest, grit.node.include_unittest.IncludeNodeUnittest, grit.node.message_unittest.MessageUnittest, grit.node.misc_unittest.GritNodeUnittest, grit.node.misc_unittest.IfNodeUnittest, grit.node.misc_unittest.ReleaseNodeUnittest, grit.node.structure_unittest.StructureUnittest, grit.node.custom.filename_unittest.WindowsFilenameUnittest, grit.tool.android2grd_unittest.Android2GrdUnittest, grit.tool.build_unittest.BuildUnittest, grit.tool.buildinfo_unittest.BuildInfoUnittest, grit.tool.postprocess_unittest.PostProcessingUnittest, grit.tool.preprocess_unittest.PreProcessingUnittest, grit.tool.rc2grd_unittest.Rc2GrdUnittest, grit.tool.transl2tc_unittest.TranslationToTcUnittest, grit.tool.xmb_unittest.XmbUnittest, # add test classes here, in alphabetical order... ] for test_class in test_classes: self.addTest(unittest.makeSuite(test_class)) if __name__ == '__main__': test_result = unittest.TextTestRunner(verbosity=2).run(TestSuiteAll()) sys.exit(len(test_result.errors) + len(test_result.failures))
bsd-2-clause
lilydjwg/you-get
src/you_get/extractors/netease.py
1
9738
#!/usr/bin/env python from json import loads import hashlib import base64 import os import binascii try: from Crypto.Cipher import AES import xml.etree.ElementTree as ET has_crypto = True except ImportError: has_crypto = False from ..common import * from ..extractor import VideoExtractor from ..util import log def netease_hymn(): return """ player's Game Over, u can abandon. u get pissed, get pissed, Hallelujah my King! errr oh! fuck ohhh!!!! """ def encrypted_id(dfsId): x = [ord(i[0]) for i in netease_hymn().split()] y = ''.join([chr(i - 61) if i > 96 else chr(i + 32) for i in x]) byte1 = bytearray(y, encoding='ascii') byte2 = bytearray(str(dfsId), encoding='ascii') for i in range(len(byte2)): byte2[i] ^= byte1[i % len(byte1)] m = hashlib.md5() m.update(byte2) result = base64.b64encode(m.digest()).decode('ascii') result = result.replace('/', '_') result = result.replace('+', '-') return result def make_url(songNet, dfsId): encId = encrypted_id(dfsId) mp3_url = "http://%s/%s/%s.mp3" % (songNet, encId, dfsId) return mp3_url # for http://open.163.com/movie/2014/12/I/9/MAD7EMDVE_MAD7K95I9.html keys = ["4fxGZqoGmesXqg2o", "3fxVNqoPmesAqg2o"] def decrypto_video_url(data, whichkey): key = keys[whichkey - 1] cipher = AES.new(key, mode=AES.MODE_ECB) ciphertext = binascii.a2b_hex(data) cleartext = cipher.decrypt(ciphertext) padding = cleartext[-1] cleartext = cleartext[:-padding] return cleartext.decode('ascii') class NetEase(VideoExtractor): # test URLs: # http://live.ws.126.net/movie/I/9/2_MAD7EMDVE_MAD7K95I9.xml # http://live.ws.126.net/movie/V/H/2_MB3M6LDG1_MB3OBKTVH.xml name = '网易' if has_crypto: stream_types = [ {'id': 'SHD', 'video_profile': '超清'}, {'id': 'HD', 'video_profile': '高清'}, {'id': 'SD', 'video_profile': '标清'}, ] else: stream_types = [ {'id': 'default'}, ] def prepare(self, **kwargs): # compatibility for _cloud_music_prepare self.output_dir = kwargs.get('output_dir') self.info_only = kwargs.get('info_only') self.subs = [] self.lyrics = None url = self.url if "163.fm" in url: url = get_location(url) if "music.163.com" in url: self._cloud_music_prepare(url) elif has_crypto: self._crypto_prepare(url) else: log.w('PyCrypto not found, ' 'high resolution videos may be unavailable.') self._legacy_prepare(url) def _crypto_prepare(self, url): if url.startswith('http://swf.ws.126.net/openplayer/'): video_id = url.split('-')[2] assert video_id.startswith('2_') video_id = video_id[2:] else: # http://open.163.com/movie/2015/10/V/H/MB3M6LDG1_MB3OBKTVH.html video_id = url.split('/')[-1].split('.')[0] xml = self._get_xml_for_video_id(video_id) encrypt_key = int(xml.find('encrypt').text) playurl = xml.find('playurl_origin') if len(playurl) == 0: playurl = xml.find('playurl') streams = {} for stream in self.stream_types: e = playurl.find('./%s/mp4' % stream['id']) if e is not None: url = decrypto_video_url(e.text, encrypt_key) streams[stream['id']] = { 'url': url, 'video_profile': stream['video_profile'], 'size': url_size(url), } self.streams = streams for sub in xml.findall('subs/*'): name = sub.find('name').text url = sub.find('url').text self.subs.append((name, url)) def _legacy_prepare(self, url): if url.startswith('http://swf.ws.126.net/openplayer/'): video_id = url.split('-')[2] assert video_id.startswith('2_') video_id = video_id[2:] xml = self._get_xml_for_video_id(video_id) url = xml.find('pageUrl').text html = get_decoded_html(url) title = match1(html, "movieDescription='([^']+)'") or \ match1(html, '<title>(.+)</title>') self.title = title.strip() src = match1(html, r'<source src="([^"]+)"') or \ match1(html, r'<source type="[^"]+" src="([^"]+)"') if src: url = src else: url = (match1(html, r'["\'](.+)-list.m3u8["\']') or match1(html, r'["\'](.+).m3u8["\']')) + ".mp4" self.streams['default'] = { 'url': url, } def _cloud_music_prepare(self, url): rid = match1(url, r'id=(.*)') output_dir = self.output_dir info_only = self.info_only if rid is None: rid = match1(url, r'/(\d+)/?$') if "album" in url: # FIXME: only last is processed j = loads(get_content("http://music.163.com/api/album/%s?id=%s&csrf_token=" % (rid, rid), headers={"Referer": "http://music.163.com/"})) artist_name = j['album']['artists'][0]['name'] album_name = j['album']['name'] new_dir = output_dir + '/' + "%s - %s" % (artist_name, album_name) if not os.path.exists(new_dir): os.mkdir(new_dir) if not info_only: cover_url = j['album']['picUrl'] download_urls([cover_url], "cover", "jpg", 0, new_dir) for i in j['album']['songs']: self._song_prepare(i) try: # download lyrics assert kwargs['caption'] l = loads(get_content("http://music.163.com/api/song/lyric/?id=%s&lv=-1&csrf_token=" % i['id'], headers={"Referer": "http://music.163.com/"})) self._lyrics_prepare(i, l["lrc"]["lyric"]) except: pass elif "playlist" in url: # FIXME: only last is processed j = loads(get_content("http://music.163.com/api/playlist/detail?id=%s&csrf_token=" % rid, headers={"Referer": "http://music.163.com/"})) new_dir = output_dir + '/' + j['result']['name'] if not os.path.exists(new_dir): os.mkdir(new_dir) if not info_only: cover_url = j['result']['coverImgUrl'] download_urls([cover_url], "cover", "jpg", 0, new_dir) for i in j['result']['tracks']: self._song_prepare(i) try: # download lyrics assert kwargs['caption'] l = loads(get_content("http://music.163.com/api/song/lyric/?id=%s&lv=-1&csrf_token=" % i['id'], headers={"Referer": "http://music.163.com/"})) self._lyrics_prepare(i, l["lrc"]["lyric"]) except: pass elif "song" in url: j = loads(get_content("http://music.163.com/api/song/detail/?id=%s&ids=[%s]&csrf_token=" % (rid, rid), headers={"Referer": "http://music.163.com/"})) self._song_prepare(j["songs"][0]) try: # download lyrics l = loads(get_content("http://music.163.com/api/song/lyric/?id=%s&lv=-1&csrf_token=" % rid, headers={"Referer": "http://music.163.com/"})) self._lyrics_prepare(j["songs"][0], l["lrc"]["lyric"]) except: pass elif "mv" in url: j = loads(get_content("http://music.163.com/api/mv/detail/?id=%s&ids=[%s]&csrf_token=" % (rid, rid), headers={"Referer": "http://music.163.com/"})) self._video_prepare(j['data']) def _song_prepare(self, song): # test URL: http://music.163.com/#/song?id=29043459 self.title = "%s. %s" % (song['position'], song['name']) songNet = 'p' + song['mp3Url'].split('/')[2][1:] s = self.streams if 'hMusic' in song and song['hMusic'] is not None: s['hMusic'] = {'url': make_url(songNet, song['hMusic']['dfsId'])} if 'mp3Url' in song: s['mp3Url'] = {'url': song['mp3Url']} if 'bMusic' in song: s['bMusic'] = {'url': make_url(songNet, song['bMusic']['dfsId'])} self.stream_types = [ {'id': x} for x in ['hMusic', 'mp3Url', 'bMusic'] ] def _video_prepare(self, vinfo): # test URL: http://music.163.com/#/mv/343100/ self.title = "%s - %s" % (vinfo['name'], vinfo['artistName']) s = self.streams for bitrate, url in vinfo['brs'].items(): s[bitrate] = {'url': url} self.stream_types = [ {'id': x} for x in sorted(s, key=int, reverse=True) ] def _lyrics_prepare(self, song, lyrics): # test URL: http://music.163.com/#/song?id=29043459 title = "%s. %s" % (song['position'], song['name']) filename = '%s.lrc' % get_filename(title) self.plain_files.append({ 'filename': filename, 'content': lyrics, }) def _get_xml_for_video_id(self, vid): xml_url = 'http://live.ws.126.net/movie/%s/%s/2_%s.xml' % ( vid[-2], vid[-1], vid) xml = get_content(xml_url) e = ET.fromstring(xml) self.title = e.find('title').text return e def extract(self, **kwargs): for i in self.streams: s = self.streams[i] _, s['container'], s['size'] = url_info(s['url']) s['src'] = [s['url']] for name, url in self.subs: self.caption_tracks[name] = get_content(url) site = NetEase() download = site.download_by_url
mit
gregdek/ansible
test/units/modules/network/slxos/test_slxos_vlan.py
30
4622
# # (c) 2018 Extreme Networks Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # from __future__ import (absolute_import, division, print_function) __metaclass__ = type import re import json from units.compat.mock import patch from ansible.modules.network.slxos import slxos_vlan from units.modules.utils import set_module_args from .slxos_module import TestSlxosModule, load_fixture class TestSlxosVlanModule(TestSlxosModule): module = slxos_vlan def setUp(self): super(TestSlxosVlanModule, self).setUp() self._patch_run_commands = patch( 'ansible.modules.network.slxos.slxos_vlan.run_commands' ) self._patch_load_config = patch( 'ansible.modules.network.slxos.slxos_vlan.load_config' ) self._run_commands = self._patch_run_commands.start() self._load_config = self._patch_load_config.start() def tearDown(self): super(TestSlxosVlanModule, self).tearDown() self._patch_run_commands.stop() self._patch_load_config.stop() def load_fixtures(self, commands=None): config_file = 'show_vlan_brief' self._run_commands.return_value = [load_fixture(config_file)] self._load_config.return_value = None def test_slxos_vlan_id_with_name(self, *args, **kwargs): load_fixture('show_vlan_brief') set_module_args(dict( vlan_id=100, name='ONEHUNDRED' )) result = self.execute_module(changed=True) self.assertEqual( result, { 'commands': [ 'vlan 100', 'name ONEHUNDRED' ], 'changed': True } ) def test_slxos_vlan_with_members(self, *args, **kwargs): set_module_args(dict( vlan_id=100, name='ONEHUNDRED', interfaces=[ 'Ethernet 0/1', 'Ethernet 0/2' ] )) result = self.execute_module(changed=True) self.assertEqual( result, { 'commands': [ 'vlan 100', 'name ONEHUNDRED', 'interface Ethernet 0/1', 'switchport', 'switchport mode access', 'switchport access vlan 100', 'interface Ethernet 0/2', 'switchport', 'switchport mode access', 'switchport access vlan 100' ], 'changed': True } ) def test_slxos_vlan_state_absent(self, *args, **kwargs): set_module_args(dict( vlan_id=200, state='absent' )) result = self.execute_module(changed=True) self.assertEqual( result, { 'commands': [ 'no vlan 200' ], 'changed': True } ) def test_slxos_vlan_state_absent_nonexistant_vlan(self, *args, **kwargs): set_module_args(dict( vlan_id=100, state='absent' )) result = self.execute_module() self.assertEqual( result, { 'commands': [], 'changed': False } ) def test_slxos_interface_invalid_argument(self, *args, **kwargs): set_module_args(dict( name='Ethernet 0/1', shawshank='Redemption' )) result = self.execute_module(failed=True) self.assertEqual(result['failed'], True) self.assertTrue(re.match( r'Unsupported parameters for \((basic.py|basic.pyc)\) module: ' 'shawshank Supported parameters include: aggregate, delay, ' 'interfaces, name, purge, state, vlan_id', result['msg'] ), 'Result did not match expected output. Got: %s' % result['msg'])
gpl-3.0
ar7z1/ansible
lib/ansible/modules/network/f5/bigip_iapplx_package.py
9
11731
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2017 F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified'} DOCUMENTATION = r''' --- module: bigip_iapplx_package short_description: Manages Javascript iApp packages on a BIG-IP description: - Manages Javascript iApp packages on a BIG-IP. This module will allow you to deploy iAppLX packages to the BIG-IP and manage their lifecycle. version_added: 2.5 options: package: description: - The iAppLX package that you want to upload or remove. When C(state) is C(present), and you intend to use this module in a C(role), it is recommended that you use the C({{ role_path }}) variable. An example is provided in the C(EXAMPLES) section. - When C(state) is C(absent), it is not necessary for the package to exist on the Ansible controller. If the full path to the package is provided, the fileame will specifically be cherry picked from it to properly remove the package. state: description: - Whether the iAppLX package should exist or not. default: present choices: - present - absent notes: - Requires the rpm tool be installed on the host. This can be accomplished through different ways on each platform. On Debian based systems with C(apt); C(apt-get install rpm). On Mac with C(brew); C(brew install rpm). This command is already present on RedHat based systems. - Requires BIG-IP >= 12.1.0 because the required functionality is missing on versions earlier than that. requirements: - Requires BIG-IP >= 12.1.0 - The 'rpm' tool installed on the Ansible controller extends_documentation_fragment: f5 author: - Tim Rupp (@caphrim007) ''' EXAMPLES = r''' - name: Add an iAppLX package bigip_iapplx_package: package: MyApp-0.1.0-0001.noarch.rpm password: secret server: lb.mydomain.com state: present user: admin delegate_to: localhost - name: Add an iAppLX package stored in a role bigip_iapplx_package: package: "{{ roles_path }}/files/MyApp-0.1.0-0001.noarch.rpm'" password: secret server: lb.mydomain.com state: present user: admin delegate_to: localhost - name: Remove an iAppLX package bigip_iapplx_package: package: MyApp-0.1.0-0001.noarch.rpm password: secret server: lb.mydomain.com state: absent user: admin delegate_to: localhost ''' RETURN = r''' # only common fields returned ''' import os import time from ansible.module_utils.basic import AnsibleModule from distutils.version import LooseVersion try: from library.module_utils.network.f5.bigip import HAS_F5SDK from library.module_utils.network.f5.bigip import F5Client from library.module_utils.network.f5.common import F5ModuleError from library.module_utils.network.f5.common import AnsibleF5Parameters from library.module_utils.network.f5.common import cleanup_tokens from library.module_utils.network.f5.common import f5_argument_spec try: from library.module_utils.network.f5.common import iControlUnexpectedHTTPError except ImportError: HAS_F5SDK = False except ImportError: from ansible.module_utils.network.f5.bigip import HAS_F5SDK from ansible.module_utils.network.f5.bigip import F5Client from ansible.module_utils.network.f5.common import F5ModuleError from ansible.module_utils.network.f5.common import AnsibleF5Parameters from ansible.module_utils.network.f5.common import cleanup_tokens from ansible.module_utils.network.f5.common import f5_argument_spec try: from ansible.module_utils.network.f5.common import iControlUnexpectedHTTPError except ImportError: HAS_F5SDK = False class Parameters(AnsibleF5Parameters): api_attributes = [] returnables = [] @property def package(self): if self._values['package'] is None: return None return self._values['package'] @property def package_file(self): if self._values['package'] is None: return None return os.path.basename(self._values['package']) @property def package_name(self): """Return a valid name for the package BIG-IP determines the package name by the content of the RPM info. It does not use the filename. Therefore, we do the same. This method is only used though when the file actually exists on your Ansible controller. If the package does not exist, then we instead use the filename portion of the 'package' argument that is provided. Non-existence typically occurs when using 'state' = 'absent' :return: """ cmd = ['rpm', '-qp', '--queryformat', '%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}', self.package] rc, out, err = self._module.run_command(cmd) if not out: return str(self.package_file) return out @property def package_root(self): if self._values['package'] is None: return None base = os.path.basename(self._values['package']) result = os.path.splitext(base) return result[0] def to_return(self): result = {} try: for returnable in self.returnables: result[returnable] = getattr(self, returnable) result = self._filter_params(result) except Exception: pass return result class ModuleManager(object): def __init__(self, *args, **kwargs): self.module = kwargs.get('module', None) self.client = kwargs.get('client', None) self.want = Parameters(module=self.module, params=self.module.params) self.changes = Parameters() def exec_module(self): result = dict() changed = False state = self.want.state version = self.client.api.tmos_version if LooseVersion(version) <= LooseVersion('12.0.0'): raise F5ModuleError( "This version of BIG-IP is not supported." ) try: if state == "present": changed = self.present() elif state == "absent": changed = self.absent() except iControlUnexpectedHTTPError as e: raise F5ModuleError(str(e)) changes = self.changes.to_return() result.update(**changes) result.update(dict(changed=changed)) return result def present(self): if self.exists(): return False else: return self.create() def absent(self): changed = False if self.exists(): changed = self.remove() return changed def exists(self): exists = False packages = self.get_installed_packages_on_device() if os.path.exists(self.want.package): exists = True for package in packages: if exists: if self.want.package_name == package['packageName']: return True else: if self.want.package_root == package['packageName']: return True return False def get_installed_packages_on_device(self): collection = self.client.api.shared.iapp.package_management_tasks_s task = collection.package_management_task.create( operation='QUERY' ) status = self._wait_for_task(task) if status == 'FINISHED': return task.queryResponse raise F5ModuleError( "Failed to find the installed packages on the device" ) def create(self): if self.module.check_mode: return True if not os.path.exists(self.want.package): if self.want.package.startswith('/'): raise F5ModuleError( "The specified iAppLX package was not found at {0}.".format(self.want.package) ) else: raise F5ModuleError( "The specified iAppLX package was not found in {0}.".format(os.getcwd()) ) self.upload_to_device() self.create_on_device() self.enable_iapplx_on_device() self.remove_package_file_from_device() if self.exists(): return True else: raise F5ModuleError("Failed to create the iApp template") def upload_to_device(self): upload = self.client.api.shared.file_transfer.uploads upload.upload_file( self.want.package ) def remove_package_file_from_device(self): self.client.api.tm.util.unix_rm.exec_cmd( 'run', utilCmdArgs="/var/config/rest/downloads/{0}".format(self.want.package_file) ) def create_on_device(self): remote_path = "/var/config/rest/downloads/{0}".format(self.want.package_file) collection = self.client.api.shared.iapp.package_management_tasks_s task = collection.package_management_task.create( operation='INSTALL', packageFilePath=remote_path ) status = self._wait_for_task(task) if status == 'FINISHED': return True else: raise F5ModuleError(task.errorMessage) def remove(self): if self.module.check_mode: return True self.remove_from_device() if self.exists(): raise F5ModuleError("Failed to delete the iAppLX package") return True def remove_from_device(self): collection = self.client.api.shared.iapp.package_management_tasks_s task = collection.package_management_task.create( operation='UNINSTALL', packageName=self.want.package_root ) status = self._wait_for_task(task) if status == 'FINISHED': return True return False def _wait_for_task(self, task): for x in range(0, 60): task.refresh() if task.status in ['FINISHED', 'FAILED']: return task.status time.sleep(1) return task.status def enable_iapplx_on_device(self): self.client.api.tm.util.bash.exec_cmd( 'run', utilCmdArgs='-c "touch /var/config/rest/iapps/enable"' ) class ArgumentSpec(object): def __init__(self): self.supports_check_mode = True argument_spec = dict( state=dict( default='present', choices=['present', 'absent'] ), package=dict() ) self.argument_spec = {} self.argument_spec.update(f5_argument_spec) self.argument_spec.update(argument_spec) self.required_if = [ ['state', 'present', ['package']] ] def main(): spec = ArgumentSpec() module = AnsibleModule( argument_spec=spec.argument_spec, supports_check_mode=spec.supports_check_mode, required_if=spec.required_if ) if not HAS_F5SDK: module.fail_json(msg="The python f5-sdk module is required") try: client = F5Client(**module.params) mm = ModuleManager(module=module, client=client) results = mm.exec_module() cleanup_tokens(client) module.exit_json(**results) except F5ModuleError as e: cleanup_tokens(client) module.fail_json(msg=str(e)) if __name__ == '__main__': main()
gpl-3.0
heeraj123/oh-mainline
vendor/packages/zope.interface/setup.py
16
4974
############################################################################## # # Copyright (c) 2004-2007 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (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. # ############################################################################## # This package is developed by the Zope Toolkit project, documented here: # http://docs.zope.org/zopetoolkit # When developing and releasing this package, please follow the documented # Zope Toolkit policies as described by this documentation. ############################################################################## """Setup for zope.interface package """ import os import platform import sys try: from setuptools import setup, Extension, Feature except ImportError: # do we need to support plain distutils for building when even # the package itself requires setuptools for installing? from distutils.core import setup, Extension if sys.version_info[:2] >= (2, 4): extra = dict( package_data={ 'zope.interface': ['*.txt'], 'zope.interface.tests': ['*.txt'], } ) else: extra = {} else: codeoptimization_c = os.path.join('src', 'zope', 'interface', '_zope_interface_coptimizations.c') codeoptimization = Feature( "Optional code optimizations", standard = True, ext_modules = [Extension( "zope.interface._zope_interface_coptimizations", [os.path.normcase(codeoptimization_c)] )]) py_impl = getattr(platform, 'python_implementation', lambda: None) is_pypy = py_impl() == 'PyPy' is_jython = 'java' in sys.platform # Jython cannot build the C optimizations, while on PyPy they are # anti-optimizations (the C extension compatibility layer is known-slow, # and defeats JIT opportunities). if is_pypy or is_jython: features = {} else: features = {'codeoptimization': codeoptimization} extra = dict( namespace_packages=["zope"], include_package_data = True, zip_safe = False, tests_require = ['zope.event'], install_requires = ['setuptools'], extras_require={'docs': ['z3c.recipe.sphinxdoc'], 'test': ['zope.event']}, features = features ) def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() long_description=( read('README.txt') + '\n' + read('CHANGES.txt') ) try: # Zope setuptools versions from build_ext_3 import optional_build_ext # This is Python 3. Setuptools is now required, and so is zope.fixers. extra['install_requires'] = ['setuptools'] extra['setup_requires'] = ['zope.fixers'] extra['use_2to3'] = True extra['convert_2to3_doctests'] = [ 'src/zope/interface/README.ru.txt', 'src/zope/interface/README.txt', 'src/zope/interface/adapter.ru.txt', 'src/zope/interface/adapter.txt', 'src/zope/interface/human.ru.txt', 'src/zope/interface/human.txt', 'src/zope/interface/index.txt', 'src/zope/interface/verify.txt', ] extra['use_2to3_fixers'] = ['zope.fixers'] except (ImportError, SyntaxError): from build_ext_2 import optional_build_ext setup(name='zope.interface', version='3.8.0', url='http://pypi.python.org/pypi/zope.interface', license='ZPL 2.1', description='Interfaces for Python', author='Zope Foundation and Contributors', author_email='zope-dev@zope.org', long_description=long_description, classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: Zope Public License", "Operating System :: OS Independent", "Programming Language :: Python :: 2.4", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.1", "Programming Language :: Python :: 3.2", "Topic :: Software Development :: Libraries :: Python Modules", ], packages = ['zope', 'zope.interface', 'zope.interface.tests'], package_dir = {'': 'src'}, cmdclass = {'build_ext': optional_build_ext, }, test_suite = 'zope.interface.tests', **extra)
agpl-3.0
p0psicles/SickRage
lib/feedparser/parsers/loose.py
43
3425
# The loose feed parser that interfaces with an SGML parsing library # Copyright 2010-2015 Kurt McKee <contactme@kurtmckee.org> # Copyright 2002-2008 Mark Pilgrim # All rights reserved. # # This file is a part of feedparser. # # 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. # # 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. from __future__ import absolute_import, unicode_literals class _LooseFeedParser(object): def __init__(self, baseuri=None, baselang=None, encoding=None, entities=None): self.baseuri = baseuri or '' self.lang = baselang or None self.encoding = encoding or 'utf-8' # character encoding self.entities = entities or {} super(_LooseFeedParser, self).__init__() def _normalize_attributes(self, kv): k = kv[0].lower() v = k in ('rel', 'type') and kv[1].lower() or kv[1] # the sgml parser doesn't handle entities in attributes, nor # does it pass the attribute values through as unicode, while # strict xml parsers do -- account for this difference v = v.replace('&amp;', '&') return (k, v) def decodeEntities(self, element, data): data = data.replace('&#60;', '&lt;') data = data.replace('&#x3c;', '&lt;') data = data.replace('&#x3C;', '&lt;') data = data.replace('&#62;', '&gt;') data = data.replace('&#x3e;', '&gt;') data = data.replace('&#x3E;', '&gt;') data = data.replace('&#38;', '&amp;') data = data.replace('&#x26;', '&amp;') data = data.replace('&#34;', '&quot;') data = data.replace('&#x22;', '&quot;') data = data.replace('&#39;', '&apos;') data = data.replace('&#x27;', '&apos;') if not self.contentparams.get('type', 'xml').endswith('xml'): data = data.replace('&lt;', '<') data = data.replace('&gt;', '>') data = data.replace('&amp;', '&') data = data.replace('&quot;', '"') data = data.replace('&apos;', "'") data = data.replace('&#x2f;', '/') data = data.replace('&#x2F;', '/') return data def strattrs(self, attrs): return ''.join([' %s="%s"' % (n,v.replace('"','&quot;')) for n,v in attrs])
gpl-3.0
jnovinger/django
tests/lookup/tests.py
153
37208
from __future__ import unicode_literals from datetime import datetime from operator import attrgetter from unittest import skipUnless from django.core.exceptions import FieldError from django.db import connection from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature from .models import Article, Author, Game, MyISAMArticle, Player, Season, Tag class LookupTests(TestCase): def setUp(self): # Create a few Authors. self.au1 = Author(name='Author 1') self.au1.save() self.au2 = Author(name='Author 2') self.au2.save() # Create a couple of Articles. self.a1 = Article(headline='Article 1', pub_date=datetime(2005, 7, 26), author=self.au1) self.a1.save() self.a2 = Article(headline='Article 2', pub_date=datetime(2005, 7, 27), author=self.au1) self.a2.save() self.a3 = Article(headline='Article 3', pub_date=datetime(2005, 7, 27), author=self.au1) self.a3.save() self.a4 = Article(headline='Article 4', pub_date=datetime(2005, 7, 28), author=self.au1) self.a4.save() self.a5 = Article(headline='Article 5', pub_date=datetime(2005, 8, 1, 9, 0), author=self.au2) self.a5.save() self.a6 = Article(headline='Article 6', pub_date=datetime(2005, 8, 1, 8, 0), author=self.au2) self.a6.save() self.a7 = Article(headline='Article 7', pub_date=datetime(2005, 7, 27), author=self.au2) self.a7.save() # Create a few Tags. self.t1 = Tag(name='Tag 1') self.t1.save() self.t1.articles.add(self.a1, self.a2, self.a3) self.t2 = Tag(name='Tag 2') self.t2.save() self.t2.articles.add(self.a3, self.a4, self.a5) self.t3 = Tag(name='Tag 3') self.t3.save() self.t3.articles.add(self.a5, self.a6, self.a7) def test_exists(self): # We can use .exists() to check that there are some self.assertTrue(Article.objects.exists()) for a in Article.objects.all(): a.delete() # There should be none now! self.assertFalse(Article.objects.exists()) def test_lookup_int_as_str(self): # Integer value can be queried using string self.assertQuerysetEqual(Article.objects.filter(id__iexact=str(self.a1.id)), ['<Article: Article 1>']) @skipUnlessDBFeature('supports_date_lookup_using_string') def test_lookup_date_as_str(self): # A date lookup can be performed using a string search self.assertQuerysetEqual(Article.objects.filter(pub_date__startswith='2005'), [ '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ]) def test_iterator(self): # Each QuerySet gets iterator(), which is a generator that "lazily" # returns results using database-level iteration. self.assertQuerysetEqual(Article.objects.iterator(), [ 'Article 5', 'Article 6', 'Article 4', 'Article 2', 'Article 3', 'Article 7', 'Article 1', ], transform=attrgetter('headline')) # iterator() can be used on any QuerySet. self.assertQuerysetEqual( Article.objects.filter(headline__endswith='4').iterator(), ['Article 4'], transform=attrgetter('headline')) def test_count(self): # count() returns the number of objects matching search criteria. self.assertEqual(Article.objects.count(), 7) self.assertEqual(Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).count(), 3) self.assertEqual(Article.objects.filter(headline__startswith='Blah blah').count(), 0) # count() should respect sliced query sets. articles = Article.objects.all() self.assertEqual(articles.count(), 7) self.assertEqual(articles[:4].count(), 4) self.assertEqual(articles[1:100].count(), 6) self.assertEqual(articles[10:100].count(), 0) # Date and date/time lookups can also be done with strings. self.assertEqual(Article.objects.filter(pub_date__exact='2005-07-27 00:00:00').count(), 3) def test_in_bulk(self): # in_bulk() takes a list of IDs and returns a dictionary mapping IDs to objects. arts = Article.objects.in_bulk([self.a1.id, self.a2.id]) self.assertEqual(arts[self.a1.id], self.a1) self.assertEqual(arts[self.a2.id], self.a2) self.assertEqual(Article.objects.in_bulk([self.a3.id]), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk({self.a3.id}), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk(frozenset([self.a3.id])), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk((self.a3.id,)), {self.a3.id: self.a3}) self.assertEqual(Article.objects.in_bulk([1000]), {}) self.assertEqual(Article.objects.in_bulk([]), {}) self.assertEqual(Article.objects.in_bulk(iter([self.a1.id])), {self.a1.id: self.a1}) self.assertEqual(Article.objects.in_bulk(iter([])), {}) self.assertRaises(TypeError, Article.objects.in_bulk) self.assertRaises(TypeError, Article.objects.in_bulk, headline__startswith='Blah') def test_values(self): # values() returns a list of dictionaries instead of object instances -- # and you can specify which fields you want to retrieve. identity = lambda x: x self.assertQuerysetEqual(Article.objects.values('headline'), [ {'headline': 'Article 5'}, {'headline': 'Article 6'}, {'headline': 'Article 4'}, {'headline': 'Article 2'}, {'headline': 'Article 3'}, {'headline': 'Article 7'}, {'headline': 'Article 1'}, ], transform=identity) self.assertQuerysetEqual( Article.objects.filter(pub_date__exact=datetime(2005, 7, 27)).values('id'), [{'id': self.a2.id}, {'id': self.a3.id}, {'id': self.a7.id}], transform=identity) self.assertQuerysetEqual(Article.objects.values('id', 'headline'), [ {'id': self.a5.id, 'headline': 'Article 5'}, {'id': self.a6.id, 'headline': 'Article 6'}, {'id': self.a4.id, 'headline': 'Article 4'}, {'id': self.a2.id, 'headline': 'Article 2'}, {'id': self.a3.id, 'headline': 'Article 3'}, {'id': self.a7.id, 'headline': 'Article 7'}, {'id': self.a1.id, 'headline': 'Article 1'}, ], transform=identity) # You can use values() with iterator() for memory savings, # because iterator() uses database-level iteration. self.assertQuerysetEqual(Article.objects.values('id', 'headline').iterator(), [ {'headline': 'Article 5', 'id': self.a5.id}, {'headline': 'Article 6', 'id': self.a6.id}, {'headline': 'Article 4', 'id': self.a4.id}, {'headline': 'Article 2', 'id': self.a2.id}, {'headline': 'Article 3', 'id': self.a3.id}, {'headline': 'Article 7', 'id': self.a7.id}, {'headline': 'Article 1', 'id': self.a1.id}, ], transform=identity) # The values() method works with "extra" fields specified in extra(select). self.assertQuerysetEqual( Article.objects.extra(select={'id_plus_one': 'id + 1'}).values('id', 'id_plus_one'), [ {'id': self.a5.id, 'id_plus_one': self.a5.id + 1}, {'id': self.a6.id, 'id_plus_one': self.a6.id + 1}, {'id': self.a4.id, 'id_plus_one': self.a4.id + 1}, {'id': self.a2.id, 'id_plus_one': self.a2.id + 1}, {'id': self.a3.id, 'id_plus_one': self.a3.id + 1}, {'id': self.a7.id, 'id_plus_one': self.a7.id + 1}, {'id': self.a1.id, 'id_plus_one': self.a1.id + 1}, ], transform=identity) data = { 'id_plus_one': 'id+1', 'id_plus_two': 'id+2', 'id_plus_three': 'id+3', 'id_plus_four': 'id+4', 'id_plus_five': 'id+5', 'id_plus_six': 'id+6', 'id_plus_seven': 'id+7', 'id_plus_eight': 'id+8', } self.assertQuerysetEqual( Article.objects.filter(id=self.a1.id).extra(select=data).values(*data.keys()), [{ 'id_plus_one': self.a1.id + 1, 'id_plus_two': self.a1.id + 2, 'id_plus_three': self.a1.id + 3, 'id_plus_four': self.a1.id + 4, 'id_plus_five': self.a1.id + 5, 'id_plus_six': self.a1.id + 6, 'id_plus_seven': self.a1.id + 7, 'id_plus_eight': self.a1.id + 8, }], transform=identity) # You can specify fields from forward and reverse relations, just like filter(). self.assertQuerysetEqual( Article.objects.values('headline', 'author__name'), [ {'headline': self.a5.headline, 'author__name': self.au2.name}, {'headline': self.a6.headline, 'author__name': self.au2.name}, {'headline': self.a4.headline, 'author__name': self.au1.name}, {'headline': self.a2.headline, 'author__name': self.au1.name}, {'headline': self.a3.headline, 'author__name': self.au1.name}, {'headline': self.a7.headline, 'author__name': self.au2.name}, {'headline': self.a1.headline, 'author__name': self.au1.name}, ], transform=identity) self.assertQuerysetEqual( Author.objects.values('name', 'article__headline').order_by('name', 'article__headline'), [ {'name': self.au1.name, 'article__headline': self.a1.headline}, {'name': self.au1.name, 'article__headline': self.a2.headline}, {'name': self.au1.name, 'article__headline': self.a3.headline}, {'name': self.au1.name, 'article__headline': self.a4.headline}, {'name': self.au2.name, 'article__headline': self.a5.headline}, {'name': self.au2.name, 'article__headline': self.a6.headline}, {'name': self.au2.name, 'article__headline': self.a7.headline}, ], transform=identity) self.assertQuerysetEqual( Author.objects.values('name', 'article__headline', 'article__tag__name').order_by('name', 'article__headline', 'article__tag__name'), [ {'name': self.au1.name, 'article__headline': self.a1.headline, 'article__tag__name': self.t1.name}, {'name': self.au1.name, 'article__headline': self.a2.headline, 'article__tag__name': self.t1.name}, {'name': self.au1.name, 'article__headline': self.a3.headline, 'article__tag__name': self.t1.name}, {'name': self.au1.name, 'article__headline': self.a3.headline, 'article__tag__name': self.t2.name}, {'name': self.au1.name, 'article__headline': self.a4.headline, 'article__tag__name': self.t2.name}, {'name': self.au2.name, 'article__headline': self.a5.headline, 'article__tag__name': self.t2.name}, {'name': self.au2.name, 'article__headline': self.a5.headline, 'article__tag__name': self.t3.name}, {'name': self.au2.name, 'article__headline': self.a6.headline, 'article__tag__name': self.t3.name}, {'name': self.au2.name, 'article__headline': self.a7.headline, 'article__tag__name': self.t3.name}, ], transform=identity) # However, an exception FieldDoesNotExist will be thrown if you specify # a non-existent field name in values() (a field that is neither in the # model nor in extra(select)). self.assertRaises(FieldError, Article.objects.extra(select={'id_plus_one': 'id + 1'}).values, 'id', 'id_plus_two') # If you don't specify field names to values(), all are returned. self.assertQuerysetEqual(Article.objects.filter(id=self.a5.id).values(), [{ 'id': self.a5.id, 'author_id': self.au2.id, 'headline': 'Article 5', 'pub_date': datetime(2005, 8, 1, 9, 0) }], transform=identity) def test_values_list(self): # values_list() is similar to values(), except that the results are # returned as a list of tuples, rather than a list of dictionaries. # Within each tuple, the order of the elements is the same as the order # of fields in the values_list() call. identity = lambda x: x self.assertQuerysetEqual(Article.objects.values_list('headline'), [ ('Article 5',), ('Article 6',), ('Article 4',), ('Article 2',), ('Article 3',), ('Article 7',), ('Article 1',), ], transform=identity) self.assertQuerysetEqual(Article.objects.values_list('id').order_by('id'), [(self.a1.id,), (self.a2.id,), (self.a3.id,), (self.a4.id,), (self.a5.id,), (self.a6.id,), (self.a7.id,)], transform=identity) self.assertQuerysetEqual( Article.objects.values_list('id', flat=True).order_by('id'), [self.a1.id, self.a2.id, self.a3.id, self.a4.id, self.a5.id, self.a6.id, self.a7.id], transform=identity) self.assertQuerysetEqual( Article.objects.extra(select={'id_plus_one': 'id+1'}) .order_by('id').values_list('id'), [(self.a1.id,), (self.a2.id,), (self.a3.id,), (self.a4.id,), (self.a5.id,), (self.a6.id,), (self.a7.id,)], transform=identity) self.assertQuerysetEqual( Article.objects.extra(select={'id_plus_one': 'id+1'}) .order_by('id').values_list('id_plus_one', 'id'), [ (self.a1.id + 1, self.a1.id), (self.a2.id + 1, self.a2.id), (self.a3.id + 1, self.a3.id), (self.a4.id + 1, self.a4.id), (self.a5.id + 1, self.a5.id), (self.a6.id + 1, self.a6.id), (self.a7.id + 1, self.a7.id) ], transform=identity) self.assertQuerysetEqual( Article.objects.extra(select={'id_plus_one': 'id+1'}) .order_by('id').values_list('id', 'id_plus_one'), [ (self.a1.id, self.a1.id + 1), (self.a2.id, self.a2.id + 1), (self.a3.id, self.a3.id + 1), (self.a4.id, self.a4.id + 1), (self.a5.id, self.a5.id + 1), (self.a6.id, self.a6.id + 1), (self.a7.id, self.a7.id + 1) ], transform=identity) self.assertQuerysetEqual( Author.objects.values_list('name', 'article__headline', 'article__tag__name').order_by('name', 'article__headline', 'article__tag__name'), [ (self.au1.name, self.a1.headline, self.t1.name), (self.au1.name, self.a2.headline, self.t1.name), (self.au1.name, self.a3.headline, self.t1.name), (self.au1.name, self.a3.headline, self.t2.name), (self.au1.name, self.a4.headline, self.t2.name), (self.au2.name, self.a5.headline, self.t2.name), (self.au2.name, self.a5.headline, self.t3.name), (self.au2.name, self.a6.headline, self.t3.name), (self.au2.name, self.a7.headline, self.t3.name), ], transform=identity) self.assertRaises(TypeError, Article.objects.values_list, 'id', 'headline', flat=True) def test_get_next_previous_by(self): # Every DateField and DateTimeField creates get_next_by_FOO() and # get_previous_by_FOO() methods. In the case of identical date values, # these methods will use the ID as a fallback check. This guarantees # that no records are skipped or duplicated. self.assertEqual(repr(self.a1.get_next_by_pub_date()), '<Article: Article 2>') self.assertEqual(repr(self.a2.get_next_by_pub_date()), '<Article: Article 3>') self.assertEqual(repr(self.a2.get_next_by_pub_date(headline__endswith='6')), '<Article: Article 6>') self.assertEqual(repr(self.a3.get_next_by_pub_date()), '<Article: Article 7>') self.assertEqual(repr(self.a4.get_next_by_pub_date()), '<Article: Article 6>') self.assertRaises(Article.DoesNotExist, self.a5.get_next_by_pub_date) self.assertEqual(repr(self.a6.get_next_by_pub_date()), '<Article: Article 5>') self.assertEqual(repr(self.a7.get_next_by_pub_date()), '<Article: Article 4>') self.assertEqual(repr(self.a7.get_previous_by_pub_date()), '<Article: Article 3>') self.assertEqual(repr(self.a6.get_previous_by_pub_date()), '<Article: Article 4>') self.assertEqual(repr(self.a5.get_previous_by_pub_date()), '<Article: Article 6>') self.assertEqual(repr(self.a4.get_previous_by_pub_date()), '<Article: Article 7>') self.assertEqual(repr(self.a3.get_previous_by_pub_date()), '<Article: Article 2>') self.assertEqual(repr(self.a2.get_previous_by_pub_date()), '<Article: Article 1>') def test_escaping(self): # Underscores, percent signs and backslashes have special meaning in the # underlying SQL code, but Django handles the quoting of them automatically. a8 = Article(headline='Article_ with underscore', pub_date=datetime(2005, 11, 20)) a8.save() self.assertQuerysetEqual(Article.objects.filter(headline__startswith='Article'), [ '<Article: Article_ with underscore>', '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ]) self.assertQuerysetEqual(Article.objects.filter(headline__startswith='Article_'), ['<Article: Article_ with underscore>']) a9 = Article(headline='Article% with percent sign', pub_date=datetime(2005, 11, 21)) a9.save() self.assertQuerysetEqual(Article.objects.filter(headline__startswith='Article'), [ '<Article: Article% with percent sign>', '<Article: Article_ with underscore>', '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ]) self.assertQuerysetEqual(Article.objects.filter(headline__startswith='Article%'), ['<Article: Article% with percent sign>']) a10 = Article(headline='Article with \\ backslash', pub_date=datetime(2005, 11, 22)) a10.save() self.assertQuerysetEqual(Article.objects.filter(headline__contains='\\'), ['<Article: Article with \ backslash>']) def test_exclude(self): Article.objects.create(headline='Article_ with underscore', pub_date=datetime(2005, 11, 20)) Article.objects.create(headline='Article% with percent sign', pub_date=datetime(2005, 11, 21)) Article.objects.create(headline='Article with \\ backslash', pub_date=datetime(2005, 11, 22)) # exclude() is the opposite of filter() when doing lookups: self.assertQuerysetEqual( Article.objects.filter(headline__contains='Article').exclude(headline__contains='with'), [ '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ]) self.assertQuerysetEqual(Article.objects.exclude(headline__startswith="Article_"), [ '<Article: Article with \\ backslash>', '<Article: Article% with percent sign>', '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ]) self.assertQuerysetEqual(Article.objects.exclude(headline="Article 7"), [ '<Article: Article with \\ backslash>', '<Article: Article% with percent sign>', '<Article: Article_ with underscore>', '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 1>', ]) def test_none(self): # none() returns a QuerySet that behaves like any other QuerySet object self.assertQuerysetEqual(Article.objects.none(), []) self.assertQuerysetEqual( Article.objects.none().filter(headline__startswith='Article'), []) self.assertQuerysetEqual( Article.objects.filter(headline__startswith='Article').none(), []) self.assertEqual(Article.objects.none().count(), 0) self.assertEqual( Article.objects.none().update(headline="This should not take effect"), 0) self.assertQuerysetEqual( [article for article in Article.objects.none().iterator()], []) def test_in(self): # using __in with an empty list should return an empty query set self.assertQuerysetEqual(Article.objects.filter(id__in=[]), []) self.assertQuerysetEqual(Article.objects.exclude(id__in=[]), [ '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 4>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 7>', '<Article: Article 1>', ]) def test_error_messages(self): # Programming errors are pointed out with nice error messages try: Article.objects.filter(pub_date_year='2005').count() self.fail('FieldError not raised') except FieldError as ex: self.assertEqual(str(ex), "Cannot resolve keyword 'pub_date_year' " "into field. Choices are: author, author_id, headline, " "id, pub_date, tag") try: Article.objects.filter(headline__starts='Article') self.fail('FieldError not raised') except FieldError as ex: self.assertEqual( str(ex), "Unsupported lookup 'starts' for CharField " "or join on the field not permitted.") def test_regex(self): # Create some articles with a bit more interesting headlines for testing field lookups: for a in Article.objects.all(): a.delete() now = datetime.now() a1 = Article(pub_date=now, headline='f') a1.save() a2 = Article(pub_date=now, headline='fo') a2.save() a3 = Article(pub_date=now, headline='foo') a3.save() a4 = Article(pub_date=now, headline='fooo') a4.save() a5 = Article(pub_date=now, headline='hey-Foo') a5.save() a6 = Article(pub_date=now, headline='bar') a6.save() a7 = Article(pub_date=now, headline='AbBa') a7.save() a8 = Article(pub_date=now, headline='baz') a8.save() a9 = Article(pub_date=now, headline='baxZ') a9.save() # zero-or-more self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'fo*'), ['<Article: f>', '<Article: fo>', '<Article: foo>', '<Article: fooo>']) self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'fo*'), [ '<Article: f>', '<Article: fo>', '<Article: foo>', '<Article: fooo>', '<Article: hey-Foo>', ]) # one-or-more self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'fo+'), ['<Article: fo>', '<Article: foo>', '<Article: fooo>']) # wildcard self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'fooo?'), ['<Article: foo>', '<Article: fooo>']) # leading anchor self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'^b'), ['<Article: bar>', '<Article: baxZ>', '<Article: baz>']) self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'^a'), ['<Article: AbBa>']) # trailing anchor self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'z$'), ['<Article: baz>']) self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'z$'), ['<Article: baxZ>', '<Article: baz>']) # character sets self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'ba[rz]'), ['<Article: bar>', '<Article: baz>']) self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'ba.[RxZ]'), ['<Article: baxZ>']) self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'ba[RxZ]'), ['<Article: bar>', '<Article: baxZ>', '<Article: baz>']) # and more articles: a10 = Article(pub_date=now, headline='foobar') a10.save() a11 = Article(pub_date=now, headline='foobaz') a11.save() a12 = Article(pub_date=now, headline='ooF') a12.save() a13 = Article(pub_date=now, headline='foobarbaz') a13.save() a14 = Article(pub_date=now, headline='zoocarfaz') a14.save() a15 = Article(pub_date=now, headline='barfoobaz') a15.save() a16 = Article(pub_date=now, headline='bazbaRFOO') a16.save() # alternation self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'oo(f|b)'), [ '<Article: barfoobaz>', '<Article: foobar>', '<Article: foobarbaz>', '<Article: foobaz>', ]) self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'oo(f|b)'), [ '<Article: barfoobaz>', '<Article: foobar>', '<Article: foobarbaz>', '<Article: foobaz>', '<Article: ooF>', ]) self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'^foo(f|b)'), ['<Article: foobar>', '<Article: foobarbaz>', '<Article: foobaz>']) # greedy matching self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'b.*az'), [ '<Article: barfoobaz>', '<Article: baz>', '<Article: bazbaRFOO>', '<Article: foobarbaz>', '<Article: foobaz>', ]) self.assertQuerysetEqual(Article.objects.filter(headline__iregex=r'b.*ar'), [ '<Article: bar>', '<Article: barfoobaz>', '<Article: bazbaRFOO>', '<Article: foobar>', '<Article: foobarbaz>', ]) @skipUnlessDBFeature('supports_regex_backreferencing') def test_regex_backreferencing(self): # grouping and backreferences now = datetime.now() a10 = Article(pub_date=now, headline='foobar') a10.save() a11 = Article(pub_date=now, headline='foobaz') a11.save() a12 = Article(pub_date=now, headline='ooF') a12.save() a13 = Article(pub_date=now, headline='foobarbaz') a13.save() a14 = Article(pub_date=now, headline='zoocarfaz') a14.save() a15 = Article(pub_date=now, headline='barfoobaz') a15.save() a16 = Article(pub_date=now, headline='bazbaRFOO') a16.save() self.assertQuerysetEqual(Article.objects.filter(headline__regex=r'b(.).*b\1'), ['<Article: barfoobaz>', '<Article: bazbaRFOO>', '<Article: foobarbaz>']) def test_regex_null(self): """ Ensure that a regex lookup does not fail on null/None values """ Season.objects.create(year=2012, gt=None) self.assertQuerysetEqual(Season.objects.filter(gt__regex=r'^$'), []) def test_regex_non_string(self): """ Ensure that a regex lookup does not fail on non-string fields """ Season.objects.create(year=2013, gt=444) self.assertQuerysetEqual(Season.objects.filter(gt__regex=r'^444$'), ['<Season: 2013>']) def test_regex_non_ascii(self): """ Ensure that a regex lookup does not trip on non-ASCII characters. """ Player.objects.create(name='\u2660') Player.objects.get(name__regex='\u2660') def test_nonfield_lookups(self): """ Ensure that a lookup query containing non-fields raises the proper exception. """ with self.assertRaises(FieldError): Article.objects.filter(headline__blahblah=99) with self.assertRaises(FieldError): Article.objects.filter(headline__blahblah__exact=99) with self.assertRaises(FieldError): Article.objects.filter(blahblah=99) def test_lookup_collision(self): """ Ensure that genuine field names don't collide with built-in lookup types ('year', 'gt', 'range', 'in' etc.). Refs #11670. """ # Here we're using 'gt' as a code number for the year, e.g. 111=>2009. season_2009 = Season.objects.create(year=2009, gt=111) season_2009.games.create(home="Houston Astros", away="St. Louis Cardinals") season_2010 = Season.objects.create(year=2010, gt=222) season_2010.games.create(home="Houston Astros", away="Chicago Cubs") season_2010.games.create(home="Houston Astros", away="Milwaukee Brewers") season_2010.games.create(home="Houston Astros", away="St. Louis Cardinals") season_2011 = Season.objects.create(year=2011, gt=333) season_2011.games.create(home="Houston Astros", away="St. Louis Cardinals") season_2011.games.create(home="Houston Astros", away="Milwaukee Brewers") hunter_pence = Player.objects.create(name="Hunter Pence") hunter_pence.games = Game.objects.filter(season__year__in=[2009, 2010]) pudge = Player.objects.create(name="Ivan Rodriquez") pudge.games = Game.objects.filter(season__year=2009) pedro_feliz = Player.objects.create(name="Pedro Feliz") pedro_feliz.games = Game.objects.filter(season__year__in=[2011]) johnson = Player.objects.create(name="Johnson") johnson.games = Game.objects.filter(season__year__in=[2011]) # Games in 2010 self.assertEqual(Game.objects.filter(season__year=2010).count(), 3) self.assertEqual(Game.objects.filter(season__year__exact=2010).count(), 3) self.assertEqual(Game.objects.filter(season__gt=222).count(), 3) self.assertEqual(Game.objects.filter(season__gt__exact=222).count(), 3) # Games in 2011 self.assertEqual(Game.objects.filter(season__year=2011).count(), 2) self.assertEqual(Game.objects.filter(season__year__exact=2011).count(), 2) self.assertEqual(Game.objects.filter(season__gt=333).count(), 2) self.assertEqual(Game.objects.filter(season__gt__exact=333).count(), 2) self.assertEqual(Game.objects.filter(season__year__gt=2010).count(), 2) self.assertEqual(Game.objects.filter(season__gt__gt=222).count(), 2) # Games played in 2010 and 2011 self.assertEqual(Game.objects.filter(season__year__in=[2010, 2011]).count(), 5) self.assertEqual(Game.objects.filter(season__year__gt=2009).count(), 5) self.assertEqual(Game.objects.filter(season__gt__in=[222, 333]).count(), 5) self.assertEqual(Game.objects.filter(season__gt__gt=111).count(), 5) # Players who played in 2009 self.assertEqual(Player.objects.filter(games__season__year=2009).distinct().count(), 2) self.assertEqual(Player.objects.filter(games__season__year__exact=2009).distinct().count(), 2) self.assertEqual(Player.objects.filter(games__season__gt=111).distinct().count(), 2) self.assertEqual(Player.objects.filter(games__season__gt__exact=111).distinct().count(), 2) # Players who played in 2010 self.assertEqual(Player.objects.filter(games__season__year=2010).distinct().count(), 1) self.assertEqual(Player.objects.filter(games__season__year__exact=2010).distinct().count(), 1) self.assertEqual(Player.objects.filter(games__season__gt=222).distinct().count(), 1) self.assertEqual(Player.objects.filter(games__season__gt__exact=222).distinct().count(), 1) # Players who played in 2011 self.assertEqual(Player.objects.filter(games__season__year=2011).distinct().count(), 2) self.assertEqual(Player.objects.filter(games__season__year__exact=2011).distinct().count(), 2) self.assertEqual(Player.objects.filter(games__season__gt=333).distinct().count(), 2) self.assertEqual(Player.objects.filter(games__season__year__gt=2010).distinct().count(), 2) self.assertEqual(Player.objects.filter(games__season__gt__gt=222).distinct().count(), 2) def test_chain_date_time_lookups(self): self.assertQuerysetEqual( Article.objects.filter(pub_date__month__gt=7), ['<Article: Article 5>', '<Article: Article 6>'], ordered=False ) self.assertQuerysetEqual( Article.objects.filter(pub_date__day__gte=27), ['<Article: Article 2>', '<Article: Article 3>', '<Article: Article 4>', '<Article: Article 7>'], ordered=False ) self.assertQuerysetEqual( Article.objects.filter(pub_date__hour__lt=8), ['<Article: Article 1>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 4>', '<Article: Article 7>'], ordered=False ) self.assertQuerysetEqual( Article.objects.filter(pub_date__minute__lte=0), ['<Article: Article 1>', '<Article: Article 2>', '<Article: Article 3>', '<Article: Article 4>', '<Article: Article 5>', '<Article: Article 6>', '<Article: Article 7>'], ordered=False ) class LookupTransactionTests(TransactionTestCase): available_apps = ['lookup'] @skipUnless(connection.vendor == 'mysql', 'requires MySQL') def test_mysql_lookup_search(self): # To use fulltext indexes on MySQL either version 5.6 is needed, or one must use # MyISAM tables. Neither of these combinations is currently available on CI, so # lets manually create a MyISAM table for Article model. with connection.cursor() as cursor: cursor.execute( "CREATE TEMPORARY TABLE myisam_article (" " id INTEGER PRIMARY KEY AUTO_INCREMENT, " " headline VARCHAR(100) NOT NULL " ") ENGINE MYISAM") dr = MyISAMArticle.objects.create(headline='Django Reinhardt') MyISAMArticle.objects.create(headline='Ringo Star') # NOTE: Needs to be created after the article has been saved. cursor.execute( 'CREATE FULLTEXT INDEX myisam_article_ft ON myisam_article (headline)') self.assertQuerysetEqual( MyISAMArticle.objects.filter(headline__search='Reinhardt'), [dr], lambda x: x)
bsd-3-clause
wemanuel/smry
server-auth/ls/google-cloud-sdk/lib/requests/packages/urllib3/contrib/ntlmpool.py
1010
4507
""" NTLM authenticating pool, contributed by erikcederstran Issue #10, see: http://code.google.com/p/urllib3/issues/detail?id=10 """ try: from http.client import HTTPSConnection except ImportError: from httplib import HTTPSConnection from logging import getLogger from ntlm import ntlm from urllib3 import HTTPSConnectionPool log = getLogger(__name__) class NTLMConnectionPool(HTTPSConnectionPool): """ Implements an NTLM authentication version of an urllib3 connection pool """ scheme = 'https' def __init__(self, user, pw, authurl, *args, **kwargs): """ authurl is a random URL on the server that is protected by NTLM. user is the Windows user, probably in the DOMAIN\\username format. pw is the password for the user. """ super(NTLMConnectionPool, self).__init__(*args, **kwargs) self.authurl = authurl self.rawuser = user user_parts = user.split('\\', 1) self.domain = user_parts[0].upper() self.user = user_parts[1] self.pw = pw def _new_conn(self): # Performs the NTLM handshake that secures the connection. The socket # must be kept open while requests are performed. self.num_connections += 1 log.debug('Starting NTLM HTTPS connection no. %d: https://%s%s' % (self.num_connections, self.host, self.authurl)) headers = {} headers['Connection'] = 'Keep-Alive' req_header = 'Authorization' resp_header = 'www-authenticate' conn = HTTPSConnection(host=self.host, port=self.port) # Send negotiation message headers[req_header] = ( 'NTLM %s' % ntlm.create_NTLM_NEGOTIATE_MESSAGE(self.rawuser)) log.debug('Request headers: %s' % headers) conn.request('GET', self.authurl, None, headers) res = conn.getresponse() reshdr = dict(res.getheaders()) log.debug('Response status: %s %s' % (res.status, res.reason)) log.debug('Response headers: %s' % reshdr) log.debug('Response data: %s [...]' % res.read(100)) # Remove the reference to the socket, so that it can not be closed by # the response object (we want to keep the socket open) res.fp = None # Server should respond with a challenge message auth_header_values = reshdr[resp_header].split(', ') auth_header_value = None for s in auth_header_values: if s[:5] == 'NTLM ': auth_header_value = s[5:] if auth_header_value is None: raise Exception('Unexpected %s response header: %s' % (resp_header, reshdr[resp_header])) # Send authentication message ServerChallenge, NegotiateFlags = \ ntlm.parse_NTLM_CHALLENGE_MESSAGE(auth_header_value) auth_msg = ntlm.create_NTLM_AUTHENTICATE_MESSAGE(ServerChallenge, self.user, self.domain, self.pw, NegotiateFlags) headers[req_header] = 'NTLM %s' % auth_msg log.debug('Request headers: %s' % headers) conn.request('GET', self.authurl, None, headers) res = conn.getresponse() log.debug('Response status: %s %s' % (res.status, res.reason)) log.debug('Response headers: %s' % dict(res.getheaders())) log.debug('Response data: %s [...]' % res.read()[:100]) if res.status != 200: if res.status == 401: raise Exception('Server rejected request: wrong ' 'username or password') raise Exception('Wrong server response: %s %s' % (res.status, res.reason)) res.fp = None log.debug('Connection established') return conn def urlopen(self, method, url, body=None, headers=None, retries=3, redirect=True, assert_same_host=True): if headers is None: headers = {} headers['Connection'] = 'Keep-Alive' return super(NTLMConnectionPool, self).urlopen(method, url, body, headers, retries, redirect, assert_same_host)
apache-2.0
jlaunonen/kirppu
kirppu/views/csv_utils.py
1
1469
# -*- coding: utf-8 -*- import functools import html import io from urllib.parse import quote from django.conf import settings from django.http import HttpResponse, StreamingHttpResponse def strip_generator(fn): @functools.wraps(fn) def inner(output, event, generator=False): if generator: # Return the generator object only when using StringIO. return fn(output, event) for _ in fn(output, event): pass return inner def csv_streamer_view(request, generator, filename_base): debug = settings.DEBUG and request.GET.get("debug") is not None def streamer(): if debug: yield "<!DOCTYPE html>\n<html>\n<body>\n<pre>" output = io.StringIO() for a_string in generator(output): val = output.getvalue() if debug: yield html.escape(val, quote=False) else: yield val output.truncate(0) output.seek(0) if debug: yield "</pre>\n</body>\n</html>" if debug: response = HttpResponse("".join(streamer())) else: response = StreamingHttpResponse(streamer(), content_type="text/plain; charset=utf-8") if request.GET.get("download") is not None: response["Content-Disposition"] = 'attachment; filename="%s.csv"' % quote(filename_base, safe="") response["Content-Type"] = "text/csv; charset=utf-8" return response
mit
marziyeah/Medhacks_admin
full/node_modules/node-gyp/gyp/gyptest.py
1752
8019
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. __doc__ = """ gyptest.py -- test runner for GYP tests. """ import os import optparse import subprocess import sys class CommandRunner(object): """ Executor class for commands, including "commands" implemented by Python functions. """ verbose = True active = True def __init__(self, dictionary={}): self.subst_dictionary(dictionary) def subst_dictionary(self, dictionary): self._subst_dictionary = dictionary def subst(self, string, dictionary=None): """ Substitutes (via the format operator) the values in the specified dictionary into the specified command. The command can be an (action, string) tuple. In all cases, we perform substitution on strings and don't worry if something isn't a string. (It's probably a Python function to be executed.) """ if dictionary is None: dictionary = self._subst_dictionary if dictionary: try: string = string % dictionary except TypeError: pass return string def display(self, command, stdout=None, stderr=None): if not self.verbose: return if type(command) == type(()): func = command[0] args = command[1:] s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args))) if type(command) == type([]): # TODO: quote arguments containing spaces # TODO: handle meta characters? s = ' '.join(command) else: s = self.subst(command) if not s.endswith('\n'): s += '\n' sys.stdout.write(s) sys.stdout.flush() def execute(self, command, stdout=None, stderr=None): """ Executes a single command. """ if not self.active: return 0 if type(command) == type(''): command = self.subst(command) cmdargs = shlex.split(command) if cmdargs[0] == 'cd': command = (os.chdir,) + tuple(cmdargs[1:]) if type(command) == type(()): func = command[0] args = command[1:] return func(*args) else: if stdout is sys.stdout: # Same as passing sys.stdout, except python2.4 doesn't fail on it. subout = None else: # Open pipe for anything else so Popen works on python2.4. subout = subprocess.PIPE if stderr is sys.stderr: # Same as passing sys.stderr, except python2.4 doesn't fail on it. suberr = None elif stderr is None: # Merge with stdout if stderr isn't specified. suberr = subprocess.STDOUT else: # Open pipe for anything else so Popen works on python2.4. suberr = subprocess.PIPE p = subprocess.Popen(command, shell=(sys.platform == 'win32'), stdout=subout, stderr=suberr) p.wait() if stdout is None: self.stdout = p.stdout.read() elif stdout is not sys.stdout: stdout.write(p.stdout.read()) if stderr not in (None, sys.stderr): stderr.write(p.stderr.read()) return p.returncode def run(self, command, display=None, stdout=None, stderr=None): """ Runs a single command, displaying it first. """ if display is None: display = command self.display(display) return self.execute(command, stdout, stderr) class Unbuffered(object): def __init__(self, fp): self.fp = fp def write(self, arg): self.fp.write(arg) self.fp.flush() def __getattr__(self, attr): return getattr(self.fp, attr) sys.stdout = Unbuffered(sys.stdout) sys.stderr = Unbuffered(sys.stderr) def is_test_name(f): return f.startswith('gyptest') and f.endswith('.py') def find_all_gyptest_files(directory): result = [] for root, dirs, files in os.walk(directory): if '.svn' in dirs: dirs.remove('.svn') result.extend([ os.path.join(root, f) for f in files if is_test_name(f) ]) result.sort() return result def main(argv=None): if argv is None: argv = sys.argv usage = "gyptest.py [-ahlnq] [-f formats] [test ...]" parser = optparse.OptionParser(usage=usage) parser.add_option("-a", "--all", action="store_true", help="run all tests") parser.add_option("-C", "--chdir", action="store", default=None, help="chdir to the specified directory") parser.add_option("-f", "--format", action="store", default='', help="run tests with the specified formats") parser.add_option("-G", '--gyp_option', action="append", default=[], help="Add -G options to the gyp command line") parser.add_option("-l", "--list", action="store_true", help="list available tests and exit") parser.add_option("-n", "--no-exec", action="store_true", help="no execute, just print the command line") parser.add_option("--passed", action="store_true", help="report passed tests") parser.add_option("--path", action="append", default=[], help="additional $PATH directory") parser.add_option("-q", "--quiet", action="store_true", help="quiet, don't print test command lines") opts, args = parser.parse_args(argv[1:]) if opts.chdir: os.chdir(opts.chdir) if opts.path: extra_path = [os.path.abspath(p) for p in opts.path] extra_path = os.pathsep.join(extra_path) os.environ['PATH'] = extra_path + os.pathsep + os.environ['PATH'] if not args: if not opts.all: sys.stderr.write('Specify -a to get all tests.\n') return 1 args = ['test'] tests = [] for arg in args: if os.path.isdir(arg): tests.extend(find_all_gyptest_files(os.path.normpath(arg))) else: if not is_test_name(os.path.basename(arg)): print >>sys.stderr, arg, 'is not a valid gyp test name.' sys.exit(1) tests.append(arg) if opts.list: for test in tests: print test sys.exit(0) CommandRunner.verbose = not opts.quiet CommandRunner.active = not opts.no_exec cr = CommandRunner() os.environ['PYTHONPATH'] = os.path.abspath('test/lib') if not opts.quiet: sys.stdout.write('PYTHONPATH=%s\n' % os.environ['PYTHONPATH']) passed = [] failed = [] no_result = [] if opts.format: format_list = opts.format.split(',') else: # TODO: not duplicate this mapping from pylib/gyp/__init__.py format_list = { 'aix5': ['make'], 'freebsd7': ['make'], 'freebsd8': ['make'], 'openbsd5': ['make'], 'cygwin': ['msvs'], 'win32': ['msvs', 'ninja'], 'linux2': ['make', 'ninja'], 'linux3': ['make', 'ninja'], 'darwin': ['make', 'ninja', 'xcode', 'xcode-ninja'], }[sys.platform] for format in format_list: os.environ['TESTGYP_FORMAT'] = format if not opts.quiet: sys.stdout.write('TESTGYP_FORMAT=%s\n' % format) gyp_options = [] for option in opts.gyp_option: gyp_options += ['-G', option] if gyp_options and not opts.quiet: sys.stdout.write('Extra Gyp options: %s\n' % gyp_options) for test in tests: status = cr.run([sys.executable, test] + gyp_options, stdout=sys.stdout, stderr=sys.stderr) if status == 2: no_result.append(test) elif status: failed.append(test) else: passed.append(test) if not opts.quiet: def report(description, tests): if tests: if len(tests) == 1: sys.stdout.write("\n%s the following test:\n" % description) else: fmt = "\n%s the following %d tests:\n" sys.stdout.write(fmt % (description, len(tests))) sys.stdout.write("\t" + "\n\t".join(tests) + "\n") if opts.passed: report("Passed", passed) report("Failed", failed) report("No result from", no_result) if failed: return 1 else: return 0 if __name__ == "__main__": sys.exit(main())
mit
doomsterinc/odoo
openerp/tests/common.py
50
13675
# -*- coding: utf-8 -*- """ The module :mod:`openerp.tests.common` provides unittest2 test cases and a few helpers and classes to write tests. """ import errno import glob import json import logging import os import select import subprocess import threading import time import itertools import unittest2 import urllib2 import xmlrpclib from contextlib import contextmanager from datetime import datetime, timedelta import werkzeug import openerp from openerp import api from openerp.modules.registry import RegistryManager _logger = logging.getLogger(__name__) # The openerp library is supposed already configured. ADDONS_PATH = openerp.tools.config['addons_path'] HOST = '127.0.0.1' PORT = openerp.tools.config['xmlrpc_port'] # Useless constant, tests are aware of the content of demo data ADMIN_USER_ID = openerp.SUPERUSER_ID def get_db_name(): db = openerp.tools.config['db_name'] # If the database name is not provided on the command-line, # use the one on the thread (which means if it is provided on # the command-line, this will break when installing another # database from XML-RPC). if not db and hasattr(threading.current_thread(), 'dbname'): return threading.current_thread().dbname return db # For backwards-compatibility - get_db_name() should be used instead DB = get_db_name() def at_install(flag): """ Sets the at-install state of a test, the flag is a boolean specifying whether the test should (``True``) or should not (``False``) run during module installation. By default, tests are run right after installing the module, before starting the installation of the next module. """ def decorator(obj): obj.at_install = flag return obj return decorator def post_install(flag): """ Sets the post-install state of a test. The flag is a boolean specifying whether the test should or should not run after a set of module installations. By default, tests are *not* run after installation of all modules in the current installation set. """ def decorator(obj): obj.post_install = flag return obj return decorator class BaseCase(unittest2.TestCase): """ Subclass of TestCase for common OpenERP-specific code. This class is abstract and expects self.registry, self.cr and self.uid to be initialized by subclasses. """ def cursor(self): return self.registry.cursor() def ref(self, xid): """ Returns database ID for the provided :term:`external identifier`, shortcut for ``get_object_reference`` :param xid: fully-qualified :term:`external identifier`, in the form :samp:`{module}.{identifier}` :raise: ValueError if not found :returns: registered id """ assert "." in xid, "this method requires a fully qualified parameter, in the following form: 'module.identifier'" module, xid = xid.split('.') _, id = self.registry('ir.model.data').get_object_reference(self.cr, self.uid, module, xid) return id def browse_ref(self, xid): """ Returns a record object for the provided :term:`external identifier` :param xid: fully-qualified :term:`external identifier`, in the form :samp:`{module}.{identifier}` :raise: ValueError if not found :returns: :class:`~openerp.models.BaseModel` """ assert "." in xid, "this method requires a fully qualified parameter, in the following form: 'module.identifier'" module, xid = xid.split('.') return self.registry('ir.model.data').get_object(self.cr, self.uid, module, xid) @contextmanager def _assertRaises(self, exception): """ Context manager that clears the environment upon failure. """ with super(BaseCase, self).assertRaises(exception) as cm: with self.env.clear_upon_failure(): yield cm def assertRaises(self, exception, func=None, *args, **kwargs): if func: with self._assertRaises(exception): func(*args, **kwargs) else: return self._assertRaises(exception) class TransactionCase(BaseCase): """ TestCase in which each test method is run in its own transaction, and with its own cursor. The transaction is rolled back and the cursor is closed after each test. """ def setUp(self): self.registry = RegistryManager.get(get_db_name()) #: current transaction's cursor self.cr = self.cursor() self.uid = openerp.SUPERUSER_ID #: :class:`~openerp.api.Environment` for the current test case self.env = api.Environment(self.cr, self.uid, {}) def tearDown(self): # rollback and close the cursor, and reset the environments self.env.reset() self.cr.rollback() self.cr.close() class SingleTransactionCase(BaseCase): """ TestCase in which all test methods are run in the same transaction, the transaction is started with the first test method and rolled back at the end of the last. """ @classmethod def setUpClass(cls): cls.registry = RegistryManager.get(get_db_name()) cls.cr = cls.registry.cursor() cls.uid = openerp.SUPERUSER_ID cls.env = api.Environment(cls.cr, cls.uid, {}) @classmethod def tearDownClass(cls): # rollback and close the cursor, and reset the environments cls.env.reset() cls.cr.rollback() cls.cr.close() savepoint_seq = itertools.count() class SavepointCase(SingleTransactionCase): """ Similar to :class:`SingleTransactionCase` in that all test methods are run in a single transaction *but* each test case is run inside a rollbacked savepoint (sub-transaction). Useful for test cases containing fast tests but with significant database setup common to all cases (complex in-db test data): :meth:`~.setUpClass` can be used to generate db test data once, then all test cases use the same data without influencing one another but without having to recreate the test data either. """ def setUp(self): self._savepoint_id = next(savepoint_seq) self.cr.execute('SAVEPOINT test_%d' % self._savepoint_id) def tearDown(self): self.cr.execute('ROLLBACK TO SAVEPOINT test_%d' % self._savepoint_id) self.env.clear() self.registry.clear_caches() class RedirectHandler(urllib2.HTTPRedirectHandler): """ HTTPRedirectHandler is predicated upon HTTPErrorProcessor being used and works by intercepting 3xy "errors". Inherit from it to handle 3xy non-error responses instead, as we're not using the error processor """ def http_response(self, request, response): code, msg, hdrs = response.code, response.msg, response.info() if 300 <= code < 400: return self.parent.error( 'http', request, response, code, msg, hdrs) return response https_response = http_response class HttpCase(TransactionCase): """ Transactional HTTP TestCase with url_open and phantomjs helpers. """ def __init__(self, methodName='runTest'): super(HttpCase, self).__init__(methodName) # v8 api with correct xmlrpc exception handling. self.xmlrpc_url = url_8 = 'http://%s:%d/xmlrpc/2/' % (HOST, PORT) self.xmlrpc_common = xmlrpclib.ServerProxy(url_8 + 'common') self.xmlrpc_db = xmlrpclib.ServerProxy(url_8 + 'db') self.xmlrpc_object = xmlrpclib.ServerProxy(url_8 + 'object') def setUp(self): super(HttpCase, self).setUp() self.registry.enter_test_mode() # setup a magic session_id that will be rollbacked self.session = openerp.http.root.session_store.new() self.session_id = self.session.sid self.session.db = get_db_name() openerp.http.root.session_store.save(self.session) # setup an url opener helper self.opener = urllib2.OpenerDirector() self.opener.add_handler(urllib2.UnknownHandler()) self.opener.add_handler(urllib2.HTTPHandler()) self.opener.add_handler(urllib2.HTTPSHandler()) self.opener.add_handler(urllib2.HTTPCookieProcessor()) self.opener.add_handler(RedirectHandler()) self.opener.addheaders.append(('Cookie', 'session_id=%s' % self.session_id)) def tearDown(self): self.registry.leave_test_mode() super(HttpCase, self).tearDown() def url_open(self, url, data=None, timeout=10): if url.startswith('/'): url = "http://localhost:%s%s" % (PORT, url) return self.opener.open(url, data, timeout) def authenticate(self, user, password): if user is not None: url = '/login?%s' % werkzeug.urls.url_encode({'db': get_db_name(),'login': user, 'key': password}) auth = self.url_open(url) assert auth.getcode() < 400, "Auth failure %d" % auth.getcode() def phantom_poll(self, phantom, timeout): """ Phantomjs Test protocol. Use console.log in phantomjs to output test results: - for a success: console.log("ok") - for an error: console.log("error") Other lines are relayed to the test log. """ t0 = datetime.now() td = timedelta(seconds=timeout) buf = bytearray() while True: # timeout self.assertLess(datetime.now() - t0, td, "PhantomJS tests should take less than %s seconds" % timeout) # read a byte try: ready, _, _ = select.select([phantom.stdout], [], [], 0.5) except select.error, e: # In Python 2, select.error has no relation to IOError or # OSError, and no errno/strerror/filename, only a pair of # unnamed arguments (matching errno and strerror) err, _ = e.args if err == errno.EINTR: continue raise if ready: s = phantom.stdout.read(1) if not s: break buf.append(s) # process lines if '\n' in buf: line, buf = buf.split('\n', 1) line = str(line) # relay everything from console.log, even 'ok' or 'error...' lines _logger.info("phantomjs: %s", line) if line == "ok": break if line.startswith("error"): line_ = line[6:] # when error occurs the execution stack may be sent as as JSON try: line_ = json.loads(line_) except ValueError: pass self.fail(line_ or "phantomjs test failed") def phantom_run(self, cmd, timeout): _logger.info('phantom_run executing %s', ' '.join(cmd)) ls_glob = os.path.expanduser('~/.qws/share/data/Ofi Labs/PhantomJS/http_localhost_%s.*'%PORT) for i in glob.glob(ls_glob): _logger.info('phantomjs unlink localstorage %s', i) os.unlink(i) try: phantom = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=None) except OSError: raise unittest2.SkipTest("PhantomJS not found") try: self.phantom_poll(phantom, timeout) finally: # kill phantomjs if phantom.exit() wasn't called in the test if phantom.poll() is None: phantom.terminate() phantom.wait() self._wait_remaining_requests() # we ignore phantomjs return code as we kill it as soon as we have ok _logger.info("phantom_run execution finished") def _wait_remaining_requests(self): t0 = int(time.time()) for thread in threading.enumerate(): if thread.name.startswith('openerp.service.http.request.'): while thread.isAlive(): # Need a busyloop here as thread.join() masks signals # and would prevent the forced shutdown. thread.join(0.05) time.sleep(0.05) t1 = int(time.time()) if t0 != t1: _logger.info('remaining requests') openerp.tools.misc.dumpstacks() t0 = t1 def phantom_js(self, url_path, code, ready="window", login=None, timeout=60, **kw): """ Test js code running in the browser - optionnally log as 'login' - load page given by url_path - wait for ready object to be available - eval(code) inside the page To signal success test do: console.log('ok') To signal failure do: console.log('error') If neither are done before timeout test fails. """ options = { 'port': PORT, 'db': get_db_name(), 'url_path': url_path, 'code': code, 'ready': ready, 'timeout' : timeout, 'login' : login, 'session_id': self.session_id, } options.update(kw) options.setdefault('password', options.get('login')) phantomtest = os.path.join(os.path.dirname(__file__), 'phantomtest.js') cmd = ['phantomjs', phantomtest, json.dumps(options)] self.phantom_run(cmd, timeout) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
cyc805/FTRerouting
.waf-1.7.11-edc6ccb516c5e3f9b892efc9f53a610f/waflib/Context.py
70
8431
#! /usr/bin/env python # encoding: utf-8 # WARNING! Do not edit! http://waf.googlecode.com/git/docs/wafbook/single.html#_obtaining_the_waf_file import os,imp,sys from waflib import Utils,Errors,Logs import waflib.Node HEXVERSION=0x1070b00 WAFVERSION="1.7.11" WAFREVISION="50f631bc5e00bdda966c68094229b99be9a21084" ABI=98 DBFILE='.wafpickle-%s-%d-%d'%(sys.platform,sys.hexversion,ABI) APPNAME='APPNAME' VERSION='VERSION' TOP='top' OUT='out' WSCRIPT_FILE='wscript' launch_dir='' run_dir='' top_dir='' out_dir='' waf_dir='' local_repo='' remote_repo='http://waf.googlecode.com/git/' remote_locs=['waflib/extras','waflib/Tools'] g_module=None STDOUT=1 STDERR=-1 BOTH=0 classes=[] def create_context(cmd_name,*k,**kw): global classes for x in classes: if x.cmd==cmd_name: return x(*k,**kw) ctx=Context(*k,**kw) ctx.fun=cmd_name return ctx class store_context(type): def __init__(cls,name,bases,dict): super(store_context,cls).__init__(name,bases,dict) name=cls.__name__ if name=='ctx'or name=='Context': return try: cls.cmd except AttributeError: raise Errors.WafError('Missing command for the context class %r (cmd)'%name) if not getattr(cls,'fun',None): cls.fun=cls.cmd global classes classes.insert(0,cls) ctx=store_context('ctx',(object,),{}) class Context(ctx): errors=Errors tools={} def __init__(self,**kw): try: rd=kw['run_dir'] except KeyError: global run_dir rd=run_dir class node_class(waflib.Node.Node): pass self.node_class=node_class self.node_class.__module__="waflib.Node" self.node_class.__name__="Nod3" self.node_class.ctx=self self.root=self.node_class('',None) self.cur_script=None self.path=self.root.find_dir(rd) self.stack_path=[] self.exec_dict={'ctx':self,'conf':self,'bld':self,'opt':self} self.logger=None def __hash__(self): return id(self) def load(self,tool_list,*k,**kw): tools=Utils.to_list(tool_list) path=Utils.to_list(kw.get('tooldir','')) for t in tools: module=load_tool(t,path) fun=getattr(module,kw.get('name',self.fun),None) if fun: fun(self) def execute(self): global g_module self.recurse([os.path.dirname(g_module.root_path)]) def pre_recurse(self,node): self.stack_path.append(self.cur_script) self.cur_script=node self.path=node.parent def post_recurse(self,node): self.cur_script=self.stack_path.pop() if self.cur_script: self.path=self.cur_script.parent def recurse(self,dirs,name=None,mandatory=True,once=True): try: cache=self.recurse_cache except AttributeError: cache=self.recurse_cache={} for d in Utils.to_list(dirs): if not os.path.isabs(d): d=os.path.join(self.path.abspath(),d) WSCRIPT=os.path.join(d,WSCRIPT_FILE) WSCRIPT_FUN=WSCRIPT+'_'+(name or self.fun) node=self.root.find_node(WSCRIPT_FUN) if node and(not once or node not in cache): cache[node]=True self.pre_recurse(node) try: function_code=node.read('rU') exec(compile(function_code,node.abspath(),'exec'),self.exec_dict) finally: self.post_recurse(node) elif not node: node=self.root.find_node(WSCRIPT) tup=(node,name or self.fun) if node and(not once or tup not in cache): cache[tup]=True self.pre_recurse(node) try: wscript_module=load_module(node.abspath()) user_function=getattr(wscript_module,(name or self.fun),None) if not user_function: if not mandatory: continue raise Errors.WafError('No function %s defined in %s'%(name or self.fun,node.abspath())) user_function(self) finally: self.post_recurse(node) elif not node: if not mandatory: continue raise Errors.WafError('No wscript file in directory %s'%d) def exec_command(self,cmd,**kw): subprocess=Utils.subprocess kw['shell']=isinstance(cmd,str) Logs.debug('runner: %r'%cmd) Logs.debug('runner_env: kw=%s'%kw) if self.logger: self.logger.info(cmd) if'stdout'not in kw: kw['stdout']=subprocess.PIPE if'stderr'not in kw: kw['stderr']=subprocess.PIPE try: if kw['stdout']or kw['stderr']: p=subprocess.Popen(cmd,**kw) (out,err)=p.communicate() ret=p.returncode else: out,err=(None,None) ret=subprocess.Popen(cmd,**kw).wait() except Exception ,e: raise Errors.WafError('Execution failure: %s'%str(e),ex=e) if out: if not isinstance(out,str): out=out.decode(sys.stdout.encoding or'iso8859-1') if self.logger: self.logger.debug('out: %s'%out) else: sys.stdout.write(out) if err: if not isinstance(err,str): err=err.decode(sys.stdout.encoding or'iso8859-1') if self.logger: self.logger.error('err: %s'%err) else: sys.stderr.write(err) return ret def cmd_and_log(self,cmd,**kw): subprocess=Utils.subprocess kw['shell']=isinstance(cmd,str) Logs.debug('runner: %r'%cmd) if'quiet'in kw: quiet=kw['quiet'] del kw['quiet'] else: quiet=None if'output'in kw: to_ret=kw['output'] del kw['output'] else: to_ret=STDOUT kw['stdout']=kw['stderr']=subprocess.PIPE if quiet is None: self.to_log(cmd) try: p=subprocess.Popen(cmd,**kw) (out,err)=p.communicate() except Exception ,e: raise Errors.WafError('Execution failure: %s'%str(e),ex=e) if not isinstance(out,str): out=out.decode(sys.stdout.encoding or'iso8859-1') if not isinstance(err,str): err=err.decode(sys.stdout.encoding or'iso8859-1') if out and quiet!=STDOUT and quiet!=BOTH: self.to_log('out: %s'%out) if err and quiet!=STDERR and quiet!=BOTH: self.to_log('err: %s'%err) if p.returncode: e=Errors.WafError('Command %r returned %r'%(cmd,p.returncode)) e.returncode=p.returncode e.stderr=err e.stdout=out raise e if to_ret==BOTH: return(out,err) elif to_ret==STDERR: return err return out def fatal(self,msg,ex=None): if self.logger: self.logger.info('from %s: %s'%(self.path.abspath(),msg)) try: msg='%s\n(complete log in %s)'%(msg,self.logger.handlers[0].baseFilename) except Exception: pass raise self.errors.ConfigurationError(msg,ex=ex) def to_log(self,msg): if not msg: return if self.logger: self.logger.info(msg) else: sys.stderr.write(str(msg)) sys.stderr.flush() def msg(self,msg,result,color=None): self.start_msg(msg) if not isinstance(color,str): color=result and'GREEN'or'YELLOW' self.end_msg(result,color) def start_msg(self,msg): try: if self.in_msg: self.in_msg+=1 return except AttributeError: self.in_msg=0 self.in_msg+=1 try: self.line_just=max(self.line_just,len(msg)) except AttributeError: self.line_just=max(40,len(msg)) for x in(self.line_just*'-',msg): self.to_log(x) Logs.pprint('NORMAL',"%s :"%msg.ljust(self.line_just),sep='') def end_msg(self,result,color=None): self.in_msg-=1 if self.in_msg: return defcolor='GREEN' if result==True: msg='ok' elif result==False: msg='not found' defcolor='YELLOW' else: msg=str(result) self.to_log(msg) Logs.pprint(color or defcolor,msg) def load_special_tools(self,var,ban=[]): global waf_dir lst=self.root.find_node(waf_dir).find_node('waflib/extras').ant_glob(var) for x in lst: if not x.name in ban: load_tool(x.name.replace('.py','')) cache_modules={} def load_module(path): try: return cache_modules[path] except KeyError: pass module=imp.new_module(WSCRIPT_FILE) try: code=Utils.readf(path,m='rU') except(IOError,OSError): raise Errors.WafError('Could not read the file %r'%path) module_dir=os.path.dirname(path) sys.path.insert(0,module_dir) exec(compile(code,path,'exec'),module.__dict__) sys.path.remove(module_dir) cache_modules[path]=module return module def load_tool(tool,tooldir=None): if tool=='java': tool='javaw' elif tool=='compiler_cc': tool='compiler_c' else: tool=tool.replace('++','xx') if tooldir: assert isinstance(tooldir,list) sys.path=tooldir+sys.path try: __import__(tool) ret=sys.modules[tool] Context.tools[tool]=ret return ret finally: for d in tooldir: sys.path.remove(d) else: global waf_dir try: os.stat(os.path.join(waf_dir,'waflib','extras',tool+'.py')) except OSError: try: os.stat(os.path.join(waf_dir,'waflib','Tools',tool+'.py')) except OSError: d=tool else: d='waflib.Tools.%s'%tool else: d='waflib.extras.%s'%tool __import__(d) ret=sys.modules[d] Context.tools[tool]=ret return ret
gpl-2.0
jsocol/django-authority
authority/templatetags/permissions.py
6
15531
from django import template from django.core.urlresolvers import reverse from django.core.exceptions import ImproperlyConfigured from django.contrib.auth.models import User, AnonymousUser from django.core.urlresolvers import reverse from authority import get_check from authority import permissions from authority.models import Permission from authority.forms import UserPermissionForm register = template.Library() @register.simple_tag def url_for_obj(view_name, obj): return reverse(view_name, kwargs={ 'app_label': obj._meta.app_label, 'module_name': obj._meta.module_name, 'pk': obj.pk}) @register.simple_tag def add_url_for_obj(obj): return url_for_obj('authority-add-permission', obj) @register.simple_tag def request_url_for_obj(obj): return url_for_obj('authority-add-permission-request', obj) class ResolverNode(template.Node): """ A small wrapper that adds a convenient resolve method. """ def resolve(self, var, context): """Resolves a variable out of context if it's not in quotes""" if var is None: return var if var[0] in ('"', "'") and var[-1] == var[0]: return var[1:-1] else: return template.Variable(var).resolve(context) @classmethod def next_bit_for(cls, bits, key, if_none=None): try: return bits[bits.index(key)+1] except ValueError: return if_none class PermissionComparisonNode(ResolverNode): """ Implements a node to provide an "if user/group has permission on object" """ @classmethod def handle_token(cls, parser, token): bits = token.contents.split() if 5 < len(bits) < 3: raise template.TemplateSyntaxError("'%s' tag takes three, " "four or five arguments" % bits[0]) end_tag = 'endifhasperm' nodelist_true = parser.parse(('else', end_tag)) token = parser.next_token() if token.contents == 'else': # there is an 'else' clause in the tag nodelist_false = parser.parse((end_tag,)) parser.delete_first_token() else: nodelist_false = template.NodeList() if len(bits) == 3: # this tag requires at most 2 objects . None is given objs = (None, None) elif len(bits) == 4:# one is given objs = (bits[3], None) else: #two are given objs = (bits[3], bits[4]) return cls(bits[2], bits[1], nodelist_true, nodelist_false, *objs) def __init__(self, user, perm, nodelist_true, nodelist_false, *objs): self.user = user self.objs = objs self.perm = perm self.nodelist_true = nodelist_true self.nodelist_false = nodelist_false def render(self, context): try: user = self.resolve(self.user, context) perm = self.resolve(self.perm, context) if self.objs: objs = [] for obj in self.objs: if obj is not None: objs.append(self.resolve(obj, context)) else: objs = None check = get_check(user, perm) if check is not None: if check(*objs): # return True if check was successful return self.nodelist_true.render(context) # If the app couldn't be found except (ImproperlyConfigured, ImportError): return '' # If either variable fails to resolve, return nothing. except template.VariableDoesNotExist: return '' # If the types don't permit comparison, return nothing. except (TypeError, AttributeError): return '' return self.nodelist_false.render(context) @register.tag def ifhasperm(parser, token): """ This function provides functionality for the 'ifhasperm' template tag Syntax:: {% ifhasperm PERMISSION_LABEL.CHECK_NAME USER *OBJS %} lalala {% else %} meh {% endifhasperm %} {% if hasperm "poll_permission.change_poll" request.user %} lalala {% else %} meh {% endifhasperm %} """ return PermissionComparisonNode.handle_token(parser, token) class PermissionFormNode(ResolverNode): @classmethod def handle_token(cls, parser, token, approved): bits = token.contents.split() tag_name = bits[0] kwargs = { 'obj': cls.next_bit_for(bits, 'for'), 'perm': cls.next_bit_for(bits, 'using', None), 'template_name': cls.next_bit_for(bits, 'with', ''), 'approved': approved, } return cls(**kwargs) def __init__(self, obj, perm=None, approved=False, template_name=None): self.obj = obj self.perm = perm self.approved = approved self.template_name = template_name def render(self, context): obj = self.resolve(self.obj, context) perm = self.resolve(self.perm, context) if self.template_name: template_name = [self.resolve(obj, context) for obj in self.template_name.split(',')] else: template_name = 'authority/permission_form.html' request = context['request'] extra_context = {} if self.approved: if (request.user.is_authenticated() and request.user.has_perm('authority.add_permission')): extra_context = { 'form_url': url_for_obj('authority-add-permission', obj), 'next': request.build_absolute_uri(), 'approved': self.approved, 'form': UserPermissionForm(perm, obj, approved=self.approved, initial=dict(codename=perm)), } else: if request.user.is_authenticated() and not request.user.is_superuser: extra_context = { 'form_url': url_for_obj('authority-add-permission-request', obj), 'next': request.build_absolute_uri(), 'approved': self.approved, 'form': UserPermissionForm(perm, obj, approved=self.approved, initial=dict( codename=perm, user=request.user.username)), } return template.loader.render_to_string(template_name, extra_context, context_instance=template.RequestContext(request)) @register.tag def permission_form(parser, token): """ Renders an "add permissions" form for the given object. If no object is given it will render a select box to choose from. Syntax:: {% permission_form for OBJ using PERMISSION_LABEL.CHECK_NAME [with TEMPLATE] %} {% permission_form for lesson using "lesson_permission.add_lesson" %} """ return PermissionFormNode.handle_token(parser, token, approved=True) @register.tag def permission_request_form(parser, token): """ Renders an "add permissions" form for the given object. If no object is given it will render a select box to choose from. Syntax:: {% permission_request_form for OBJ and PERMISSION_LABEL.CHECK_NAME [with TEMPLATE] %} {% permission_request_form for lesson using "lesson_permission.add_lesson" with "authority/permission_request_form.html" %} """ return PermissionFormNode.handle_token(parser, token, approved=False) class PermissionsForObjectNode(ResolverNode): @classmethod def handle_token(cls, parser, token, approved, name): bits = token.contents.split() tag_name = bits[0] kwargs = { 'obj': cls.next_bit_for(bits, tag_name), 'user': cls.next_bit_for(bits, 'for'), 'var_name': cls.next_bit_for(bits, 'as', name), 'approved': approved, } return cls(**kwargs) def __init__(self, obj, user, var_name, approved, perm=None): self.obj = obj self.user = user self.perm = perm self.var_name = var_name self.approved = approved def render(self, context): obj = self.resolve(self.obj, context) var_name = self.resolve(self.var_name, context) user = self.resolve(self.user, context) perms = [] if not isinstance(user, AnonymousUser): perms = Permission.objects.for_object(obj, self.approved) if isinstance(user, User): perms = perms.filter(user=user) context[var_name] = perms return '' @register.tag def get_permissions(parser, token): """ Retrieves all permissions associated with the given obj and user and assigns the result to a context variable. Syntax:: {% get_permissions obj %} {% for perm in permissions %} {{ perm }} {% endfor %} {% get_permissions obj as "my_permissions" %} {% get_permissions obj for request.user as "my_permissions" %} """ return PermissionsForObjectNode.handle_token(parser, token, approved=True, name='"permissions"') @register.tag def get_permission_requests(parser, token): """ Retrieves all permissions requests associated with the given obj and user and assigns the result to a context variable. Syntax:: {% get_permission_requests obj %} {% for perm in permissions %} {{ perm }} {% endfor %} {% get_permission_requests obj as "my_permissions" %} {% get_permission_requests obj for request.user as "my_permissions" %} """ return PermissionsForObjectNode.handle_token(parser, token, approved=False, name='"permission_requests"') class PermissionForObjectNode(ResolverNode): @classmethod def handle_token(cls, parser, token, approved, name): bits = token.contents.split() tag_name = bits[0] kwargs = { 'perm': cls.next_bit_for(bits, tag_name), 'user': cls.next_bit_for(bits, 'for'), 'objs': cls.next_bit_for(bits, 'and'), 'var_name': cls.next_bit_for(bits, 'as', name), 'approved': approved, } return cls(**kwargs) def __init__(self, perm, user, objs, approved, var_name): self.perm = perm self.user = user self.objs = objs self.var_name = var_name self.approved = approved def render(self, context): objs = [self.resolve(obj, context) for obj in self.objs.split(',')] var_name = self.resolve(self.var_name, context) perm = self.resolve(self.perm, context) user = self.resolve(self.user, context) granted = False if not isinstance(user, AnonymousUser): if self.approved: check = get_check(user, perm) if check is not None: granted = check(*objs) else: check = permissions.BasePermission(user=user) for obj in objs: granted = check.requested_perm(perm, obj) if granted: break context[var_name] = granted return '' @register.tag def get_permission(parser, token): """ Performs a permission check with the given signature, user and objects and assigns the result to a context variable. Syntax:: {% get_permission PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %} {% get_permission "poll_permission.change_poll" for request.user and poll as "is_allowed" %} {% get_permission "poll_permission.change_poll" for request.user and poll,second_poll as "is_allowed" %} {% if is_allowed %} I've got ze power to change ze pollllllzzz. Muahahaa. {% else %} Meh. No power for meeeee. {% endif %} """ return PermissionForObjectNode.handle_token(parser, token, approved=True, name='"permission"') @register.tag def get_permission_request(parser, token): """ Performs a permission request check with the given signature, user and objects and assigns the result to a context variable. Syntax:: {% get_permission_request PERMISSION_LABEL.CHECK_NAME for USER and *OBJS [as VARNAME] %} {% get_permission_request "poll_permission.change_poll" for request.user and poll as "asked_for_permissio" %} {% get_permission_request "poll_permission.change_poll" for request.user and poll,second_poll as "asked_for_permissio" %} {% if asked_for_permissio %} Dude, you already asked for permission! {% else %} Oh, please fill out this 20 page form and sign here. {% endif %} """ return PermissionForObjectNode.handle_token(parser, token, approved=False, name='"permission_request"') def base_link(context, perm, view_name): return { 'next': context['request'].build_absolute_uri(), 'url': reverse(view_name, kwargs={'permission_pk': perm.pk,}), } @register.inclusion_tag('authority/permission_delete_link.html', takes_context=True) def permission_delete_link(context, perm): """ Renders a html link to the delete view of the given permission. Returns no content if the request-user has no permission to delete foreign permissions. """ user = context['request'].user if user.is_authenticated(): if user.has_perm('authority.delete_foreign_permissions') \ or user.pk == perm.creator.pk: return base_link(context, perm, 'authority-delete-permission') return {'url': None} @register.inclusion_tag('authority/permission_request_delete_link.html', takes_context=True) def permission_request_delete_link(context, perm): """ Renders a html link to the delete view of the given permission request. Returns no content if the request-user has no permission to delete foreign permissions. """ user = context['request'].user if user.is_authenticated(): link_kwargs = base_link(context, perm, 'authority-delete-permission-request') if user.has_perm('authority.delete_permission'): link_kwargs['is_requestor'] = False return link_kwargs if not perm.approved and perm.user == user: link_kwargs['is_requestor'] = True return link_kwargs return {'url': None} @register.inclusion_tag('authority/permission_request_approve_link.html', takes_context=True) def permission_request_approve_link(context, perm): """ Renders a html link to the approve view of the given permission request. Returns no content if the request-user has no permission to delete foreign permissions. """ user = context['request'].user if user.is_authenticated(): if user.has_perm('authority.approve_permission_requests'): return base_link(context, perm, 'authority-approve-permission-request') return {'url': None}
bsd-3-clause
bossjones/scarlett
scarlett/listener/gstlistenerfsm.py
1
17131
# -*- coding: UTF-8 -*- import scarlett import pygst pygst.require('0.10') import gobject gobject.threads_init() import dbus import dbus.service # TODO: Figure out if we need this or not, re dbus threading # from dbus.mainloop.glib import DBusGMainLoop # dbus_loop = DBusGMainLoop(set_as_default=True) # dsession = SessionBus(mainloop=dbus_loop) dbus.mainloop.glib.threads_init() import gst import os import threading import time import logging from transitions import Machine from scarlett.events import scarlett_event from colorama import init, Fore, Back, Style from scarlett.constants import ( EVENT_SCARLETT_START, EVENT_SCARLETT_STOP, EVENT_STATE_CHANGED, EVENT_TIME_CHANGED, EVENT_CALL_SERVICE, EVENT_SERVICE_EXECUTED, EVENT_SERVICE_REGISTER, EVENT_PLATFORM_DISCOVERED, EVENT_SCARLETT_SAY, EVENT_BRAIN_UPDATE, EVENT_BRAIN_CHECK ) SCARLETT_ROLE = 'listener' CORE_OBJECT = 'GstlistenerFSM' _INSTANCE = None logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-9s) %(message)s',) def setup_core(ss): # logging.info("attempting to setup GstlistenerFSM") global _INSTANCE if _INSTANCE is None: _INSTANCE = GstlistenerFSM() return _INSTANCE class GstlistenerFSM(gobject.GObject): """GstListener with FSM. Preforms pocketsphinx speech recognition. """ __gproperties__ = { 'override_parse': ( gobject.TYPE_STRING, # type 'Override parse', # nick name # description 'Allows you to override what the gst parse line looks like', '', # default value gobject.PARAM_READWRITE ), 'failed': ( gobject.TYPE_INT, # type 'Failed', # nick name 'Number of times recognition failed', # description 0, # min value 5, # max value 0, # default value gobject.PARAM_READWRITE ), 'kw_found': ( gobject.TYPE_INT, # type 'Keyword Match', # nick name 'int value for keyword', # description 0, # min value 5, # max value 0, # default value gobject.PARAM_READWRITE ) } __gsignals__ = { 'gst-started': ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,) ), 'kw-found-ps': ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,) ), 'failed-ps': ( gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_STRING,) ) } capability = [] states = ['initalize', 'ready', 'running', 'is_checking_states', 'time_change', 'done_checking_states'] DBUS_NAME = 'org.scarlettapp.scarlettdaemon' DBUS_PATH = '/org/scarlettapp/scarlettdaemon' def __init__(self, *args, **kwargs): gobject.GObject.__init__(self) # managed by gproperties self.override_parse = '' self.failed = 0 self.kw_found = 0 self.wit_thread = None self.loop = None self.config = scarlett.config self.name = 'GstlistenerFSM' # Initalize the state machine self.machine = Machine( model=self, # TODO: Fix this, its def not working states=self.states, initial='initalize') # startup transition self.machine.add_transition( trigger='startup', source='initalize', dest='ready') # checking_states transition self.machine.add_transition( trigger='checking_states', source='ready', dest='is_checking_states', conditions=['is_ready']) # array / dict of state machines connected to scarlett self._machines = {} # Check interval, in seconds self.interval = 1 # bus = dbus.SessionBus() # self.remote = bus.get_object(GstlistenerFSM.DBUS_NAME, # GstlistenerFSM.DBUS_PATH) # "/usr/local/share/pocketsphinx/model/hmm/en_US/hub4wsj_sc_8k" self.ps_hmm = self.get_hmm_full_path() self.ps_dict = self.get_dict_full_path() self.ps_lm = self.get_lm_full_path() self.ps_device = self.config.get('audio', 'usb_input_device') self.speech_system = self.config.get('speech', 'system') # default, use what we have set self.parse_launch_array = self._get_pocketsphinx_definition( self.override_parse) scarlett.log.debug( Fore.YELLOW + 'Initializing gst-parse-launch -------->') self.pipeline = gst.parse_launch( ' ! '.join(self.parse_launch_array)) listener = self.pipeline.get_by_name('listener') listener.connect('result', self.__result__) listener.set_property('configured', True) scarlett.log.debug( Fore.YELLOW + "Initializing connection to vader element -------->") # TODO: Play with vader object some more # vader = self.pipeline.get_by_name("vader") # vader.connect("vader-start", self._on_vader_start) # vader.connect("vader-stop", self._on_vader_stop) scarlett.log.debug(Fore.YELLOW + "Initializing Bus -------->") bus = self.pipeline.get_bus() bus.add_signal_watch() scarlett.log.debug(Fore.YELLOW + "Sending Message to Bus ---------->") bus.connect('message::application', self.__application_message__) # logging.debug('running with %s and %s', args, kwargs) # TODO: Uncomment this when we're ready to try this ss_listener = threading.Thread(name='Scarlett Listener',target=self.start_listener) ss_listener.daemon = True ss_listener.start() # GObject translates all the underscore characters to hyphen # characters so if you have a property called background_color, # its internal and valid name will be background-color. def do_get_property(self, property): if property.name == 'kw-found': return self.kw_found elif property.name == 'failed': return self.failed elif property.name == 'override-parse': return self.override_parse else: raise AttributeError('unknown property %s' % property.name) def do_set_property(self, property, value): if property == 'kw-found': self.kw_found = value elif property == 'failed': self.failed = value elif property == 'override-parse': self.override_parse = value else: raise AttributeError('unknown property %s' % property) def start_listener(self): global CORE_OBJECT # register service start listener_connect = scarlett_event( 'service_state', data=CORE_OBJECT ) # idle_emit since this is something with low priority gobject.idle_add( self.emit, 'gst-started', listener_connect ) self.pipeline.set_state(gst.STATE_PLAYING) scarlett.log.debug( Fore.YELLOW + 'KEYWORD: ' + self.config.get('scarlett', 'owner') ) self.loop = gobject.MainLoop() self.loop.run() def stop(self): self.pipeline.set_state(gst.STATE_NULL) if self.loop is not None: self.loop.quit() def scarlett_start_listen(self): self.pipeline.set_state(gst.STATE_PLAYING) def scarlett_stop_listen(self): self.pipeline.set_state(gst.STATE_READY) def scarlett_pause_listen(self): self.pipeline.set_state(gst.STATE_PAUSED) def scarlett_reset_listen(self): self.do_set_property('failed', 0) self.do_set_property('kw-found', 0) def partial_result(self, asr, text, uttid): """Forward partial result signals on the bus to the main thread.""" pass def result(self, hyp, uttid): """Forward result signals on the bus to the main thread.""" scarlett.log.debug(Fore.YELLOW + "Inside result function") if hyp in self.config.get('scarlett', 'keywords'): scarlett.log.debug( Fore.YELLOW + "HYP-IS-SOMETHING: " + hyp + "\n\n\n") scarlett.log.debug( Fore.YELLOW + "UTTID-IS-SOMETHING:" + uttid + "\n") self.do_set_property('failed', 0) self.do_set_property('kw-found', 1) # TODO: Change this to emit to main thread # scarlett.basics.voice.play_block('pi-listening') else: failed_temp = self.do_get_property('failed') + 1 self.do_set_property('failed', failed_temp) scarlett.log.debug( Fore.YELLOW + "self.failed = %i" % (self.do_get_property('failed'))) if self.do_get_property('failed') > 4: # reset pipline self.scarlett_reset_listen() # TODO: Change this to emit text data to main thread # ScarlettTalk.speak( # " %s , if you need me, just say my name." % # (self.config.get('scarlett', 'owner'))) def run_cmd(self, hyp, uttid): scarlett.log.debug(Fore.YELLOW + "Inside run_cmd function") scarlett.log.debug(Fore.YELLOW + "KEYWORD IDENTIFIED BABY") scarlett.log.debug( Fore.RED + "self.kw_found = %i" % (self.do_get_property('kw-found'))) if hyp == 'CANCEL': self.cancel_listening() else: # TODO: Change this into emit hypothesis instead hyp_event = scarlett_event( "listener_hyp", data=hyp ) self.emit('kw-found-ps', hyp_event) current_kw_identified = self.do_get_property('kw-found') self.do_set_property('kw-found', current_kw_identified) scarlett.log.debug( Fore.RED + "AFTER run_cmd, self.kw_found = %i" % (self.do_get_property('kw-found'))) def hello(self): print 'hello hello hello!' def listen(self, valve, vader): scarlett.log.debug(Fore.YELLOW + "Inside listen function") # TODO: have this emit pi-listening to mainthread # scarlett.basics.voice.play_block('pi-listening') valve.set_property('drop', False) valve.set_property('drop', True) def cancel_listening(self): scarlett.log.debug(Fore.YELLOW + "Inside cancel_listening function") self.scarlett_reset_listen() scarlett.log.debug(Fore.YELLOW + "self.failed = %i" % (self.failed)) scarlett.log.debug( Fore.RED + "self.keyword_identified = %i" % (self.do_get_property('kw-found'))) def get_hmm_full_path(self): if os.environ.get('SCARLETT_HMM'): _hmm_full_path = os.environ.get('SCARLETT_HMM') else: _hmm_full_path = self.config.get('pocketsphinx', 'hmm') return _hmm_full_path def get_lm_full_path(self): if os.environ.get('SCARLETT_LM'): _lm_full_path = os.environ.get('SCARLETT_LM') else: _lm_full_path = self.config.get('pocketsphinx', 'lm') return _lm_full_path def get_dict_full_path(self): if os.environ.get('SCARLETT_DICT'): _dict_full_path = os.environ.get('SCARLETT_DICT') else: _dict_full_path = self.config.get('pocketsphinx', 'dict') return _dict_full_path def get_pipeline(self): scarlett.log.debug(Fore.YELLOW + "Inside get_pipeline") return self.pipeline def get_voice(self): scarlett.log.debug(Fore.YELLOW + "Inside get_voice") return self.voice def get_pipeline_state(self): return self.pipeline.get_state() def _get_pocketsphinx_definition(self, override_parse): scarlett.log.debug(Fore.YELLOW + "Inside _get_pocketsphinx_definition") """Return ``pocketsphinx`` definition for :func:`gst.parse_launch`.""" # default, use what we have set if override_parse == '': return [ 'alsasrc device=' + self.ps_device, 'queue silent=false leaky=2 max-size-buffers=0 max-size-time=0 max-size-bytes=0', # noqa 'audioconvert', 'audioresample', 'audio/x-raw-int, rate=16000, width=16, depth=16, channels=1', 'audioresample', 'audio/x-raw-int, rate=8000', 'vader name=vader auto-threshold=true', 'pocketsphinx lm=' + self.ps_lm + ' dict=' + self.ps_dict + ' hmm=' + self.ps_hmm + ' name=listener', 'fakesink dump=1'] # NOTE, I commented out the refrence to the tee # 'fakesink dump=1 t.' else: return override_parse def _get_vader_definition(self): scarlett.log.debug(Fore.YELLOW + "Inside _get_vader_definition") """Return ``vader`` definition for :func:`gst.parse_launch`.""" # source: https://github.com/bossjones/eshayari/blob/master/eshayari/application.py # noqa # Convert noise level from spin button range [0,32768] to gstreamer # element's range [0,1]. Likewise, convert silence from spin button's # milliseconds to gstreamer element's nanoseconds. # MY DEFAULT VADER DEFINITON WAS: vader name=vader auto-threshold=true # vader name=vader auto-threshold=true noise = 256 / 32768 silence = 300 * 1000000 return ("vader " + "name=vader " + "auto-threshold=false " + "threshold=%.9f " % noise + "run-length=%d " % silence ) def _on_vader_start(self, vader, pos): scarlett.log.debug(Fore.YELLOW + "Inside _on_vader_start") """Send start position as a message on the bus.""" import gst struct = gst.Structure("start") pos = pos / 1000000000 # ns to s struct.set_value("start", pos) vader.post_message(gst.message_new_application(vader, struct)) def _on_vader_stop(self, vader, pos): scarlett.log.debug(Fore.YELLOW + "Inside _on_vader_stop") """Send stop position as a message on the bus.""" import gst struct = gst.Structure("stop") pos = pos / 1000000000 # ns to s struct.set_value("stop", pos) def __result__(self, listener, text, uttid): """We're inside __result__""" scarlett.log.debug(Fore.YELLOW + "Inside __result__") import gst struct = gst.Structure('result') struct.set_value('hyp', text) struct.set_value('uttid', uttid) listener.post_message(gst.message_new_application(listener, struct)) def __partial_result__(self, listener, text, uttid): """We're inside __partial_result__""" scarlett.log.debug(Fore.YELLOW + "Inside __partial_result__") struct = gst.Structure('partial_result') struct.set_value('hyp', text) struct.set_value('uttid', uttid) listener.post_message(gst.message_new_application(listener, struct)) def __run_cmd__(self, listener, text, uttid): """We're inside __run_cmd__""" import gst scarlett.log.debug(Fore.YELLOW + "Inside __run_cmd__") struct = gst.Structure('result') struct.set_value('hyp', text) struct.set_value('uttid', uttid) listener.post_message(gst.message_new_application(listener, struct)) def __application_message__(self, bus, msg): msgtype = msg.structure.get_name() scarlett.log.debug(Fore.YELLOW + "msgtype: " + msgtype) if msgtype == 'partial_result': self.partial_result(msg.structure['hyp'], msg.structure['uttid']) elif msgtype == 'result': if self.do_get_property('kw-found') == 1: self.run_cmd(msg.structure['hyp'], msg.structure['uttid']) else: self.result(msg.structure['hyp'], msg.structure['uttid']) elif msgtype == 'run_cmd': self.run_cmd(msg.structure['hyp'], msg.structure['uttid']) elif msgtype == gst.MESSAGE_EOS: pass # TODO: SEE IF WE NEED THIS # self.pipeline.set_state(gst.STATE_NULL) elif msgtype == gst.MESSAGE_ERROR: (err, debug) = msgtype.parse_error() scarlett.log.debug(Fore.RED + "Error: %s" % err, debug) pass # Register to be able to emit signals gobject.type_register(GstlistenerFSM)
mit
bsmr-ansible/ansible-modules-extras
windows/win_iis_webapppool.py
153
3531
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2015, Henrik Wallström <henrik@wallstroms.nu> # # 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/>. DOCUMENTATION = ''' --- module: win_iis_webapppool version_added: "2.0" short_description: Configures a IIS Web Application Pool. description: - Creates, Removes and configures a IIS Web Application Pool options: name: description: - Names of application pool required: true default: null aliases: [] state: description: - State of the binding choices: - absent - stopped - started - restarted required: false default: null aliases: [] attributes: description: - Application Pool attributes from string where attributes are seperated by a pipe and attribute name/values by colon Ex. "foo:1|bar:2" required: false default: null aliases: [] author: Henrik Wallström ''' EXAMPLES = ''' # This return information about an existing application pool $ansible -i inventory -m win_iis_webapppool -a "name='DefaultAppPool'" windows host | success >> { "attributes": {}, "changed": false, "info": { "attributes": { "CLRConfigFile": "", "applicationPoolSid": "S-1-5-82-3006700770-424185619-1745488364-794895919-4004696415", "autoStart": true, "enable32BitAppOnWin64": false, "enableConfigurationOverride": true, "managedPipelineMode": 0, "managedRuntimeLoader": "webengine4.dll", "managedRuntimeVersion": "v4.0", "name": "DefaultAppPool", "passAnonymousToken": true, "queueLength": 1000, "startMode": 0, "state": 1 }, "name": "DefaultAppPool", "state": "Started" } } # This creates a new application pool in 'Started' state $ ansible -i inventory -m win_iis_webapppool -a "name='AppPool' state=started" windows # This stoppes an application pool $ ansible -i inventory -m win_iis_webapppool -a "name='AppPool' state=stopped" windows # This restarts an application pool $ ansible -i inventory -m win_iis_webapppool -a "name='AppPool' state=restart" windows # This restarts an application pool $ ansible -i inventory -m win_iis_webapppool -a "name='AppPool' state=restart" windows # This change application pool attributes without touching state $ ansible -i inventory -m win_iis_webapppool -a "name='AppPool' attributes='managedRuntimeVersion:v4.0|autoStart:false'" windows # This creates an application pool and sets attributes $ ansible -i inventory -m win_iis_webapppool -a "name='AnotherAppPool' state=started attributes='managedRuntimeVersion:v4.0|autoStart:false'" windows # Playbook example --- - name: App Pool with .NET 4.0 win_iis_webapppool: name: 'AppPool' state: started attributes: managedRuntimeVersion:v4.0 register: webapppool '''
gpl-3.0
sexmachine/msm
Documentation/target/tcm_mod_builder.py
2358
40707
#!/usr/bin/python # The TCM v4 multi-protocol fabric module generation script for drivers/target/$NEW_MOD # # Copyright (c) 2010 Rising Tide Systems # Copyright (c) 2010 Linux-iSCSI.org # # Author: nab@kernel.org # import os, sys import subprocess as sub import string import re import optparse tcm_dir = "" fabric_ops = [] fabric_mod_dir = "" fabric_mod_port = "" fabric_mod_init_port = "" def tcm_mod_err(msg): print msg sys.exit(1) def tcm_mod_create_module_subdir(fabric_mod_dir_var): if os.path.isdir(fabric_mod_dir_var) == True: return 1 print "Creating fabric_mod_dir: " + fabric_mod_dir_var ret = os.mkdir(fabric_mod_dir_var) if ret: tcm_mod_err("Unable to mkdir " + fabric_mod_dir_var) return def tcm_mod_build_FC_include(fabric_mod_dir_var, fabric_mod_name): global fabric_mod_port global fabric_mod_init_port buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_base.h" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#define " + fabric_mod_name.upper() + "_VERSION \"v0.1\"\n" buf += "#define " + fabric_mod_name.upper() + "_NAMELEN 32\n" buf += "\n" buf += "struct " + fabric_mod_name + "_nacl {\n" buf += " /* Binary World Wide unique Port Name for FC Initiator Nport */\n" buf += " u64 nport_wwpn;\n" buf += " /* ASCII formatted WWPN for FC Initiator Nport */\n" buf += " char nport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_nodeacl() */\n" buf += " struct se_node_acl se_node_acl;\n" buf += "};\n" buf += "\n" buf += "struct " + fabric_mod_name + "_tpg {\n" buf += " /* FC lport target portal group tag for TCM */\n" buf += " u16 lport_tpgt;\n" buf += " /* Pointer back to " + fabric_mod_name + "_lport */\n" buf += " struct " + fabric_mod_name + "_lport *lport;\n" buf += " /* Returned by " + fabric_mod_name + "_make_tpg() */\n" buf += " struct se_portal_group se_tpg;\n" buf += "};\n" buf += "\n" buf += "struct " + fabric_mod_name + "_lport {\n" buf += " /* SCSI protocol the lport is providing */\n" buf += " u8 lport_proto_id;\n" buf += " /* Binary World Wide unique Port Name for FC Target Lport */\n" buf += " u64 lport_wwpn;\n" buf += " /* ASCII formatted WWPN for FC Target Lport */\n" buf += " char lport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_lport() */\n" buf += " struct se_wwn lport_wwn;\n" buf += "};\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() fabric_mod_port = "lport" fabric_mod_init_port = "nport" return def tcm_mod_build_SAS_include(fabric_mod_dir_var, fabric_mod_name): global fabric_mod_port global fabric_mod_init_port buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_base.h" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#define " + fabric_mod_name.upper() + "_VERSION \"v0.1\"\n" buf += "#define " + fabric_mod_name.upper() + "_NAMELEN 32\n" buf += "\n" buf += "struct " + fabric_mod_name + "_nacl {\n" buf += " /* Binary World Wide unique Port Name for SAS Initiator port */\n" buf += " u64 iport_wwpn;\n" buf += " /* ASCII formatted WWPN for Sas Initiator port */\n" buf += " char iport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_nodeacl() */\n" buf += " struct se_node_acl se_node_acl;\n" buf += "};\n\n" buf += "struct " + fabric_mod_name + "_tpg {\n" buf += " /* SAS port target portal group tag for TCM */\n" buf += " u16 tport_tpgt;\n" buf += " /* Pointer back to " + fabric_mod_name + "_tport */\n" buf += " struct " + fabric_mod_name + "_tport *tport;\n" buf += " /* Returned by " + fabric_mod_name + "_make_tpg() */\n" buf += " struct se_portal_group se_tpg;\n" buf += "};\n\n" buf += "struct " + fabric_mod_name + "_tport {\n" buf += " /* SCSI protocol the tport is providing */\n" buf += " u8 tport_proto_id;\n" buf += " /* Binary World Wide unique Port Name for SAS Target port */\n" buf += " u64 tport_wwpn;\n" buf += " /* ASCII formatted WWPN for SAS Target port */\n" buf += " char tport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_tport() */\n" buf += " struct se_wwn tport_wwn;\n" buf += "};\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() fabric_mod_port = "tport" fabric_mod_init_port = "iport" return def tcm_mod_build_iSCSI_include(fabric_mod_dir_var, fabric_mod_name): global fabric_mod_port global fabric_mod_init_port buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_base.h" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#define " + fabric_mod_name.upper() + "_VERSION \"v0.1\"\n" buf += "#define " + fabric_mod_name.upper() + "_NAMELEN 32\n" buf += "\n" buf += "struct " + fabric_mod_name + "_nacl {\n" buf += " /* ASCII formatted InitiatorName */\n" buf += " char iport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_nodeacl() */\n" buf += " struct se_node_acl se_node_acl;\n" buf += "};\n\n" buf += "struct " + fabric_mod_name + "_tpg {\n" buf += " /* iSCSI target portal group tag for TCM */\n" buf += " u16 tport_tpgt;\n" buf += " /* Pointer back to " + fabric_mod_name + "_tport */\n" buf += " struct " + fabric_mod_name + "_tport *tport;\n" buf += " /* Returned by " + fabric_mod_name + "_make_tpg() */\n" buf += " struct se_portal_group se_tpg;\n" buf += "};\n\n" buf += "struct " + fabric_mod_name + "_tport {\n" buf += " /* SCSI protocol the tport is providing */\n" buf += " u8 tport_proto_id;\n" buf += " /* ASCII formatted TargetName for IQN */\n" buf += " char tport_name[" + fabric_mod_name.upper() + "_NAMELEN];\n" buf += " /* Returned by " + fabric_mod_name + "_make_tport() */\n" buf += " struct se_wwn tport_wwn;\n" buf += "};\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() fabric_mod_port = "tport" fabric_mod_init_port = "iport" return def tcm_mod_build_base_includes(proto_ident, fabric_mod_dir_val, fabric_mod_name): if proto_ident == "FC": tcm_mod_build_FC_include(fabric_mod_dir_val, fabric_mod_name) elif proto_ident == "SAS": tcm_mod_build_SAS_include(fabric_mod_dir_val, fabric_mod_name) elif proto_ident == "iSCSI": tcm_mod_build_iSCSI_include(fabric_mod_dir_val, fabric_mod_name) else: print "Unsupported proto_ident: " + proto_ident sys.exit(1) return def tcm_mod_build_configfs(proto_ident, fabric_mod_dir_var, fabric_mod_name): buf = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_configfs.c" print "Writing file: " + f p = open(f, 'w'); if not p: tcm_mod_err("Unable to open file: " + f) buf = "#include <linux/module.h>\n" buf += "#include <linux/moduleparam.h>\n" buf += "#include <linux/version.h>\n" buf += "#include <generated/utsrelease.h>\n" buf += "#include <linux/utsname.h>\n" buf += "#include <linux/init.h>\n" buf += "#include <linux/slab.h>\n" buf += "#include <linux/kthread.h>\n" buf += "#include <linux/types.h>\n" buf += "#include <linux/string.h>\n" buf += "#include <linux/configfs.h>\n" buf += "#include <linux/ctype.h>\n" buf += "#include <asm/unaligned.h>\n\n" buf += "#include <target/target_core_base.h>\n" buf += "#include <target/target_core_fabric.h>\n" buf += "#include <target/target_core_fabric_configfs.h>\n" buf += "#include <target/target_core_configfs.h>\n" buf += "#include <target/configfs_macros.h>\n\n" buf += "#include \"" + fabric_mod_name + "_base.h\"\n" buf += "#include \"" + fabric_mod_name + "_fabric.h\"\n\n" buf += "/* Local pointer to allocated TCM configfs fabric module */\n" buf += "struct target_fabric_configfs *" + fabric_mod_name + "_fabric_configfs;\n\n" buf += "static struct se_node_acl *" + fabric_mod_name + "_make_nodeacl(\n" buf += " struct se_portal_group *se_tpg,\n" buf += " struct config_group *group,\n" buf += " const char *name)\n" buf += "{\n" buf += " struct se_node_acl *se_nacl, *se_nacl_new;\n" buf += " struct " + fabric_mod_name + "_nacl *nacl;\n" if proto_ident == "FC" or proto_ident == "SAS": buf += " u64 wwpn = 0;\n" buf += " u32 nexus_depth;\n\n" buf += " /* " + fabric_mod_name + "_parse_wwn(name, &wwpn, 1) < 0)\n" buf += " return ERR_PTR(-EINVAL); */\n" buf += " se_nacl_new = " + fabric_mod_name + "_alloc_fabric_acl(se_tpg);\n" buf += " if (!se_nacl_new)\n" buf += " return ERR_PTR(-ENOMEM);\n" buf += "//#warning FIXME: Hardcoded nexus depth in " + fabric_mod_name + "_make_nodeacl()\n" buf += " nexus_depth = 1;\n" buf += " /*\n" buf += " * se_nacl_new may be released by core_tpg_add_initiator_node_acl()\n" buf += " * when converting a NodeACL from demo mode -> explict\n" buf += " */\n" buf += " se_nacl = core_tpg_add_initiator_node_acl(se_tpg, se_nacl_new,\n" buf += " name, nexus_depth);\n" buf += " if (IS_ERR(se_nacl)) {\n" buf += " " + fabric_mod_name + "_release_fabric_acl(se_tpg, se_nacl_new);\n" buf += " return se_nacl;\n" buf += " }\n" buf += " /*\n" buf += " * Locate our struct " + fabric_mod_name + "_nacl and set the FC Nport WWPN\n" buf += " */\n" buf += " nacl = container_of(se_nacl, struct " + fabric_mod_name + "_nacl, se_node_acl);\n" if proto_ident == "FC" or proto_ident == "SAS": buf += " nacl->" + fabric_mod_init_port + "_wwpn = wwpn;\n" buf += " /* " + fabric_mod_name + "_format_wwn(&nacl->" + fabric_mod_init_port + "_name[0], " + fabric_mod_name.upper() + "_NAMELEN, wwpn); */\n\n" buf += " return se_nacl;\n" buf += "}\n\n" buf += "static void " + fabric_mod_name + "_drop_nodeacl(struct se_node_acl *se_acl)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_nacl *nacl = container_of(se_acl,\n" buf += " struct " + fabric_mod_name + "_nacl, se_node_acl);\n" buf += " core_tpg_del_initiator_node_acl(se_acl->se_tpg, se_acl, 1);\n" buf += " kfree(nacl);\n" buf += "}\n\n" buf += "static struct se_portal_group *" + fabric_mod_name + "_make_tpg(\n" buf += " struct se_wwn *wwn,\n" buf += " struct config_group *group,\n" buf += " const char *name)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + "*" + fabric_mod_port + " = container_of(wwn,\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + ", " + fabric_mod_port + "_wwn);\n\n" buf += " struct " + fabric_mod_name + "_tpg *tpg;\n" buf += " unsigned long tpgt;\n" buf += " int ret;\n\n" buf += " if (strstr(name, \"tpgt_\") != name)\n" buf += " return ERR_PTR(-EINVAL);\n" buf += " if (strict_strtoul(name + 5, 10, &tpgt) || tpgt > UINT_MAX)\n" buf += " return ERR_PTR(-EINVAL);\n\n" buf += " tpg = kzalloc(sizeof(struct " + fabric_mod_name + "_tpg), GFP_KERNEL);\n" buf += " if (!tpg) {\n" buf += " printk(KERN_ERR \"Unable to allocate struct " + fabric_mod_name + "_tpg\");\n" buf += " return ERR_PTR(-ENOMEM);\n" buf += " }\n" buf += " tpg->" + fabric_mod_port + " = " + fabric_mod_port + ";\n" buf += " tpg->" + fabric_mod_port + "_tpgt = tpgt;\n\n" buf += " ret = core_tpg_register(&" + fabric_mod_name + "_fabric_configfs->tf_ops, wwn,\n" buf += " &tpg->se_tpg, (void *)tpg,\n" buf += " TRANSPORT_TPG_TYPE_NORMAL);\n" buf += " if (ret < 0) {\n" buf += " kfree(tpg);\n" buf += " return NULL;\n" buf += " }\n" buf += " return &tpg->se_tpg;\n" buf += "}\n\n" buf += "static void " + fabric_mod_name + "_drop_tpg(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n\n" buf += " core_tpg_deregister(se_tpg);\n" buf += " kfree(tpg);\n" buf += "}\n\n" buf += "static struct se_wwn *" + fabric_mod_name + "_make_" + fabric_mod_port + "(\n" buf += " struct target_fabric_configfs *tf,\n" buf += " struct config_group *group,\n" buf += " const char *name)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + ";\n" if proto_ident == "FC" or proto_ident == "SAS": buf += " u64 wwpn = 0;\n\n" buf += " /* if (" + fabric_mod_name + "_parse_wwn(name, &wwpn, 1) < 0)\n" buf += " return ERR_PTR(-EINVAL); */\n\n" buf += " " + fabric_mod_port + " = kzalloc(sizeof(struct " + fabric_mod_name + "_" + fabric_mod_port + "), GFP_KERNEL);\n" buf += " if (!" + fabric_mod_port + ") {\n" buf += " printk(KERN_ERR \"Unable to allocate struct " + fabric_mod_name + "_" + fabric_mod_port + "\");\n" buf += " return ERR_PTR(-ENOMEM);\n" buf += " }\n" if proto_ident == "FC" or proto_ident == "SAS": buf += " " + fabric_mod_port + "->" + fabric_mod_port + "_wwpn = wwpn;\n" buf += " /* " + fabric_mod_name + "_format_wwn(&" + fabric_mod_port + "->" + fabric_mod_port + "_name[0], " + fabric_mod_name.upper() + "_NAMELEN, wwpn); */\n\n" buf += " return &" + fabric_mod_port + "->" + fabric_mod_port + "_wwn;\n" buf += "}\n\n" buf += "static void " + fabric_mod_name + "_drop_" + fabric_mod_port + "(struct se_wwn *wwn)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = container_of(wwn,\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + ", " + fabric_mod_port + "_wwn);\n" buf += " kfree(" + fabric_mod_port + ");\n" buf += "}\n\n" buf += "static ssize_t " + fabric_mod_name + "_wwn_show_attr_version(\n" buf += " struct target_fabric_configfs *tf,\n" buf += " char *page)\n" buf += "{\n" buf += " return sprintf(page, \"" + fabric_mod_name.upper() + " fabric module %s on %s/%s\"\n" buf += " \"on \"UTS_RELEASE\"\\n\", " + fabric_mod_name.upper() + "_VERSION, utsname()->sysname,\n" buf += " utsname()->machine);\n" buf += "}\n\n" buf += "TF_WWN_ATTR_RO(" + fabric_mod_name + ", version);\n\n" buf += "static struct configfs_attribute *" + fabric_mod_name + "_wwn_attrs[] = {\n" buf += " &" + fabric_mod_name + "_wwn_version.attr,\n" buf += " NULL,\n" buf += "};\n\n" buf += "static struct target_core_fabric_ops " + fabric_mod_name + "_ops = {\n" buf += " .get_fabric_name = " + fabric_mod_name + "_get_fabric_name,\n" buf += " .get_fabric_proto_ident = " + fabric_mod_name + "_get_fabric_proto_ident,\n" buf += " .tpg_get_wwn = " + fabric_mod_name + "_get_fabric_wwn,\n" buf += " .tpg_get_tag = " + fabric_mod_name + "_get_tag,\n" buf += " .tpg_get_default_depth = " + fabric_mod_name + "_get_default_depth,\n" buf += " .tpg_get_pr_transport_id = " + fabric_mod_name + "_get_pr_transport_id,\n" buf += " .tpg_get_pr_transport_id_len = " + fabric_mod_name + "_get_pr_transport_id_len,\n" buf += " .tpg_parse_pr_out_transport_id = " + fabric_mod_name + "_parse_pr_out_transport_id,\n" buf += " .tpg_check_demo_mode = " + fabric_mod_name + "_check_false,\n" buf += " .tpg_check_demo_mode_cache = " + fabric_mod_name + "_check_true,\n" buf += " .tpg_check_demo_mode_write_protect = " + fabric_mod_name + "_check_true,\n" buf += " .tpg_check_prod_mode_write_protect = " + fabric_mod_name + "_check_false,\n" buf += " .tpg_alloc_fabric_acl = " + fabric_mod_name + "_alloc_fabric_acl,\n" buf += " .tpg_release_fabric_acl = " + fabric_mod_name + "_release_fabric_acl,\n" buf += " .tpg_get_inst_index = " + fabric_mod_name + "_tpg_get_inst_index,\n" buf += " .release_cmd = " + fabric_mod_name + "_release_cmd,\n" buf += " .shutdown_session = " + fabric_mod_name + "_shutdown_session,\n" buf += " .close_session = " + fabric_mod_name + "_close_session,\n" buf += " .stop_session = " + fabric_mod_name + "_stop_session,\n" buf += " .fall_back_to_erl0 = " + fabric_mod_name + "_reset_nexus,\n" buf += " .sess_logged_in = " + fabric_mod_name + "_sess_logged_in,\n" buf += " .sess_get_index = " + fabric_mod_name + "_sess_get_index,\n" buf += " .sess_get_initiator_sid = NULL,\n" buf += " .write_pending = " + fabric_mod_name + "_write_pending,\n" buf += " .write_pending_status = " + fabric_mod_name + "_write_pending_status,\n" buf += " .set_default_node_attributes = " + fabric_mod_name + "_set_default_node_attrs,\n" buf += " .get_task_tag = " + fabric_mod_name + "_get_task_tag,\n" buf += " .get_cmd_state = " + fabric_mod_name + "_get_cmd_state,\n" buf += " .queue_data_in = " + fabric_mod_name + "_queue_data_in,\n" buf += " .queue_status = " + fabric_mod_name + "_queue_status,\n" buf += " .queue_tm_rsp = " + fabric_mod_name + "_queue_tm_rsp,\n" buf += " .is_state_remove = " + fabric_mod_name + "_is_state_remove,\n" buf += " /*\n" buf += " * Setup function pointers for generic logic in target_core_fabric_configfs.c\n" buf += " */\n" buf += " .fabric_make_wwn = " + fabric_mod_name + "_make_" + fabric_mod_port + ",\n" buf += " .fabric_drop_wwn = " + fabric_mod_name + "_drop_" + fabric_mod_port + ",\n" buf += " .fabric_make_tpg = " + fabric_mod_name + "_make_tpg,\n" buf += " .fabric_drop_tpg = " + fabric_mod_name + "_drop_tpg,\n" buf += " .fabric_post_link = NULL,\n" buf += " .fabric_pre_unlink = NULL,\n" buf += " .fabric_make_np = NULL,\n" buf += " .fabric_drop_np = NULL,\n" buf += " .fabric_make_nodeacl = " + fabric_mod_name + "_make_nodeacl,\n" buf += " .fabric_drop_nodeacl = " + fabric_mod_name + "_drop_nodeacl,\n" buf += "};\n\n" buf += "static int " + fabric_mod_name + "_register_configfs(void)\n" buf += "{\n" buf += " struct target_fabric_configfs *fabric;\n" buf += " int ret;\n\n" buf += " printk(KERN_INFO \"" + fabric_mod_name.upper() + " fabric module %s on %s/%s\"\n" buf += " \" on \"UTS_RELEASE\"\\n\"," + fabric_mod_name.upper() + "_VERSION, utsname()->sysname,\n" buf += " utsname()->machine);\n" buf += " /*\n" buf += " * Register the top level struct config_item_type with TCM core\n" buf += " */\n" buf += " fabric = target_fabric_configfs_init(THIS_MODULE, \"" + fabric_mod_name[4:] + "\");\n" buf += " if (IS_ERR(fabric)) {\n" buf += " printk(KERN_ERR \"target_fabric_configfs_init() failed\\n\");\n" buf += " return PTR_ERR(fabric);\n" buf += " }\n" buf += " /*\n" buf += " * Setup fabric->tf_ops from our local " + fabric_mod_name + "_ops\n" buf += " */\n" buf += " fabric->tf_ops = " + fabric_mod_name + "_ops;\n" buf += " /*\n" buf += " * Setup default attribute lists for various fabric->tf_cit_tmpl\n" buf += " */\n" buf += " TF_CIT_TMPL(fabric)->tfc_wwn_cit.ct_attrs = " + fabric_mod_name + "_wwn_attrs;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_base_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_attrib_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_param_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_np_base_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_nacl_base_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_nacl_attrib_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_nacl_auth_cit.ct_attrs = NULL;\n" buf += " TF_CIT_TMPL(fabric)->tfc_tpg_nacl_param_cit.ct_attrs = NULL;\n" buf += " /*\n" buf += " * Register the fabric for use within TCM\n" buf += " */\n" buf += " ret = target_fabric_configfs_register(fabric);\n" buf += " if (ret < 0) {\n" buf += " printk(KERN_ERR \"target_fabric_configfs_register() failed\"\n" buf += " \" for " + fabric_mod_name.upper() + "\\n\");\n" buf += " return ret;\n" buf += " }\n" buf += " /*\n" buf += " * Setup our local pointer to *fabric\n" buf += " */\n" buf += " " + fabric_mod_name + "_fabric_configfs = fabric;\n" buf += " printk(KERN_INFO \"" + fabric_mod_name.upper() + "[0] - Set fabric -> " + fabric_mod_name + "_fabric_configfs\\n\");\n" buf += " return 0;\n" buf += "};\n\n" buf += "static void __exit " + fabric_mod_name + "_deregister_configfs(void)\n" buf += "{\n" buf += " if (!" + fabric_mod_name + "_fabric_configfs)\n" buf += " return;\n\n" buf += " target_fabric_configfs_deregister(" + fabric_mod_name + "_fabric_configfs);\n" buf += " " + fabric_mod_name + "_fabric_configfs = NULL;\n" buf += " printk(KERN_INFO \"" + fabric_mod_name.upper() + "[0] - Cleared " + fabric_mod_name + "_fabric_configfs\\n\");\n" buf += "};\n\n" buf += "static int __init " + fabric_mod_name + "_init(void)\n" buf += "{\n" buf += " int ret;\n\n" buf += " ret = " + fabric_mod_name + "_register_configfs();\n" buf += " if (ret < 0)\n" buf += " return ret;\n\n" buf += " return 0;\n" buf += "};\n\n" buf += "static void __exit " + fabric_mod_name + "_exit(void)\n" buf += "{\n" buf += " " + fabric_mod_name + "_deregister_configfs();\n" buf += "};\n\n" buf += "MODULE_DESCRIPTION(\"" + fabric_mod_name.upper() + " series fabric driver\");\n" buf += "MODULE_LICENSE(\"GPL\");\n" buf += "module_init(" + fabric_mod_name + "_init);\n" buf += "module_exit(" + fabric_mod_name + "_exit);\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() return def tcm_mod_scan_fabric_ops(tcm_dir): fabric_ops_api = tcm_dir + "include/target/target_core_fabric.h" print "Using tcm_mod_scan_fabric_ops: " + fabric_ops_api process_fo = 0; p = open(fabric_ops_api, 'r') line = p.readline() while line: if process_fo == 0 and re.search('struct target_core_fabric_ops {', line): line = p.readline() continue if process_fo == 0: process_fo = 1; line = p.readline() # Search for function pointer if not re.search('\(\*', line): continue fabric_ops.append(line.rstrip()) continue line = p.readline() # Search for function pointer if not re.search('\(\*', line): continue fabric_ops.append(line.rstrip()) p.close() return def tcm_mod_dump_fabric_ops(proto_ident, fabric_mod_dir_var, fabric_mod_name): buf = "" bufi = "" f = fabric_mod_dir_var + "/" + fabric_mod_name + "_fabric.c" print "Writing file: " + f p = open(f, 'w') if not p: tcm_mod_err("Unable to open file: " + f) fi = fabric_mod_dir_var + "/" + fabric_mod_name + "_fabric.h" print "Writing file: " + fi pi = open(fi, 'w') if not pi: tcm_mod_err("Unable to open file: " + fi) buf = "#include <linux/slab.h>\n" buf += "#include <linux/kthread.h>\n" buf += "#include <linux/types.h>\n" buf += "#include <linux/list.h>\n" buf += "#include <linux/types.h>\n" buf += "#include <linux/string.h>\n" buf += "#include <linux/ctype.h>\n" buf += "#include <asm/unaligned.h>\n" buf += "#include <scsi/scsi.h>\n" buf += "#include <scsi/scsi_host.h>\n" buf += "#include <scsi/scsi_device.h>\n" buf += "#include <scsi/scsi_cmnd.h>\n" buf += "#include <scsi/libfc.h>\n\n" buf += "#include <target/target_core_base.h>\n" buf += "#include <target/target_core_fabric.h>\n" buf += "#include <target/target_core_configfs.h>\n\n" buf += "#include \"" + fabric_mod_name + "_base.h\"\n" buf += "#include \"" + fabric_mod_name + "_fabric.h\"\n\n" buf += "int " + fabric_mod_name + "_check_true(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " return 1;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_check_true(struct se_portal_group *);\n" buf += "int " + fabric_mod_name + "_check_false(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_check_false(struct se_portal_group *);\n" total_fabric_ops = len(fabric_ops) i = 0 while i < total_fabric_ops: fo = fabric_ops[i] i += 1 # print "fabric_ops: " + fo if re.search('get_fabric_name', fo): buf += "char *" + fabric_mod_name + "_get_fabric_name(void)\n" buf += "{\n" buf += " return \"" + fabric_mod_name[4:] + "\";\n" buf += "}\n\n" bufi += "char *" + fabric_mod_name + "_get_fabric_name(void);\n" continue if re.search('get_fabric_proto_ident', fo): buf += "u8 " + fabric_mod_name + "_get_fabric_proto_ident(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n" buf += " u8 proto_id;\n\n" buf += " switch (" + fabric_mod_port + "->" + fabric_mod_port + "_proto_id) {\n" if proto_ident == "FC": buf += " case SCSI_PROTOCOL_FCP:\n" buf += " default:\n" buf += " proto_id = fc_get_fabric_proto_ident(se_tpg);\n" buf += " break;\n" elif proto_ident == "SAS": buf += " case SCSI_PROTOCOL_SAS:\n" buf += " default:\n" buf += " proto_id = sas_get_fabric_proto_ident(se_tpg);\n" buf += " break;\n" elif proto_ident == "iSCSI": buf += " case SCSI_PROTOCOL_ISCSI:\n" buf += " default:\n" buf += " proto_id = iscsi_get_fabric_proto_ident(se_tpg);\n" buf += " break;\n" buf += " }\n\n" buf += " return proto_id;\n" buf += "}\n\n" bufi += "u8 " + fabric_mod_name + "_get_fabric_proto_ident(struct se_portal_group *);\n" if re.search('get_wwn', fo): buf += "char *" + fabric_mod_name + "_get_fabric_wwn(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n\n" buf += " return &" + fabric_mod_port + "->" + fabric_mod_port + "_name[0];\n" buf += "}\n\n" bufi += "char *" + fabric_mod_name + "_get_fabric_wwn(struct se_portal_group *);\n" if re.search('get_tag', fo): buf += "u16 " + fabric_mod_name + "_get_tag(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " return tpg->" + fabric_mod_port + "_tpgt;\n" buf += "}\n\n" bufi += "u16 " + fabric_mod_name + "_get_tag(struct se_portal_group *);\n" if re.search('get_default_depth', fo): buf += "u32 " + fabric_mod_name + "_get_default_depth(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " return 1;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_get_default_depth(struct se_portal_group *);\n" if re.search('get_pr_transport_id\)\(', fo): buf += "u32 " + fabric_mod_name + "_get_pr_transport_id(\n" buf += " struct se_portal_group *se_tpg,\n" buf += " struct se_node_acl *se_nacl,\n" buf += " struct t10_pr_registration *pr_reg,\n" buf += " int *format_code,\n" buf += " unsigned char *buf)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n" buf += " int ret = 0;\n\n" buf += " switch (" + fabric_mod_port + "->" + fabric_mod_port + "_proto_id) {\n" if proto_ident == "FC": buf += " case SCSI_PROTOCOL_FCP:\n" buf += " default:\n" buf += " ret = fc_get_pr_transport_id(se_tpg, se_nacl, pr_reg,\n" buf += " format_code, buf);\n" buf += " break;\n" elif proto_ident == "SAS": buf += " case SCSI_PROTOCOL_SAS:\n" buf += " default:\n" buf += " ret = sas_get_pr_transport_id(se_tpg, se_nacl, pr_reg,\n" buf += " format_code, buf);\n" buf += " break;\n" elif proto_ident == "iSCSI": buf += " case SCSI_PROTOCOL_ISCSI:\n" buf += " default:\n" buf += " ret = iscsi_get_pr_transport_id(se_tpg, se_nacl, pr_reg,\n" buf += " format_code, buf);\n" buf += " break;\n" buf += " }\n\n" buf += " return ret;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_get_pr_transport_id(struct se_portal_group *,\n" bufi += " struct se_node_acl *, struct t10_pr_registration *,\n" bufi += " int *, unsigned char *);\n" if re.search('get_pr_transport_id_len\)\(', fo): buf += "u32 " + fabric_mod_name + "_get_pr_transport_id_len(\n" buf += " struct se_portal_group *se_tpg,\n" buf += " struct se_node_acl *se_nacl,\n" buf += " struct t10_pr_registration *pr_reg,\n" buf += " int *format_code)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n" buf += " int ret = 0;\n\n" buf += " switch (" + fabric_mod_port + "->" + fabric_mod_port + "_proto_id) {\n" if proto_ident == "FC": buf += " case SCSI_PROTOCOL_FCP:\n" buf += " default:\n" buf += " ret = fc_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,\n" buf += " format_code);\n" buf += " break;\n" elif proto_ident == "SAS": buf += " case SCSI_PROTOCOL_SAS:\n" buf += " default:\n" buf += " ret = sas_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,\n" buf += " format_code);\n" buf += " break;\n" elif proto_ident == "iSCSI": buf += " case SCSI_PROTOCOL_ISCSI:\n" buf += " default:\n" buf += " ret = iscsi_get_pr_transport_id_len(se_tpg, se_nacl, pr_reg,\n" buf += " format_code);\n" buf += " break;\n" buf += " }\n\n" buf += " return ret;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_get_pr_transport_id_len(struct se_portal_group *,\n" bufi += " struct se_node_acl *, struct t10_pr_registration *,\n" bufi += " int *);\n" if re.search('parse_pr_out_transport_id\)\(', fo): buf += "char *" + fabric_mod_name + "_parse_pr_out_transport_id(\n" buf += " struct se_portal_group *se_tpg,\n" buf += " const char *buf,\n" buf += " u32 *out_tid_len,\n" buf += " char **port_nexus_ptr)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_tpg *tpg = container_of(se_tpg,\n" buf += " struct " + fabric_mod_name + "_tpg, se_tpg);\n" buf += " struct " + fabric_mod_name + "_" + fabric_mod_port + " *" + fabric_mod_port + " = tpg->" + fabric_mod_port + ";\n" buf += " char *tid = NULL;\n\n" buf += " switch (" + fabric_mod_port + "->" + fabric_mod_port + "_proto_id) {\n" if proto_ident == "FC": buf += " case SCSI_PROTOCOL_FCP:\n" buf += " default:\n" buf += " tid = fc_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,\n" buf += " port_nexus_ptr);\n" elif proto_ident == "SAS": buf += " case SCSI_PROTOCOL_SAS:\n" buf += " default:\n" buf += " tid = sas_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,\n" buf += " port_nexus_ptr);\n" elif proto_ident == "iSCSI": buf += " case SCSI_PROTOCOL_ISCSI:\n" buf += " default:\n" buf += " tid = iscsi_parse_pr_out_transport_id(se_tpg, buf, out_tid_len,\n" buf += " port_nexus_ptr);\n" buf += " }\n\n" buf += " return tid;\n" buf += "}\n\n" bufi += "char *" + fabric_mod_name + "_parse_pr_out_transport_id(struct se_portal_group *,\n" bufi += " const char *, u32 *, char **);\n" if re.search('alloc_fabric_acl\)\(', fo): buf += "struct se_node_acl *" + fabric_mod_name + "_alloc_fabric_acl(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_nacl *nacl;\n\n" buf += " nacl = kzalloc(sizeof(struct " + fabric_mod_name + "_nacl), GFP_KERNEL);\n" buf += " if (!nacl) {\n" buf += " printk(KERN_ERR \"Unable to allocate struct " + fabric_mod_name + "_nacl\\n\");\n" buf += " return NULL;\n" buf += " }\n\n" buf += " return &nacl->se_node_acl;\n" buf += "}\n\n" bufi += "struct se_node_acl *" + fabric_mod_name + "_alloc_fabric_acl(struct se_portal_group *);\n" if re.search('release_fabric_acl\)\(', fo): buf += "void " + fabric_mod_name + "_release_fabric_acl(\n" buf += " struct se_portal_group *se_tpg,\n" buf += " struct se_node_acl *se_nacl)\n" buf += "{\n" buf += " struct " + fabric_mod_name + "_nacl *nacl = container_of(se_nacl,\n" buf += " struct " + fabric_mod_name + "_nacl, se_node_acl);\n" buf += " kfree(nacl);\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_release_fabric_acl(struct se_portal_group *,\n" bufi += " struct se_node_acl *);\n" if re.search('tpg_get_inst_index\)\(', fo): buf += "u32 " + fabric_mod_name + "_tpg_get_inst_index(struct se_portal_group *se_tpg)\n" buf += "{\n" buf += " return 1;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_tpg_get_inst_index(struct se_portal_group *);\n" if re.search('\*release_cmd\)\(', fo): buf += "void " + fabric_mod_name + "_release_cmd(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_release_cmd(struct se_cmd *);\n" if re.search('shutdown_session\)\(', fo): buf += "int " + fabric_mod_name + "_shutdown_session(struct se_session *se_sess)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_shutdown_session(struct se_session *);\n" if re.search('close_session\)\(', fo): buf += "void " + fabric_mod_name + "_close_session(struct se_session *se_sess)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_close_session(struct se_session *);\n" if re.search('stop_session\)\(', fo): buf += "void " + fabric_mod_name + "_stop_session(struct se_session *se_sess, int sess_sleep , int conn_sleep)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_stop_session(struct se_session *, int, int);\n" if re.search('fall_back_to_erl0\)\(', fo): buf += "void " + fabric_mod_name + "_reset_nexus(struct se_session *se_sess)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_reset_nexus(struct se_session *);\n" if re.search('sess_logged_in\)\(', fo): buf += "int " + fabric_mod_name + "_sess_logged_in(struct se_session *se_sess)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_sess_logged_in(struct se_session *);\n" if re.search('sess_get_index\)\(', fo): buf += "u32 " + fabric_mod_name + "_sess_get_index(struct se_session *se_sess)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_sess_get_index(struct se_session *);\n" if re.search('write_pending\)\(', fo): buf += "int " + fabric_mod_name + "_write_pending(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_write_pending(struct se_cmd *);\n" if re.search('write_pending_status\)\(', fo): buf += "int " + fabric_mod_name + "_write_pending_status(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_write_pending_status(struct se_cmd *);\n" if re.search('set_default_node_attributes\)\(', fo): buf += "void " + fabric_mod_name + "_set_default_node_attrs(struct se_node_acl *nacl)\n" buf += "{\n" buf += " return;\n" buf += "}\n\n" bufi += "void " + fabric_mod_name + "_set_default_node_attrs(struct se_node_acl *);\n" if re.search('get_task_tag\)\(', fo): buf += "u32 " + fabric_mod_name + "_get_task_tag(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "u32 " + fabric_mod_name + "_get_task_tag(struct se_cmd *);\n" if re.search('get_cmd_state\)\(', fo): buf += "int " + fabric_mod_name + "_get_cmd_state(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_get_cmd_state(struct se_cmd *);\n" if re.search('queue_data_in\)\(', fo): buf += "int " + fabric_mod_name + "_queue_data_in(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_queue_data_in(struct se_cmd *);\n" if re.search('queue_status\)\(', fo): buf += "int " + fabric_mod_name + "_queue_status(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_queue_status(struct se_cmd *);\n" if re.search('queue_tm_rsp\)\(', fo): buf += "int " + fabric_mod_name + "_queue_tm_rsp(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_queue_tm_rsp(struct se_cmd *);\n" if re.search('is_state_remove\)\(', fo): buf += "int " + fabric_mod_name + "_is_state_remove(struct se_cmd *se_cmd)\n" buf += "{\n" buf += " return 0;\n" buf += "}\n\n" bufi += "int " + fabric_mod_name + "_is_state_remove(struct se_cmd *);\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() ret = pi.write(bufi) if ret: tcm_mod_err("Unable to write fi: " + fi) pi.close() return def tcm_mod_build_kbuild(fabric_mod_dir_var, fabric_mod_name): buf = "" f = fabric_mod_dir_var + "/Makefile" print "Writing file: " + f p = open(f, 'w') if not p: tcm_mod_err("Unable to open file: " + f) buf += fabric_mod_name + "-objs := " + fabric_mod_name + "_fabric.o \\\n" buf += " " + fabric_mod_name + "_configfs.o\n" buf += "obj-$(CONFIG_" + fabric_mod_name.upper() + ") += " + fabric_mod_name + ".o\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() return def tcm_mod_build_kconfig(fabric_mod_dir_var, fabric_mod_name): buf = "" f = fabric_mod_dir_var + "/Kconfig" print "Writing file: " + f p = open(f, 'w') if not p: tcm_mod_err("Unable to open file: " + f) buf = "config " + fabric_mod_name.upper() + "\n" buf += " tristate \"" + fabric_mod_name.upper() + " fabric module\"\n" buf += " depends on TARGET_CORE && CONFIGFS_FS\n" buf += " default n\n" buf += " ---help---\n" buf += " Say Y here to enable the " + fabric_mod_name.upper() + " fabric module\n" ret = p.write(buf) if ret: tcm_mod_err("Unable to write f: " + f) p.close() return def tcm_mod_add_kbuild(tcm_dir, fabric_mod_name): buf = "obj-$(CONFIG_" + fabric_mod_name.upper() + ") += " + fabric_mod_name.lower() + "/\n" kbuild = tcm_dir + "/drivers/target/Makefile" f = open(kbuild, 'a') f.write(buf) f.close() return def tcm_mod_add_kconfig(tcm_dir, fabric_mod_name): buf = "source \"drivers/target/" + fabric_mod_name.lower() + "/Kconfig\"\n" kconfig = tcm_dir + "/drivers/target/Kconfig" f = open(kconfig, 'a') f.write(buf) f.close() return def main(modname, proto_ident): # proto_ident = "FC" # proto_ident = "SAS" # proto_ident = "iSCSI" tcm_dir = os.getcwd(); tcm_dir += "/../../" print "tcm_dir: " + tcm_dir fabric_mod_name = modname fabric_mod_dir = tcm_dir + "drivers/target/" + fabric_mod_name print "Set fabric_mod_name: " + fabric_mod_name print "Set fabric_mod_dir: " + fabric_mod_dir print "Using proto_ident: " + proto_ident if proto_ident != "FC" and proto_ident != "SAS" and proto_ident != "iSCSI": print "Unsupported proto_ident: " + proto_ident sys.exit(1) ret = tcm_mod_create_module_subdir(fabric_mod_dir) if ret: print "tcm_mod_create_module_subdir() failed because module already exists!" sys.exit(1) tcm_mod_build_base_includes(proto_ident, fabric_mod_dir, fabric_mod_name) tcm_mod_scan_fabric_ops(tcm_dir) tcm_mod_dump_fabric_ops(proto_ident, fabric_mod_dir, fabric_mod_name) tcm_mod_build_configfs(proto_ident, fabric_mod_dir, fabric_mod_name) tcm_mod_build_kbuild(fabric_mod_dir, fabric_mod_name) tcm_mod_build_kconfig(fabric_mod_dir, fabric_mod_name) input = raw_input("Would you like to add " + fabric_mod_name + "to drivers/target/Makefile..? [yes,no]: ") if input == "yes" or input == "y": tcm_mod_add_kbuild(tcm_dir, fabric_mod_name) input = raw_input("Would you like to add " + fabric_mod_name + "to drivers/target/Kconfig..? [yes,no]: ") if input == "yes" or input == "y": tcm_mod_add_kconfig(tcm_dir, fabric_mod_name) return parser = optparse.OptionParser() parser.add_option('-m', '--modulename', help='Module name', dest='modname', action='store', nargs=1, type='string') parser.add_option('-p', '--protoident', help='Protocol Ident', dest='protoident', action='store', nargs=1, type='string') (opts, args) = parser.parse_args() mandatories = ['modname', 'protoident'] for m in mandatories: if not opts.__dict__[m]: print "mandatory option is missing\n" parser.print_help() exit(-1) if __name__ == "__main__": main(str(opts.modname), opts.protoident)
gpl-2.0
jcftang/ansible
lib/ansible/modules/windows/win_template.py
35
3126
# this is a virtual module that is entirely implemented server side # 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': ['stableinterface'], 'supported_by': 'core', 'version': '1.0'} DOCUMENTATION = r''' --- module: win_template version_added: "1.9.2" short_description: Templates a file out to a remote server. description: - Templates are processed by the Jinja2 templating language (U(http://jinja.pocoo.org/docs/)) - documentation on the template formatting can be found in the Template Designer Documentation (U(http://jinja.pocoo.org/docs/templates/)). - "Six additional variables can be used in templates: C(ansible_managed) (configurable via the C(defaults) section of C(ansible.cfg)) contains a string which can be used to describe the template name, host, modification time of the template file and the owner uid, C(template_host) contains the node name of the template's machine, C(template_uid) the owner, C(template_path) the absolute path of the template, C(template_fullpath) is the absolute path of the template, and C(template_run_date) is the date that the template was rendered. Note that including a string that uses a date in the template will result in the template being marked 'changed' each time." options: src: description: - Path of a Jinja2 formatted template on the local server. This can be a relative or absolute path. required: true dest: description: - Location to render the template to on the remote machine. required: true notes: - "templates are loaded with C(trim_blocks=True)." - By default, windows line endings are not created in the generated file. - "In order to ensure windows line endings are in the generated file, add the following header as the first line of your template: ``#jinja2: newline_sequence:'\\r\\n'`` and ensure each line of the template ends with \\\\r\\\\n" - Beware fetching files from windows machines when creating templates because certain tools, such as Powershell ISE, and regedit's export facility add a Byte Order Mark as the first character of the file, which can cause tracebacks. - Use "od -cx" to examine your templates for Byte Order Marks. author: "Jon Hawkesworth (@jhawkesworth)" ''' EXAMPLES = r''' - name: Create a file from a Jinja2 template win_template: src: /mytemplates/file.conf.j2 dest: C:\temp\file.conf '''
gpl-3.0
destijl/grr
grr/client/stdlib.py
2
8367
#!/usr/bin/env python """This file imports the Python std lib so it can be used by components.""" # pylint: disable=g-import-not-at-top, unused-import, using-constant-test if False: import BaseHTTPServer import CGIHTTPServer import ConfigParser import Cookie import DocXMLRPCServer import HTMLParser import MimeWriter import Queue import SimpleHTTPServer import SimpleXMLRPCServer import SocketServer import StringIO import UserDict import UserList import UserString import _LWPCookieJar import _abcoll # https://github.com/pyinstaller/pyinstaller/issues/1425 import _cffi_backend import _osx_support import _pyio import _strptime import _sysconfigdata import _threading_local import _weakrefset import abc import aifc import anydbm import argparse import ast import asynchat import asyncore import atexit import audiodev import base64 import bdb import binhex import bisect import bsddb.db import bsddb.dbobj import bsddb.dbrecio import bsddb.dbshelve import bsddb.dbtables import bsddb.dbutils import cProfile import calendar import cgi import cgitb import chunk import cmd import code import codecs import codeop import collections import colorsys import commands import compileall import compiler.ast import compiler.consts import compiler.future import compiler.misc import compiler.pyassem import compiler.pycodegen import compiler.symbols import compiler.syntax import compiler.transformer import compiler.visitor import contextlib import cookielib import copy import copy_reg import csv import ctypes._endian import ctypes.util import curses.ascii import curses.has_key import curses.panel import curses.textpad import curses.wrapper import dbhash import decimal import difflib import dircache import dis import distutils.archive_util import distutils.bcppcompiler import distutils.ccompiler import distutils.cmd import distutils.command.bdist import distutils.command.bdist_dumb import distutils.command.bdist_rpm import distutils.command.bdist_wininst import distutils.command.build import distutils.command.build_clib import distutils.command.build_ext import distutils.command.build_py import distutils.command.build_scripts import distutils.command.check import distutils.command.clean import distutils.command.config import distutils.command.install import distutils.command.install_data import distutils.command.install_egg_info import distutils.command.install_headers import distutils.command.install_lib import distutils.command.install_scripts import distutils.command.register import distutils.command.sdist import distutils.command.upload import distutils.config import distutils.core import distutils.cygwinccompiler import distutils.debug import distutils.dep_util import distutils.dir_util import distutils.dist import distutils.emxccompiler import distutils.errors import distutils.extension import distutils.fancy_getopt import distutils.file_util import distutils.filelist import distutils.log import distutils.spawn import distutils.sysconfig import distutils.text_file import distutils.unixccompiler import distutils.util import distutils.version import distutils.versionpredicate import doctest import dumbdbm import dummy_thread import dummy_threading import email._parseaddr import email.base64mime import email.charset import email.encoders import email.errors import email.feedparser import email.generator import email.header import email.iterators import email.message import email.mime.application import email.mime.audio import email.mime.base import email.mime.image import email.mime.message import email.mime.multipart import email.mime.nonmultipart import email.mime.text import email.parser import email.quoprimime import email.utils import filecmp import fileinput import fnmatch import formatter import fpformat import fractions import ftplib import functools import genericpath import getopt import getpass import gettext import glob import gzip import hashlib import heapq import hmac import hotshot.log import hotshot.stats import hotshot.stones import htmlentitydefs import htmllib import httplib import ihooks import imaplib import imghdr import imputil import inspect import io import json.decoder import json.encoder import json.scanner import json.tool import keyword import linecache import locale import logging.config import logging.handlers import macpath import macurl2path import mailbox import mailcap import markupbase import md5 import mhlib import mimetools import mimetypes import mimify import modulefinder import multifile import multiprocessing.connection import multiprocessing.dummy.connection import multiprocessing.forking import multiprocessing.heap import multiprocessing.managers import multiprocessing.pool import multiprocessing.process import multiprocessing.queues import multiprocessing.reduction import multiprocessing.sharedctypes import multiprocessing.synchronize import multiprocessing.util import mutex import netrc import new import nntplib import ntpath import nturl2path import numbers import opcode import optparse import os import os2emxpath import pdb import pickle import pickletools import pipes import pkgutil import platform import plistlib import popen2 import poplib import posixfile import posixpath import pprint import profile import pstats import pty import py_compile import pyclbr import pydoc import pydoc_data.topics import quopri import random import re import rfc822 import rlcompleter import robotparser import runpy import sched import sets import sgmllib import sha import shelve import shlex import shutil import site import smtpd import smtplib import sndhdr import socket import sqlite3.dbapi2 import sqlite3.dump import sre import sre_compile import sre_constants import sre_parse import ssl import stat import statvfs import string import stringold import stringprep import struct import subprocess import sunau import sunaudio import symbol import symtable import sysconfig import tabnanny import tarfile import telnetlib import tempfile import test.pystone import test.regrtest import test.test_support import textwrap import this import threading import timeit import toaiff import token import tokenize import trace import traceback import tty import types import urllib import urllib2 import urlparse import user import uu import uuid import warnings import wave import weakref import whichdb import wsgiref.handlers import wsgiref.headers import wsgiref.simple_server import wsgiref.util import wsgiref.validate import xdrlib import xml.dom.NodeFilter import xml.dom.domreg import xml.dom.expatbuilder import xml.dom.minicompat import xml.dom.minidom import xml.dom.pulldom import xml.dom.xmlbuilder import xml.etree.ElementInclude import xml.etree.ElementPath import xml.etree.ElementTree import xml.etree.cElementTree import xml.parsers.expat import xml.sax._exceptions import xml.sax.expatreader import xml.sax.handler import xml.sax.saxutils import xml.sax.xmlreader import xmllib import xmlrpclib import zipfile # lib-dynload import audioop import _bsddb import bz2 import _codecs_cn import _codecs_hk import _codecs_iso2022 import _codecs_jp import _codecs_kr import _codecs_tw import crypt import _csv import _ctypes_test import _ctypes import _curses_panel import _curses import datetime import dbm import _elementtree import fpectl import future_builtins import gdbm import _hashlib import _hotshot import _json import linuxaudiodev import _lsprof import mmap import _multibytecodec import _multiprocessing import nis import ossaudiodev import parser import pyexpat import readline import resource import _sqlite3 import _ssl import termios import _testcapi import _tkinter
apache-2.0
walteryang47/ovirt-engine
packaging/setup/plugins/ovirt-engine-common/base/network/firewall_manager_iptables.py
7
8581
# # ovirt-engine-setup -- ovirt engine setup # Copyright (C) 2013-2015 Red Hat, 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. # """ Firewall manager iptables plugin. """ import difflib import gettext import os from otopi import constants as otopicons from otopi import filetransaction, plugin, util from ovirt_engine import util as outil from ovirt_engine_setup import constants as osetupcons from ovirt_engine_setup import dialog, firewall_manager_base from . import process_firewalld_services def _(m): return gettext.dgettext(message=m, domain='ovirt-engine-setup') @util.export class Plugin(plugin.PluginBase): """ Firewall manager iptables plugin. """ class _IpTablesManager(firewall_manager_base.FirewallManagerBase): _SERVICE = 'iptables' def _get_rules(self): if self._rules is None: self._rules = outil.processTemplate( osetupcons.FileLocations.OVIRT_IPTABLES_DEFAULT, subst={ '@CUSTOM_RULES@': ( process_firewalld_services.Process.getInstance( environment=self.environment, ).parseFirewalld( format=( '-A INPUT -p {protocol} -m state ' '--state NEW -m {protocol} ' '--dport {port} -j ACCEPT\n' ), portSeparator=':', ) ), } ) return self._rules def __init__(self, plugin): super(Plugin._IpTablesManager, self).__init__(plugin) self._rules = None @property def name(self): return osetupcons.Const.FIREWALL_MANAGER_IPTABLES def detect(self): return self.plugin.services.exists(self._SERVICE) def active(self): return self.plugin.services.status(self._SERVICE) def prepare_examples(self): content = self._get_rules() self.environment[otopicons.CoreEnv.MAIN_TRANSACTION].append( filetransaction.FileTransaction( name=osetupcons.FileLocations.OVIRT_IPTABLES_EXAMPLE, content=content, modifiedList=self.environment[ otopicons.CoreEnv.MODIFIED_FILES ], ) ) def enable(self): self.environment[otopicons.NetEnv.IPTABLES_ENABLE] = True self.environment[ otopicons.NetEnv.IPTABLES_RULES ] = self._get_rules() # This file is updated by otopi. Here we just prevent it from # being deleted on cleanup. # TODO: copy/move some uninstall code from the engine to otopi # to allow just adding lines to iptables instead of replacing # the file and also remove these lines on cleanup. self.environment[ osetupcons.CoreEnv.UNINSTALL_UNREMOVABLE_FILES ].append( osetupcons.FileLocations.SYSCONFIG_IPTABLES, ) def print_manual_configuration_instructions(self): self.plugin.dialog.note( text=_( 'An example of the required configuration for iptables ' 'can be found at:\n' ' {example}' ).format( example=osetupcons.FileLocations.OVIRT_IPTABLES_EXAMPLE ) ) def review_config(self): diff_lines = '' current_rules = '' current_modified_since_prev_setup = False interactive = True if os.path.isfile(osetupcons.FileLocations.SYSCONFIG_IPTABLES): with open( osetupcons.FileLocations.SYSCONFIG_IPTABLES, 'r' ) as current: current_rules = current.read().splitlines() if os.path.isfile(osetupcons.FileLocations.OVIRT_IPTABLES_EXAMPLE): with open( osetupcons.FileLocations.OVIRT_IPTABLES_EXAMPLE, 'r' ) as prev_setup_example: prev_setup_rules = prev_setup_example.read().splitlines() diff_prev_cur = difflib.unified_diff( current_rules, prev_setup_rules, lineterm='', ) diff_lines = '\n'.join(diff_prev_cur) if len(diff_lines) > 0: current_modified_since_prev_setup = True diff = difflib.unified_diff( current_rules, self._get_rules().splitlines(), lineterm='', fromfile=_('current'), tofile=_('proposed'), ) diff_lines = '\n'.join(diff) if len(diff_lines) > 0: if current_modified_since_prev_setup: self.logger.warning( _( "It seams that previously generated iptables " "configuration was manually edited,\n" "please carefully review the proposed " "configuration" ) ) if self.environment[ osetupcons.ConfigEnv.FIREWALL_CHANGES_REVIEW ] is None: self.environment[ osetupcons.ConfigEnv.FIREWALL_CHANGES_REVIEW ] = dialog.queryBoolean( dialog=self.plugin.dialog, name='OVESETUP_REVIEW_IPTABLES_CHANGES', note=_( 'Generated iptables rules are different ' 'from current ones.\n' 'Do you want to review them? ' '(@VALUES@) [@DEFAULT@]: ' ), prompt=True, true=_('Yes'), false=_('No'), default=False, ) else: interactive = False if self.environment[ osetupcons.ConfigEnv.FIREWALL_CHANGES_REVIEW ] and interactive: confirmed = dialog.queryBoolean( dialog=self.plugin.dialog, name='OVESETUP_CONFIRM_IPTABLES_CHANGES', note=_( 'Please review the changes:\n\n' '{diff}\n\n' 'Do you want to proceed with firewall ' 'configuration? ' '(@VALUES@) [@DEFAULT@]: ' ).format( diff=diff_lines ), prompt=True, true=_('Yes'), false=_('No'), default=True, ) if not confirmed: raise RuntimeError( _( 'iptables proposed configuration ' 'was rejected by user' ) ) @plugin.event( stage=plugin.Stages.STAGE_SETUP, before=( osetupcons.Stages.KEEP_ONLY_VALID_FIREWALL_MANAGERS, ), ) def _setup(self): self.environment[ osetupcons.ConfigEnv.FIREWALL_MANAGERS ].append(Plugin._IpTablesManager(self)) # vim: expandtab tabstop=4 shiftwidth=4
apache-2.0
wbrp/dnsimple-zoneimport
setup.py
1
1349
# -*- coding: utf-8 -*- from setuptools import setup, find_packages from dnsimple_zoneimport import meta f = open('requirements.txt', 'r') lines = f.readlines() requirements = [l.strip().strip('\n') for l in lines if l.strip() and not l.strip().startswith('#')] readme = open('README.rst').read() setup(name='dnsimple-zoneimport', version=meta.version, description=meta.description, author=meta.author, author_email=meta.author_email, url='https://github.com/wbrp/dnsimple-zoneimport', packages=find_packages(), zip_safe=False, include_package_data=True, license=meta.license, keywords='dnsimple dns "zone files" bind import api', long_description=readme, install_requires=requirements, entry_points={ 'console_scripts': [ '%s = dnsimple_zoneimport.importer:main' % meta.title.replace('-', '_'), ] }, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: MacOS', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: Name Service (DNS)', 'Topic :: Terminals', ], )
mit
Antiun/stock-logistics-workflow
product_customer_code_picking/__init__.py
25
1043
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2013 Agile Business Group sagl (<http://www.agilebg.com>) # Author: Nicola Malcontenti <nicola.malcontenti@agilebg.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import stock_picking
agpl-3.0
flavour/cedarbluff
modules/eden/project.py
1
132447
# -*- coding: utf-8 -*- """ Sahana Eden Project Model @copyright: 2011-2012 (c) Sahana Software Foundation @license: MIT 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. """ __all__ = ["S3ProjectModel", "S3ProjectDRRModel", "S3ProjectTaskModel", "S3ProjectTaskHRMModel", "S3ProjectTaskIReportModel", "project_rheader", "S3ProjectTaskVirtualfields"] import datetime from gluon import * from gluon.dal import Row from gluon.storage import Storage from gluon.sqlhtml import CheckboxesWidget from ..s3 import * try: from lxml import etree, html except ImportError: import sys print >> sys.stderr, "ERROR: lxml module needed for XML handling" raise # ============================================================================= class S3ProjectModel(S3Model): """ Project Model Note: This module operates in 2 quite different modes: - 'drr': suitable for use by multinational organisations tracking projects at a high level - non-drr: suitable for use by a smaller organsiation tracking tasks at a detailed level This class contains the tables common to both uses There are additional tabels in S3ProjectDRRModel and S3ProjectTaskModel for the other 2 use cases There are also additional Classes for optional Link Tables """ names = ["project_theme", "project_hazard", "project_project", "project_activity_type", "project_activity", "project_activity_contact", "project_project_id", "project_activity_id", "project_hfa_opts", "project_project_represent", ] def model(self): T = current.T db = current.db request = current.request s3 = current.response.s3 settings = current.deployment_settings currency_type = s3.currency_type person_id = self.pr_person_id location_id = self.gis_location_id countries_id = self.gis_countries_id organisation_id = self.org_organisation_id sector_id = self.org_sector_id human_resource_id = self.hrm_human_resource_id s3_date_format = settings.get_L10n_date_format() s3_date_represent = lambda dt: S3DateTime.date_represent(dt, utc=True) # Enable DRR extensions? drr = settings.get_project_drr() pca = settings.get_project_community_activity() # Shortcuts add_component = self.add_component comments = s3.comments configure = self.configure crud_strings = s3.crud_strings define_table = self.define_table meta_fields = s3.meta_fields super_link = self.super_link # --------------------------------------------------------------------- # Theme # @ToDo: Move to link table to move to S3ProjectDRRModel # tablename = "project_theme" table = define_table(tablename, Field("name", length=128, notnull=True, unique=True), Field("comments"), format = "%(name)s", *meta_fields()) # Field configuration? # CRUD Strings? # Search Method? # Resource Configuration? # Reusable Field multi_theme_id = S3ReusableField("multi_theme_id", "list:reference project_theme", label = T("Themes"), sortby = "name", requires = IS_NULL_OR(IS_ONE_OF(db, "project_theme.id", "%(name)s", sort=True, multiple=True)), represent = lambda opt, row=None: \ self.multiref_represent(opt, "project_theme"), default = [], ondelete = "RESTRICT", widget = lambda f, v: \ CheckboxesWidgetS3.widget(f, v, cols = 3)) # --------------------------------------------------------------------- # Hazard # @ToDo: Move to link table to move to S3ProjectDRRModel # tablename = "project_hazard" table = define_table(tablename, Field("name", length=128, notnull=True, unique=True), Field("comments"), format="%(name)s", *meta_fields()) # Field configuration? # CRUD Strings? # Search Method? # Resource Configuration? # Reusable Field multi_hazard_id = S3ReusableField("multi_hazard_id", "list:reference project_hazard", sortby = "name", label = T("Hazards"), requires = IS_NULL_OR(IS_ONE_OF(db, "project_hazard.id", "%(name)s", sort=True, multiple=True)), represent = lambda opt, row=None: \ self.multiref_represent(opt, "project_hazard"), ondelete = "RESTRICT", widget = lambda f, v: CheckboxesWidgetS3.widget(f, v, cols = 3)) # --------------------------------------------------------------------- # Project # # HFA # @todo: localization? project_hfa_opts = { 1: "HFA1: Ensure that disaster risk reduction is a national and a local priority with a strong institutional basis for implementation.", 2: "HFA2: Identify, assess and monitor disaster risks and enhance early warning.", 3: "HFA3: Use knowledge, innovation and education to build a culture of safety and resilience at all levels.", 4: "HFA4: Reduce the underlying risk factors.", 5: "HFA5: Strengthen disaster preparedness for effective response at all levels.", } tablename = "project_project" table = define_table(tablename, super_link("doc_id", "doc_entity"), # drr uses the separate project_organisation table organisation_id( readable=False if drr else True, writable=False if drr else True, ), Field("name", label = T("Name"), # Require unique=True if using IS_NOT_ONE_OF like here (same table, # no filter) in order to allow both automatic indexing (faster) # and key-based de-duplication (i.e. before field validation) unique = True, requires = [IS_NOT_EMPTY(error_message=T("Please fill this!")), IS_NOT_ONE_OF(db, "project_project.name")] ), Field("code", label = T("Code"), readable=False, writable=False, ), Field("description", "text", label = T("Description")), # NB There is additional client-side validation for start/end date in the Controller Field("start_date", "date", label = T("Start date"), represent = s3_date_represent, requires = IS_NULL_OR(IS_DATE(format = s3_date_format)), widget = S3DateWidget() ), Field("end_date", "date", label = T("End date"), represent = s3_date_represent, requires = IS_NULL_OR(IS_DATE(format = s3_date_format)), widget = S3DateWidget() ), Field("duration", readable=False, writable=False, label = T("Duration")), Field("calendar", readable=False if drr else True, writable=False if drr else True, label = T("Calendar"), requires = IS_NULL_OR(IS_URL()), comment = DIV(_class="tooltip", _title="%s|%s" % (T("Calendar"), T("URL to a Google Calendar to display on the project timeline.")))), currency_type( readable=False if drr else True, writable=False if drr else True, ), Field("budget", "double", # DRR handles on the Organisations Tab readable=False if drr else True, writable=False if drr else True, label = T("Budget")), sector_id( #readable=False, #writable=False, widget=lambda f, v: \ CheckboxesWidget.widget(f, v, cols=3)), countries_id( readable=drr, writable=drr ), multi_hazard_id( readable=drr, writable=drr ), multi_theme_id( readable=drr, writable=drr ), Field("hfa", "list:integer", label = T("HFA Priorities"), readable=drr, writable=drr, requires = IS_NULL_OR(IS_IN_SET(project_hfa_opts, multiple = True)), represent = self.hfa_opts_represent, widget = CheckboxesWidgetS3.widget), Field("objectives", "text", readable = drr, writable = drr, label = T("Objectives")), human_resource_id(label=T("Contact Person")), comments(comment=DIV(_class="tooltip", _title="%s|%s" % (T("Comments"), T("Outcomes, Impact, Challenges")))), format="%(name)s", *meta_fields()) # Field configuration? # CRUD Strings ADD_PROJECT = T("Add Project") crud_strings[tablename] = Storage( title_create = ADD_PROJECT, title_display = T("Project Details"), title_list = T("List Projects"), title_update = T("Edit Project"), title_search = T("Search Projects"), title_upload = T("Import Project List"), subtitle_create = T("Add New Project"), subtitle_list = T("Projects"), subtitle_upload = T("Upload Project List"), label_list_button = T("List Projects"), label_create_button = ADD_PROJECT, label_delete_button = T("Delete Project"), msg_record_created = T("Project added"), msg_record_modified = T("Project updated"), msg_record_deleted = T("Project deleted"), msg_list_empty = T("No Projects currently registered")) # Search Method if settings.get_ui_cluster(): sector = T("Cluster") else: sector = T("Sector") if drr: project_search = S3Search( advanced = ( S3SearchSimpleWidget( name = "project_search_text_advanced", label = T("Description"), comment = T("Search for a Project by description."), field = [ "name", "description", ] ), S3SearchOptionsWidget( name = "project_search_sector", label = sector, field = ["sector_id"], cols = 4 ), S3SearchOptionsWidget( name = "project_search_hazard", label = T("Hazard"), field = ["multi_hazard_id"], cols = 4 ), S3SearchOptionsWidget( name = "project_search_theme", label = T("Theme"), field = ["multi_theme_id"], cols = 4 ), S3SearchOptionsWidget( name = "project_search_hfa", label = T("HFA"), field = ["hfa"], cols = 4 ), ) ) else: project_search = S3Search( advanced = ( S3SearchSimpleWidget( name = "project_search_text_advanced", label = T("Description"), comment = T("Search for a Project by description."), field = [ "name", "description", ] ), S3SearchOptionsWidget( name = "project_search_sector", label = sector, field = ["sector_id"], cols = 4 ), ) ) # Resource Configuration if drr: next = "organisation" else: next = "activity" if drr: table.virtualfields.append(S3ProjectVirtualfields()) list_fields=["id", "name", (T("Lead Organisation"), "organisation"), "sector_id", "start_date", "end_date", "countries_id", "multi_hazard_id", "multi_theme_id", ] else: list_fields=["id", "name", "organisation_id", "start_date", "end_date", ] configure(tablename, super_entity="doc_entity", deduplicate=self.project_project_deduplicate, onvalidation=self.project_project_onvalidation, onaccept=self.project_project_onaccept, create_next=URL(c="project", f="project", args=["[id]", next]), search_method=project_search, list_fields=list_fields) # Reusable Field project_id = S3ReusableField("project_id", db.project_project, sortby="name", requires = IS_NULL_OR(IS_ONE_OF(db, "project_project.id", "%(name)s")), represent = self.project_represent, comment = s3_popup_comment(c="project", f="project", title=ADD_PROJECT, tooltip=T("If you don't see the project in the list, you can add a new one by clicking link 'Add Project'.")), label = T("Project"), ondelete = "CASCADE") # --------------------------------------------------------------------- # Custom Methods self.set_method(tablename, method="timeline", action=self.project_timeline) # Components # Organisations add_component("project_organisation", project_project="project_id") # Sites add_component("project_site", project_project="project_id") # Activities add_component("project_activity", project_project="project_id") # Milestones add_component("project_milestone", project_project="project_id") # Beneficiaries add_component("project_beneficiary", project_project="project_id") # Tasks add_component("project_task", project_project=Storage( link="project_task_project", joinby="project_id", key="task_id", actuate="replace", autocomplete="name", autodelete=False)) # --------------------------------------------------------------------- # Activity Type # tablename = "project_activity_type" table = define_table(tablename, Field("name", length=128, notnull=True, unique=True), format="%(name)s", *meta_fields()) # Field configuration? # CRUD Strings ADD_ACTIVITY_TYPE = T("Add Activity Type") LIST_ACTIVITY_TYPES = T("List of Activity Types") crud_strings[tablename] = Storage( title_create = ADD_ACTIVITY_TYPE, title_display = T("Activity Type"), title_list = LIST_ACTIVITY_TYPES, title_update = T("Edit Activity Type"), title_search = T("Search for Activity Type"), subtitle_create = T("Add New Activity Type"), subtitle_list = T("All Activity Types"), label_list_button = LIST_ACTIVITY_TYPES, label_create_button = ADD_ACTIVITY_TYPE, msg_record_created = T("Activity Type Added"), msg_record_modified = T("Activity Type Updated"), msg_record_deleted = T("Activity Type Deleted"), msg_list_empty = T("No Activity Types Found") ) # Search Method? # Resource Configuration? # Reusable Fields activity_type_id = S3ReusableField("activity_type_id", db.project_activity_type, sortby="name", requires = IS_NULL_OR(IS_ONE_OF(db, "project_activity_type.id", "%(name)s", sort=True)), represent = lambda id, row=None: \ s3_get_db_field_value(tablename = "project_activity_type", fieldname = "name", look_up_value = id), label = T("Activity Type"), comment = s3_popup_comment(c="project", f="activity_type", title=ADD_ACTIVITY_TYPE, tooltip=T("If you don't see the type in the list, you can add a new one by clicking link 'Add Activity Type'.")), ondelete = "RESTRICT") multi_activity_type_id = S3ReusableField("multi_activity_type_id", "list:reference project_activity_type", sortby = "name", label = T("Types of Activities"), requires = IS_NULL_OR(IS_ONE_OF(db, "project_activity_type.id", "%(name)s", sort=True, multiple=True)), represent = lambda opt, row=None: \ self.multiref_represent(opt, "project_activity_type"), #comment = skill_help, default = [], widget = lambda f, v: \ CheckboxesWidgetS3.widget(f, v, col=3), ondelete = "RESTRICT") # --------------------------------------------------------------------- # Project Activity # tablename = "project_activity" table = define_table(tablename, super_link("doc_id", "doc_entity"), project_id(), Field("name", label = T("Short Description"), requires=IS_NOT_EMPTY()), location_id( readable = drr, writable = drr, widget = S3LocationSelectorWidget(hide_address=True)), multi_activity_type_id(), Field("time_estimated", "double", readable=False if drr else True, writable=False if drr else True, label = "%s (%s)" % (T("Time Estimate"), T("hours"))), Field("time_actual", "double", readable=False if drr else True, # Gets populated from constituent Tasks writable=False, label = "%s (%s)" % (T("Time Taken"), T("hours"))), comments(), format="%(name)s", *meta_fields()) # Field configuration if pca: table.name.label = T("Name") # for list_fields table.name.readable = False table.name.writable = False table.name.requires = None # CRUD Strings if pca: ACTIVITY = T("Community") ACTIVITY_TOOLTIP = T("If you don't see the community in the list, you can add a new one by clicking link 'Add Community'.") ADD_ACTIVITY = T("Add Community") LIST_ACTIVITIES = T("List Communities") crud_strings[tablename] = Storage( title_create = ADD_ACTIVITY, title_display = T("Community Details"), title_list = LIST_ACTIVITIES, title_update = T("Edit Community Details"), title_search = T("Search Community"), title_upload = T("Import Community Data"), title_report = T("Who is doing What Where"), subtitle_create = T("Add New Community"), subtitle_list = T("Communities"), subtitle_report = T("Communities"), label_list_button = LIST_ACTIVITIES, label_create_button = ADD_ACTIVITY, msg_record_created = T("Community Added"), msg_record_modified = T("Community Updated"), msg_record_deleted = T("Community Deleted"), msg_list_empty = T("No Communities Found") ) else: ACTIVITY = T("Activity") ACTIVITY_TOOLTIP = T("If you don't see the activity in the list, you can add a new one by clicking link 'Add Activity'.") ADD_ACTIVITY = T("Add Activity") LIST_ACTIVITIES = T("List Activities") crud_strings[tablename] = Storage( title_create = ADD_ACTIVITY, title_display = T("Activity Details"), title_list = LIST_ACTIVITIES, title_update = T("Edit Activity"), title_search = T("Search Activities"), title_upload = T("Import Activity Data"), title_report = T("Who is doing What Where") if drr else T("Activity Report"), subtitle_create = T("Add New Activity"), subtitle_list = T("Activities"), subtitle_report = T("Activities"), label_list_button = LIST_ACTIVITIES, label_create_button = ADD_ACTIVITY, msg_record_created = T("Activity Added"), msg_record_modified = T("Activity Updated"), msg_record_deleted = T("Activity Deleted"), msg_list_empty = T("No Activities Found") ) # Virtual Fields if drr: table.virtualfields.append(S3ProjectActivityVirtualfields()) # Search Method if pca: project_activity_search = S3Search(field="location_id$name") else: project_activity_search = S3Search(field="name") # Resource Configuration report_fields = [] append = report_fields.append if drr: append((T("Organization"), "organisation")) append((T("Project"), "project_id")) if not pca: append((T("Activity"), "name")) append((T("Activity Type"), "multi_activity_type_id")) if drr: append((T("Sector"), "project_id$sector_id")) append((T("Theme"), "project_id$multi_theme_id")) append((T("Hazard"), "project_id$multi_hazard_id")) append((T("HFA"), "project_id$hfa")) lh = current.gis.get_location_hierarchy() lh = [(lh[opt], opt) for opt in lh] report_fields.extend(lh) append("location_id") list_fields = ["name", "project_id", "multi_activity_type_id", "comments" ] else: append((T("Time Estimated"), "time_estimated")) append((T("Time Actual"), "time_actual")) list_fields = ["name", "project_id", "location_id", "multi_activity_type_id", "comments" ] if drr: next = "beneficiary" else: next = "task" configure(tablename, super_entity="doc_entity", create_next=URL(c="project", f="activity", args=["[id]", next]), search_method=project_activity_search, onvalidation=self.project_activity_onvalidation, deduplicate=self.project_activity_deduplicate, report_rows=report_fields, report_cols=report_fields, report_fact=report_fields, list_fields = list_fields, ) # Reusable Field activity_id = S3ReusableField("activity_id", db.project_activity, sortby="name", requires = IS_NULL_OR(IS_ONE_OF(db, "project_activity.id", "%(name)s", sort=True)), represent = lambda id, row=None: \ s3_get_db_field_value(tablename = "project_activity", fieldname = "name", look_up_value = id), label = ACTIVITY, comment = s3_popup_comment(c="project", f="activity", title=ADD_ACTIVITY, tooltip=ACTIVITY_TOOLTIP), ondelete = "CASCADE") # Components # Contact Persons add_component("pr_person", project_activity=Storage( name="contact", link="project_activity_contact", joinby="activity_id", key="person_id", actuate="hide", autodelete=False)) # Beneficiaries add_component("project_beneficiary", project_activity="activity_id") # Tasks add_component("project_task", project_activity=Storage( link="project_task_activity", joinby="activity_id", key="task_id", actuate="replace", autocomplete="name", autodelete=False)) # --------------------------------------------------------------------- # Project Activity Contact Person # # @ToDo: This is a Community Contact nmot an Activity contact,l so # should be renamed when we add proper Communities # tablename = "project_activity_contact" table = define_table(tablename, activity_id(), person_id(widget=S3AddPersonWidget(controller="pr"), requires=IS_ADD_PERSON_WIDGET(), comment=None), *meta_fields()) table.virtualfields.append(S3ProjectActivityContactVirtualFields()) # CRUD Strings ADD_CONTACT = T("Add Contact") LIST_CONTACTS = T("List Contacts") if pca: LIST_OF_CONTACTS = T("Community Contacts") else: LIST_OF_CONTACTS = T("Contacts") crud_strings[tablename] = Storage( title_create = ADD_CONTACT, title_display = T("Contact Details"), title_list = LIST_CONTACTS, title_update = T("Edit Contact Details"), title_search = T("Search Contacts"), subtitle_create = T("Add New Contact"), subtitle_list = LIST_OF_CONTACTS, label_list_button = LIST_CONTACTS, label_create_button = ADD_CONTACT, msg_record_created = T("Contact Added"), msg_record_modified = T("Contact Updated"), msg_record_deleted = T("Contact Deleted"), msg_list_empty = T("No Contacts Found")) activity_contact_search = S3Search( advanced=(S3SearchSimpleWidget( name = "activity_contact_search_simple", label = T("Name"), comment = T("You can search by person name - enter any of the first, middle or last names, separated by spaces. You may use % as wildcard. Press 'Search' without input to list all persons."), field = ["person_id$first_name", "person_id$middle_name", "person_id$last_name" ] ), S3SearchLocationHierarchyWidget( name="activity_contact_search_L1", field="person_id$L1", cols = 3, ), S3SearchLocationHierarchyWidget( name="activity_contact_search_L2", field="person_id$L2", cols = 3, ), )) # Resource configuration hierarchy = current.gis.get_location_hierarchy() configure(tablename, search_method=activity_contact_search, list_fields=["activity_id", (T("Project"), "activity_id$project_id"), "person_id", (hierarchy["L0"], "person_id$L0"), (hierarchy["L1"], "person_id$L1"), (hierarchy["L2"], "person_id$L2"), (hierarchy["L3"], "person_id$L3"), (T("Email"), "email"), (T("Mobile Phone"), "sms")]) # --------------------------------------------------------------------- # Pass variables back to global scope (response.s3.*) # return dict( project_project_id = project_id, project_activity_id = activity_id, project_hfa_opts = project_hfa_opts, project_project_represent = self.project_represent, ) # ------------------------------------------------------------------------- def defaults(self): """ Safe defaults for model-global names if module is disabled """ dummy = S3ReusableField("dummy_id", "integer", readable=False, writable=False) return Storage( project_project_id = lambda: dummy("project_id"), project_activity_id = lambda: dummy("activity_id"), project_project_represent = lambda v, r: current.messages.NONE ) # ------------------------------------------------------------------------- @staticmethod def multiref_represent(opts, tablename, represent_string = "%(name)s"): """ Represent a list of references @param opt: the current value or list of values @param tablename: the referenced table @param represent_string: format string to represent the records """ DEFAULT = "" db = current.db s3db = current.s3db UNKNOWN_OPT = current.messages.UNKNOWN_OPT table = s3db.table(tablename, None) if table is None: return DEFAULT if not isinstance(opts, (list, tuple)): opts = [opts] rows = db(table.id.belongs(opts)).select() rstr = Storage([(str(row.id), row) for row in rows]) keys = rstr.keys() represent = lambda o: str(o) in keys and \ represent_string % rstr[str(o)] or UNKNOWN_OPT vals = [represent(o) for o in opts] if len(opts) > 1: vals = ", ".join(vals) else: vals = len(vals) and vals[0] or DEFAULT return vals # --------------------------------------------------------------------- @staticmethod def project_represent(id, row=None, show_link=True): """ FK representation """ db = current.db NONE = current.messages.NONE if id: val = (id and [db.project_project[id].name] or [NONE])[0] if not show_link: return val return A(val, _href = URL(c="project", f="project", args=[id])) else: return NONE # --------------------------------------------------------------------- @staticmethod def project_project_onvalidation(form): """ Form validation """ if not form.vars.code and "name" in form.vars: # Populate code from name form.vars.code = form.vars.name return # --------------------------------------------------------------------- @staticmethod def project_project_onaccept(form): """ Set the project to be owned by the customer """ db = current.db s3db = current.s3db if "organisation_id" in form.vars: # Set Project to be owned by this Customer organisation_id = form.vars.organisation_id otable = s3db.org_organisation query = (otable.id == organisation_id) role = db(query).select(otable.owned_by_organisation, limitby=(0, 1)).first() if role: table = s3db.project_project query = (table.id == form.vars.id) db(query).update(owned_by_organisation=role.owned_by_organisation) return # --------------------------------------------------------------------- @staticmethod def project_project_deduplicate(item): """ Import item de-duplication """ if item.id: return if item.tablename == "project_project" and \ "name" in item.data: # Match project by name (all-lowercase) table = item.table name = item.data.name try: query = (table.name.lower() == name.lower()) except AttributeError, exception: s3_debug("project_deduplicate", exception.message) else: duplicate = current.db(query).select(table.id, table.name, limitby=(0, 1)).first() if duplicate: item.id = duplicate.id item.data.name = duplicate.name item.method = item.METHOD.UPDATE return # ------------------------------------------------------------------------- @staticmethod def project_timeline(r, **attr): """ Display the project on a Simile Timeline http://www.simile-widgets.org/wiki/Reference_Documentation_for_Timeline Currently this just displays a Google Calendar @ToDo: Add Milestones @ToDo: Filters for different 'layers' @ToDo: export milestones/tasks as .ics """ if r.representation == "html" and r.name == "project": T = current.T request = current.request response = current.response session = current.session s3 = response.s3 calendar = r.record.calendar # Add core Simile Code s3.scripts.append("/%s/static/scripts/simile/timeline/timeline-api.js" % request.application) # Pass vars to our JS code s3.js_global.append("S3.timeline.calendar = '%s';" % calendar) # Add our control script if session.s3.debug: s3.scripts.append("/%s/static/scripts/S3/s3.timeline.js" % request.application) else: s3.scripts.append("/%s/static/scripts/S3/s3.timeline.min.js" % request.application) # Create the DIV item = DIV(_id="s3timeline", _style="height: 400px; border: 1px solid #aaa; font-family: Trebuchet MS, sans-serif; font-size: 85%;") output = dict(item=item) output["title"] = T("Project Calendar") # Maintain RHeader for consistency if "rheader" in attr: rheader = attr["rheader"](r) if rheader: output["rheader"] = rheader response.view = "timeline.html" return output else: raise HTTP(501, BADMETHOD) # --------------------------------------------------------------------- @staticmethod def hfa_opts_represent(opt, row=None): """ Option representation """ s3 = current.response.s3 NONE = current.messages.NONE project_hfa_opts = s3.project_hfa_opts opts = opt if isinstance(opt, int): opts = [opt] elif not isinstance(opt, (list, tuple)): return NONE vals = [project_hfa_opts.get(o, NONE) for o in opts] return ", ".join(vals) # --------------------------------------------------------------------- @staticmethod def project_activity_onvalidation(form): """ """ pca = current.deployment_settings.get_project_community_activity() if pca: location_id = form.vars.location_id if location_id: db = current.db s3db = current.s3db table = s3db.gis_location query = (table.id == form.vars.location_id) row = db(query).select(table.parent, limitby=(0, 1)).first() if row and row.parent: query = (table.id == row.parent) parent = db(query).select(table.name, limitby=(0, 1)).first() if parent: form.vars.name = parent.name return # --------------------------------------------------------------------- @staticmethod def project_activity_deduplicate(item): """ Import item de-duplication """ db = current.db settings = current.deployment_settings pca = settings.get_project_community_activity() if item.id: return if item.tablename != "project_activity": return table = item.table duplicate = None if pca: if "project_id" in item.data and \ "location_id" in item.data: # Match activity by project_id and location_id project_id = item.data.project_id location_id = item.data.location_id query = (table.project_id == project_id) & \ (table.location_id == location_id) duplicate = db(query).select(table.id, limitby=(0, 1)).first() else: if "project_id" in item.data and "name" in item.data: # Match activity by project_id and name project_id = item.data.project_id name = item.data.name query = (table.project_id == project_id) & \ (table.name == name) duplicate = db(query).select(table.id, limitby=(0, 1)).first() if duplicate: item.id = duplicate.id item.method = item.METHOD.UPDATE return # ============================================================================= class S3ProjectDRRModel(S3Model): """ Project DRR Model This class contains the tabels suitable for use by multinational organisations tracking projects at a high level """ names = ["project_organisation", #"project_site", "project_beneficiary_type", "project_beneficiary", "project_organisation_roles", "project_organisation_lead_role" ] def model(self): T = current.T db = current.db s3 = current.response.s3 currency_type = s3.currency_type #location_id = self.gis_location_id organisation_id = self.org_organisation_id project_id = self.project_project_id activity_id = self.project_activity_id #multi_activity_type_id = self.project_multi_activity_type_id pca = current.deployment_settings.get_project_community_activity() messages = current.messages NONE = messages.NONE # --------------------------------------------------------------------- # Project Organisation # project_organisation_roles = { 1: T("Lead Implementer"), # T("Host National Society") 2: T("Partner"), # T("Partner National Society") 3: T("Donor"), 4: T("Customer"), # T("Beneficiary")? } project_organisation_lead_role = 1 organisation_help = T("Add all organizations which are involved in different roles in this project") tablename = "project_organisation" table = self.define_table(tablename, project_id(), organisation_id(comment = DIV(A(T("Add Organization"), _class="colorbox", _href=URL(c="org", f="organisation", args="create", vars=dict(format="popup")), _target="top", _title=T("Add Organization")), DIV(_class="tooltip", _title="%s|%s" % (T("Organization"), organisation_help)) ) ), Field("role", "integer", requires = IS_NULL_OR(IS_IN_SET(project_organisation_roles)), represent = lambda opt, row=None: \ project_organisation_roles.get(opt, NONE)), Field("amount", "double", requires = IS_FLOAT_AMOUNT(), represent = lambda v, row=None: \ IS_FLOAT_AMOUNT.represent(v, precision=2), widget = IS_FLOAT_AMOUNT.widget, label = T("Funds Contributed by this Organization")), currency_type(), s3.comments(), *s3.meta_fields()) # Field configuration? # CRUD Strings ADD_PROJECT_ORG = T("Add Organization to Project") LIST_PROJECT_ORG = T("List Project Organizations") s3.crud_strings[tablename] = Storage( title_create = ADD_PROJECT_ORG, title_display = T("Project Organization Details"), title_list = LIST_PROJECT_ORG, title_update = T("Edit Project Organization"), title_search = T("Search Project Organizations"), title_upload = T("Import Project Organizations"), title_report = T("Funding Report"), subtitle_create = T("Add Organization to Project"), subtitle_list = T("Project Organizations"), subtitle_report = T("Funding"), label_list_button = LIST_PROJECT_ORG, label_create_button = ADD_PROJECT_ORG, label_delete_button = T("Remove Organization from Project"), msg_record_created = T("Organization added to Project"), msg_record_modified = T("Project Organization updated"), msg_record_deleted = T("Organization removed from Project"), msg_list_empty = T("No Organizations for this Project")) # Search Method? # Resource Configuration self.configure(tablename, deduplicate=self.project_organisation_deduplicate, onvalidation=self.project_organisation_onvalidation) # Reusable Field # Components # --------------------------------------------------------------------- # Project Site # @ToDo: Deprecated? # # tablename = "project_site" # table = self.define_table(tablename, # self.super_link("site_id", "org_site"), # project_id(), # Field("name", notnull=True, # length=64, # Mayon Compatibility # label = T("Name")), # location_id(), # multi_activity_type_id(), # *(s3.address_fields() + s3.meta_fields())) # Field configuration # CRUD Strings # Search Method # Resource Configuration # Reusable Field # CRUD strings # ADD_PROJECT_SITE = T("Add Project Site") # LIST_PROJECT_SITE = T("List Project Sites") # s3.crud_strings[tablename] = Storage( # title_create = ADD_PROJECT_SITE, # title_display = T("Project Site Details"), # title_list = LIST_PROJECT_SITE, # title_update = T("Edit Project Site"), # title_search = T("Search Project Sites"), # title_upload = T("Import Project Sites"), # subtitle_create = T("Add New Project Site"), # subtitle_list = T("Sites"), # label_list_button = LIST_PROJECT_SITE, # label_create_button = ADD_PROJECT_SITE, # label_delete_button = T("Delete Project Site"), # msg_record_created = T("Project Site added"), # msg_record_modified = T("Project Site updated"), # msg_record_deleted = T("Project Site deleted"), # msg_list_empty = T("No Project Sites currently registered")) # project_site_id = S3ReusableField("project_site_id", db.project_site, # #sortby="default/indexname", # requires = IS_NULL_OR(IS_ONE_OF(db, "project_site.id", "%(name)s")), # represent = lambda id, row=None: \ # (id and [db(db.project_site.id == id).select(db.project_site.name, # limitby=(0, 1)).first().name] or [NONE])[0], # label = T("Project Site"), # comment = s3_popup_comment(c="project", # f="site", # title=ADD_PROJECT_SITE, # tooltip=T("If you don't see the site in the list, you can add a new one by clicking link 'Add Project Site'.")),, # ondelete = "CASCADE") # self.configure(tablename, # super_entity="org_site", # onvalidation=s3.address_onvalidation) # --------------------------------------------------------------------- # Project Beneficiary Type # tablename = "project_beneficiary_type" table = self.define_table(tablename, Field("name", length=128, unique=True, requires = IS_NOT_IN_DB(db, "project_beneficiary_type.name")), *s3.meta_fields()) # Field configuration? # CRUD Strings ADD_BNF_TYPE = T("Add Beneficiary Type") LIST_BNF_TYPE = T("List Beneficiary Types") s3.crud_strings[tablename] = Storage( title_create = ADD_BNF_TYPE, title_display = T("Beneficiary Type"), title_list = LIST_BNF_TYPE, title_update = T("Edit Beneficiary Type"), title_search = T("Search Beneficiary Types"), subtitle_create = T("Add New Beneficiary Type"), subtitle_list = T("Beneficiary Types"), label_list_button = LIST_BNF_TYPE, label_create_button = ADD_BNF_TYPE, msg_record_created = T("Beneficiary Type Added"), msg_record_modified = T("Beneficiary Type Updated"), msg_record_deleted = T("Beneficiary Type Deleted"), msg_list_empty = T("No Beneficiary Types Found") ) # Search Method? # Resource Configuration? # Reusable Field beneficiary_type_id = S3ReusableField("beneficiary_type_id", db.project_beneficiary_type, requires = IS_NULL_OR(IS_ONE_OF(db, "project_beneficiary_type.id", self.beneficiary_type_represent)), represent = self.beneficiary_type_represent, label = T("Beneficiary Type"), comment = s3_popup_comment(c="project", f="beneficiary_type", title=ADD_BNF_TYPE, tooltip=T("Please record Beneficiary according to the reporting needs of your project")), ondelete = "CASCADE") # --------------------------------------------------------------------- # Project Beneficiary # tablename = "project_beneficiary" table = self.define_table(tablename, # populated automatically project_id(readable=False, writable=False), activity_id(comment=None), beneficiary_type_id(empty=False), Field("number", "integer", label = T("Quantity"), requires = IS_INT_IN_RANGE(0, 99999999)), s3.comments(), *s3.meta_fields()) # Field configuration if pca: table.activity_id.label = T("Community") # CRUD Strings ADD_BNF = T("Add Beneficiaries") LIST_BNF = T("List Beneficiaries") s3.crud_strings[tablename] = Storage( title_create = ADD_BNF, title_display = T("Beneficiaries Details"), title_list = LIST_BNF, title_update = T("Edit Beneficiaries"), title_search = T("Search Beneficiaries"), title_report = T("Beneficiary Report"), subtitle_create = T("Add New Beneficiaries"), subtitle_list = T("Beneficiaries"), label_list_button = LIST_BNF, label_create_button = ADD_BNF, msg_record_created = T("Beneficiaries Added"), msg_record_modified = T("Beneficiaries Updated"), msg_record_deleted = T("Beneficiaries Deleted"), msg_list_empty = T("No Beneficiaries Found") ) table.virtualfields.append(S3ProjectBeneficiaryVirtualfields()) # Search Method? # Resource Configuration report_fields=[ "activity_id", (T("Beneficiary Type"), "beneficiary_type_id"), "project_id", "project_id$multi_hazard_id", "project_id$multi_theme_id", "activity_id$multi_activity_type_id" ] lh = current.gis.get_location_hierarchy() lh = [(lh[opt], opt) for opt in lh] report_fields.extend(lh) self.configure(tablename, onaccept=self.project_beneficiary_onaccept, deduplicate=self.project_beneficiary_deduplicate, report_filter=[ S3SearchOptionsWidget( field=["project_id"], name="project", label=T("Project") ), S3SearchOptionsWidget( field=["beneficiary_type_id"], name="beneficiary_type_id", label=T("Beneficiary Type") ), # Can't search be VirtualFields currently # S3SearchLocationHierarchyWidget( # name="beneficiary_search_L1", # field="activity_id$L1", # cols = 3, # ), ], report_rows=report_fields, report_cols=report_fields, report_fact=["number"], report_method=["sum"]) # Reusable Field beneficiary_id = S3ReusableField("beneficiary_id", db.project_beneficiary, sortby="name", requires = IS_NULL_OR(IS_ONE_OF(db, "project_beneficiary.id", "%(type)s", sort=True)), represent = lambda id, row=None: \ s3_get_db_field_value(tablename = "project_beneficiary", fieldname = "type", look_up_value = id), label = T("Beneficiaries"), comment = s3_popup_comment(c="project", f="beneficiary", title=ADD_BNF, tooltip=T("If you don't see the beneficiary in the list, you can add a new one by clicking link 'Add Beneficiary'.")), ondelete = "SET NULL") # --------------------------------------------------------------------- # Pass variables back to global scope (response.s3.*) # return dict( project_organisation_roles = project_organisation_roles, project_organisation_lead_role = project_organisation_lead_role, ) # ------------------------------------------------------------------------- def defaults(self): """ Safe defaults for model-global names if module is disabled """ dummy = S3ReusableField("dummy_id", "integer", readable=False, writable=False) return Storage( ) # --------------------------------------------------------------------- @staticmethod def project_organisation_onvalidation(form, lead_role=None): """ Form validation """ db = current.db s3db = current.s3db s3 = current.response.s3 otable = s3db.project_organisation if lead_role is None: lead_role = s3.project_organisation_lead_role project_id = form.vars.project_id organisation_id = form.vars.organisation_id if str(form.vars.role) == str(lead_role) and project_id: query = (otable.deleted != True) & \ (otable.project_id == project_id) & \ (otable.role == lead_role) & \ (otable.organisation_id != organisation_id) row = db(query).select(otable.id, limitby=(0, 1)).first() if row: form.errors.role = T("Lead Implementer for this project is already set, please choose another role.") return # --------------------------------------------------------------------- @staticmethod def project_organisation_deduplicate(item): """ Import item de-duplication """ db = current.db if item.id: return if item.tablename == "project_organisation" and \ "project_id" in item.data and \ "organisation_id" in item.data: # Match project by org_id and project_id table = item.table project_id = item.data.project_id organisation_id = item.data.organisation_id query = (table.project_id == project_id) & \ (table.organisation_id == organisation_id) duplicate = db(query).select(table.id, limitby=(0, 1)).first() if duplicate: item.id = duplicate.id item.method = item.METHOD.UPDATE return # --------------------------------------------------------------------- @staticmethod def beneficiary_type_represent(type_id, row=None): """ FK representation """ db = current.db s3db = current.s3db UNKNOWN_OPT = current.messages.UNKNOWN_OPT if isinstance(type_id, Row): if "name" in type_id: return type_id.name elif "id" in type_id: type_id = type_id.id else: return UNKNOWN_OPT bnf_type = s3db.project_beneficiary_type query = bnf_type.id == type_id row = db(query).select(bnf_type.name, limitby=(0, 1)).first() if row: return row.name else: return UNKNOWN_OPT # --------------------------------------------------------------------- @staticmethod def project_beneficiary_onaccept(form): """ Record creation post-processing """ db = current.db s3db = current.s3db btable = s3db.project_beneficiary atable = s3db.project_activity record_id = form.vars.id query = (btable.id == record_id) & \ (atable.id == btable.activity_id) activity = db(query).select(atable.project_id, limitby=(0, 1)).first() if activity: db(btable.id == record_id).update(project_id=activity.project_id) return # --------------------------------------------------------------------- @staticmethod def project_beneficiary_deduplicate(item): """ Import item de-duplication """ db = current.db if item.id: return if item.tablename == "project_beneficiary" and \ "beneficiary_type_id" in item.data and \ "activity_id" in item.data: # Match beneficiary by type and activity_id table = item.table beneficiary_type_id = item.data.beneficiary_type_id activity_id = item.data.activity_id query = (table.beneficiary_type_id == beneficiary_type_id) & \ (table.activity_id == activity_id) duplicate = db(query).select(table.id, limitby=(0, 1)).first() if duplicate: item.id = duplicate.id item.method = item.METHOD.UPDATE return # ============================================================================= class S3ProjectTaskModel(S3Model): """ Project Task Model This class holds the tables used for a smaller Organisation to manage their Tasks in detail. """ names = ["project_milestone", "project_task", "project_time", "project_comment", "project_task_project", "project_task_activity", "project_task_id", ] def model(self): db = current.db T = current.T auth = current.auth request = current.request s3 = current.response.s3 settings = current.deployment_settings person_id = self.pr_person_id location_id = self.gis_location_id site_id = self.org_site_id project_id = self.project_project_id activity_id = self.project_activity_id s3_date_format = settings.get_L10n_date_format() s3_utc_represent = lambda dt: S3DateTime.datetime_represent(dt, utc=True) s3_date_represent = lambda dt: S3DateTime.date_represent(dt, utc=True) messages = current.messages NONE = messages.NONE UNKNOWN_OPT = messages.UNKNOWN_OPT # Shortcuts add_component = self.add_component comments = s3.comments configure = self.configure crud_strings = s3.crud_strings define_table = self.define_table super_link = self.super_link meta_fields = s3.meta_fields # --------------------------------------------------------------------- # Project Milestone # tablename = "project_milestone" table = define_table(tablename, # Stage Report super_link("doc_id", "doc_entity"), project_id(), Field("name", label = T("Short Description"), requires=IS_NOT_EMPTY()), Field("date", "date", label = T("Date"), represent = s3_date_represent, requires = IS_NULL_OR(IS_DATE(format = s3_date_format))), comments(), format="%(name)s", *meta_fields()) # CRUD Strings ADD_MILESTONE = T("Add Milestone") crud_strings[tablename] = Storage( title_create = ADD_MILESTONE, title_display = T("Milestone Details"), title_list = T("List Milestones"), title_update = T("Edit Milestone"), title_search = T("Search Milestones"), title_upload = T("Import Milestone Data"), subtitle_create = T("Add New Milestone"), subtitle_list = T("Milestones"), subtitle_report = T("Milestones"), label_list_button = T("List Milestones"), label_create_button = ADD_MILESTONE, msg_record_created = T("Milestone Added"), msg_record_modified = T("Milestone Updated"), msg_record_deleted = T("Milestone Deleted"), msg_list_empty = T("No Milestones Found") ) # Reusable Field milestone_id = S3ReusableField("milestone_id", db.project_milestone, sortby="name", requires = IS_NULL_OR(IS_ONE_OF(db, "project_milestone.id", "%(name)s")), represent = self.milestone_represent, comment = s3_popup_comment(c="project", f="milestone", title=ADD_MILESTONE, tooltip=T("A project milestone marks a significant date in the calendar which shows that progress towards the overall objective is being made.")), label = T("Milestone"), ondelete = "RESTRICT") # --------------------------------------------------------------------- # Tasks # # Tasks can be linked to Activities or directly to Projects # - they can also be used by the Event/Scenario modules # # @ToDo: Recurring tasks # # These Statuses can be customised, although doing so limits the ability to do synchronization # - best bet is simply to comment statuses that you don't wish to use # project_task_status_opts = { 1: T("Draft"), 2: T("New"), 3: T("Assigned"), 4: T("Feedback"), 5: T("Blocked"), 6: T("On Hold"), 7: T("Cancelled"), 8: T("Duplicate"), 9: T("Ready"), 10: T("Verified"), 11: T("Reopened"), 12: T("Completed"), #99: T("unspecified") } project_task_active_statuses = [2, 3, 4, 11] project_task_priority_opts = { 1:T("Urgent"), 2:T("High"), 3:T("Normal"), 4:T("Low") } #staff = auth.s3_has_role("STAFF") staff = True milestones = settings.get_project_milestones() tablename = "project_task" table = define_table(tablename, super_link("doc_id", "doc_entity"), Field("template", "boolean", default=False, readable=False, writable=False), Field("name", label = T("Short Description"), length=100, notnull=True, requires = IS_LENGTH(maxsize=100, minsize=1)), Field("description", "text", label = T("Detailed Description/URL"), comment = DIV(_class="tooltip", _title="%s|%s" % (T("Detailed Description/URL"), T("Please provide as much detail as you can, including the URL(s) where the bug occurs or you'd like the new feature to go.")))), site_id, location_id(label=T("Deployment Location"), readable=False, writable=False ), Field("source", label = T("Source")), Field("priority", "integer", requires = IS_IN_SET(project_task_priority_opts, zero=None), default = 3, label = T("Priority"), represent = lambda opt, row=None: \ project_task_priority_opts.get(opt, UNKNOWN_OPT)), # Could be a Person, Team or Organisation super_link("pe_id", "pr_pentity", readable = staff, writable = staff, label = T("Assigned to"), filterby = "instance_type", filter_opts = ["pr_person", "pr_group", "org_organisation"], represent = lambda id, row=None: \ project_assignee_represent(id), # @ToDo: Widget #widget = S3PentityWidget(), #comment = DIV(_class="tooltip", # _title="%s|%s" % (T("Assigned to"), # T("Enter some characters to bring up a list of possible matches"))) ), Field("date_due", "datetime", label = T("Date Due"), readable = staff, writable = staff, requires = [IS_EMPTY_OR( IS_UTC_DATETIME_IN_RANGE( minimum=request.utcnow - datetime.timedelta(days=1), error_message="%s %%(min)s!" % T("Enter a valid future date")))], widget = S3DateTimeWidget(past=0, future=8760), # Hours, so 1 year represent = s3_date_represent), milestone_id( readable = milestones and staff, writable = milestones and staff, ), Field("time_estimated", "double", readable = staff, writable = staff, represent = lambda v: v or "", label = "%s (%s)" % (T("Time Estimate"), T("hours"))), Field("time_actual", "double", readable = staff, # This comes from the Time component writable=False, label = "%s (%s)" % (T("Time Taken"), T("hours"))), Field("status", "integer", requires = IS_IN_SET(project_task_status_opts, zero=None), default = 2, readable = staff, writable = staff, label = T("Status"), represent = lambda opt, row=None: \ project_task_status_opts.get(opt, UNKNOWN_OPT)), *meta_fields()) # Field configurations # Comment these if you don't need a Site associated with Tasks #table.site_id.readable = table.site_id.writable = True #table.site_id.label = T("Check-in at Facility") # T("Managing Office") table.created_on.represent = s3_date_represent # CRUD Strings ADD_TASK = T("Add Task") LIST_TASKS = T("List Tasks") crud_strings[tablename] = Storage( title_create = ADD_TASK, title_display = T("Task Details"), title_list = LIST_TASKS, title_update = T("Edit Task"), title_search = T("Search Tasks"), title_upload = T("Import Tasks"), subtitle_create = T("Add New Task"), subtitle_list = T("Tasks"), label_list_button = LIST_TASKS, label_create_button = ADD_TASK, msg_record_created = T("Task added"), msg_record_modified = T("Task updated"), msg_record_deleted = T("Task deleted"), msg_list_empty = T("No tasks currently registered")) # Virtual Fields # Do just for the common report table.virtualfields.append(S3ProjectTaskVirtualfields()) # Search Method task_search = S3Search( advanced = ( # Virtual fields not supported by Search Widgets yet #S3SearchOptionsWidget( #name = "task_search_project", #label = T("Project"), #field = ["project"], #cols = 3 #), # This Syntax not supported by Search Widgets yet #S3SearchOptionsWidget( # name = "task_search_project", # label = T("Project"), # field = ["task.task_id:project_task:project_id$name"], # cols = 3 #), # Virtual fields not supported by Search Widgets yet #S3SearchOptionsWidget( #name = "task_search_activity", #label = T("Activity"), #field = ["activity"], #cols = 3 #), S3SearchOptionsWidget( name = "task_search_priority", label = T("Priority"), field = ["priority"], cols = 4 ), S3SearchSimpleWidget( name = "task_search_text_advanced", label = T("Description"), comment = T("Search for a Task by description."), field = [ "name", "description", ] ), S3SearchOptionsWidget( name = "task_search_created_by", label = T("Created By"), field = ["created_by"], cols = 4 ), S3SearchOptionsWidget( name = "task_search_assignee", label = T("Assigned To"), field = ["pe_id"], cols = 4 ), S3SearchMinMaxWidget( name="task_search_date_created", method="range", label=T("Date Created"), field=["created_on"] ), S3SearchMinMaxWidget( name="task_search_date_due", method="range", label=T("Date Due"), field=["date_due"] ), S3SearchOptionsWidget( name = "task_search_status", label = T("Status"), field = ["status"], cols = 4 ), ) ) list_fields=["id", "priority", (T("ID"), "task_id"), "name", "pe_id", "date_due", "time_estimated", "created_on", "status", #"site_id" ] if settings.get_project_milestones(): list_fields.insert(5, "milestone_id") # Resource Configuration configure(tablename, super_entity="doc_entity", copyable=True, orderby="project_task.priority", onvalidation=self.task_onvalidation, create_next=URL(f="task", args=["[id]"]), create_onaccept=self.task_create_onaccept, update_onaccept=self.task_update_onaccept, search_method=task_search, list_fields=list_fields, extra="description") # Reusable field task_id = S3ReusableField("task_id", db.project_task, label = T("Task"), sortby="name", requires = IS_NULL_OR(IS_ONE_OF(db, "project_task.id", "%(name)s")), represent = lambda id, row=None: \ (id and [db.project_task[id].name] or [NONE])[0], comment = s3_popup_comment(c="project", f="task", title=ADD_TASK, tooltip=T("A task is a piece of work that an individual or team can do in 1-2 days.")), ondelete = "CASCADE") # --------------------------------------------------------------------- # Custom Methods self.set_method("project_task", method="dispatch", action=self.task_dispatch) # Components # Projects (for imports) add_component("project_project", project_task=Storage( link="project_task_project", joinby="task_id", key="project_id", actuate="embed", autocomplete="name", autodelete=False)) # Activities (for imports) add_component("project_activity", project_task=Storage( link="project_task_activity", joinby="task_id", key="activity_id", actuate="embed", autocomplete="name", autodelete=False)) # Job roles add_component("hrm_job_role", project_task=Storage( link="project_task_job_role", joinby="task_id", key="job_role_id", actuate="embed", autocomplete="name", autodelete=False)) # Human Resources (assigned) add_component("hrm_human_resource", project_task=Storage( link="project_task_human_resource", joinby="task_id", key="human_resource_id", actuate="embed", autocomplete="name", autodelete=False)) # Requests add_component("req_req", project_task=Storage( link="project_task_req", joinby="task_id", key="req_id", actuate="embed", autocomplete="request_number", autodelete=False)) # Time add_component("project_time", project_task="task_id") # Comments (for imports)) add_component("project_comment", project_task="task_id") # --------------------------------------------------------------------- # Link Tasks <-> Projects # tablename = "project_task_project" table = define_table(tablename, task_id(), project_id(), *meta_fields()) # Field configuration # CRUD Strings # Search Method # Resource Configuration # Reusable Field # --------------------------------------------------------------------- # Link task <-> activity # # Tasks <> Activities tablename = "project_task_activity" table = define_table(tablename, task_id(), activity_id(), *meta_fields()) # Field configuration # CRUD Strings # Search Method # Resource Configuration # Reusable Field # --------------------------------------------------------------------- # Project comment # # @ToDo: Attachments? # # Parent field allows us to: # * easily filter for top-level threads # * easily filter for next level of threading # * hook a new reply into the correct location in the hierarchy # tablename = "project_comment" table = define_table(tablename, Field("parent", "reference project_comment", requires = IS_EMPTY_OR(IS_ONE_OF(db, "project_comment.id")), readable=False), #project_id(), #activity_id(), task_id(), Field("body", "text", notnull=True, label = T("Comment")), *meta_fields()) # Field configuration? # CRUD Strings? # Search Method? # Resource Configuration configure(tablename, list_fields=["id", "task_id", "created_by", "modified_on" ]) # Reusable Field? # --------------------------------------------------------------------- # Project Time # - used to Log hours spent on a Task # tablename = "project_time" table = define_table(tablename, task_id(), person_id(default=auth.s3_logged_in_person()), Field("date", "datetime", label = T("Date"), requires = IS_EMPTY_OR(IS_UTC_DATETIME()), represent = s3_utc_represent, widget = S3DateTimeWidget(past=8760, # Hours, so 1 year future=0), default = request.utcnow), Field("hours", "double", label = "%s (%s)" % (T("Time"), T("hours"))), comments(), format="%(comments)s", *meta_fields()) # CRUD Strings ADD_TIME = T("Log Time Spent") crud_strings[tablename] = Storage( title_create = ADD_TIME, title_display = T("Logged Time Details"), title_list = T("List Logged Time"), title_update = T("Edit Logged Time"), title_search = T("Search Logged Time"), title_upload = T("Import Logged Time data"), title_report = T("Last Week's Work"), subtitle_create = T("Log New Time"), subtitle_list = T("Logged Time"), subtitle_report = T("Logged Time"), label_list_button = T("List Logged Time"), label_create_button = ADD_TIME, msg_record_created = T("Time Logged"), msg_record_modified = T("Time Log Updated"), msg_record_deleted = T("Time Log Deleted"), msg_list_empty = T("No Time Logged") ) if "rows" in request.get_vars and request.get_vars.rows == "project": s3.crud_strings[tablename].title_report = T("Project Time Report") # Virtual Fields table.virtualfields.append(S3ProjectTimeVirtualfields()) configure(tablename, onaccept=self.time_onaccept, list_fields=["id", (T("Project"), "project"), "task_id", "person_id", "date", "hours", "comments", ]) # --------------------------------------------------------------------- # Pass variables back to global scope (response.s3.*) # return dict( project_task_id = task_id, project_task_active_statuses = project_task_active_statuses, ) # ------------------------------------------------------------------------- def defaults(self): """ Safe defaults for model-global names if module is disabled """ dummy = S3ReusableField("dummy_id", "integer", readable=False, writable=False) return Storage( project_task_id = lambda: dummy("task_id") ) # --------------------------------------------------------------------- @staticmethod def milestone_represent(id, row=None): """ FK representation """ db = current.db NONE = current.messages.NONE if id: val = (id and [db.project_milestone[id].name] or [NONE])[0] return val else: return NONE # ------------------------------------------------------------------------- @staticmethod def task_onvalidation(form): """ Task form validation """ T = current.T vars = form.vars if str(vars.status) == "3" and not vars.pe_id: form.errors.pe_id = \ T("Status 'assigned' requires the %(fieldname)s to not be blank") % \ dict(fieldname=current.db.project_task.pe_id.label) elif vars.pe_id and str(vars.status) == "2": # Set the Status to 'Assigned' if left at default 'New' vars.status = 3 return # ------------------------------------------------------------------------- @staticmethod def task_update_onaccept(form): """ * Process the additional fields: Project/Activity * Log changes as comments * If the task is assigned to someone then notify them """ db = current.db s3db = current.s3db s3mgr = current.manager vars = form.vars id = vars.id record = form.record table = s3db.project_task changed = {} for var in vars: vvar = vars[var] rvar = record[var] if vvar != rvar: if table[var].type == "integer": vvar = int(vvar) if vvar == rvar: continue represent = table[var].represent if not represent: represent = lambda o: o if rvar: changed[var] = "%s changed from %s to %s" % \ (table[var].label, represent(rvar), represent(vvar)) else: changed[var] = "%s changed to %s" % \ (table[var].label, represent(vvar)) if changed: table = s3db.project_comment text = s3_user_represent(current.auth.user.id) for var in changed: text = "%s\n%s" % (text, changed[var]) table.insert(task_id=id, body=text) vars = current.request.post_vars if "project_id" in vars: ptable = s3db.project_project ltable = s3db.project_task_project filter = (ltable.task_id == id) if vars.project_id: # Create the link to the Project #master = s3mgr.define_resource("project", "task", id=id) #record = db(ptable.id == vars.project_id).select(ptable.id, # limitby=(0, 1)).first() #link = s3mgr.define_resource("project", "task_project") #link_id = link.update_link(master, record) query = (ltable.task_id == id) & \ (ltable.project_id == vars.project_id) record = db(query).select(ltable.id, limitby=(0, 1)).first() if record: link_id = record.id else: link_id = ltable.insert(task_id = id, project_id = vars.project_id) filter = filter & (ltable.id != link_id) # Remove any other links links = s3mgr.define_resource("project", "task_project", filter=filter) ondelete = s3mgr.model.get_config("project_task_project", "ondelete") links.delete(ondelete=ondelete) if "activity_id" in vars: atable = s3db.project_activity ltable = s3db.project_task_activity filter = (ltable.task_id == id) if vars.activity_id: # Create the link to the Activity #master = s3mgr.define_resource("project", "task", id=id) #record = db(atable.id == vars.activity_id).select(atable.id, # limitby=(0, 1)).first() #link = s3mgr.define_resource("project", "task_activity") #link_id = link.update_link(master, record) query = (ltable.task_id == id) & \ (ltable.activity_id == vars.activity_id) record = db(query).select(ltable.id, limitby=(0, 1)).first() if record: link_id = record.id else: link_id = ltable.insert(task_id = id, activity_id = vars.activity_id) filter = filter & (ltable.id != link_id) # Remove any other links links = s3mgr.define_resource("project", "task_activity", filter=filter) ondelete = s3mgr.model.get_config("project_task_activity", "ondelete") links.delete(ondelete=ondelete) # Notify Assignee task_notify(form) return # ------------------------------------------------------------------------- @staticmethod def task_create_onaccept(form): """ When a Task is created: * Process the additional fields: Project/Activity * create associated Link Tables * ensure that it is owned by the Project Customer * notify assignee """ db = current.db s3db = current.s3db session = current.session vars = form.vars id = vars.id _vars = current.request.post_vars if session.s3.event: # Create a link between this Task & the active Event etable = s3db.event_task etable.insert(event_id=session.s3.event, task_id=id) vars = current.request.post_vars table = s3db.project_task if "project_id" in vars: # Create Link to Project ltable = s3db.project_task_project if vars.project_id: link_id = ltable.insert(task_id = id, project_id = _vars.project_id) if "activity_id" in vars: # Create Link to Activity ltable = s3db.project_task_activity if vars.activity_id: link_id = ltable.insert(task_id = id, activity_id = _vars.activity_id) # Find the associated Project ptable = db.project_project ltable = db.project_task_project query = (ltable.task_id == id) & \ (ltable.project_id == ptable.id) project = db(query).select(ptable.organisation_id, limitby=(0, 1)).first() if project: # Set Task to be owned by this Customer organisation_id = project.organisation_id otable = s3db.org_organisation query = (otable.id == organisation_id) role = db(query).select(otable.owned_by_organisation, limitby=(0, 1)).first() if role: table = s3db.project_task query = (table.id == vars.id) db(query).update(owned_by_organisation=role.owned_by_organisation) # Make sure the task is also linked to the project # when created under an activity if id: lta = s3db.project_task_activity ltp = s3db.project_task_project ta = s3db.project_activity query = (ltp.task_id == id) row = db(query).select(ltp.project_id, limitby=(0, 1)).first() if not row: query = (lta.task_id == id) & \ (lta.activity_id == ta.id) row = db(query).select(ta.project_id, limitby=(0, 1)).first() if row and row.project_id: ltp.insert(task_id=id, project_id=row.project_id) # Notify Assignee task_notify(form) return # ------------------------------------------------------------------------- @staticmethod def task_dispatch(r, **attr): """ Send a Task Dispatch notice from a Task - if a location is supplied, this will be formatted as an OpenGeoSMS """ T = current.T msg = current.msg response = current.response if r.representation == "html" and \ r.name == "task" and r.id and not r.component: record = r.record text = "%s: %s" % (record.name, record.description) # Encode the message as an OpenGeoSMS message = msg.prepare_opengeosms(record.location_id, code="ST", map="google", text=text) # URL to redirect to after message sent url = URL(c="project", f="task", args=r.id) # Create the form if record.pe_id: opts = dict(recipient=record.pe_id) else: opts = dict(recipient_type="pr_person") output = msg.compose(type="SMS", message = message, url = url, **opts) # Maintain RHeader for consistency if "rheader" in attr: rheader = attr["rheader"](r) if rheader: output["rheader"] = rheader output["title"] = T("Send Task Notification") response.view = "msg/compose.html" return output else: raise HTTP(501, BADMETHOD) # ------------------------------------------------------------------------- @staticmethod def time_onaccept(form): """ When Time is logged, update the Task & Activity """ db = current.db titable = db.project_time ttable = db.project_task atable = db.project_activity tatable = db.project_task_activity # Find the Task task_id = form.vars.task_id if not task_id: # Component Form query = (titable.id == form.vars.id) record = db(query).select(titable.task_id, limitby=(0, 1)).first() if record: task_id = record.task_id # Total the Hours Logged query = (titable.deleted == False) & \ (titable.task_id == task_id) rows = db(query).select(titable.hours) hours = 0 for row in rows: hours += row.hours # Update the Task query = (ttable.id == task_id) db(query).update(time_actual=hours) # Find the Activity query = (tatable.deleted == False) & \ (tatable.task_id == task_id) activity = db(query).select(tatable.activity_id, limitby=(0, 1)).first() if activity: activity_id = activity.activity_id # Find all Tasks in this Activity query = (ttable.deleted == False) & \ (tatable.deleted == False) & \ (tatable.task_id == ttable.id) & \ (tatable.activity_id == activity_id) tasks = db(query).select(ttable.time_actual) # Total the Hours Logged hours = 0 for task in tasks: hours += task.time_actual # Update the Activity query = (atable.id == activity_id) db(query).update(time_actual=hours) return # ============================================================================= class S3ProjectTaskHRMModel(S3Model): """ Project Task HRM Model This class holds the tables used to link Tasks to Human Resources - either individuals or Job Roles """ names = ["project_task_job_role", "project_task_human_resource", ] def model(self): s3 = current.response.s3 task_id = self.project_task_id human_resource_id = self.hrm_human_resource_id job_role_id = self.hrm_job_role_id # Shortcuts define_table = self.define_table # --------------------------------------------------------------------- # Link Tasks <> Human Resources tablename = "project_task_human_resource" table = define_table(tablename, task_id(), human_resource_id(), *s3.meta_fields()) # --------------------------------------------------------------------- # Link Tasks <> Job Roles tablename = "project_task_job_role" table = define_table(tablename, task_id(), job_role_id(), *s3.meta_fields()) # --------------------------------------------------------------------- # Pass variables back to global scope (response.s3.*) # return dict( ) # ============================================================================= class S3ProjectTaskIReportModel(S3Model): """ Project Task IReport Model This class holds the table used to link Tasks with Incident Reports. """ names = ["project_task_ireport", ] def model(self): s3 = current.response.s3 task_id = self.project_task_id ireport_id = self.irs_ireport_id # --------------------------------------------------------------------- # Link Tasks <-> Incident Reports # tablename = "project_task_ireport" table = self.define_table(tablename, task_id(), ireport_id(), *s3.meta_fields()) self.configure(tablename, onaccept=self.task_ireport_onaccept) # --------------------------------------------------------------------- # Pass variables back to global scope (response.s3.*) # return dict( ) # ------------------------------------------------------------------------- @staticmethod def task_ireport_onaccept(form): """ When a Task is linked to an IReport, then populate the location_id """ vars = form.vars ireport_id = vars.ireport_id task_id = vars.task_id db = current.db s3db = current.s3db # Check if we already have a Location for the Task table = s3db.project_task query = (table.id == task_id) record = db(query).select(table.location_id, limitby=(0, 1)).first() if not record or record.location_id: return # Find the Incident Location itable = s3db.irs_ireport query = (itable.id == ireport_id) record = db(query).select(itable.location_id, limitby=(0, 1)).first() if not record or not record.location_id: return location_id = record.location_id # Update the Task query = (table.id == task_id) db(query).update(location_id=location_id) return # ----------------------------------------------------------------------------- def project_assignee_represent(id): """ Represent the Person a Task is assigned-to or list views """ db = current.db s3db = current.s3db cache = s3db.cache output = current.messages.NONE if not id: return output if isinstance(id, Row): instance_type = id.instance_type id = id.pe_id else: etable = s3db.pr_pentity query = (etable.id == id) record = db(query).select(etable.instance_type, cache=cache, limitby=(0, 1)).first() if not record: return output instance_type = record.instance_type table = s3db[instance_type] query = (table.pe_id == id) if instance_type == "pr_person": record = db(query).select(table.first_name, table.middle_name, table.last_name, table.initials, cache=cache, limitby=(0, 1)).first() if record: output = record.initials or s3_fullname(record) elif instance_type in ("pr_group", "org_organisation"): # Team or Organisation record = db(query).select(table.name, cache=cache, limitby=(0, 1)).first() if record: output = record.name else: # Should not happen of correctly filtered, return default pass return output # ============================================================================= def project_rheader(r, tabs=[]): """ Project Resource Headers - used in Project & Budget modules """ if r.representation != "html": # RHeaders only used in interactive views return None record = r.record if record is None: # List or Create form: rheader makes no sense here return None table = r.table resourcename = r.name T = current.T auth = current.auth settings = current.deployment_settings drr = settings.get_project_drr() pca = settings.get_project_community_activity() milestones = settings.get_project_milestones() if resourcename == "project": # Tabs tabs = [(T("Basic Details"), None)] append = tabs.append if drr: append((T("Organizations"), "organisation")) ADMIN = current.session.s3.system_roles.ADMIN admin = auth.s3_has_role(ADMIN) #staff = auth.s3_has_role("STAFF") staff = True if staff or drr: append((T("Communities") if pca else T("Activities"), "activity")) if staff and milestones: append((T("Milestones"), "milestone")) if not drr: append((T("Tasks"), "task")) if drr: append((T("Documents"), "document")) elif staff: append((T("Attachments"), "document")) if record.calendar: append((T("Calendar"), "timeline")) rheader_tabs = s3_rheader_tabs(r, tabs) row3 = "" if drr: row2 = TR( TH("%s: " % table.countries_id.label), table.countries_id.represent(record.countries_id), ) else: row2 = TR( TH("%s: " % table.organisation_id.label), table.organisation_id.represent(record.organisation_id) ) if record.end_date: row3 = TR( TH("%s: " % table.end_date.label), table.end_date.represent(record.end_date) ) rheader = DIV(TABLE( TR( TH("%s: " % table.name.label), record.name ), row2, row3, ), rheader_tabs) elif resourcename == "activity": # @ToDo: integrate tabs? rheader_tabs = s3_rheader_tabs(r, tabs) tbl = TABLE() if record.project_id is not None: tbl.append( TR( TH("%s: " % table.project_id.label), table.project_id.represent(record.project_id)) ) if pca: tbl.append( TR( TH("%s: " % table.location_id.label), table.location_id.represent(record.location_id) ) ) else: tbl.append( TR( TH("%s: " % table.name.label), record.name ) ) rheader = DIV(tbl, rheader_tabs) elif resourcename == "task": db = current.db s3db = current.s3db # Tabs tabs = [(T("Details"), None)] append = tabs.append staff = auth.s3_has_role("STAFF") if staff: append((T("Time"), "time")), #append((T("Comments"), "discuss")) append((T("Attachments"), "document")) if settings.has_module("msg"): append((T("Notify"), "dispatch")) #(T("Roles"), "job_role"), #(T("Assignments"), "human_resource"), #(T("Requests"), "req") rheader_tabs = s3_rheader_tabs(r, tabs) # RHeader ptable = s3db.project_project ltable = s3db.project_task_project query = (ltable.deleted == False) & \ (ltable.task_id == r.id) & \ (ltable.project_id == ptable.id) project = db(query).select(ptable.id, limitby=(0, 1)).first() if project: project = TR( TH("%s: " % T("Project")), s3db.project_project_represent(project.id) ) else: project = "" atable = s3db.project_activity ltable = s3db.project_task_activity query = (ltable.deleted == False) & \ (ltable.task_id == r.id) & \ (ltable.activity_id == atable.id) activity = db(query).select(atable.name, limitby=(0, 1)).first() if activity: activity = TR( TH("%s: " % T("Activity")), activity.name ) else: activity = "" if record.description: description = TR( TH("%s: " % table.description.label), record.description ) else: description = "" if record.site_id: facility = TR( TH("%s: " % table.site_id.label), table.site_id.represent(record.site_id), ) else: facility = "" if record.location_id: location = TR( TH("%s: " % table.location_id.label), table.location_id.represent(record.location_id), ) else: location = "" if record.pe_id: assignee = TR( TH("%s: " % table.pe_id.label), s3db.pr_pentity_represent(record.pe_id, show_label=False), ) else: assignee = "" if record.time_estimated: time_estimated = TR( TH("%s: " % table.time_estimated.label), record.time_estimated ) else: time_estimated = "" if record.time_actual: time_actual = TR( TH("%s: " % table.time_actual.label), record.time_actual ) else: time_actual = "" # Comments # if r.method == "discuss": # comments = "" # else: # ctable = s3db.project_comment # query = (ctable.deleted == False) & \ # (ctable.task_id == r.id) # comments = db(query).select(ctable.body).last() # if comments: # try: # markup = etree.XML(comments.body) # text = markup.xpath(".//text()") # if text: # text = " ".join(text) # else: # text = "" # except etree.XMLSyntaxError: # t = html.fromstring(comments.body) # text = t.text_content() # comments = TR( # TH("%s: " % T("Latest Comment")), # A(text, # _href=URL(args=[r.id, "discuss"])) # ) # else: # comments = "" rheader = DIV(TABLE( project, activity, TR( TH("%s: " % table.name.label), record.name, ), description, facility, location, assignee, time_estimated, time_actual, #comments, ), rheader_tabs) return rheader # ------------------------------------------------------------------------- def task_notify(form): """ If the task is assigned to someone then notify them """ vars = form.vars try: pe_id = int(vars.pe_id) except TypeError, ValueError: return if form.record is None or (pe_id != form.record.pe_id): # Assignee has changed settings = current.deployment_settings if settings.has_module("msg"): # Notify assignee subject = "%s: Task assigned to you" % settings.get_system_name_short() url = "%s%s" % (settings.get_base_public_url(), URL(c="project", f="task", args=vars.id)) message = "You have been assigned a Task:\n\n%s\n\n%s\n\n%s" % \ (url, vars.name, vars.description or "") current.msg.send_by_pe_id(pe_id, subject, message) return # ============================================================================= class S3ProjectVirtualfields: """ Virtual fields for the project_project table """ def organisation(self): """ Name of the lead organisation of the project """ db = current.db s3db = current.s3db s3 = current.response.s3 otable = s3db.org_organisation ltable = s3db.project_organisation LEAD_ROLE = s3.project_organisation_lead_role query = (ltable.deleted != True) & \ (ltable.project_id == self.project_project.id) & \ (ltable.role == LEAD_ROLE) & \ (ltable.organisation_id == otable.id) org = db(query).select(otable.name, limitby=(0, 1)).first() if org: return org.name else: return None # ============================================================================= class S3ProjectActivityVirtualfields: """ Virtual fields for the project_activity table """ extra_fields = ["project_id", "location_id"] def organisation(self): """ Name of the lead organisation of the project """ db = current.db s3db = current.s3db s3 = current.response.s3 otable = s3db.org_organisation ltable = s3db.project_organisation LEAD_ROLE = s3.project_organisation_lead_role query = (ltable.deleted != True) & \ (ltable.project_id == self.project_activity.project_id) & \ (ltable.role == LEAD_ROLE) & \ (ltable.organisation_id == otable.id) org = db(query).select(otable.name, limitby=(0, 1)).first() if org: return org.name else: return None def L0(self): parents = Storage() parents = current.gis.get_parent_per_level(parents, self.project_activity.location_id, ids=False, names=True) if "L0" in parents: return parents["L0"] else: return None def L1(self): parents = Storage() parents = current.gis.get_parent_per_level(parents, self.project_activity.location_id, ids=False, names=True) if "L1" in parents: return parents["L1"] else: return None def L2(self): parents = Storage() parents = current.gis.get_parent_per_level(parents, self.project_activity.location_id, ids=False, names=True) if "L2" in parents: return parents["L2"] else: return None def L3(self): parents = Storage() parents = current.gis.get_parent_per_level(parents, self.project_activity.location_id, ids=False, names=True) if "L3" in parents: return parents["L3"] else: return None # ============================================================================= class S3ProjectBeneficiaryVirtualfields: """ Virtual fields for the project_beneficiary table """ extra_fields = ["activity_id"] def L0(self): db = current.db s3db = current.s3db s3 = current.response.s3 atable = s3db.project_activity query = (atable.id == self.project_beneficiary.activity_id) activity = db(query).select(atable.location_id, limitby=(0, 1)).first() if activity: parents = Storage() parents = current.gis.get_parent_per_level(parents, activity.location_id, ids=False, names=True) if "L0" in parents: return parents["L0"] else: return current.messages.NONE else: return current.messages.NONE def L1(self): db = current.db s3db = current.s3db s3 = current.response.s3 atable = s3db.project_activity query = (atable.id == self.project_beneficiary.activity_id) activity = db(query).select(atable.location_id, limitby=(0, 1)).first() if activity: parents = Storage() parents = current.gis.get_parent_per_level(parents, activity.location_id, ids=False, names=True) if "L1" in parents: return parents["L1"] else: return current.messages.NONE else: return current.messages.NONE def L2(self): db = current.db s3db = current.s3db s3 = current.response.s3 atable = s3db.project_activity query = (atable.id == self.project_beneficiary.activity_id) activity = db(query).select(atable.location_id, limitby=(0, 1)).first() if activity: parents = Storage() parents = current.gis.get_parent_per_level(parents, activity.location_id, ids=False, names=True) if "L2" in parents: return parents["L2"] else: return current.messages.NONE else: return current.messages.NONE def L3(self): db = current.db s3db = current.s3db s3 = current.response.s3 atable = s3db.project_activity query = (atable.id == self.project_beneficiary.activity_id) activity = db(query).select(atable.location_id, limitby=(0, 1)).first() if activity: parents = Storage() parents = current.gis.get_parent_per_level(parents, activity.location_id, ids=False, names=True) if "L3" in parents: return parents["L3"] else: return current.messages.NONE else: return current.messages.NONE # ============================================================================= class S3ProjectActivityContactVirtualFields: """ Virtual fields for the project_activity_contact table """ extra_fields = ["person_id"] def email(self): db = current.db s3db = current.s3db ptable = s3db.pr_person ctable = s3db.pr_contact person_id = self.project_activity_contact.person_id query = (ctable.deleted != True) & \ (ptable.id == person_id) & \ (ctable.pe_id == ptable.pe_id) & \ (ctable.contact_method == "EMAIL") items = db(query).select(ctable.value) return ", ".join([item.value for item in items]) def sms(self): db = current.db s3db = current.s3db ptable = s3db.pr_person ctable = s3db.pr_contact person_id = self.project_activity_contact.person_id query = (ctable.deleted != True) & \ (ptable.id == person_id) & \ (ctable.pe_id == ptable.pe_id) & \ (ctable.contact_method == "SMS") items = db(query).select(ctable.value) return ", ".join([item.value for item in items]) # ============================================================================= class S3ProjectTaskVirtualfields: """ Virtual fields for the project_task table """ extra_fields = ["id", "project_task_project:project_id$name", "project_task_activity:activity_id$name"] def project(self): """ Project associated with this task """ try: return self.project_project.name except AttributeError: return None def activity(self): """ Activity associated with this task """ try: return self.project_activity.name except AttributeError: return None def task_id(self): try: return self.project_task.id except AttributeError: return None # ============================================================================= class S3ProjectTimeVirtualfields: """ Virtual fields for the project_time table """ extra_fields = ["task_id", "person_id", "date"] def project(self): """ Project associated with this time entry - used by the 'Project Time' report """ db = current.db s3db = current.s3db ptable = s3db.project_project ltable = s3db.project_task_project query = (ltable.deleted != True) & \ (ltable.task_id == self.project_time.task_id) & \ (ltable.project_id == ptable.id) project = db(query).select(ptable.name, limitby=(0, 1)).first() if project: return project.name else: return None def day(self): """ Day of the last Week this time entry relates to - used by the 'Last Week's Work' report """ T = current.T now = current.request.utcnow thisdate = self.project_time.date if not thisdate: return "-" week = datetime.timedelta(days=7) if thisdate < (now - week): # Ignore data older than the last week # - should already be filtered in controller anyway return "-" return thisdate.date().strftime("%d %B") # END =========================================================================
mit
zenlambda/pip
tests/conftest.py
36
6986
import os import shutil import py import pytest from pip.utils import appdirs from tests.lib import SRC_DIR, TestData from tests.lib.path import Path from tests.lib.scripttest import PipTestEnvironment from tests.lib.venv import VirtualEnvironment def pytest_collection_modifyitems(items): for item in items: if not hasattr(item, 'module'): # e.g.: DoctestTextfile continue module_path = os.path.relpath( item.module.__file__, os.path.commonprefix([__file__, item.module.__file__]), ) module_root_dir = module_path.split(os.pathsep)[0] if (module_root_dir.startswith("functional") or module_root_dir.startswith("integration") or module_root_dir.startswith("lib")): item.add_marker(pytest.mark.integration) elif module_root_dir.startswith("unit"): item.add_marker(pytest.mark.unit) # We don't want to allow using the script resource if this is a # unit test, as unit tests should not need all that heavy lifting if set(getattr(item, "funcargnames", [])) & set(["script"]): raise RuntimeError( "Cannot use the ``script`` funcarg in a unit test: " "(filename = {0}, item = {1})".format(module_path, item) ) else: raise RuntimeError( "Unknown test type (filename = {0})".format(module_path) ) @pytest.fixture def tmpdir(request): """ Return a temporary directory path object which is unique to each test function invocation, created as a sub directory of the base temporary directory. The returned object is a ``tests.lib.path.Path`` object. This is taken from pytest itself but modified to return our typical path object instead of py.path.local as well as deleting the temporary directories at the end of each test case. """ name = request.node.name name = py.std.re.sub("[\W]", "_", name) tmp = request.config._tmpdirhandler.mktemp(name, numbered=True) # Clear out the temporary directory after the test has finished using it. # This should prevent us from needing a multiple gigabyte temporary # directory while running the tests. request.addfinalizer(lambda: shutil.rmtree(str(tmp), ignore_errors=True)) return Path(str(tmp)) @pytest.fixture(autouse=True) def isolate(tmpdir): """ Isolate our tests so that things like global configuration files and the like do not affect our test results. We use an autouse function scoped fixture because we want to ensure that every test has it's own isolated home directory. """ # TODO: Ensure Windows will respect $HOME, including for the cache # directory # TODO: Figure out how to isolate from *system* level configuration files # as well as user level configuration files. # Create a directory to use as our home location. home_dir = os.path.join(str(tmpdir), "home") os.makedirs(home_dir) # Create a directory to use as a fake root fake_root = os.path.join(str(tmpdir), "fake-root") os.makedirs(fake_root) # Set our home directory to our temporary directory, this should force all # of our relative configuration files to be read from here instead of the # user's actual $HOME directory. os.environ["HOME"] = home_dir # Isolate ourselves from XDG directories os.environ["XDG_DATA_HOME"] = os.path.join(home_dir, ".local", "share") os.environ["XDG_CONFIG_HOME"] = os.path.join(home_dir, ".config") os.environ["XDG_CACHE_HOME"] = os.path.join(home_dir, ".cache") os.environ["XDG_RUNTIME_DIR"] = os.path.join(home_dir, ".runtime") os.environ["XDG_DATA_DIRS"] = ":".join([ os.path.join(fake_root, "usr", "local", "share"), os.path.join(fake_root, "usr", "share"), ]) os.environ["XDG_CONFIG_DIRS"] = os.path.join(fake_root, "etc", "xdg") # Configure git, because without an author name/email git will complain # and cause test failures. os.environ["GIT_CONFIG_NOSYSTEM"] = "1" os.environ["GIT_AUTHOR_NAME"] = "pip" os.environ["GIT_AUTHOR_EMAIL"] = "pypa-dev@googlegroups.com" # We want to disable the version check from running in the tests os.environ["PIP_DISABLE_PIP_VERSION_CHECK"] = "true" os.makedirs(os.path.join(home_dir, ".config", "git")) with open(os.path.join(home_dir, ".config", "git", "config"), "wb") as fp: fp.write( b"[user]\n\tname = pip\n\temail = pypa-dev@googlegroups.com\n" ) @pytest.fixture def virtualenv(tmpdir, monkeypatch, isolate): """ Return a virtual environment which is unique to each test function invocation created inside of a sub directory of the test function's temporary directory. The returned object is a ``tests.lib.venv.VirtualEnvironment`` object. """ # Force shutil to use the older method of rmtree that didn't use the fd # functions. These seem to fail on Travis (and only on Travis). monkeypatch.setattr(shutil, "_use_fd_functions", False, raising=False) # Copy over our source tree so that each virtual environment is self # contained pip_src = tmpdir.join("pip_src").abspath shutil.copytree( SRC_DIR, pip_src, ignore=shutil.ignore_patterns( "*.pyc", "__pycache__", "contrib", "docs", "tasks", "*.txt", "tests", "pip.egg-info", "build", "dist", ".tox", ".git", ), ) # Create the virtual environment venv = VirtualEnvironment.create( tmpdir.join("workspace", "venv"), pip_source_dir=pip_src, ) # Clean out our cache: creating the venv injects wheels into it. if os.path.exists(appdirs.user_cache_dir("pip")): shutil.rmtree(appdirs.user_cache_dir("pip")) # Undo our monkeypatching of shutil monkeypatch.undo() return venv @pytest.fixture def script(tmpdir, virtualenv): """ Return a PipTestEnvironment which is unique to each test function and will execute all commands inside of the unique virtual environment for this test function. The returned object is a ``tests.lib.scripttest.PipTestEnvironment``. """ return PipTestEnvironment( # The base location for our test environment tmpdir.join("workspace"), # Tell the Test Environment where our virtualenv is located virtualenv=virtualenv.location, # Do not ignore hidden files, they need to be checked as well ignore_hidden=False, # We are starting with an already empty directory start_clear=False, # We want to ensure no temporary files are left behind, so the # PipTestEnvironment needs to capture and assert against temp capture_temp=True, assert_no_temp=True, ) @pytest.fixture def data(tmpdir): return TestData.copy(tmpdir.join("data"))
mit
anandology/pyjamas
pygtkweb/demos/010-radiobuttons.py
7
2093
#!/usr/bin/env python # example radiobuttons.py import pygtk pygtk.require('2.0') import gtk class RadioButtons: def callback(self, widget, data=None): print "%s was toggled %s" % (data, ("OFF", "ON")[widget.get_active()]) def close_application(self, widget, event, data=None): gtk.main_quit() return False def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.connect("delete_event", self.close_application) self.window.set_title("radio buttons") self.window.set_border_width(0) box1 = gtk.VBox(False, 0) self.window.add(box1) box1.show() box2 = gtk.VBox(False, 10) box2.set_border_width(10) box1.pack_start(box2, True, True, 0) box2.show() button = gtk.RadioButton(None, "radio button1") button.connect("toggled", self.callback, "radio button 1") box2.pack_start(button, True, True, 0) button.show() button = gtk.RadioButton(button, "radio button2") button.connect("toggled", self.callback, "radio button 2") button.set_active(True) box2.pack_start(button, True, True, 0) button.show() button = gtk.RadioButton(button, "radio button3") button.connect("toggled", self.callback, "radio button 3") box2.pack_start(button, True, True, 0) button.show() separator = gtk.HSeparator() box1.pack_start(separator, False, True, 0) separator.show() box2 = gtk.VBox(False, 10) box2.set_border_width(10) box1.pack_start(box2, False, True, 0) box2.show() button = gtk.Button("close") button.connect_object("clicked", self.close_application, self.window, None) box2.pack_start(button, True, True, 0) button.set_flags(gtk.CAN_DEFAULT) button.grab_default() button.show() self.window.show() def main(): gtk.main() return 0 if __name__ == "__main__": RadioButtons() main()
apache-2.0
appsembler/edx-platform
common/test/acceptance/tests/lms/test_lms_course_discovery.py
24
2206
""" Test course discovery. """ import datetime import json import uuid from common.test.acceptance.fixtures.course import CourseFixture from common.test.acceptance.pages.common.auto_auth import AutoAuthPage from common.test.acceptance.pages.common.logout import LogoutPage from common.test.acceptance.pages.lms.discovery import CourseDiscoveryPage from common.test.acceptance.tests.helpers import AcceptanceTest, remove_file class CourseDiscoveryTest(AcceptanceTest): """ Test searching for courses. """ STAFF_USERNAME = "STAFF_TESTER" STAFF_EMAIL = "staff101@example.com" TEST_INDEX_FILENAME = "test_root/index_file.dat" def setUp(self): """ Create course page and courses to find """ # create index file with open(self.TEST_INDEX_FILENAME, "w+") as index_file: json.dump({}, index_file) self.addCleanup(remove_file, self.TEST_INDEX_FILENAME) super(CourseDiscoveryTest, self).setUp() self.page = CourseDiscoveryPage(self.browser) for i in range(12): org = 'test_org' number = "{}{}".format(str(i), str(uuid.uuid4().get_hex().upper()[0:6])) run = "test_run" name = "test course" if i < 10 else "grass is always greener" settings = {'enrollment_start': datetime.datetime(1970, 1, 1).isoformat()} CourseFixture(org, number, run, name, settings=settings).install() def _auto_auth(self, username, email, staff): """ Logout and login with given credentials. """ LogoutPage(self.browser).visit() AutoAuthPage(self.browser, username=username, email=email, staff=staff).visit() def test_page_existence(self): """ Make sure that the page is accessible. """ self.page.visit() def test_search(self): """ Make sure you can search for courses. """ self.page.visit() self.assertEqual(len(self.page.result_items), 12) self.page.search("grass") self.assertEqual(len(self.page.result_items), 2) self.page.clear_search() self.assertEqual(len(self.page.result_items), 12)
agpl-3.0
Yen-Chung-En/2015cdb_g1
static/Brython3.1.1-20150328-091302/Lib/_abcoll.py
688
5155
# Copyright 2007 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Abstract Base Classes (ABCs) for collections, according to PEP 3119. DON'T USE THIS MODULE DIRECTLY! The classes here should be imported via collections; they are defined here only to alleviate certain bootstrapping issues. Unit tests are in test_collections. """ from abc import ABCMeta, abstractmethod import sys __all__ = ["Hashable", "Iterable", "Iterator", "Sized", "Container", "Callable", "Set", "MutableSet", "Mapping", "MutableMapping", "MappingView", "KeysView", "ItemsView", "ValuesView", "Sequence", "MutableSequence", "ByteString", ] """ ### collection related types which are not exposed through builtin ### ## iterators ## #fixme brython #bytes_iterator = type(iter(b'')) bytes_iterator = type(iter('')) #fixme brython #bytearray_iterator = type(iter(bytearray())) #callable_iterator = ??? dict_keyiterator = type(iter({}.keys())) dict_valueiterator = type(iter({}.values())) dict_itemiterator = type(iter({}.items())) list_iterator = type(iter([])) list_reverseiterator = type(iter(reversed([]))) range_iterator = type(iter(range(0))) set_iterator = type(iter(set())) str_iterator = type(iter("")) tuple_iterator = type(iter(())) zip_iterator = type(iter(zip())) ## views ## dict_keys = type({}.keys()) dict_values = type({}.values()) dict_items = type({}.items()) ## misc ## dict_proxy = type(type.__dict__) """ def abstractmethod(self): return self ### ONE-TRICK PONIES ### #class Iterable(metaclass=ABCMeta): class Iterable: @abstractmethod def __iter__(self): while False: yield None @classmethod def __subclasshook__(cls, C): if cls is Iterable: if any("__iter__" in B.__dict__ for B in C.__mro__): return True return NotImplemented #class Sized(metaclass=ABCMeta): class Sized: @abstractmethod def __len__(self): return 0 @classmethod def __subclasshook__(cls, C): if cls is Sized: if any("__len__" in B.__dict__ for B in C.__mro__): return True return NotImplemented #class Container(metaclass=ABCMeta): class Container: @abstractmethod def __contains__(self, x): return False @classmethod def __subclasshook__(cls, C): if cls is Container: if any("__contains__" in B.__dict__ for B in C.__mro__): return True return NotImplemented ### MAPPINGS ### class Mapping(Sized, Iterable, Container): @abstractmethod def __getitem__(self, key): raise KeyError def get(self, key, default=None): try: return self[key] except KeyError: return default def __contains__(self, key): try: self[key] except KeyError: return False else: return True def keys(self): return KeysView(self) def items(self): return ItemsView(self) def values(self): return ValuesView(self) def __eq__(self, other): if not isinstance(other, Mapping): return NotImplemented return dict(self.items()) == dict(other.items()) def __ne__(self, other): return not (self == other) class MutableMapping(Mapping): @abstractmethod def __setitem__(self, key, value): raise KeyError @abstractmethod def __delitem__(self, key): raise KeyError __marker = object() def pop(self, key, default=__marker): try: value = self[key] except KeyError: if default is self.__marker: raise return default else: del self[key] return value def popitem(self): try: key = next(iter(self)) except StopIteration: raise KeyError value = self[key] del self[key] return key, value def clear(self): try: while True: self.popitem() except KeyError: pass def update(*args, **kwds): if len(args) > 2: raise TypeError("update() takes at most 2 positional " "arguments ({} given)".format(len(args))) elif not args: raise TypeError("update() takes at least 1 argument (0 given)") self = args[0] other = args[1] if len(args) >= 2 else () if isinstance(other, Mapping): for key in other: self[key] = other[key] elif hasattr(other, "keys"): for key in other.keys(): self[key] = other[key] else: for key, value in other: self[key] = value for key, value in kwds.items(): self[key] = value def setdefault(self, key, default=None): try: return self[key] except KeyError: self[key] = default return default #MutableMapping.register(dict)
agpl-3.0
jangler/vcii
vcii/test/test_sheet.py
1
2485
import random import unittest from vcii.sheet import * class TestSheet(unittest.TestCase): def test_key_to_indices(self): with self.assertRaises(ValueError): indices_from_label('1A') self.assertEqual(indices_from_label('A1'), (0, 0)) self.assertEqual(indices_from_label('zz99'), (26**2 + 25, 98)) def test_append(self): sheet = Sheet() sheet.cursor = [(lambda: random.randint(0, 10))()] * 2 sheet.append('rain') self.assertEqual(sheet.active_cell.content, 'rain') self.assertTrue(sheet.modified) sheet.modified = False sheet.append('bow') self.assertEqual(sheet.active_cell.content, 'rainbow') self.assertTrue(sheet.modified) def test_expand(self): sheet = Sheet() self.assertEqual(sheet.size, (0, 0)) max_size = 0, 0 for i in range(10): coords = [(lambda: random.randint(0, 10))()] * 2 sheet.expand(*coords) max_size = tuple(max(max_size[j], coords[j] + 1) for j in range(2)) self.assertEqual(sheet.size, max_size) self.assertTrue(sheet.modified) def test_setitem(self): sheet = Sheet() sheet['C2'] = 'testing' self.assertEqual(sheet.cells[2][1].content, 'testing') self.assertEqual(sheet.size, (3, 2)) self.assertTrue(sheet.modified) def test_move_cursor(self): sheet = Sheet() sheet.move_cursor(0, 0) self.assertEqual(sheet.cursor, [0, 0]) sheet.move_cursor(-1, 1) self.assertEqual(sheet.cursor, [0, 1]) sheet.move_cursor(1, -2) self.assertEqual(sheet.cursor, [1, 0]) self.assertFalse(sheet.modified) sheet.expand(0, 0) sheet.modified = False sheet.move_cursor(-1, 0) self.assertEqual(sheet.cursor, [0, 0]) self.assertFalse(sheet.modified) def test_column_width(self): sheet = Sheet() sheet.expand(1, 0) self.assertEqual(sheet.column_width(1), DEFAULT_COLUMN_WIDTH) self.assertEqual(sheet.column_width(2), DEFAULT_COLUMN_WIDTH) sheet.column_widths[1] = 5 self.assertEqual(sheet.column_width(0), DEFAULT_COLUMN_WIDTH) self.assertEqual(sheet.column_width(1), 5) def test_resize_column(self): sheet = Sheet() sheet.resize_column(0, 0) self.assertEqual(sheet.size, (1, 1)) self.assertEqual(sheet.column_widths, [2])
mit
eightyfourcoin/84
share/qt/make_spinner.py
4415
1035
#!/usr/bin/env python # W.J. van der Laan, 2011 # Make spinning .mng animation from a .png # Requires imagemagick 6.7+ from __future__ import division from os import path from PIL import Image from subprocess import Popen SRC='img/reload_scaled.png' DST='../../src/qt/res/movies/update_spinner.mng' TMPDIR='/tmp' TMPNAME='tmp-%03i.png' NUMFRAMES=35 FRAMERATE=10.0 CONVERT='convert' CLOCKWISE=True DSIZE=(16,16) im_src = Image.open(SRC) if CLOCKWISE: im_src = im_src.transpose(Image.FLIP_LEFT_RIGHT) def frame_to_filename(frame): return path.join(TMPDIR, TMPNAME % frame) frame_files = [] for frame in xrange(NUMFRAMES): rotation = (frame + 0.5) / NUMFRAMES * 360.0 if CLOCKWISE: rotation = -rotation im_new = im_src.rotate(rotation, Image.BICUBIC) im_new.thumbnail(DSIZE, Image.ANTIALIAS) outfile = frame_to_filename(frame) im_new.save(outfile, 'png') frame_files.append(outfile) p = Popen([CONVERT, "-delay", str(FRAMERATE), "-dispose", "2"] + frame_files + [DST]) p.communicate()
mit
sg00dwin/origin
vendor/github.com/google/certificate-transparency/python/ct/client/db/sqlite_temp_db.py
35
6021
import logging import sqlite3 from ct.client.db import temp_db from ct.client.db import database from ct.client.db import sqlite_connection as sqlitecon from ct.proto import client_pb2 class SQLiteTempDBFactory(object): """A database factory that manages mappings from public identifiers (log names) to SQLite databases.""" def __init__(self, connection_manager, database_dir): """Initialize the database factory. Args: connection_manager: an SQLiteConnectionManager object database_dir: the directory where the database files reside. """ self.__mgr = connection_manager self.__database_dir = database_dir # This is the meta-table mapping database IDs to server names. with self.__mgr.get_connection() as conn: conn.execute("CREATE TABLE IF NOT EXISTS database_mapping(" "id INTEGER PRIMARY KEY, server_name TEXT UNIQUE)") self.__tables = ["database_mapping"] def __repr__(self): return "%r(%r)" % (self.__class__.__name__, self.__mgr) def __str__(self): return "%s(%s, tables: %s): " % (self.__class__.__name__, self.__mgr, self.__tables) @staticmethod def __database_id_to_name(database_id): return "db%d" % database_id def __get_db_name(self, cursor, log_server): cursor.execute("SELECT id from database_mapping WHERE server_name = ?", (log_server,)) row = cursor.fetchone() if row is None: raise database.KeyError("No database for log server %s" % log_server) return self.__database_id_to_name(row["id"]) # TODO(ekasper): add a remove_storage() for removing obsolete data. def create_storage(self, log_server): """Create a SQLiteTempDB object pointing to the temporary storage of a given log server. If the temporary storage does not exist, creates one. Args: log_server: the server name. """ with self.__mgr.get_connection() as conn: cursor = conn.cursor() try: database_name = self.__get_db_name(cursor, log_server) except database.KeyError: try: cursor.execute("INSERT INTO database_mapping(server_name) " "VALUES (?)", (log_server,)) database_name = self.__database_id_to_name(cursor.lastrowid) except sqlite3.IntegrityError as e: raise database.KeyError("Failed to create a table mapping " "for server %s: is a concurrent " "factory running?\n%s" % (log_server, e)) return SQLiteTempDB(sqlitecon.SQLiteConnectionManager( self.__database_dir + "/" + database_name)) class SQLiteTempDB(temp_db.TempDB): """SQLite implementation of TempDB.""" def __init__(self, connection_manager): """Create an SQLiteTempDB object. Args: connection_manager: and SQLiteConnectionManager object """ self.__mgr = connection_manager with self.__mgr.get_connection() as conn: conn.execute("CREATE TABLE IF NOT EXISTS entries(" "id INTEGER PRIMARY KEY, entry BLOB)") self.__tables = ["entries"] def __repr__(self): return "%r(%r)" % (self.__class__.__name__, self.__mgr) def __str__(self): return "%s(%s, tables: %s): " % (self.__class__.__name__, self.__mgr, self.__tables) # Not part of the abstract interface: used to identify the database file # we're writing to. def db_name(self): return self.__mgr.db_name def drop_entries(self): """Drop all entries.""" with self.__mgr.get_connection() as conn: conn.execute("DELETE FROM entries") def store_entries(self, entries): """Batch store log entries. Args: entries: an iterable of (entry_number, client_pb2.EntryResponse) tuples """ with self.__mgr.get_connection() as conn: cursor = conn.cursor() serialized_entries = map(lambda x: ( x[0], sqlite3.Binary(x[1].SerializeToString())), entries) try: cursor.executemany("INSERT OR REPLACE INTO entries(id, entry) VALUES " "(?, ?)", serialized_entries) except sqlite3.IntegrityError as e: raise database.KeyError("Failed to insert entries: an entry " "with the given sequence number " "already exists\n%s" % e) def scan_entries(self, start, end): """Retrieve log entries. Args: start: index of the first entry to retrieve. end: index of the last entry to retrieve. Yields: client_pb2.EntryResponse protos Raises: KeyError: an entry with a sequence number in the range does not exist. """ with self.__mgr.get_connection() as conn: cursor = conn.cursor() next_id = start for row in cursor.execute("SELECT id, entry FROM entries WHERE id " "BETWEEN ? and ? ORDER BY id ASC", (start, end)): if row["id"] != next_id: raise database.KeyError("No such entry: %d" % next_id) entry = client_pb2.EntryResponse() entry.ParseFromString(str(row["entry"])) yield entry next_id += 1 if next_id != end + 1: raise database.KeyError("No such entry: %d" % next_id)
apache-2.0
kikocorreoso/brython
www/src/Lib/encodings/cp864.py
37
34353
""" Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP864.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_map) 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_map)[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='cp864', encode=Codec().encode, decode=Codec().decode, incrementalencoder=IncrementalEncoder, incrementaldecoder=IncrementalDecoder, streamreader=StreamReader, streamwriter=StreamWriter, ) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0025: 0x066a, # ARABIC PERCENT SIGN 0x0080: 0x00b0, # DEGREE SIGN 0x0081: 0x00b7, # MIDDLE DOT 0x0082: 0x2219, # BULLET OPERATOR 0x0083: 0x221a, # SQUARE ROOT 0x0084: 0x2592, # MEDIUM SHADE 0x0085: 0x2500, # FORMS LIGHT HORIZONTAL 0x0086: 0x2502, # FORMS LIGHT VERTICAL 0x0087: 0x253c, # FORMS LIGHT VERTICAL AND HORIZONTAL 0x0088: 0x2524, # FORMS LIGHT VERTICAL AND LEFT 0x0089: 0x252c, # FORMS LIGHT DOWN AND HORIZONTAL 0x008a: 0x251c, # FORMS LIGHT VERTICAL AND RIGHT 0x008b: 0x2534, # FORMS LIGHT UP AND HORIZONTAL 0x008c: 0x2510, # FORMS LIGHT DOWN AND LEFT 0x008d: 0x250c, # FORMS LIGHT DOWN AND RIGHT 0x008e: 0x2514, # FORMS LIGHT UP AND RIGHT 0x008f: 0x2518, # FORMS LIGHT UP AND LEFT 0x0090: 0x03b2, # GREEK SMALL BETA 0x0091: 0x221e, # INFINITY 0x0092: 0x03c6, # GREEK SMALL PHI 0x0093: 0x00b1, # PLUS-OR-MINUS SIGN 0x0094: 0x00bd, # FRACTION 1/2 0x0095: 0x00bc, # FRACTION 1/4 0x0096: 0x2248, # ALMOST EQUAL TO 0x0097: 0x00ab, # LEFT POINTING GUILLEMET 0x0098: 0x00bb, # RIGHT POINTING GUILLEMET 0x0099: 0xfef7, # ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE ISOLATED FORM 0x009a: 0xfef8, # ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE FINAL FORM 0x009b: None, # UNDEFINED 0x009c: None, # UNDEFINED 0x009d: 0xfefb, # ARABIC LIGATURE LAM WITH ALEF ISOLATED FORM 0x009e: 0xfefc, # ARABIC LIGATURE LAM WITH ALEF FINAL FORM 0x009f: None, # UNDEFINED 0x00a1: 0x00ad, # SOFT HYPHEN 0x00a2: 0xfe82, # ARABIC LETTER ALEF WITH MADDA ABOVE FINAL FORM 0x00a5: 0xfe84, # ARABIC LETTER ALEF WITH HAMZA ABOVE FINAL FORM 0x00a6: None, # UNDEFINED 0x00a7: None, # UNDEFINED 0x00a8: 0xfe8e, # ARABIC LETTER ALEF FINAL FORM 0x00a9: 0xfe8f, # ARABIC LETTER BEH ISOLATED FORM 0x00aa: 0xfe95, # ARABIC LETTER TEH ISOLATED FORM 0x00ab: 0xfe99, # ARABIC LETTER THEH ISOLATED FORM 0x00ac: 0x060c, # ARABIC COMMA 0x00ad: 0xfe9d, # ARABIC LETTER JEEM ISOLATED FORM 0x00ae: 0xfea1, # ARABIC LETTER HAH ISOLATED FORM 0x00af: 0xfea5, # ARABIC LETTER KHAH ISOLATED FORM 0x00b0: 0x0660, # ARABIC-INDIC DIGIT ZERO 0x00b1: 0x0661, # ARABIC-INDIC DIGIT ONE 0x00b2: 0x0662, # ARABIC-INDIC DIGIT TWO 0x00b3: 0x0663, # ARABIC-INDIC DIGIT THREE 0x00b4: 0x0664, # ARABIC-INDIC DIGIT FOUR 0x00b5: 0x0665, # ARABIC-INDIC DIGIT FIVE 0x00b6: 0x0666, # ARABIC-INDIC DIGIT SIX 0x00b7: 0x0667, # ARABIC-INDIC DIGIT SEVEN 0x00b8: 0x0668, # ARABIC-INDIC DIGIT EIGHT 0x00b9: 0x0669, # ARABIC-INDIC DIGIT NINE 0x00ba: 0xfed1, # ARABIC LETTER FEH ISOLATED FORM 0x00bb: 0x061b, # ARABIC SEMICOLON 0x00bc: 0xfeb1, # ARABIC LETTER SEEN ISOLATED FORM 0x00bd: 0xfeb5, # ARABIC LETTER SHEEN ISOLATED FORM 0x00be: 0xfeb9, # ARABIC LETTER SAD ISOLATED FORM 0x00bf: 0x061f, # ARABIC QUESTION MARK 0x00c0: 0x00a2, # CENT SIGN 0x00c1: 0xfe80, # ARABIC LETTER HAMZA ISOLATED FORM 0x00c2: 0xfe81, # ARABIC LETTER ALEF WITH MADDA ABOVE ISOLATED FORM 0x00c3: 0xfe83, # ARABIC LETTER ALEF WITH HAMZA ABOVE ISOLATED FORM 0x00c4: 0xfe85, # ARABIC LETTER WAW WITH HAMZA ABOVE ISOLATED FORM 0x00c5: 0xfeca, # ARABIC LETTER AIN FINAL FORM 0x00c6: 0xfe8b, # ARABIC LETTER YEH WITH HAMZA ABOVE INITIAL FORM 0x00c7: 0xfe8d, # ARABIC LETTER ALEF ISOLATED FORM 0x00c8: 0xfe91, # ARABIC LETTER BEH INITIAL FORM 0x00c9: 0xfe93, # ARABIC LETTER TEH MARBUTA ISOLATED FORM 0x00ca: 0xfe97, # ARABIC LETTER TEH INITIAL FORM 0x00cb: 0xfe9b, # ARABIC LETTER THEH INITIAL FORM 0x00cc: 0xfe9f, # ARABIC LETTER JEEM INITIAL FORM 0x00cd: 0xfea3, # ARABIC LETTER HAH INITIAL FORM 0x00ce: 0xfea7, # ARABIC LETTER KHAH INITIAL FORM 0x00cf: 0xfea9, # ARABIC LETTER DAL ISOLATED FORM 0x00d0: 0xfeab, # ARABIC LETTER THAL ISOLATED FORM 0x00d1: 0xfead, # ARABIC LETTER REH ISOLATED FORM 0x00d2: 0xfeaf, # ARABIC LETTER ZAIN ISOLATED FORM 0x00d3: 0xfeb3, # ARABIC LETTER SEEN INITIAL FORM 0x00d4: 0xfeb7, # ARABIC LETTER SHEEN INITIAL FORM 0x00d5: 0xfebb, # ARABIC LETTER SAD INITIAL FORM 0x00d6: 0xfebf, # ARABIC LETTER DAD INITIAL FORM 0x00d7: 0xfec1, # ARABIC LETTER TAH ISOLATED FORM 0x00d8: 0xfec5, # ARABIC LETTER ZAH ISOLATED FORM 0x00d9: 0xfecb, # ARABIC LETTER AIN INITIAL FORM 0x00da: 0xfecf, # ARABIC LETTER GHAIN INITIAL FORM 0x00db: 0x00a6, # BROKEN VERTICAL BAR 0x00dc: 0x00ac, # NOT SIGN 0x00dd: 0x00f7, # DIVISION SIGN 0x00de: 0x00d7, # MULTIPLICATION SIGN 0x00df: 0xfec9, # ARABIC LETTER AIN ISOLATED FORM 0x00e0: 0x0640, # ARABIC TATWEEL 0x00e1: 0xfed3, # ARABIC LETTER FEH INITIAL FORM 0x00e2: 0xfed7, # ARABIC LETTER QAF INITIAL FORM 0x00e3: 0xfedb, # ARABIC LETTER KAF INITIAL FORM 0x00e4: 0xfedf, # ARABIC LETTER LAM INITIAL FORM 0x00e5: 0xfee3, # ARABIC LETTER MEEM INITIAL FORM 0x00e6: 0xfee7, # ARABIC LETTER NOON INITIAL FORM 0x00e7: 0xfeeb, # ARABIC LETTER HEH INITIAL FORM 0x00e8: 0xfeed, # ARABIC LETTER WAW ISOLATED FORM 0x00e9: 0xfeef, # ARABIC LETTER ALEF MAKSURA ISOLATED FORM 0x00ea: 0xfef3, # ARABIC LETTER YEH INITIAL FORM 0x00eb: 0xfebd, # ARABIC LETTER DAD ISOLATED FORM 0x00ec: 0xfecc, # ARABIC LETTER AIN MEDIAL FORM 0x00ed: 0xfece, # ARABIC LETTER GHAIN FINAL FORM 0x00ee: 0xfecd, # ARABIC LETTER GHAIN ISOLATED FORM 0x00ef: 0xfee1, # ARABIC LETTER MEEM ISOLATED FORM 0x00f0: 0xfe7d, # ARABIC SHADDA MEDIAL FORM 0x00f1: 0x0651, # ARABIC SHADDAH 0x00f2: 0xfee5, # ARABIC LETTER NOON ISOLATED FORM 0x00f3: 0xfee9, # ARABIC LETTER HEH ISOLATED FORM 0x00f4: 0xfeec, # ARABIC LETTER HEH MEDIAL FORM 0x00f5: 0xfef0, # ARABIC LETTER ALEF MAKSURA FINAL FORM 0x00f6: 0xfef2, # ARABIC LETTER YEH FINAL FORM 0x00f7: 0xfed0, # ARABIC LETTER GHAIN MEDIAL FORM 0x00f8: 0xfed5, # ARABIC LETTER QAF ISOLATED FORM 0x00f9: 0xfef5, # ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM 0x00fa: 0xfef6, # ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE FINAL FORM 0x00fb: 0xfedd, # ARABIC LETTER LAM ISOLATED FORM 0x00fc: 0xfed9, # ARABIC LETTER KAF ISOLATED FORM 0x00fd: 0xfef1, # ARABIC LETTER YEH ISOLATED FORM 0x00fe: 0x25a0, # BLACK SQUARE 0x00ff: None, # UNDEFINED }) ### Decoding Table decoding_table = ( '\x00' # 0x0000 -> NULL '\x01' # 0x0001 -> START OF HEADING '\x02' # 0x0002 -> START OF TEXT '\x03' # 0x0003 -> END OF TEXT '\x04' # 0x0004 -> END OF TRANSMISSION '\x05' # 0x0005 -> ENQUIRY '\x06' # 0x0006 -> ACKNOWLEDGE '\x07' # 0x0007 -> BELL '\x08' # 0x0008 -> BACKSPACE '\t' # 0x0009 -> HORIZONTAL TABULATION '\n' # 0x000a -> LINE FEED '\x0b' # 0x000b -> VERTICAL TABULATION '\x0c' # 0x000c -> FORM FEED '\r' # 0x000d -> CARRIAGE RETURN '\x0e' # 0x000e -> SHIFT OUT '\x0f' # 0x000f -> SHIFT IN '\x10' # 0x0010 -> DATA LINK ESCAPE '\x11' # 0x0011 -> DEVICE CONTROL ONE '\x12' # 0x0012 -> DEVICE CONTROL TWO '\x13' # 0x0013 -> DEVICE CONTROL THREE '\x14' # 0x0014 -> DEVICE CONTROL FOUR '\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE '\x16' # 0x0016 -> SYNCHRONOUS IDLE '\x17' # 0x0017 -> END OF TRANSMISSION BLOCK '\x18' # 0x0018 -> CANCEL '\x19' # 0x0019 -> END OF MEDIUM '\x1a' # 0x001a -> SUBSTITUTE '\x1b' # 0x001b -> ESCAPE '\x1c' # 0x001c -> FILE SEPARATOR '\x1d' # 0x001d -> GROUP SEPARATOR '\x1e' # 0x001e -> RECORD SEPARATOR '\x1f' # 0x001f -> UNIT SEPARATOR ' ' # 0x0020 -> SPACE '!' # 0x0021 -> EXCLAMATION MARK '"' # 0x0022 -> QUOTATION MARK '#' # 0x0023 -> NUMBER SIGN '$' # 0x0024 -> DOLLAR SIGN '\u066a' # 0x0025 -> ARABIC PERCENT SIGN '&' # 0x0026 -> AMPERSAND "'" # 0x0027 -> APOSTROPHE '(' # 0x0028 -> LEFT PARENTHESIS ')' # 0x0029 -> RIGHT PARENTHESIS '*' # 0x002a -> ASTERISK '+' # 0x002b -> PLUS SIGN ',' # 0x002c -> COMMA '-' # 0x002d -> HYPHEN-MINUS '.' # 0x002e -> FULL STOP '/' # 0x002f -> SOLIDUS '0' # 0x0030 -> DIGIT ZERO '1' # 0x0031 -> DIGIT ONE '2' # 0x0032 -> DIGIT TWO '3' # 0x0033 -> DIGIT THREE '4' # 0x0034 -> DIGIT FOUR '5' # 0x0035 -> DIGIT FIVE '6' # 0x0036 -> DIGIT SIX '7' # 0x0037 -> DIGIT SEVEN '8' # 0x0038 -> DIGIT EIGHT '9' # 0x0039 -> DIGIT NINE ':' # 0x003a -> COLON ';' # 0x003b -> SEMICOLON '<' # 0x003c -> LESS-THAN SIGN '=' # 0x003d -> EQUALS SIGN '>' # 0x003e -> GREATER-THAN SIGN '?' # 0x003f -> QUESTION MARK '@' # 0x0040 -> COMMERCIAL AT 'A' # 0x0041 -> LATIN CAPITAL LETTER A 'B' # 0x0042 -> LATIN CAPITAL LETTER B 'C' # 0x0043 -> LATIN CAPITAL LETTER C 'D' # 0x0044 -> LATIN CAPITAL LETTER D 'E' # 0x0045 -> LATIN CAPITAL LETTER E 'F' # 0x0046 -> LATIN CAPITAL LETTER F 'G' # 0x0047 -> LATIN CAPITAL LETTER G 'H' # 0x0048 -> LATIN CAPITAL LETTER H 'I' # 0x0049 -> LATIN CAPITAL LETTER I 'J' # 0x004a -> LATIN CAPITAL LETTER J 'K' # 0x004b -> LATIN CAPITAL LETTER K 'L' # 0x004c -> LATIN CAPITAL LETTER L 'M' # 0x004d -> LATIN CAPITAL LETTER M 'N' # 0x004e -> LATIN CAPITAL LETTER N 'O' # 0x004f -> LATIN CAPITAL LETTER O 'P' # 0x0050 -> LATIN CAPITAL LETTER P 'Q' # 0x0051 -> LATIN CAPITAL LETTER Q 'R' # 0x0052 -> LATIN CAPITAL LETTER R 'S' # 0x0053 -> LATIN CAPITAL LETTER S 'T' # 0x0054 -> LATIN CAPITAL LETTER T 'U' # 0x0055 -> LATIN CAPITAL LETTER U 'V' # 0x0056 -> LATIN CAPITAL LETTER V 'W' # 0x0057 -> LATIN CAPITAL LETTER W 'X' # 0x0058 -> LATIN CAPITAL LETTER X 'Y' # 0x0059 -> LATIN CAPITAL LETTER Y 'Z' # 0x005a -> LATIN CAPITAL LETTER Z '[' # 0x005b -> LEFT SQUARE BRACKET '\\' # 0x005c -> REVERSE SOLIDUS ']' # 0x005d -> RIGHT SQUARE BRACKET '^' # 0x005e -> CIRCUMFLEX ACCENT '_' # 0x005f -> LOW LINE '`' # 0x0060 -> GRAVE ACCENT 'a' # 0x0061 -> LATIN SMALL LETTER A 'b' # 0x0062 -> LATIN SMALL LETTER B 'c' # 0x0063 -> LATIN SMALL LETTER C 'd' # 0x0064 -> LATIN SMALL LETTER D 'e' # 0x0065 -> LATIN SMALL LETTER E 'f' # 0x0066 -> LATIN SMALL LETTER F 'g' # 0x0067 -> LATIN SMALL LETTER G 'h' # 0x0068 -> LATIN SMALL LETTER H 'i' # 0x0069 -> LATIN SMALL LETTER I 'j' # 0x006a -> LATIN SMALL LETTER J 'k' # 0x006b -> LATIN SMALL LETTER K 'l' # 0x006c -> LATIN SMALL LETTER L 'm' # 0x006d -> LATIN SMALL LETTER M 'n' # 0x006e -> LATIN SMALL LETTER N 'o' # 0x006f -> LATIN SMALL LETTER O 'p' # 0x0070 -> LATIN SMALL LETTER P 'q' # 0x0071 -> LATIN SMALL LETTER Q 'r' # 0x0072 -> LATIN SMALL LETTER R 's' # 0x0073 -> LATIN SMALL LETTER S 't' # 0x0074 -> LATIN SMALL LETTER T 'u' # 0x0075 -> LATIN SMALL LETTER U 'v' # 0x0076 -> LATIN SMALL LETTER V 'w' # 0x0077 -> LATIN SMALL LETTER W 'x' # 0x0078 -> LATIN SMALL LETTER X 'y' # 0x0079 -> LATIN SMALL LETTER Y 'z' # 0x007a -> LATIN SMALL LETTER Z '{' # 0x007b -> LEFT CURLY BRACKET '|' # 0x007c -> VERTICAL LINE '}' # 0x007d -> RIGHT CURLY BRACKET '~' # 0x007e -> TILDE '\x7f' # 0x007f -> DELETE '\xb0' # 0x0080 -> DEGREE SIGN '\xb7' # 0x0081 -> MIDDLE DOT '\u2219' # 0x0082 -> BULLET OPERATOR '\u221a' # 0x0083 -> SQUARE ROOT '\u2592' # 0x0084 -> MEDIUM SHADE '\u2500' # 0x0085 -> FORMS LIGHT HORIZONTAL '\u2502' # 0x0086 -> FORMS LIGHT VERTICAL '\u253c' # 0x0087 -> FORMS LIGHT VERTICAL AND HORIZONTAL '\u2524' # 0x0088 -> FORMS LIGHT VERTICAL AND LEFT '\u252c' # 0x0089 -> FORMS LIGHT DOWN AND HORIZONTAL '\u251c' # 0x008a -> FORMS LIGHT VERTICAL AND RIGHT '\u2534' # 0x008b -> FORMS LIGHT UP AND HORIZONTAL '\u2510' # 0x008c -> FORMS LIGHT DOWN AND LEFT '\u250c' # 0x008d -> FORMS LIGHT DOWN AND RIGHT '\u2514' # 0x008e -> FORMS LIGHT UP AND RIGHT '\u2518' # 0x008f -> FORMS LIGHT UP AND LEFT '\u03b2' # 0x0090 -> GREEK SMALL BETA '\u221e' # 0x0091 -> INFINITY '\u03c6' # 0x0092 -> GREEK SMALL PHI '\xb1' # 0x0093 -> PLUS-OR-MINUS SIGN '\xbd' # 0x0094 -> FRACTION 1/2 '\xbc' # 0x0095 -> FRACTION 1/4 '\u2248' # 0x0096 -> ALMOST EQUAL TO '\xab' # 0x0097 -> LEFT POINTING GUILLEMET '\xbb' # 0x0098 -> RIGHT POINTING GUILLEMET '\ufef7' # 0x0099 -> ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE ISOLATED FORM '\ufef8' # 0x009a -> ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE FINAL FORM '\ufffe' # 0x009b -> UNDEFINED '\ufffe' # 0x009c -> UNDEFINED '\ufefb' # 0x009d -> ARABIC LIGATURE LAM WITH ALEF ISOLATED FORM '\ufefc' # 0x009e -> ARABIC LIGATURE LAM WITH ALEF FINAL FORM '\ufffe' # 0x009f -> UNDEFINED '\xa0' # 0x00a0 -> NON-BREAKING SPACE '\xad' # 0x00a1 -> SOFT HYPHEN '\ufe82' # 0x00a2 -> ARABIC LETTER ALEF WITH MADDA ABOVE FINAL FORM '\xa3' # 0x00a3 -> POUND SIGN '\xa4' # 0x00a4 -> CURRENCY SIGN '\ufe84' # 0x00a5 -> ARABIC LETTER ALEF WITH HAMZA ABOVE FINAL FORM '\ufffe' # 0x00a6 -> UNDEFINED '\ufffe' # 0x00a7 -> UNDEFINED '\ufe8e' # 0x00a8 -> ARABIC LETTER ALEF FINAL FORM '\ufe8f' # 0x00a9 -> ARABIC LETTER BEH ISOLATED FORM '\ufe95' # 0x00aa -> ARABIC LETTER TEH ISOLATED FORM '\ufe99' # 0x00ab -> ARABIC LETTER THEH ISOLATED FORM '\u060c' # 0x00ac -> ARABIC COMMA '\ufe9d' # 0x00ad -> ARABIC LETTER JEEM ISOLATED FORM '\ufea1' # 0x00ae -> ARABIC LETTER HAH ISOLATED FORM '\ufea5' # 0x00af -> ARABIC LETTER KHAH ISOLATED FORM '\u0660' # 0x00b0 -> ARABIC-INDIC DIGIT ZERO '\u0661' # 0x00b1 -> ARABIC-INDIC DIGIT ONE '\u0662' # 0x00b2 -> ARABIC-INDIC DIGIT TWO '\u0663' # 0x00b3 -> ARABIC-INDIC DIGIT THREE '\u0664' # 0x00b4 -> ARABIC-INDIC DIGIT FOUR '\u0665' # 0x00b5 -> ARABIC-INDIC DIGIT FIVE '\u0666' # 0x00b6 -> ARABIC-INDIC DIGIT SIX '\u0667' # 0x00b7 -> ARABIC-INDIC DIGIT SEVEN '\u0668' # 0x00b8 -> ARABIC-INDIC DIGIT EIGHT '\u0669' # 0x00b9 -> ARABIC-INDIC DIGIT NINE '\ufed1' # 0x00ba -> ARABIC LETTER FEH ISOLATED FORM '\u061b' # 0x00bb -> ARABIC SEMICOLON '\ufeb1' # 0x00bc -> ARABIC LETTER SEEN ISOLATED FORM '\ufeb5' # 0x00bd -> ARABIC LETTER SHEEN ISOLATED FORM '\ufeb9' # 0x00be -> ARABIC LETTER SAD ISOLATED FORM '\u061f' # 0x00bf -> ARABIC QUESTION MARK '\xa2' # 0x00c0 -> CENT SIGN '\ufe80' # 0x00c1 -> ARABIC LETTER HAMZA ISOLATED FORM '\ufe81' # 0x00c2 -> ARABIC LETTER ALEF WITH MADDA ABOVE ISOLATED FORM '\ufe83' # 0x00c3 -> ARABIC LETTER ALEF WITH HAMZA ABOVE ISOLATED FORM '\ufe85' # 0x00c4 -> ARABIC LETTER WAW WITH HAMZA ABOVE ISOLATED FORM '\ufeca' # 0x00c5 -> ARABIC LETTER AIN FINAL FORM '\ufe8b' # 0x00c6 -> ARABIC LETTER YEH WITH HAMZA ABOVE INITIAL FORM '\ufe8d' # 0x00c7 -> ARABIC LETTER ALEF ISOLATED FORM '\ufe91' # 0x00c8 -> ARABIC LETTER BEH INITIAL FORM '\ufe93' # 0x00c9 -> ARABIC LETTER TEH MARBUTA ISOLATED FORM '\ufe97' # 0x00ca -> ARABIC LETTER TEH INITIAL FORM '\ufe9b' # 0x00cb -> ARABIC LETTER THEH INITIAL FORM '\ufe9f' # 0x00cc -> ARABIC LETTER JEEM INITIAL FORM '\ufea3' # 0x00cd -> ARABIC LETTER HAH INITIAL FORM '\ufea7' # 0x00ce -> ARABIC LETTER KHAH INITIAL FORM '\ufea9' # 0x00cf -> ARABIC LETTER DAL ISOLATED FORM '\ufeab' # 0x00d0 -> ARABIC LETTER THAL ISOLATED FORM '\ufead' # 0x00d1 -> ARABIC LETTER REH ISOLATED FORM '\ufeaf' # 0x00d2 -> ARABIC LETTER ZAIN ISOLATED FORM '\ufeb3' # 0x00d3 -> ARABIC LETTER SEEN INITIAL FORM '\ufeb7' # 0x00d4 -> ARABIC LETTER SHEEN INITIAL FORM '\ufebb' # 0x00d5 -> ARABIC LETTER SAD INITIAL FORM '\ufebf' # 0x00d6 -> ARABIC LETTER DAD INITIAL FORM '\ufec1' # 0x00d7 -> ARABIC LETTER TAH ISOLATED FORM '\ufec5' # 0x00d8 -> ARABIC LETTER ZAH ISOLATED FORM '\ufecb' # 0x00d9 -> ARABIC LETTER AIN INITIAL FORM '\ufecf' # 0x00da -> ARABIC LETTER GHAIN INITIAL FORM '\xa6' # 0x00db -> BROKEN VERTICAL BAR '\xac' # 0x00dc -> NOT SIGN '\xf7' # 0x00dd -> DIVISION SIGN '\xd7' # 0x00de -> MULTIPLICATION SIGN '\ufec9' # 0x00df -> ARABIC LETTER AIN ISOLATED FORM '\u0640' # 0x00e0 -> ARABIC TATWEEL '\ufed3' # 0x00e1 -> ARABIC LETTER FEH INITIAL FORM '\ufed7' # 0x00e2 -> ARABIC LETTER QAF INITIAL FORM '\ufedb' # 0x00e3 -> ARABIC LETTER KAF INITIAL FORM '\ufedf' # 0x00e4 -> ARABIC LETTER LAM INITIAL FORM '\ufee3' # 0x00e5 -> ARABIC LETTER MEEM INITIAL FORM '\ufee7' # 0x00e6 -> ARABIC LETTER NOON INITIAL FORM '\ufeeb' # 0x00e7 -> ARABIC LETTER HEH INITIAL FORM '\ufeed' # 0x00e8 -> ARABIC LETTER WAW ISOLATED FORM '\ufeef' # 0x00e9 -> ARABIC LETTER ALEF MAKSURA ISOLATED FORM '\ufef3' # 0x00ea -> ARABIC LETTER YEH INITIAL FORM '\ufebd' # 0x00eb -> ARABIC LETTER DAD ISOLATED FORM '\ufecc' # 0x00ec -> ARABIC LETTER AIN MEDIAL FORM '\ufece' # 0x00ed -> ARABIC LETTER GHAIN FINAL FORM '\ufecd' # 0x00ee -> ARABIC LETTER GHAIN ISOLATED FORM '\ufee1' # 0x00ef -> ARABIC LETTER MEEM ISOLATED FORM '\ufe7d' # 0x00f0 -> ARABIC SHADDA MEDIAL FORM '\u0651' # 0x00f1 -> ARABIC SHADDAH '\ufee5' # 0x00f2 -> ARABIC LETTER NOON ISOLATED FORM '\ufee9' # 0x00f3 -> ARABIC LETTER HEH ISOLATED FORM '\ufeec' # 0x00f4 -> ARABIC LETTER HEH MEDIAL FORM '\ufef0' # 0x00f5 -> ARABIC LETTER ALEF MAKSURA FINAL FORM '\ufef2' # 0x00f6 -> ARABIC LETTER YEH FINAL FORM '\ufed0' # 0x00f7 -> ARABIC LETTER GHAIN MEDIAL FORM '\ufed5' # 0x00f8 -> ARABIC LETTER QAF ISOLATED FORM '\ufef5' # 0x00f9 -> ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM '\ufef6' # 0x00fa -> ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE FINAL FORM '\ufedd' # 0x00fb -> ARABIC LETTER LAM ISOLATED FORM '\ufed9' # 0x00fc -> ARABIC LETTER KAF ISOLATED FORM '\ufef1' # 0x00fd -> ARABIC LETTER YEH ISOLATED FORM '\u25a0' # 0x00fe -> BLACK SQUARE '\ufffe' # 0x00ff -> UNDEFINED ) ### Encoding Map encoding_map = { 0x0000: 0x0000, # NULL 0x0001: 0x0001, # START OF HEADING 0x0002: 0x0002, # START OF TEXT 0x0003: 0x0003, # END OF TEXT 0x0004: 0x0004, # END OF TRANSMISSION 0x0005: 0x0005, # ENQUIRY 0x0006: 0x0006, # ACKNOWLEDGE 0x0007: 0x0007, # BELL 0x0008: 0x0008, # BACKSPACE 0x0009: 0x0009, # HORIZONTAL TABULATION 0x000a: 0x000a, # LINE FEED 0x000b: 0x000b, # VERTICAL TABULATION 0x000c: 0x000c, # FORM FEED 0x000d: 0x000d, # CARRIAGE RETURN 0x000e: 0x000e, # SHIFT OUT 0x000f: 0x000f, # SHIFT IN 0x0010: 0x0010, # DATA LINK ESCAPE 0x0011: 0x0011, # DEVICE CONTROL ONE 0x0012: 0x0012, # DEVICE CONTROL TWO 0x0013: 0x0013, # DEVICE CONTROL THREE 0x0014: 0x0014, # DEVICE CONTROL FOUR 0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE 0x0016: 0x0016, # SYNCHRONOUS IDLE 0x0017: 0x0017, # END OF TRANSMISSION BLOCK 0x0018: 0x0018, # CANCEL 0x0019: 0x0019, # END OF MEDIUM 0x001a: 0x001a, # SUBSTITUTE 0x001b: 0x001b, # ESCAPE 0x001c: 0x001c, # FILE SEPARATOR 0x001d: 0x001d, # GROUP SEPARATOR 0x001e: 0x001e, # RECORD SEPARATOR 0x001f: 0x001f, # UNIT SEPARATOR 0x0020: 0x0020, # SPACE 0x0021: 0x0021, # EXCLAMATION MARK 0x0022: 0x0022, # QUOTATION MARK 0x0023: 0x0023, # NUMBER SIGN 0x0024: 0x0024, # DOLLAR SIGN 0x0026: 0x0026, # AMPERSAND 0x0027: 0x0027, # APOSTROPHE 0x0028: 0x0028, # LEFT PARENTHESIS 0x0029: 0x0029, # RIGHT PARENTHESIS 0x002a: 0x002a, # ASTERISK 0x002b: 0x002b, # PLUS SIGN 0x002c: 0x002c, # COMMA 0x002d: 0x002d, # HYPHEN-MINUS 0x002e: 0x002e, # FULL STOP 0x002f: 0x002f, # SOLIDUS 0x0030: 0x0030, # DIGIT ZERO 0x0031: 0x0031, # DIGIT ONE 0x0032: 0x0032, # DIGIT TWO 0x0033: 0x0033, # DIGIT THREE 0x0034: 0x0034, # DIGIT FOUR 0x0035: 0x0035, # DIGIT FIVE 0x0036: 0x0036, # DIGIT SIX 0x0037: 0x0037, # DIGIT SEVEN 0x0038: 0x0038, # DIGIT EIGHT 0x0039: 0x0039, # DIGIT NINE 0x003a: 0x003a, # COLON 0x003b: 0x003b, # SEMICOLON 0x003c: 0x003c, # LESS-THAN SIGN 0x003d: 0x003d, # EQUALS SIGN 0x003e: 0x003e, # GREATER-THAN SIGN 0x003f: 0x003f, # QUESTION MARK 0x0040: 0x0040, # COMMERCIAL AT 0x0041: 0x0041, # LATIN CAPITAL LETTER A 0x0042: 0x0042, # LATIN CAPITAL LETTER B 0x0043: 0x0043, # LATIN CAPITAL LETTER C 0x0044: 0x0044, # LATIN CAPITAL LETTER D 0x0045: 0x0045, # LATIN CAPITAL LETTER E 0x0046: 0x0046, # LATIN CAPITAL LETTER F 0x0047: 0x0047, # LATIN CAPITAL LETTER G 0x0048: 0x0048, # LATIN CAPITAL LETTER H 0x0049: 0x0049, # LATIN CAPITAL LETTER I 0x004a: 0x004a, # LATIN CAPITAL LETTER J 0x004b: 0x004b, # LATIN CAPITAL LETTER K 0x004c: 0x004c, # LATIN CAPITAL LETTER L 0x004d: 0x004d, # LATIN CAPITAL LETTER M 0x004e: 0x004e, # LATIN CAPITAL LETTER N 0x004f: 0x004f, # LATIN CAPITAL LETTER O 0x0050: 0x0050, # LATIN CAPITAL LETTER P 0x0051: 0x0051, # LATIN CAPITAL LETTER Q 0x0052: 0x0052, # LATIN CAPITAL LETTER R 0x0053: 0x0053, # LATIN CAPITAL LETTER S 0x0054: 0x0054, # LATIN CAPITAL LETTER T 0x0055: 0x0055, # LATIN CAPITAL LETTER U 0x0056: 0x0056, # LATIN CAPITAL LETTER V 0x0057: 0x0057, # LATIN CAPITAL LETTER W 0x0058: 0x0058, # LATIN CAPITAL LETTER X 0x0059: 0x0059, # LATIN CAPITAL LETTER Y 0x005a: 0x005a, # LATIN CAPITAL LETTER Z 0x005b: 0x005b, # LEFT SQUARE BRACKET 0x005c: 0x005c, # REVERSE SOLIDUS 0x005d: 0x005d, # RIGHT SQUARE BRACKET 0x005e: 0x005e, # CIRCUMFLEX ACCENT 0x005f: 0x005f, # LOW LINE 0x0060: 0x0060, # GRAVE ACCENT 0x0061: 0x0061, # LATIN SMALL LETTER A 0x0062: 0x0062, # LATIN SMALL LETTER B 0x0063: 0x0063, # LATIN SMALL LETTER C 0x0064: 0x0064, # LATIN SMALL LETTER D 0x0065: 0x0065, # LATIN SMALL LETTER E 0x0066: 0x0066, # LATIN SMALL LETTER F 0x0067: 0x0067, # LATIN SMALL LETTER G 0x0068: 0x0068, # LATIN SMALL LETTER H 0x0069: 0x0069, # LATIN SMALL LETTER I 0x006a: 0x006a, # LATIN SMALL LETTER J 0x006b: 0x006b, # LATIN SMALL LETTER K 0x006c: 0x006c, # LATIN SMALL LETTER L 0x006d: 0x006d, # LATIN SMALL LETTER M 0x006e: 0x006e, # LATIN SMALL LETTER N 0x006f: 0x006f, # LATIN SMALL LETTER O 0x0070: 0x0070, # LATIN SMALL LETTER P 0x0071: 0x0071, # LATIN SMALL LETTER Q 0x0072: 0x0072, # LATIN SMALL LETTER R 0x0073: 0x0073, # LATIN SMALL LETTER S 0x0074: 0x0074, # LATIN SMALL LETTER T 0x0075: 0x0075, # LATIN SMALL LETTER U 0x0076: 0x0076, # LATIN SMALL LETTER V 0x0077: 0x0077, # LATIN SMALL LETTER W 0x0078: 0x0078, # LATIN SMALL LETTER X 0x0079: 0x0079, # LATIN SMALL LETTER Y 0x007a: 0x007a, # LATIN SMALL LETTER Z 0x007b: 0x007b, # LEFT CURLY BRACKET 0x007c: 0x007c, # VERTICAL LINE 0x007d: 0x007d, # RIGHT CURLY BRACKET 0x007e: 0x007e, # TILDE 0x007f: 0x007f, # DELETE 0x00a0: 0x00a0, # NON-BREAKING SPACE 0x00a2: 0x00c0, # CENT SIGN 0x00a3: 0x00a3, # POUND SIGN 0x00a4: 0x00a4, # CURRENCY SIGN 0x00a6: 0x00db, # BROKEN VERTICAL BAR 0x00ab: 0x0097, # LEFT POINTING GUILLEMET 0x00ac: 0x00dc, # NOT SIGN 0x00ad: 0x00a1, # SOFT HYPHEN 0x00b0: 0x0080, # DEGREE SIGN 0x00b1: 0x0093, # PLUS-OR-MINUS SIGN 0x00b7: 0x0081, # MIDDLE DOT 0x00bb: 0x0098, # RIGHT POINTING GUILLEMET 0x00bc: 0x0095, # FRACTION 1/4 0x00bd: 0x0094, # FRACTION 1/2 0x00d7: 0x00de, # MULTIPLICATION SIGN 0x00f7: 0x00dd, # DIVISION SIGN 0x03b2: 0x0090, # GREEK SMALL BETA 0x03c6: 0x0092, # GREEK SMALL PHI 0x060c: 0x00ac, # ARABIC COMMA 0x061b: 0x00bb, # ARABIC SEMICOLON 0x061f: 0x00bf, # ARABIC QUESTION MARK 0x0640: 0x00e0, # ARABIC TATWEEL 0x0651: 0x00f1, # ARABIC SHADDAH 0x0660: 0x00b0, # ARABIC-INDIC DIGIT ZERO 0x0661: 0x00b1, # ARABIC-INDIC DIGIT ONE 0x0662: 0x00b2, # ARABIC-INDIC DIGIT TWO 0x0663: 0x00b3, # ARABIC-INDIC DIGIT THREE 0x0664: 0x00b4, # ARABIC-INDIC DIGIT FOUR 0x0665: 0x00b5, # ARABIC-INDIC DIGIT FIVE 0x0666: 0x00b6, # ARABIC-INDIC DIGIT SIX 0x0667: 0x00b7, # ARABIC-INDIC DIGIT SEVEN 0x0668: 0x00b8, # ARABIC-INDIC DIGIT EIGHT 0x0669: 0x00b9, # ARABIC-INDIC DIGIT NINE 0x066a: 0x0025, # ARABIC PERCENT SIGN 0x2219: 0x0082, # BULLET OPERATOR 0x221a: 0x0083, # SQUARE ROOT 0x221e: 0x0091, # INFINITY 0x2248: 0x0096, # ALMOST EQUAL TO 0x2500: 0x0085, # FORMS LIGHT HORIZONTAL 0x2502: 0x0086, # FORMS LIGHT VERTICAL 0x250c: 0x008d, # FORMS LIGHT DOWN AND RIGHT 0x2510: 0x008c, # FORMS LIGHT DOWN AND LEFT 0x2514: 0x008e, # FORMS LIGHT UP AND RIGHT 0x2518: 0x008f, # FORMS LIGHT UP AND LEFT 0x251c: 0x008a, # FORMS LIGHT VERTICAL AND RIGHT 0x2524: 0x0088, # FORMS LIGHT VERTICAL AND LEFT 0x252c: 0x0089, # FORMS LIGHT DOWN AND HORIZONTAL 0x2534: 0x008b, # FORMS LIGHT UP AND HORIZONTAL 0x253c: 0x0087, # FORMS LIGHT VERTICAL AND HORIZONTAL 0x2592: 0x0084, # MEDIUM SHADE 0x25a0: 0x00fe, # BLACK SQUARE 0xfe7d: 0x00f0, # ARABIC SHADDA MEDIAL FORM 0xfe80: 0x00c1, # ARABIC LETTER HAMZA ISOLATED FORM 0xfe81: 0x00c2, # ARABIC LETTER ALEF WITH MADDA ABOVE ISOLATED FORM 0xfe82: 0x00a2, # ARABIC LETTER ALEF WITH MADDA ABOVE FINAL FORM 0xfe83: 0x00c3, # ARABIC LETTER ALEF WITH HAMZA ABOVE ISOLATED FORM 0xfe84: 0x00a5, # ARABIC LETTER ALEF WITH HAMZA ABOVE FINAL FORM 0xfe85: 0x00c4, # ARABIC LETTER WAW WITH HAMZA ABOVE ISOLATED FORM 0xfe8b: 0x00c6, # ARABIC LETTER YEH WITH HAMZA ABOVE INITIAL FORM 0xfe8d: 0x00c7, # ARABIC LETTER ALEF ISOLATED FORM 0xfe8e: 0x00a8, # ARABIC LETTER ALEF FINAL FORM 0xfe8f: 0x00a9, # ARABIC LETTER BEH ISOLATED FORM 0xfe91: 0x00c8, # ARABIC LETTER BEH INITIAL FORM 0xfe93: 0x00c9, # ARABIC LETTER TEH MARBUTA ISOLATED FORM 0xfe95: 0x00aa, # ARABIC LETTER TEH ISOLATED FORM 0xfe97: 0x00ca, # ARABIC LETTER TEH INITIAL FORM 0xfe99: 0x00ab, # ARABIC LETTER THEH ISOLATED FORM 0xfe9b: 0x00cb, # ARABIC LETTER THEH INITIAL FORM 0xfe9d: 0x00ad, # ARABIC LETTER JEEM ISOLATED FORM 0xfe9f: 0x00cc, # ARABIC LETTER JEEM INITIAL FORM 0xfea1: 0x00ae, # ARABIC LETTER HAH ISOLATED FORM 0xfea3: 0x00cd, # ARABIC LETTER HAH INITIAL FORM 0xfea5: 0x00af, # ARABIC LETTER KHAH ISOLATED FORM 0xfea7: 0x00ce, # ARABIC LETTER KHAH INITIAL FORM 0xfea9: 0x00cf, # ARABIC LETTER DAL ISOLATED FORM 0xfeab: 0x00d0, # ARABIC LETTER THAL ISOLATED FORM 0xfead: 0x00d1, # ARABIC LETTER REH ISOLATED FORM 0xfeaf: 0x00d2, # ARABIC LETTER ZAIN ISOLATED FORM 0xfeb1: 0x00bc, # ARABIC LETTER SEEN ISOLATED FORM 0xfeb3: 0x00d3, # ARABIC LETTER SEEN INITIAL FORM 0xfeb5: 0x00bd, # ARABIC LETTER SHEEN ISOLATED FORM 0xfeb7: 0x00d4, # ARABIC LETTER SHEEN INITIAL FORM 0xfeb9: 0x00be, # ARABIC LETTER SAD ISOLATED FORM 0xfebb: 0x00d5, # ARABIC LETTER SAD INITIAL FORM 0xfebd: 0x00eb, # ARABIC LETTER DAD ISOLATED FORM 0xfebf: 0x00d6, # ARABIC LETTER DAD INITIAL FORM 0xfec1: 0x00d7, # ARABIC LETTER TAH ISOLATED FORM 0xfec5: 0x00d8, # ARABIC LETTER ZAH ISOLATED FORM 0xfec9: 0x00df, # ARABIC LETTER AIN ISOLATED FORM 0xfeca: 0x00c5, # ARABIC LETTER AIN FINAL FORM 0xfecb: 0x00d9, # ARABIC LETTER AIN INITIAL FORM 0xfecc: 0x00ec, # ARABIC LETTER AIN MEDIAL FORM 0xfecd: 0x00ee, # ARABIC LETTER GHAIN ISOLATED FORM 0xfece: 0x00ed, # ARABIC LETTER GHAIN FINAL FORM 0xfecf: 0x00da, # ARABIC LETTER GHAIN INITIAL FORM 0xfed0: 0x00f7, # ARABIC LETTER GHAIN MEDIAL FORM 0xfed1: 0x00ba, # ARABIC LETTER FEH ISOLATED FORM 0xfed3: 0x00e1, # ARABIC LETTER FEH INITIAL FORM 0xfed5: 0x00f8, # ARABIC LETTER QAF ISOLATED FORM 0xfed7: 0x00e2, # ARABIC LETTER QAF INITIAL FORM 0xfed9: 0x00fc, # ARABIC LETTER KAF ISOLATED FORM 0xfedb: 0x00e3, # ARABIC LETTER KAF INITIAL FORM 0xfedd: 0x00fb, # ARABIC LETTER LAM ISOLATED FORM 0xfedf: 0x00e4, # ARABIC LETTER LAM INITIAL FORM 0xfee1: 0x00ef, # ARABIC LETTER MEEM ISOLATED FORM 0xfee3: 0x00e5, # ARABIC LETTER MEEM INITIAL FORM 0xfee5: 0x00f2, # ARABIC LETTER NOON ISOLATED FORM 0xfee7: 0x00e6, # ARABIC LETTER NOON INITIAL FORM 0xfee9: 0x00f3, # ARABIC LETTER HEH ISOLATED FORM 0xfeeb: 0x00e7, # ARABIC LETTER HEH INITIAL FORM 0xfeec: 0x00f4, # ARABIC LETTER HEH MEDIAL FORM 0xfeed: 0x00e8, # ARABIC LETTER WAW ISOLATED FORM 0xfeef: 0x00e9, # ARABIC LETTER ALEF MAKSURA ISOLATED FORM 0xfef0: 0x00f5, # ARABIC LETTER ALEF MAKSURA FINAL FORM 0xfef1: 0x00fd, # ARABIC LETTER YEH ISOLATED FORM 0xfef2: 0x00f6, # ARABIC LETTER YEH FINAL FORM 0xfef3: 0x00ea, # ARABIC LETTER YEH INITIAL FORM 0xfef5: 0x00f9, # ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE ISOLATED FORM 0xfef6: 0x00fa, # ARABIC LIGATURE LAM WITH ALEF WITH MADDA ABOVE FINAL FORM 0xfef7: 0x0099, # ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE ISOLATED FORM 0xfef8: 0x009a, # ARABIC LIGATURE LAM WITH ALEF WITH HAMZA ABOVE FINAL FORM 0xfefb: 0x009d, # ARABIC LIGATURE LAM WITH ALEF ISOLATED FORM 0xfefc: 0x009e, # ARABIC LIGATURE LAM WITH ALEF FINAL FORM }
bsd-3-clause
thorwhalen/ut
ml/stream/sequences.py
1
6137
from sklearn.base import BaseEstimator from collections import Counter import pandas as pd from numpy import sum, nan, isnan from ut.util.uiter import window class NextElementPredictor(BaseEstimator): def predict(self, seqs): preds = self.predict_proba(seqs) return [max(pred, key=lambda key: pred[key]) for pred in preds] def predict_proba(self, seqs): return list(map(self._predict_proba_conditioned_on_recent_subseq, seqs)) def _predict_proba_conditioned_on_recent_subseq(self, recent_subseq): raise NotImplementedError("Need to implement this method") class MarkovNextElementPred(NextElementPredictor): _list_of_attributes_to_display = ['markov_window', 'empty_element', 'keep_stats_in_memory'] def __init__(self, markov_window=2, empty_element=-1, keep_stats_in_memory=True): self.markov_window = markov_window self.keep_stats_in_memory = keep_stats_in_memory self.empty_element = empty_element self._empty_element_padding = [empty_element] * (self.markov_window - 1) @property def total_tuple_count(self): """ :return: Number of observed window tuples (sum of values in self.snip_tuples_counter_) """ if self.total_tuple_count_ is not None: return self.total_tuple_count_ else: total_tuple_count_ = sum(self.snip_tuples_counter_.values()) if self.keep_stats_in_memory: self.total_tuple_count_ = total_tuple_count_ return total_tuple_count_ @property def pair_prob(self): """ :return: Series of probabilities (unsmoothed count ratios) indexed by snip pairs """ if self.pair_prob_ is not None: return self.pair_prob_ else: pair_prob_ = pd.Series(self.snip_tuples_counter_) / self.total_tuple_count if self.keep_stats_in_memory: self.pair_probs_ = pair_prob_ return pair_prob_ @property def element_prob(self): """ :return: Series of snips probabilities (unsmoothed count ratios) """ if self.element_prob_ is not None: return self.element_prob_ else: element_prob_ = (self.pair_prob * self.total_tuple_count) element_prob_ = element_prob_.groupby(level=0).sum() element_prob_ = element_prob_.drop(labels=self.empty_element) # element_prob_ = element_prob_.iloc[ # element_prob_.index.get_level_values(level=0) != self.empty_element] element_prob_ /= element_prob_.sum() if self.keep_stats_in_memory: self.element_prob_ = element_prob_ return element_prob_ @property def conditional_prob(self): """ :return: Series of probabilities of last element (level) conditional on previous ones (including empty elements) """ if self.conditional_prob_ is not None: return self.conditional_prob_ else: conditional_prob_ = self._drop_empty_elements_of_sr(self.pair_prob, levels=[self.markov_window - 1]) conditional_levels = list(range(self.markov_window - 1)) conditional_prob_ = conditional_prob_.div( conditional_prob_.groupby(level=conditional_levels).sum(), level=0) # TODO: Only works for two levels if self.keep_stats_in_memory: self.conditional_prob_ = conditional_prob_ return conditional_prob_ @property def initial_element_prob(self): """ :return: Series of snips probabilities (unsmoothed count ratios) """ if self.initial_element_prob_ is not None: return self.initial_element_prob_ else: initial_element_prob_ = self.pair_prob.xs(self.empty_element, level=0, drop_level=True) initial_element_prob_ /= initial_element_prob_.sum() if self.keep_stats_in_memory: self.initial_element_prob_ = initial_element_prob_ return initial_element_prob_ def fit(self, snips_list): # reset anything previously learned self._initialize_params() return self.partial_fit(snips_list) def partial_fit(self, snips_list): if not set(['snip_tuples_counter_']).issubset(list(self.__dict__.keys())): self._initialize_params() for snips in snips_list: self._partial_fit_of_a_single_snips(snips) return self def _initialize_params(self): """ Initializes model params (the snip_tuples_counter_, etc.) :return: None """ self.snip_tuples_counter_ = Counter() self._reset_properties() def _reset_properties(self): """ Resets some properties that depend on snip_tuples_counter_ to be computed (is used when the later changes) These will be recomputed when requested. :return: None """ self.total_tuple_count_ = None self.pair_prob_ = None self.element_prob_ = None self.initial_element_prob_ = None self.conditional_prob_ = None def _partial_fit_of_a_single_snips(self, snips): self._reset_properties() self.snip_tuples_counter_.update(window(self._empty_element_padding + list(snips) + self._empty_element_padding, n=self.markov_window)) def _drop_empty_elements_of_sr(self, sr, levels=None, renormalize=False): if levels is None: levels = list(range(self.markov_window)) for level in levels: sr = sr.drop(labels=self.empty_element, level=level) if renormalize: sr /= sr.sum() return sr def _predict_proba_conditioned_on_recent_subseq(self, recent_subseq): pass def __repr__(self): d = {attr: getattr(self, attr) for attr in self._list_of_attributes_to_display if attr in self.__dict__} d['total_tuple_count'] = self.total_tuple_count return self.__class__.__name__ + '\n' + str(d)
mit
ShassAro/ShassAro
Bl_project/blVirtualEnv/lib/python2.7/site-packages/setuptools/tests/test_test.py
124
3712
# -*- coding: UTF-8 -*- """develop tests """ import os import shutil import site import sys import tempfile import unittest from distutils.errors import DistutilsError from setuptools.compat import StringIO from setuptools.command.test import test from setuptools.command import easy_install as easy_install_pkg from setuptools.dist import Distribution SETUP_PY = """\ from setuptools import setup setup(name='foo', packages=['name', 'name.space', 'name.space.tests'], namespace_packages=['name'], test_suite='name.space.tests.test_suite', ) """ NS_INIT = """# -*- coding: Latin-1 -*- # Söme Arbiträry Ünicode to test Issüé 310 try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) """ # Make sure this is Latin-1 binary, before writing: if sys.version_info < (3,): NS_INIT = NS_INIT.decode('UTF-8') NS_INIT = NS_INIT.encode('Latin-1') TEST_PY = """import unittest class TestTest(unittest.TestCase): def test_test(self): print "Foo" # Should fail under Python 3 unless 2to3 is used test_suite = unittest.makeSuite(TestTest) """ class TestTestTest(unittest.TestCase): def setUp(self): if sys.version < "2.6" or hasattr(sys, 'real_prefix'): return # Directory structure self.dir = tempfile.mkdtemp() os.mkdir(os.path.join(self.dir, 'name')) os.mkdir(os.path.join(self.dir, 'name', 'space')) os.mkdir(os.path.join(self.dir, 'name', 'space', 'tests')) # setup.py setup = os.path.join(self.dir, 'setup.py') f = open(setup, 'wt') f.write(SETUP_PY) f.close() self.old_cwd = os.getcwd() # name/__init__.py init = os.path.join(self.dir, 'name', '__init__.py') f = open(init, 'wb') f.write(NS_INIT) f.close() # name/space/__init__.py init = os.path.join(self.dir, 'name', 'space', '__init__.py') f = open(init, 'wt') f.write('#empty\n') f.close() # name/space/tests/__init__.py init = os.path.join(self.dir, 'name', 'space', 'tests', '__init__.py') f = open(init, 'wt') f.write(TEST_PY) f.close() os.chdir(self.dir) self.old_base = site.USER_BASE site.USER_BASE = tempfile.mkdtemp() self.old_site = site.USER_SITE site.USER_SITE = tempfile.mkdtemp() def tearDown(self): if sys.version < "2.6" or hasattr(sys, 'real_prefix'): return os.chdir(self.old_cwd) shutil.rmtree(self.dir) shutil.rmtree(site.USER_BASE) shutil.rmtree(site.USER_SITE) site.USER_BASE = self.old_base site.USER_SITE = self.old_site def test_test(self): if sys.version < "2.6" or hasattr(sys, 'real_prefix'): return dist = Distribution(dict( name='foo', packages=['name', 'name.space', 'name.space.tests'], namespace_packages=['name'], test_suite='name.space.tests.test_suite', use_2to3=True, )) dist.script_name = 'setup.py' cmd = test(dist) cmd.user = 1 cmd.ensure_finalized() cmd.install_dir = site.USER_SITE cmd.user = 1 old_stdout = sys.stdout sys.stdout = StringIO() try: try: # try/except/finally doesn't work in Python 2.4, so we need nested try-statements. cmd.run() except SystemExit: # The test runner calls sys.exit, stop that making an error. pass finally: sys.stdout = old_stdout
gpl-2.0